Let customers cancel an order before it ships
Ruby · Rails · intermediate · modification
Adds self-service cancellation for orders that have not shipped yet. The routes gain a `cancel` member action on orders, and `Api::OrdersController#cancel` finds the order among the signed-in customer's own (404 otherwise) and calls the new `Order#cancel!`. `cancel!` takes the order's row lock with `with_lock`, checks that the order is still `paid`, refunds the whole charge through `PaymentGateway.client` with an idempotency key derived from the order id, then sets the status to `cancelled` and creates the `OrderCancellation` record in the same transaction. The controller answers 409 for an order that can no longer be cancelled and 502 with a generic message when the gateway call fails, logging the details. Includes the migration for `order_cancellations` (one per order), the new model, the `cancelled` status on the order enum, endpoint tests in `orders_controller_test.rb` next to the existing ones, and model tests in `order_test.rb` for the cancel flow.
Ruby 4.0, Rails 8.1 API endpoints, SQLite in development and test, PostgreSQL 16 in production (READ COMMITTED, the default). On PostgreSQL `with_lock` opens a transaction and reloads the record with `SELECT ... FOR UPDATE` (ActiveRecord::Locking::Pessimistic API docs); SQLite has no row locks and Rails 8.1 begins its transactions with `BEGIN IMMEDIATE`, which takes the database's write lock instead. `Api::BaseController` (existing, unchanged) inherits `ActionController::API`, reads `Authorization: Bearer <token>` and sets `Current.customer` (an `ActiveSupport::CurrentAttributes` attribute), answering 401 otherwise. `Customer has_many :orders`; `Order` has `id` (sequential, never reused), `customer_id`, a unique `number`, `status` (a string enum, `NOT NULL`), `total_cents` (integer), `payment_charge_id` and a nullable `tracking_number`. An order is paid in full at checkout by one card charge for `total_cents`; after checkout only its status and tracking number change, and no refund is made on an order before it ships other than this one. The warehouse dispatch job (existing, unchanged) calls `Order#mark_shipped!`, shown in the diff, which also takes the order's lock and ships only a `paid` order; the warehouse dispatches every order that is still `paid` within 7 days of checkout. `PaymentGateway.client.refund(charge_id:, amount_cents:, idempotency_key:)` (existing) returns a `PaymentGateway::Refund` (`id`, `charge_id`, `amount_cents`); for a key it has seen in the last 30 days the gateway returns the refund it made the first time instead of refunding again. The client wraps every gateway rejection and transport failure (open timeout 5 s, read timeout 10 s) in `PaymentGateway::Error`. An existing nightly reconciliation job (out of scope) reports gateway refunds that no order records (a lost reply the customer never retried, or an order dispatched before the retry). Each Puma thread has its own database connection (pool size equals the thread count), and cancellations are a few dozen a day. In development and test `PaymentGateway.client` is `PaymentGateway::Fake` (existing): it keeps its refunds in memory, honours idempotency keys the same way, and `fail_next!` makes the next call raise `PaymentGateway::Error`, with `after_refund: true` only after making the refund, as when the reply is lost. In production `ActiveRecord::RecordNotFound` is answered with Rails' default 404. Tests are Minitest with inline records. The cancel button itself ships separately in the storefront.
Requirements
- `POST /api/orders/:id/cancel` (new) lets a signed-in customer cancel one of their own orders while its status is `paid` (charged, not yet handed to the carrier): the whole charge is refunded through the payment gateway, the status becomes `cancelled`, an `order_cancellations` row records the refund's id and amount, and the response is 200 with the order as `GET /api/orders/:id` renders it.
- An order that does not exist or belongs to another customer answers 404 and changes nothing, as `GET /api/orders/:id` does. An order of their own in any other status (`shipped`, `delivered`, or already `cancelled`) answers 409 and refunds nothing.
- An order is refunded at most once. Two cancel requests for the same order at the same time (a double click, two open tabs) produce one refund: one answers 200, the other 409. A cancel that races the warehouse dispatch either cancels the order (and the dispatch then skips it) or loses to it (409, no refund), never both (apart from a lost gateway reply, requirement 4, which the nightly reconciliation reports).
- The status change and the `order_cancellations` row are saved together or not at all. The refund call is made while the order is locked and before they are saved; it is safe to repeat because the gateway honours idempotency keys (context). If the gateway call fails, or its result never reaches the app (a timeout), the order stays `paid` and nothing is recorded; the response is 502 with a generic message and the customer can try again, and that retry must not refund a second time.
- Unchanged: every `/api` request needs a valid bearer token (401 otherwise), and `GET /api/orders` and `GET /api/orders/:id` keep their behaviour.
Files touched
- config/routes.rb
- db/migrate/20261102090000_create_order_cancellations.rb
- app/models/order_cancellation.rb
- app/models/order.rb
- app/controllers/api/orders_controller.rb
- test/controllers/api/orders_controller_test.rb
- test/models/order_test.rb