Issue paid gift cards through Giftly in the background

Ruby · Rails · advanced · modification

Issues the gift card automatically once a purchase is paid, instead of staff creating it in Giftly's dashboard. The migration adds `provider_card_id` (unique), `card_last4` and `issued_at` to `gift_card_purchases`. `GiftlyClient` (new, in `app/clients/`) posts the card to Giftly's `/v1/cards` with the API key as a bearer token and 5 and 10 second open and read timeouts, raises `GiftlyClient::Error` with the status code on an error answer and returns the parsed card; `GiftlyClient.default` builds the client from the environment, and tests assign their own. `IssueGiftCardJob` skips a purchase that already has a card, otherwise issues one and stores it, and declares `retry_on Net::ReadTimeout` with 5 attempts. `GiftCardPurchase` gains `issued?`, and `mark_paid!` now records the payment once and enqueues the job while the purchase has no card. `issue_gift_card_job_test.rb` runs the job against a fake client (the card is stored, an issued purchase makes no call, a read timeout schedules a retry, a Giftly error is raised); `gift_card_purchase_test.rb` checks the enqueue and repeated `mark_paid!` calls.

Ruby 4.0, Rails 8.1 (SQLite in development and test, PostgreSQL 16 in production; nothing here depends on the database). Active Job runs on Solid Queue in production, which runs the retries `retry_on` schedules; Mission Control Jobs is the jobs dashboard staff use for failed jobs. The existing `Payments::WebhooksController` (unchanged, not shown) verifies the payment provider's signature and calls `purchase.mark_paid!` outside any transaction; if it raises, the webhook answers 500 and the provider redelivers it. The provider sends a redelivery only after the previous delivery of that event finished or timed out, so two `mark_paid!` calls for one purchase never overlap. Staff retry or discard failed jobs in the dashboard within a week of the failure. Gift card purchases are created by the existing checkout with validated, `NOT NULL` emails, `amount_cents` between 1000 and 50000 (also a check constraint), `currency` `USD` or `EUR` (both accepted by Giftly) and an optional `message` up to 200 characters (Giftly accepts `null`); purchases are never deleted and their ids are never reused. `GIFTLY_URL` is Giftly's origin (`https://api.giftly.example`, no path) and `GIFTLY_API_KEY` the shop's key, both set in production; the key is used only by production, and tests never call Giftly. A successful Giftly answer is 201 with a JSON body whose `id` and `last4` are strings. Tests are Minitest with Active Job's test adapter and inline records; `ApplicationJob` is the generated base class.

Requirements

Files touched

Review this PR

Ruby practice