Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Retire the state machines on Payment and its sessions (#14460)

Damian Legawiecb9394e8c4899
diff --git a/CLAUDE.md b/CLAUDE.md
index 51c84a260b..3373c2dfc8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -36,7 +36,7 @@ Active plans (6.0 target, work pending):
- `6.0-inventory-operations.md` — StockTransfer lifecycle (draft → ready_to_ship → in_transit → received with partial receive), new `Spree::PurchaseOrder` + `Spree::Supplier` (the procurement source; `Spree::Seller` is the marketplace seller — see decisions.md 2026-07-14 and 2026-08-17) replacing today's "external receive" hack, variant + stock-location stock history panels. Consumes the typed-movement primitives from `6.0-typed-stock-movements.md`.
- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). **Shipped to 6-0-dev (PR #14302):** the Category surface (5.5–5.6) plus the 6.0 core — `spree_taxons`→`spree_categories` table rename + inheritance flip (`Spree::Category < Spree.base_class`, `Spree::Taxon` alias kept), the full `Collection` stack (model + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data migration, and de-ruling Category. Pending (all 6.1): channel-aware `CollectionRules::AvailableOn` (ships interim now, rides with channels) + dropping `spree_taxon_rules`/`Taxonomy`. No brand feature in 6.0 — brands are modeled as a Category/Collection; `brand_taxon`/`brand_name` removed with `Taxonomy`.
- `6.0-delivery-method-rules.md` — `Spree::DeliveryMethodRule` STI on DeliveryMethod (design finalized 2026-07-29): ItemTotal/Weight rules first (Channel/Market/CustomerGroup later in lockstep with payment-method-rules), enforced solely in `Stock::Estimator`'s method filter so calculator- AND provider-priced methods obey eligibility; replaces the FlatRate-only bound preferences (one-release bridge + data task). **Phase 1 shipped** (rules + Estimator seam + admin nested CRUD/types discovery + dashboard Conditions card). **2026-08-06:** `ExcludedProductsRule` (products via `spree_delivery_method_rule_products` join, Saleor-style method-side exclusion) replaces the dropped `spree_products.excluded_delivery_method_ids` JSON column; rule-reference storage picks by cardinality — small reference sets stay `normalize_id_preference` arrays, catalog-scale (products) gets a join table.
-- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` — named steps inside a plain `def perform(order:, ...)` (the ActiveJob::Continuable shape; bare `super` turns parameters into readers). Vocabulary: `step`/`external_step` (+ `with:`, `on_flow_failure:`), `run_hooks` + class-level `hooks`, `failure`/`halt!`; plain `ApplicationRecord.transaction`/`with_lock`/`rescue`/`publish_event`; every step instrumented as `step.spree_workflow`. Money lives in `Carts::RecalculateTotals` (single totals seam; the completed-order branch is the post-placement resum — rows re-summed, never regenerated), statuses in `Orders::UpdateStatuses` (refreshes each fulfillment's state, then rolls up); Order/CartUpdater are 6.1-removed warning shells. Shared Cart/Order surface lives in `Spree::Purchase::*` concerns; completion side effects (newsletter, account creation, risk) run in the sync `OrderPlacedSubscriber` on order.placed. Reserved for flows needing hooks, compensation/external I/O, or replay — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively — but hooks on flows already in the tier ship deliberately on the 6.0 boundary (2026-08-02), since hook keys are public API and moving one later is breaking. **New models get no state machine** — plain `status` string + inclusion validation, transitions through workflows; gateway I/O never in a save callback. Three hook families, contracts settled 2026-08-02: **lifecycle** (past tense, read-only), **validate** (handler calls `workflow.reject!(message)` to veto), **context** (`set_*_context`/`get_provider_data` — handler returns a hash, `run_hooks` deep-merges all handlers and returns it; last writer wins on collision). Phase 3 **shipped (2026-08-02)**: `run_hooks` returns the merged hash and `Workflow#reject!` is public API; `validate`/context/lifecycle hooks live on AddItem, Complete, Recalculate, RecalculateTotals, Cancel and Resume; `Fulfillments::Create`, `Payments::Capture`/`Refund`, `Payments::HandleWebhook` and `Carts::Merge` moved to `app/workflows/` (seams `fulfillment_create_workflow`, `payment_capture_workflow`, `payment_refund_workflow`, `payments_handle_webhook_workflow`, `cart_merge_workflow`; legacy names readable one release). **Customer registration (2026-08-05):** `Customers::Create` (seam `customer_create_workflow`, hooks `customers.create.validate`/`after_create`) is the single storefront customer-creation flow — self-registration + checkout account box (optional `order:` adopts addresses and links the order); absorbs `Orders::CreateUserAccount` (deprecated shell); admin create stays plain CRUD; token issuance stays in controllers; core sends NO welcome email — signup email is host-app code on `user.created` or the `after_create` hook. Payment workflows own the transaction boundary and guards — money movement stays in the model, called from an `external_step`. No workflows for plain CRUD. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `Carts::Complete` battery must pass unmodified. **Durability = plain Rails:** long-running background work uses `ActiveJob::Continuable` directly (reference: `Spree::Imports::ProcessJob` — CSV spine with a row-number cursor; `CreateRowsJob`/`ProcessRowsJob` deprecated shells); workflows are synchronous request-cycle flows and are NOT jobs — Workflow-level durable execution ships only if the payout run proves the need.
+- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` — named steps inside a plain `def perform(order:, ...)` (the ActiveJob::Continuable shape; bare `super` turns parameters into readers). Vocabulary: `step`/`external_step` (+ `with:`, `on_flow_failure:`), `run_hooks` + class-level `hooks`, `failure`/`halt!`; plain `ApplicationRecord.transaction`/`with_lock`/`rescue`/`publish_event`; every step instrumented as `step.spree_workflow`. Money lives in `Carts::RecalculateTotals` (single totals seam; the completed-order branch is the post-placement re-sum — rows re-summed, never regenerated), statuses in `Orders::UpdateStatuses` (refreshes each fulfillment's state, then rolls up); Order/CartUpdater are 6.1-removed warning shells. Shared Cart/Order surface lives in `Spree::Purchase::*` concerns; completion side effects (newsletter, account creation, risk) run in the sync `OrderPlacedSubscriber` on order.placed. Reserved for flows needing hooks, compensation/external I/O, or replay — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively — but hooks on flows already in the tier ship deliberately on the 6.0 boundary (2026-08-02), since hook keys are public API and moving one later is breaking. **New models get no state machine** — plain `status` string + inclusion validation, transitions through workflows; gateway I/O never in a save callback. Three hook families, contracts settled 2026-08-02: **lifecycle** (past tense, read-only), **validate** (handler calls `workflow.reject!(message)` to veto), **context** (`set_*_context`/`get_provider_data` — handler returns a hash, `run_hooks` deep-merges all handlers and returns it; last writer wins on collision). Phase 3 **shipped (2026-08-02)**: `run_hooks` returns the merged hash and `Workflow#reject!` is public API; `validate`/context/lifecycle hooks live on AddItem, Complete, Recalculate, RecalculateTotals, Cancel and Resume; `Fulfillments::Create`, `Payments::Capture`/`Refund`, `Payments::HandleWebhook` and `Carts::Merge` moved to `app/workflows/` (seams `fulfillment_create_workflow`, `payment_capture_workflow`, `payment_refund_workflow`, `payments_handle_webhook_workflow`, `cart_merge_workflow`; legacy names readable one release). **Customer registration (2026-08-05):** `Customers::Create` (seam `customer_create_workflow`, hooks `customers.create.validate`/`after_create`) is the single storefront customer-creation flow — self-registration + checkout account box (optional `order:` adopts addresses and links the order); absorbs `Orders::CreateUserAccount` (deprecated shell); admin create stays plain CRUD; token issuance stays in controllers; core sends NO welcome email — signup email is host-app code on `user.created` or the `after_create` hook. **Payment flows live in the workflows (2026-08-18, supersedes “money movement stays in the model”):** `Payments::Capture`/`Void`/`Process` implement capture, void and authorize/purchase inline as named steps — Capture/Process claim atomically BEFORE the gateway (a stale instance must not re-drive money movement), while Void stays gateway-authoritative (no pre-claim — the gateway decides if the authorization can still be released) with a compare-and-swap on the terminal write only; `Spree::Payment` keeps only gateway mechanics (`gateway_options`, `handle_response`, error translation) plus deprecated verb shells (`capture!`, `void_transaction!`, `process!`, `authorize!`, `purchase!`) that delegate to the workflows **until 7.0** (a full major — they have been the public money-movement API since Spree 1 and the replacement is a different shape) — new callers use `Spree.payment_*_workflow`, never the shells. `confirm!` stays on the model by design: it runs inside `settle_payment!`'s lock, where workflows cannot go, and makes no gateway call. No workflows for plain CRUD. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `Carts::Complete` battery must pass unmodified. **Durability = plain Rails:** long-running background work uses `ActiveJob::Continuable` directly (reference: `Spree::Imports::ProcessJob` — CSV spine with a row-number cursor; `CreateRowsJob`/`ProcessRowsJob` deprecated shells); workflows are synchronous request-cycle flows and are NOT jobs — Workflow-level durable execution ships only if the payout run proves the need.
- `6.0-extendable-validations.md` — Workflow `validate` hooks are THE validation extension surface; **no generic model-validation registry** (design finalized 2026-08-13 — decorators stay the documented additive path, relaxing core rules = store preferences/predicate overrides). Ships: `Carts::UpsertItems` graduated to a workflow absorbing every non-increment item mutation (bulk payloads, PATCH quantity, DELETE = quantity 0; per-item `validate` with `AddItem`-compatible readers, shared item-application steps, ONE recalculate per batch; **partial-success on the storefront** — rejected items skip onto the cart's existing `warnings` array on 2xx, while the **order twin fails the whole batch**; no whole-batch veto; `SetQuantity`/`RemoveLineItem` → deprecated shells), `Products::Create`/`Update`/`Destroy` workflows (all write paths route through: Admin API v3, CSV importer, seeds; no standalone variant workflow), **rejections carry `ActiveModel::Errors`** (`Workflow#errors` + argument-less `reject!` rendering via `render_validation_error`; `reject!(message)` bridges to `:base`), `Spree.hooks.validate!` wired into boot, Address polish (document `Spree.validators.addresses` + removal API, `require_company` store preference). Address and cart creation get NO workflow (plain CRUD); custom-field value validation deferred to its own plan (Shopify-style per-definition rules, new-writes-only; `required` stays advisory). **Constraints now:** new item mutations route through `AddItem`/`UpsertItems`, new product write paths call the `Products::*` workflows, no hardcoded error codes at hook-bearing `render_service_error` call sites, clients must check `warnings` on storefront bulk-item 2xx responses. **Shipped 2026-08-13** (all four phases).
- `6.0-store-scoped-configuration.md` — Move eight commerce-behavior globals (`auto_capture` + `auto_capture_on_dispatch` → one `capture_method` string; `allow_checkout_on_gateway_error` dropped, not moved — nothing reads it; `track_inventory_levels`, `stock_reservations_enabled`, `track_price_history`, `show_products_without_price`, `address_requires_phone`, `disable_sku_validation`) from `Spree::Config` to `Spree::Store` preferences. Store preference is **authoritative — no runtime fallback** (a fallback chain is what made `default_stock_reservation_ttl_minutes` silently unreachable); upgrade carries values over via `spree:store_settings:backfill_from_config`; globals are deprecated shells until 6.1. Storeless readers (`Address`, the product availability scope) use `Spree::Current.store` with a default fallback. Seven dead settings (`products_per_page`, `storefront_*_path`, …) get shells then deletion. **Capture timing is one vocabulary (2026-08-13):** `Spree::CaptureMethod` = `checkout | on_dispatch | manual` — a Store preference, overridable by a nullable `capture_method` **column** on PaymentMethod (null = inherit; a column, not a preference, since the payment-method preferences blob is per-provider gateway credentials); read `resolved_capture_method`, write `capture_method`; dispatch capture is decided per payment so a `manual` method is never charged by a dispatch; `spree:migrate_capture_methods` carries `auto_capture` over. **Constraints now:** no new `Spree::Config` reads of the movers; no new code against `auto_capture`/`auto_capture_on_dispatch` (deprecated on both models); new behavior flags are born on Store, never global; jobs that validate addresses or query the catalog must set `Spree::Current.store`.
- `6.0-duties-and-custom-fees.md` — Customs duties + shopper-visible custom fees on the shipped typed-`Fee` substrate (**6.0 scope implemented 2026-08-14**; 6.1 provider gem pending): a duty is a `Fee(kind: 'duty')` snapshotting its inputs (`hs_code`/`country_of_origin`/rate/provider) in `metadata` — never a TaxLine, never a new table; classification = three plain columns on `spree_variants` (`hs_code`, `country_of_origin` — **an ISO alpha-2 code, NEVER a country record id, since `spree_countries` is slated for removal**; `customs_description`) editable in both dashboard editors (variant sheet + bulk spreadsheet, sharing `normalize-customs.ts`) and shipped WITH their first consumer (EasyPost customs declaration + shipping-terms option on international labels — EasyPost declares, it never estimates); Store API cart/order serializers gain `fees` + `fee_total` (itemized shopper display is the point); duty estimation rides `Spree.adjusters` (provider gem writes duty fees + its own import-VAT `TaxLine(fee_id:)` rows) — no dedicated duty-provider contract unless a real gem proves the need; duty fees excluded from the default taxable-item set — `Spree::Purchase::Taxation#taxable_items` (shared Cart/Order) is the ONE definition every provider inherits, and it reads **fresh scopes, never the cached associations** (they load empty at record creation, so a Ruby-side `reject` over `fees` silently untaxes every fee — latent bug the duty work surfaced); a provider that does tax duties passes its own item list. 6.0 = plumbing; 6.1 = landed-cost provider gem + `Spree::Market` shipping-terms setting. **Constraints now:** never re-derive duty from the live catalog on an existing order (the metadata snapshot is authoritative); store-serializer money work must not assume fees stay hidden; EasyPost customs data is international-only, never required for domestic; admin cart/order serializers deliberately DROP the inherited `fees` association (admin reads/writes fees through `/orders/:id/fees`, and an admin serializer must never render a store serializer); a new variant attribute must be permitted in THREE places or it is silently dropped on one write path — `PermittedAttributes`, the nested `Admin::Products::VariantsController`, AND the inline `variants: [...]` list on `Admin::ProductsController` (the last is what the dashboard's product Save actually hits; a spec on the nested controller proves nothing about it).
diff --git a/docs/plans/6.0-normalize-state-to-status.md b/docs/plans/6.0-normalize-state-to-status.md
index 2c7d046315..457bffa64d 100644
--- a/docs/plans/6.0-normalize-state-to-status.md
+++ b/docs/plans/6.0-normalize-state-to-status.md
@@ -25,15 +25,15 @@ This inconsistency means developers must remember which column each model uses.
|-------|---------------|------------|
| Order | `state` | Removed (cart-order-split — no state machine on Order) |
| Adjustment | `state` | Removed (split-adjustments — no state machine) |
-| **Payment** | `state` | Rename → `status` |
-| **Shipment** | `state` | Rename → `status` |
+| **Payment** | `state` | **Done (2026-08-18)** — renamed AND machine removed (`HasStatus` + workflows; see amendment below) |
+| **Shipment** | `state` | Done — became Fulfillment (`HasStatus`, no machine) |
| **InventoryUnit** | `state` | Rename → `status` |
-| **ReturnAuthorization** | `state` | Rename → `status` |
+| **ReturnAuthorization** | `state` | Gone — model deleted by the returns rework |
| **GiftCard** | `state` | Rename → `status` |
| Product | `status` | Already correct |
| PriceList | `status` | Already correct |
-| PaymentSession | `status` | Already correct |
-| PaymentSetupSession | `status` | Already correct |
+| PaymentSession | `status` | **Done (2026-08-18)** — machine removed (`PaymentSessionTransitions`) |
+| PaymentSetupSession | `status` | **Done (2026-08-18)** — machine removed (`PaymentSessionTransitions`) |
| Import | `status` | Already correct |
| ImportRow | `status` | Already correct |
| Invitation | `status` | Already correct |
@@ -42,28 +42,69 @@ This inconsistency means developers must remember which column each model uses.
## Key Decisions (do not deviate without discussion)
-- **`status` is the standard.** All state machines use `status` as the column name.
-- **Single migration** renames all five columns at once.
+- **`status` is the standard.** All status columns use that name.
+- ~~**Single migration** renames all five columns at once.~~ Superseded
+ 2026-08-18: each model renames in its own migration, in the same change
+ that removes its machine (see the amendment below). Payment shipped as
+ `20260818000001_rename_spree_payments_state_to_status`; InventoryUnit and
+ GiftCard get their own when their turn comes.
- **Deprecation aliases** (`alias_attribute :state, :status`) for one release to avoid breaking custom code that reads `.state`.
- **API responses use `status`** everywhere. No more `state` field in serializers.
- **Order `payment_state` and `shipment_state` stay as-is.** These are derived summary fields on Order, not state machine columns. Renaming them to `payment_status`/`shipment_status` is optional and lower priority.
+
+## Amendment (2026-08-18): renames ride with machine removal
+
+The Phase 2 sketch above (`state_machine :status, ...`) is superseded for the
+payment family. When a model's column renames, its machine goes at the same
+time — following Order and Fulfillment:
+
+- **Payment** — `spree_payments.state` renamed to `status`; the machine is
+ removed in favor of `Spree::HasStatus`. Transitions live where the money
+ moves: the `Spree::Payments` workflows and `Spree::Payment::Processing`,
+ as explicit named writes (`complete!`, `pend!`, `void!`, `failure!`,
+ `invalidate!`, `started_processing!`). `payment.completed` /
+ `payment.voided` publish from the write itself, not a transition callback.
+ The machine's guards survive as `can_complete?` / `can_pend?` /
+ `can_void?` with the same from-state lists. The `invalid` status defines
+ no predicate or scope — `invalid?` stays ActiveModel's; use
+ `has_invalid_status?`.
+- **PaymentSession / PaymentSetupSession** — identical machines replaced by
+ the shared `Spree::PaymentSessionTransitions` concern: non-raising guarded
+ transitions (`process`/`complete`/`fail`/`cancel`/`expire`) matching the
+ old non-bang events, because the webhook and synchronous completion paths
+ race by design and the loser must be a no-op.
+- **`has_status` applies its `default:` as an ActiveModel attribute default**
+ at instantiation (never a database default), replacing the per-model
+ `after_initialize` callbacks. It also skips defining any predicate or
+ scope whose name Rails already owns.
+- Deprecated bridges until 6.1: `Payment#state`/`state=`,
+ `has_invalid_state?`, `with_state`, `INVALID_STATES`, and a `state`
+ ransack alias.
+
+InventoryUnit and GiftCard still pend, and follow the same doctrine when
+they move: rename + machine removal together, never a `state_machine
+:status` halfway state.
+
## Migration Path
### Phase 1: Column renames
+One migration per model, shipped with that model's machine removal — never
+a combined migration (superseded 2026-08-18). Shipped so far:
+
```ruby
-class RenameStateToStatus < ActiveRecord::Migration[7.2]
+class RenameSpreePaymentsStateToStatus < ActiveRecord::Migration[8.1]
def change
rename_column :spree_payments, :state, :status
- rename_column :spree_shipments, :state, :status
- rename_column :spree_inventory_units, :state, :status
- rename_column :spree_return_authorizations, :state, :status
- rename_column :spree_gift_cards, :state, :status
end
end
```
+Remaining: `spree_inventory_units`, `spree_gift_cards`. Shipment's column
+retired with the Fulfillment rework; ReturnAuthorization's model was deleted
+by the returns rework.
+
### Phase 2: Model updates
For each of the five models:
diff --git a/docs/plans/6.0-service-workflows.md b/docs/plans/6.0-service-workflows.md
index c18d54bf9b..e9ddee8ef3 100644
--- a/docs/plans/6.0-service-workflows.md
+++ b/docs/plans/6.0-service-workflows.md
@@ -611,9 +611,25 @@ Not new workflows — things wrong or missing in what already shipped.
menu contents at each step would cover most of them.
- ✅ **Wave B leftovers — resolved 2026-08-12.** The admin endpoints route
through `Payments::Capture`/`Void` and `Refunds::Create`; the refund credit
- left its `after_create` for an explicit `external_step`. Money movement
- deliberately stays in the model (`Payment#capture!`, `Refund#perform!`) —
- the workflows own boundary, guards and hooks, per the doctrine.
+ left its `after_create` for an explicit `external_step`.
+- ✅ **Payment flows absorbed — 2026-08-18 (supersedes "money movement stays
+ in the model").** `Payments::Capture`, `Payments::Void` and the new
+ `Payments::Process` implement capture, void and authorize/purchase inline
+ as named steps: an atomic claim (a stale instance can no longer resurrect
+ a settled payment and drive the gateway again), the gateway round trip as
+ an `external_step`, and the locked bookkeeping with its
+ settled-concurrently recheck. Every entry point routes through them —
+ admin endpoints, checkout (`Purchase::PaymentProcessing` calls
+ `Payments::Process` per payment), dispatch capture and order-cancel
+ settlement — so the validate/before/after hooks and `payment.captured`
+ fire uniformly; previously a fraud hold registered on
+ `payments.capture.validate` vetoed an admin capture but not a dispatch
+ capture. `Spree::Payment` keeps only gateway mechanics (`gateway_options`,
+ `handle_response`, error translation, `split_uncaptured_amount`) plus
+ deprecated verb shells (`capture!`, `void_transaction!`, `process!`,
+ `authorize!`, `purchase!`) delegating to the workflows until 6.1.
+ `Refund#perform!` still owns the credit call, driven by
+ `Refunds::Create`'s `external_step`.
- ⬜ **`get_provider_data` has no consumer.** Declared on
`Fulfillments::Create`, but no fulfillment provider reads the merged hash
yet. It is a published contract with no proof it fits the providers' needs.
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index bfb7de5e95..671a862852 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,24 @@
+## 2026-08-18: Payment flows leave the model — workflows implement, shells delegate
+
+**Context:** After the machine removal, `Payments::Capture` and `Payments::Void` were thin wrappers: guards and hooks in the workflow, the actual six-step choreography (`capture!` — gateway call, lock, recheck, capture event, split, remainder) opaque inside `Payment::Processing`. Mapping the callers showed the hook contract had holes: dispatch capture (`Fulfillment`) and order-cancel settlement called the model verbs directly, so a fraud hold on `payments.capture.validate` vetoed an admin capture but not a dispatch capture, and `payment.captured` fired for one and not the other. Checkout had no workflow at all. Review also confirmed two TOCTOU races (raised by coderabbit on #14460, verified real and **pre-dating the branch** — machine guards were in-memory checks over unconditional saves, and the machine allowed `completed → processing`): a stale instance could resurrect a settled payment and re-drive the gateway, and racing session writers could both pass a transition guard and double-publish.
+
+**Decision:** Workflows implement the payment flows inline as named steps; the model keeps gateway mechanics only. `Payments::Capture` absorbs `capture!` (atomic claim → gateway `external_step` → locked bookkeeping → remainder re-authorization through `Payments::Process`), `Payments::Void` absorbs `void_transaction!`, and the new `Payments::Process` (`payment_process_workflow`, hooks `payments.process.*`) absorbs `process!`/`authorize!`/`purchase!` with the machine-era preconditions as its leading guard. Every entry point routes through the workflows: checkout batch, dispatch capture, order-cancel settlement. The races close structurally: `Payment#started_processing!` is now an atomic claim (conditional `update_all` from live statuses; false when settled concurrently, raises for dead payments — `void`/`invalid` only: **`failed` is deliberately claimable (2026-08-19)**, breaking machine parity, because a failure can be a transient gateway outage and the retry must reuse the row — `response_code` is unique per order, so a session payment's intent can never move to a fresh payment) and session transitions are a conditional-update compare-and-swap (`transition_to`) — only the writer whose update moves the row publishes, the loser returning `false` with no event (a row lock was rejected: `with_lock` reloads, wiping the session's association cache mid-flow). Model verbs stay as deprecated shells delegating to the workflows **until 7.0, a full major rather than the usual one release (2026-08-19)** — they have been the public way to move money since Spree 1, every payment extension and host override calls them, and the replacement is a different shape (a workflow result, not a boolean), so migrating is real work rather than a rename; extensions keep working meanwhile, with warnings, and internal code never calls them. `Payment#confirm!` is **deliberately not a workflow**: its only caller is `PaymentSession#settle_payment!`, which runs inside `owner.with_lock` — where a workflow cannot go (`external_step` refuses a workflow-opened transaction, `halt!` raises inside any transaction) — and that lock is what makes settlement exactly-once when the webhook races the synchronous return. It makes no gateway call, so it has no I/O to isolate and nothing to compensate. Supersedes the 2026-08-12 "money movement deliberately stays in the model" position. `Refund#perform!` is unchanged — `Refunds::Create` already owned that flow.
+
+**Rejected:** keeping the verbs real on the model with workflows wrapping them (the hook holes stay open, and every new entry point has to remember which door has the guards); a `Payments::Cancel` workflow (`cancel!` is a gateway dispatcher whose refund path already runs through `Refunds::Create` — no flow of its own, no hook demand); fixing the races inside the model verbs before dissolving them (the same code would move twice).
+
+**Consequences:** `Processing` is ~130 lines of mechanics (`gateway_options`, `handle_response`, error translation) plus shells; `protect_from_connection_error`, `handle_response`, `gateway_error`, `token_based?` and `split_uncaptured_amount` are public mechanics API; order-cancel settlement now skips unvoidable payments (failed/invalid) instead of crashing mid-cancel as the machine-era code did.
+
+## 2026-08-18: Payment family: state machines removed, `state` renamed to `status`
+
+**Context:** `6.0-normalize-state-to-status.md` listed Payment as a plain column rename with the machine kept (`state_machine :status`). Reviewing the new payments workflows (Capture, Void, Refunds::Create, PaymentSessions::Complete, HandleWebhook) showed the machine had become residue: guards were duplicated between workflow steps and the transition graph, events published from two different layers (`payment.captured` from the workflow, `payment.completed` from an `after_transition` that fires inside `capture!`'s lock), and the actual transitions hid behind `send("#{success_state}!")`. Order and Fulfillment had already answered this question.
+
+**Decision:** Remove the machines from `Spree::Payment`, `Spree::PaymentSession` and `Spree::PaymentSetupSession` in the same change as the Payment column rename. Payment joins `Spree::HasStatus`; transitions are explicit named writes in `Payment::Processing` and the payments workflows, publishing `payment.completed`/`payment.voided` at the write. The two session models (identical machines) share a `Spree::PaymentSessionTransitions` concern whose non-raising guarded transitions preserve the non-bang event semantics the racing webhook/synchronous paths rely on. `has_status` now applies its `default:` as an ActiveModel attribute default (no callbacks — also removed Fulfillment's and Seller's `after_initialize`) and refuses to shadow methods Rails already defines (Payment's `invalid` vs `ActiveModel#invalid?`). Bridges until 6.1: `state`/`state=`, `has_invalid_state?`, `with_state`, `INVALID_STATES`, ransack `state` alias.
+
+**Rejected:** keeping the machine with a renamed column (two sources of truth for the transition graph, callbacks still firing side effects inside locks); non-bang event shells on Payment (the machine is gone — Order precedent is wholesale removal, and all callers were internal); a generic transition-validation layer in `HasStatus` (a state machine by another name — the concern's docs already rule it out).
+
+**Consequences:** an illegal direct status write no longer raises — the workflows are the transitions, which is the accepted trade across the family. InventoryUnit and GiftCard remain the last `state` columns and follow the same rename+removal doctrine when they move.
+
+
## 2026-08-16: A vendor's status is something that happened to it, not a field you set
Damian asked for vendor management with "invitation, approvals, all in
diff --git a/packages/admin-sdk/src/types/generated/Payment.ts b/packages/admin-sdk/src/types/generated/Payment.ts
index e7194901a4..35e3120ab8 100644
--- a/packages/admin-sdk/src/types/generated/Payment.ts
+++ b/packages/admin-sdk/src/types/generated/Payment.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 49166d15c603f4e8838e8e00d5ec2d17
+// Typelizer digest bedb465c4ed9cd9ba1726bbcce14d88f
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {CreditCard, StoreCredit, PaymentSource, PaymentMethod, Order, Refund} from '@/types'
@@ -8,9 +8,9 @@ interface Payment {
payment_method_id: string;
response_code: string | null;
number: string;
+ status: string;
amount: string;
display_amount: string;
- status: string;
source_type: 'credit_card' | 'store_credit' | 'payment_source' | null;
source_id: string | null;
source: CreditCard | StoreCredit | PaymentSource | null;
diff --git a/packages/sdk/src/types/generated/Payment.ts b/packages/sdk/src/types/generated/Payment.ts
index b9aee6aa83..a616c23ec1 100644
--- a/packages/sdk/src/types/generated/Payment.ts
+++ b/packages/sdk/src/types/generated/Payment.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 684de79ea937c2068df10e074e901b38
+// Typelizer digest f2b834f833dc01715b8a8f45499ba933
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {CreditCard, StoreCredit, PaymentSource, PaymentMethod} from '@/types'
@@ -8,9 +8,9 @@ interface Payment {
payment_method_id: string;
response_code: string | null;
number: string;
+ status: string;
amount: string | null;
display_amount: string | null;
- status: string;
source_type: 'credit_card' | 'store_credit' | 'payment_source' | null;
source_id: string | null;
source: CreditCard | StoreCredit | PaymentSource | null;
diff --git a/packages/sdk/src/zod/generated/Payment.ts b/packages/sdk/src/zod/generated/Payment.ts
index a1cad13b31..1400825f82 100644
--- a/packages/sdk/src/zod/generated/Payment.ts
+++ b/packages/sdk/src/zod/generated/Payment.ts
@@ -7,9 +7,9 @@ export const PaymentSchema = z.object({
payment_method_id: z.string(),
response_code: z.string().nullable(),
number: z.string(),
+ status: z.string(),
amount: z.string().nullable(),
display_amount: z.string().nullable(),
- status: z.string(),
source_type: z.string().nullable(),
source_id: z.string().nullable(),
source: z.any(),
diff --git a/spree/api/app/serializers/spree/api/v3/payment_serializer.rb b/spree/api/app/serializers/spree/api/v3/payment_serializer.rb
index 79c4d34ee4..a68e98d94e 100644
--- a/spree/api/app/serializers/spree/api/v3/payment_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/payment_serializer.rb
@@ -12,16 +12,12 @@ module Spree
payment.payment_method&.prefixed_id
end
- attributes :response_code, :number
+ attributes :response_code, :number, :status
# Nulled for gated (prices_hidden) guests so a payment can't leak the
# amount the cart/order totals already withhold.
money_attributes :amount, :display_amount
- attribute :status do |payment|
- payment.state
- end
-
attribute :source_type do |payment|
case payment.source_type
when 'Spree::CreditCard'
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb
index b8c5ef5f4d..84df106d9f 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb
@@ -161,7 +161,7 @@ RSpec.describe Spree::Api::V3::Admin::Orders::PaymentsController, type: :control
describe 'PATCH #capture' do
before do
- payment.update_column(:state, 'pending') if payment.state != 'pending'
+ payment.update_column(:status, 'pending') if payment.status != 'pending'
end
it 'captures the payment' do
@@ -172,20 +172,20 @@ RSpec.describe Spree::Api::V3::Admin::Orders::PaymentsController, type: :control
expect(response).to have_http_status(:ok)
expect(json_response['status']).to eq('completed')
- expect(payment.reload.state).to eq('completed')
+ expect(payment.reload.status).to eq('completed')
end
context 'when payment is already completed' do
- before { payment.update_column(:state, 'completed') }
+ before { payment.update_column(:status, 'completed') }
- it 'is a no-op (state machine treats this as success)' do
+ it 'is a no-op (an already-done transition is a success)' do
patch :capture, params: {
order_id: order_with_payment.prefixed_id,
id: payment.prefixed_id
}, as: :json
expect(response).to have_http_status(:ok)
- expect(payment.reload.state).to eq('completed')
+ expect(payment.reload.status).to eq('completed')
end
end
@@ -203,7 +203,7 @@ RSpec.describe Spree::Api::V3::Admin::Orders::PaymentsController, type: :control
expect(response).to have_http_status(:unprocessable_content)
expect(json_response['error']['message']).to eq('Bogus Gateway: Forced failure')
- expect(payment.reload.state).to eq('failed')
+ expect(payment.reload.status).to eq('failed')
end
end
end
@@ -217,20 +217,20 @@ RSpec.describe Spree::Api::V3::Admin::Orders::PaymentsController, type: :control
expect(response).to have_http_status(:ok)
expect(json_response['status']).to eq('void')
- expect(payment.reload.state).to eq('void')
+ expect(payment.reload.status).to eq('void')
end
context 'when payment is already voided' do
- before { payment.update_column(:state, 'void') }
+ before { payment.update_column(:status, 'void') }
- it 'is a no-op (state machine treats this as success)' do
+ it 'is a no-op (an already-done transition is a success)' do
patch :void, params: {
order_id: order_with_payment.prefixed_id,
id: payment.prefixed_id
}, as: :json
expect(response).to have_http_status(:ok)
- expect(payment.reload.state).to eq('void')
+ expect(payment.reload.status).to eq('void')
end
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/orders/payments_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders/payments_spec.rb
index cc84628549..9945c61895 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/orders/payments_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/orders/payments_spec.rb
@@ -142,14 +142,14 @@ RSpec.describe 'Admin Order Payments API', type: :request, swagger_doc: 'api-ref
let(:id) { payment.prefixed_id }
before do
- payment.update_column(:state, 'pending') if payment.state != 'pending'
+ payment.update_column(:status, 'pending') if payment.status != 'pending'
end
run_test! do |response|
data = JSON.parse(response.body)
expect(data['id']).to eq(payment.prefixed_id)
expect(data['status']).to eq('completed')
- expect(payment.reload.state).to eq('completed')
+ expect(payment.reload.status).to eq('completed')
end
end
@@ -160,7 +160,7 @@ RSpec.describe 'Admin Order Payments API', type: :request, swagger_doc: 'api-ref
before do
# Bogus gateway forces a failure when the authorization doesn't start with `BGS-`.
- payment.update_columns(state: 'pending', response_code: 'INVALID-AUTH')
+ payment.update_columns(status: 'pending', response_code: 'INVALID-AUTH')
end
schema '$ref' => '#/components/schemas/ErrorResponse'
@@ -168,7 +168,7 @@ RSpec.describe 'Admin Order Payments API', type: :request, swagger_doc: 'api-ref
run_test! do |response|
data = JSON.parse(response.body)
expect(data['error']['message']).to eq('Bogus Gateway: Forced failure')
- expect(payment.reload.state).to eq('failed')
+ expect(payment.reload.status).to eq('failed')
end
end
end
@@ -201,7 +201,7 @@ RSpec.describe 'Admin Order Payments API', type: :request, swagger_doc: 'api-ref
data = JSON.parse(response.body)
expect(data['id']).to eq(payment.prefixed_id)
expect(data['status']).to eq('void')
- expect(payment.reload.state).to eq('void')
+ expect(payment.reload.status).to eq('void')
end
end
end
diff --git a/spree/api/spec/serializers/spree/api/v3/refund_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/refund_serializer_spec.rb
index 4944a61d41..d1720b25f7 100644
--- a/spree/api/spec/serializers/spree/api/v3/refund_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/refund_serializer_spec.rb
@@ -4,7 +4,7 @@ require 'spec_helper'
RSpec.describe Spree::Api::V3::RefundSerializer do
let(:store) { @default_store }
- let(:payment) { create(:payment, amount: 100, state: 'completed') }
+ let(:payment) { create(:payment, amount: 100, status: 'completed') }
let(:refund) { create(:refund, payment: payment, amount: 10) }
let(:base_params) { { store: store, currency: 'USD' } }
diff --git a/spree/core/app/models/concerns/spree/has_status.rb b/spree/core/app/models/concerns/spree/has_status.rb
index f6203876e4..25a4da5a89 100644
--- a/spree/core/app/models/concerns/spree/has_status.rb
+++ b/spree/core/app/models/concerns/spree/has_status.rb
@@ -22,14 +22,17 @@ module Spree
class_methods do
# @param values [Array<Symbol, String>] the valid statuses, in order
- # @param default [Symbol, String] applied by the creating workflow —
- # never a database default (see the migration rules in CLAUDE.md)
+ # @param default [Symbol, String] applied as an attribute default at
+ # instantiation — never a database default (see the migration rules
+ # in CLAUDE.md)
def has_status(*values, default:)
values = values.map(&:to_s)
class_attribute :statuses, default: values, instance_writer: false
class_attribute :default_status, default: default.to_s, instance_writer: false
+ attribute :status, :string, default: default.to_s
+
validates :status, inclusion: { in: ->(record) { record.class.statuses } }
values.each { |value| define_status_methods(value) }
@@ -57,8 +60,11 @@ module Spree
private
def define_status_methods(value)
- define_method(:"#{value}?") { status == value }
- scope value, -> { where(status: value) }
+ # A status may collide with a method Rails already defines — Payment's
+ # `invalid` vs ActiveModel#invalid? — so an existing method is never
+ # redefined. The status itself stays valid; callers compare `status`.
+ define_method(:"#{value}?") { status == value } unless method_defined?(:"#{value}?")
+ scope value, -> { where(status: value) } unless respond_to?(value)
end
end
end
diff --git a/spree/core/app/models/concerns/spree/payment_session_transitions.rb b/spree/core/app/models/concerns/spree/payment_session_transitions.rb
new file mode 100644
index 0000000000..2efc627e94
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/payment_session_transitions.rb
@@ -0,0 +1,93 @@
+module Spree
+ # Status transitions shared by PaymentSession and PaymentSetupSession —
+ # the replacement for their (identical) state machines.
+ #
+ # Transitions are non-raising, matching the machines' non-bang events: the
+ # webhook and synchronous completion paths race by design, and the loser
+ # must land as a no-op `false`, never an exception. Each transition
+ # publishes through the model's own publish_*_event method, exactly once —
+ # only the writer whose conditional update moved the row publishes.
+ #
+ # A transition writes status alone — unlike the machine's save, it never
+ # carries other dirty attributes along; a caller persists its own.
+ module PaymentSessionTransitions
+ extend ActiveSupport::Concern
+
+ included do
+ include Spree::HasStatus
+ has_status :pending, :processing, :completed, :failed, :canceled, :expired,
+ default: :pending
+ end
+
+ # Guards preserved from the machine's transition graph.
+ def can_process?
+ pending?
+ end
+
+ %w[complete fail cancel expire].each do |transition|
+ define_method(:"can_#{transition}?") { pending? || processing? }
+ end
+
+ def process
+ return false unless transition_to('processing', from: %w[pending])
+
+ publish_processing_event
+ true
+ end
+
+ def complete
+ return false unless transition_to('completed', from: %w[pending processing])
+
+ publish_completed_event
+ true
+ end
+
+ def fail
+ return false unless transition_to('failed', from: %w[pending processing])
+
+ publish_failed_event
+ true
+ end
+
+ def cancel
+ return false unless transition_to('canceled', from: %w[pending processing])
+
+ publish_canceled_event
+ true
+ end
+
+ def expire
+ return false unless transition_to('expired', from: %w[pending processing])
+
+ publish_expired_event
+ true
+ end
+
+ private
+
+ # A compare-and-swap on the status column, like Payment's processing
+ # claim: the conditional update either moves the row or touches nothing,
+ # and the loser is the writer whose update matched no row. Deliberately
+ # not with_lock — its reload would wipe the session's association cache
+ # mid-flow. The write is the transition event's, published by the
+ # caller; the generic lifecycle updated event does not fire for status
+ # flips.
+ def transition_to(to, from:)
+ if new_record?
+ return false unless status.in?(from)
+
+ self.status = to
+ save!
+ return true
+ end
+
+ claimed = self.class.where(id: id, status: from)
+ .update_all(status: to, updated_at: Time.current) == 1
+ return false unless claimed
+
+ self.status = to
+ clear_attribute_changes(['status'])
+ true
+ end
+ end
+end
diff --git a/spree/core/app/models/concerns/spree/payment_source_concern.rb b/spree/core/app/models/concerns/spree/payment_source_concern.rb
index 9f90a5a607..3cf580e542 100644
--- a/spree/core/app/models/concerns/spree/payment_source_concern.rb
+++ b/spree/core/app/models/concerns/spree/payment_source_concern.rb
@@ -54,7 +54,7 @@ module Spree
.merge(Spree::Order.incomplete)
incomplete_payments.checkout.each(&:invalidate!)
- incomplete_payments.where.not(state: :checkout).each(&:void!)
+ incomplete_payments.where.not(status: :checkout).each(&:void!)
end
end
end
diff --git a/spree/core/app/models/concerns/spree/purchase/payment_processing.rb b/spree/core/app/models/concerns/spree/purchase/payment_processing.rb
index 7c585a8aa1..ca68f9c51b 100644
--- a/spree/core/app/models/concerns/spree/purchase/payment_processing.rb
+++ b/spree/core/app/models/concerns/spree/purchase/payment_processing.rb
@@ -9,22 +9,22 @@ module Spree
# Deliberately not locked: holding the order's row lock across gateway
# round trips is what the workflow external_step boundary exists to
# prevent. Concurrent processing of the same payment is guarded twice —
- # started_processing! refuses re-entry, and the gateway idempotency key
- # (spree-<payment.number>) makes a duplicate charge a no-op at the
- # provider.
+ # the workflow's atomic claim refuses a payment another writer settled,
+ # and the gateway idempotency key (spree-<payment.number>) makes a
+ # duplicate charge a no-op at the provider.
def process_payments!
# with_lock used to reload the record as a side effect; callers create
# payments right before processing, so the association must refresh.
payments.reset
- process_payments_with(:process!)
+ process_payments_with(nil)
end
def authorize_payments!
- process_payments_with(:authorize!)
+ process_payments_with(:authorize)
end
def capture_payments!
- process_payments_with(:purchase!)
+ process_payments_with(:purchase)
end
def pending_payments
@@ -60,7 +60,7 @@ module Spree
private
- def process_payments_with(method)
+ def process_payments_with(action)
# Don't run if there is nothing to pay.
return if payment_total >= total
# Don't run if there are authorized payments
@@ -71,7 +71,8 @@ module Spree
unprocessed_payments.each do |payment|
break if payment_total >= total
- payment.public_send(method)
+ result = Spree.payment_process_workflow.call(payment: payment, action: action)
+ raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?
end
rescue Spree::Core::GatewayError => e
errors.add(:base, e.message)
diff --git a/spree/core/app/models/concerns/spree/purchase/store_credits.rb b/spree/core/app/models/concerns/spree/purchase/store_credits.rb
index 9219198806..762a91ee7b 100644
--- a/spree/core/app/models/concerns/spree/purchase/store_credits.rb
+++ b/spree/core/app/models/concerns/spree/purchase/store_credits.rb
@@ -61,7 +61,7 @@ module Spree
if payments.loaded?
payments.
find_all(&:store_credit?).
- reject(&:has_invalid_state?).
+ reject(&:has_invalid_status?).
sum(&:amount) || BigDecimal::ZERO
else
payments.store_credits.valid.sum(:amount)
diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rb
index 11b31ab016..f1d01bd16b 100644
--- a/spree/core/app/models/spree/fulfillment.rb
+++ b/spree/core/app/models/spree/fulfillment.rb
@@ -121,12 +121,6 @@ module Spree
include Spree::HasStatus
has_status :unfulfilled, :fulfilled, :delivered, :canceled, default: :unfulfilled
- # Unlike returns and claims, fulfillments are built directly — by the stock
- # coordinator, by cart completion, by transfers — rather than always through
- # a creating workflow, so the default is applied here instead of being left
- # to each caller. This is what the machine's `initial:` used to do.
- after_initialize :apply_default_status, if: :new_record?
-
# What the carrier reports, kept apart from the merchant lifecycle: a bounced
# or damaged package changes this, never #status.
TRACKING_STATUSES = %w(
@@ -480,7 +474,9 @@ module Spree
end
cents = (capturable_amount * 100).to_i
- payment.capture!(cents)
+ result = Spree.payment_capture_workflow.call(payment: payment, amount: cents)
+ raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?
+
shipment_to_pay -= capturable_amount
end
end
@@ -808,10 +804,6 @@ module Spree
self.cost = 0 unless cost
end
- def apply_default_status
- self.status ||= self.class.default_status
- end
-
def carrier_tracking_url
template = Spree.tracking_carriers.dig(tracking_carrier.to_s, :url)
template&.gsub(':tracking', ERB::Util.url_encode(tracking))
diff --git a/spree/core/app/models/spree/payment.rb b/spree/core/app/models/spree/payment.rb
index d40c11be69..93dea46e87 100644
--- a/spree/core/app/models/spree/payment.rb
+++ b/spree/core/app/models/spree/payment.rb
@@ -21,7 +21,9 @@ module Spree
NON_RISKY_AVS_CODES = ['B', 'D', 'H', 'J', 'M', 'Q', 'T', 'V', 'X', 'Y'].freeze
RISKY_AVS_CODES = ['A', 'C', 'E', 'F', 'G', 'I', 'K', 'L', 'N', 'O', 'P', 'R', 'S', 'U', 'W', 'Z'].freeze
- INVALID_STATES = %w(failed invalid void).freeze
+ INVALID_STATUSES = %w(failed invalid void).freeze
+ INVALID_STATES = INVALID_STATUSES
+ deprecate_constant :INVALID_STATES
with_options inverse_of: :payments do
belongs_to :order, class_name: 'Spree::Order', touch: true, optional: true
@@ -72,26 +74,24 @@ module Spree
default_scope { order(:created_at) }
scope :from_credit_card, -> { where(source_type: 'Spree::CreditCard') }
- scope :with_state, ->(s) { where(state: s.to_s) }
+ # @deprecated use the status scopes / +where(status:)+ — removed in 6.1
+ scope :with_state, ->(s) { where(status: s.to_s) }
# "offset" is reserved by activerecord
- scope :offset_payment, -> { where("source_type = 'Spree::Payment' AND amount < 0 AND state = 'completed'") }
+ scope :offset_payment, -> { where("source_type = 'Spree::Payment' AND amount < 0 AND status = 'completed'") }
- scope :checkout, -> { with_state('checkout') }
- scope :completed, -> { with_state('completed') }
- scope :pending, -> { with_state('pending') }
- scope :processing, -> { with_state('processing') }
- scope :failed, -> { with_state('failed') }
+ # checkout/processing/pending/completed/failed/void scopes and predicates
+ # come from has_status below.
+ scope :incomplete, -> { where.not(status: 'completed') }
- scope :incomplete, -> { where.not(state: 'completed') }
-
- scope :risky, -> { where("avs_response IN (?) OR (cvv_response_code IS NOT NULL and cvv_response_code != 'M') OR state = 'failed'", RISKY_AVS_CODES) }
- scope :valid, -> { where.not(state: INVALID_STATES) }
+ scope :risky, -> { where("avs_response IN (?) OR (cvv_response_code IS NOT NULL and cvv_response_code != 'M') OR status = 'failed'", RISKY_AVS_CODES) }
+ scope :valid, -> { where.not(status: INVALID_STATUSES) }
scope :store_credits, -> { where(source_type: Spree::StoreCredit.to_s) }
scope :not_store_credits, -> { where(arel_table[:source_type].not_eq(Spree::StoreCredit.to_s).or(arel_table[:source_type].eq(nil))) }
self.whitelisted_ransackable_associations = %w[payment_method order source]
- self.whitelisted_ransackable_attributes = %w[number amount state response_code avs_response cvv_response_code cvv_response_message]
+ ransack_alias :state, :status # @deprecated filter alias — removed in 6.1
+ self.whitelisted_ransackable_attributes = %w[number amount status state response_code avs_response cvv_response_code cvv_response_message]
# transaction_id is much easier to understand
alias_attribute :transaction_id, :response_code
@@ -101,37 +101,102 @@ module Spree
money_methods :amount, :credit_allowed
alias money display_amount # for compatibility with older versions of Spree
- # order state machine (see http://github.com/pluginaweek/state_machine/tree/master for details)
- state_machine initial: :checkout do
- # With card payments, happens before purchase or authorization happens
- #
- # Setting it after creating a profile and authorizing a full amount will
- # prevent the payment from being authorized again once Order transitions
- # to complete
- event :started_processing do
- transition from: [:checkout, :pending, :completed, :processing], to: :processing
- end
- # When processing during checkout fails
- event :failure do
- transition from: [:pending, :processing], to: :failed
- end
- # With card payments this represents authorizing the payment
- event :pend do
- transition from: [:checkout, :processing], to: :pending
- end
- # With card payments this represents completing a purchase or capture transaction
- event :complete do
- transition from: [:processing, :pending, :checkout], to: :completed
- end
- after_transition to: :completed, do: [:after_completed, :publish_payment_completed_event]
- event :void do
- transition from: [:pending, :processing, :completed, :checkout], to: :void
+ # No state machine — transitions run inside Spree::Payments workflows and
+ # Spree::Payment::Processing (docs/plans/6.0-service-workflows.md). The
+ # `invalid` status deliberately generates no predicate or scope: `invalid?`
+ # is ActiveModel's, use +has_invalid_status?+.
+ include Spree::HasStatus
+ has_status :checkout, :processing, :pending, :completed, :failed, :void, :invalid,
+ default: :checkout
+
+ # Status writes, called from the payments workflows and Processing. The
+ # completed/voided events publish here — the one place the status changes —
+ # replacing the machine's after_transition callbacks.
+ # failed is deliberately claimable: a failure can be transient — a
+ # gateway outage, a network timeout, our own error — and the retry is
+ # simply running the workflow again on the same row. The row must be
+ # reused, not replaced: response_code is unique per order, so a session
+ # payment's intent can only ever live on one payment.
+ CLAIMABLE_STATUSES = %w[checkout pending processing failed].freeze
+
+ # Atomically claims the payment for gateway processing. Only a live or
+ # retryable payment can be claimed, so a stale instance can never
+ # resurrect a payment another writer already settled and drive the
+ # gateway again.
+ #
+ # @return [Boolean] false when the payment completed concurrently — the
+ # caller's outcome already exists and the claim must be a no-op
+ # @raise [Spree::Core::GatewayError] for a dead payment (void, invalid)
+ def started_processing!
+ if new_record?
+ self.status = 'processing'
+ save!
+ return true
end
- after_transition to: :void, do: [:after_void, :publish_payment_voided_event]
- # when the card brand isn't supported
- event :invalidate do
- transition from: [:checkout], to: :invalid
+
+ claimed = self.class.where(id: id, status: CLAIMABLE_STATUSES)
+ .update_all(status: 'processing', updated_at: Time.current) == 1
+ if claimed
+ self.status = 'processing'
+ clear_attribute_changes(['status'])
+ return true
end
+
+ fresh_status = self.class.where(id: id).pick(:status)
+ return false if fresh_status == 'completed'
+
+ raise Spree::Core::GatewayError, "Payment #{number} is #{fresh_status} and cannot be processed"
+ end
+
+ def pend!
+ update!(status: 'pending')
+ end
+
+ def complete!
+ update!(status: 'completed')
+ publish_event('payment.completed')
+ true
+ end
+
+ def void!
+ update!(status: 'void')
+ publish_event('payment.voided')
+ true
+ end
+
+ def failure!
+ update!(status: 'failed')
+ end
+ alias failure failure!
+
+ def invalidate!
+ update!(status: 'invalid')
+ end
+
+ # Guards preserved from the machine's transition graph, consulted by the
+ # workflows before money moves.
+ def can_complete?
+ status.in?(%w[processing pending checkout])
+ end
+
+ def can_pend?
+ status.in?(%w[checkout processing])
+ end
+
+ def can_void?
+ status.in?(%w[pending processing completed checkout])
+ end
+
+ # @deprecated read +status+ — removed in 6.1
+ def state
+ Spree::Deprecation.warn('Spree::Payment#state is deprecated and will be removed in Spree 6.1. Use #status instead.')
+ status
+ end
+
+ # @deprecated write +status+ — removed in 6.1
+ def state=(value)
+ Spree::Deprecation.warn('Spree::Payment#state= is deprecated and will be removed in Spree 6.1. Use #status= instead.')
+ self.status = value
end
def source
@@ -239,6 +304,25 @@ module Spree
amount - captured_amount
end
+ # Row work only — moves the uncaptured remainder onto a new pending
+ # payment and shrinks this one to what was captured. The caller authorizes
+ # the returned remainder at the gateway afterwards, outside any lock.
+ #
+ # @return [Spree::Payment, nil] the remainder payment, or nil when fully captured
+ def split_uncaptured_amount
+ return if uncaptured_amount <= 0
+
+ remainder = owner.payments.create!(
+ amount: uncaptured_amount,
+ payment_method: payment_method,
+ source: source,
+ status: 'pending',
+ capture_on_dispatch: true
+ )
+ update(amount: captured_amount)
+ remainder
+ end
+
def editable?
checkout? || pending?
end
@@ -276,8 +360,14 @@ module Spree
end
end
+ def has_invalid_status?
+ INVALID_STATUSES.include?(status)
+ end
+
+ # @deprecated use {#has_invalid_status?} — removed in 6.1
def has_invalid_state?
- INVALID_STATES.include?(state)
+ Spree::Deprecation.warn('Spree::Payment#has_invalid_state? is deprecated and will be removed in Spree 6.1. Use #has_invalid_status? instead.')
+ has_invalid_status?
end
# @return [Spree::Cart, Spree::Order, nil]
@@ -307,7 +397,7 @@ module Spree
# gateways store profile ids during source creation and never call this.
def create_payment_profile
# Don't attempt to create on bad payments.
- return if has_invalid_state?
+ return if has_invalid_status?
# Payment profile cannot be created without source
return unless source
# Imported payments shouldn't create a payment profile.
@@ -347,20 +437,6 @@ module Spree
errors.add(:amount, :greater_than_max_amount, max_amount: max_amount) if amount > max_amount
end
- def after_void
- end
-
- def after_completed
- end
-
- def publish_payment_completed_event
- publish_event('payment.completed')
- end
-
- def publish_payment_voided_event
- publish_event('payment.voided')
- end
-
def validate_source
if source && !source.valid?
source.errors.map { |error| { field: error.attribute, message: error&.message } }.each do |err|
@@ -386,24 +462,6 @@ module Spree
- # Row work only — moves the uncaptured remainder onto a new pending
- # payment and shrinks this one to what was captured. The caller authorizes
- # the returned remainder at the gateway afterwards, outside any lock.
- #
- # @return [Spree::Payment, nil] the remainder payment, or nil when fully captured
- def split_uncaptured_amount
- return if uncaptured_amount <= 0
-
- remainder = owner.payments.create!(
- amount: uncaptured_amount,
- payment_method: payment_method,
- source: source,
- state: 'pending',
- capture_on_dispatch: true
- )
- update(amount: captured_amount)
- remainder
- end
def update_order
return unless completed? || void? || (owner.is_a?(Spree::Order) && owner.completed?)
@@ -431,7 +489,7 @@ module Spree
def invalidate_old_payments
# invalid payment or store_credit payment shouldn't invalidate other payment types
- return if has_invalid_state? || store_credit?
+ return if has_invalid_status? || store_credit?
owner.payments.with_state('checkout').where.not(id: id).each do |payment|
payment.invalidate! unless payment.store_credit?
diff --git a/spree/core/app/models/spree/payment/custom_events.rb b/spree/core/app/models/spree/payment/custom_events.rb
index 9aecf13097..66e9f467b4 100644
--- a/spree/core/app/models/spree/payment/custom_events.rb
+++ b/spree/core/app/models/spree/payment/custom_events.rb
@@ -19,9 +19,9 @@ module Spree
def should_publish_paid_event?
return false unless Spree::Events.enabled?
- return false unless state_previously_changed?
+ return false unless status_previously_changed?
- state_previous_change&.last == 'completed'
+ status_previous_change&.last == 'completed'
end
def publish_payment_paid_event
diff --git a/spree/core/app/models/spree/payment/processing.rb b/spree/core/app/models/spree/payment/processing.rb
index 06e6d5acfa..82502d9828 100644
--- a/spree/core/app/models/spree/payment/processing.rb
+++ b/spree/core/app/models/spree/payment/processing.rb
@@ -2,6 +2,17 @@ require_dependency 'spree/payment/gateway_options'
module Spree
class Payment < Spree.base_class
+ # Gateway mechanics shared by the payments workflows and the payment
+ # methods: option serialization, response bookkeeping, error
+ # translation and instrumentation. The flows themselves — capture,
+ # void, authorize/purchase — live in app/workflows/spree/payments;
+ # the deprecated verb methods below delegate there until 7.0.
+ #
+ # Those five carry a full major's window rather than the usual one
+ # release: they have been the public way to move money since Spree 1,
+ # every payment extension and host override calls them, and the
+ # replacement is a different shape (a workflow result, not a boolean),
+ # so migrating is real work rather than a rename.
module Processing
extend ActiveSupport::Concern
include Spree::InstrumentsGatewayCalls
@@ -11,30 +22,53 @@ module Spree
self.gateway_options_class = Spree::Payment::GatewayOptions
end
+ # @deprecated Call Spree.payment_process_workflow — removed in 7.0.
def process!
- if payment_method&.capture_at_checkout?
- purchase!
- else
- authorize!
- end
+ Spree::Deprecation.warn('Spree::Payment#process! is deprecated and will be removed in Spree 7.0. Call Spree.payment_process_workflow instead.')
+ run_payment_workflow(Spree.payment_process_workflow, payment: self)
end
+ # @deprecated Call Spree.payment_process_workflow — removed in 7.0.
def authorize!
- handle_payment_preconditions { process_authorization }
+ Spree::Deprecation.warn('Spree::Payment#authorize! is deprecated and will be removed in Spree 7.0. Call Spree.payment_process_workflow instead.')
+ run_payment_workflow(Spree.payment_process_workflow, payment: self, action: :authorize)
end
- # Captures the entire amount of a payment.
+ # @deprecated Call Spree.payment_process_workflow — removed in 7.0.
def purchase!
- handle_payment_preconditions { process_purchase }
+ Spree::Deprecation.warn('Spree::Payment#purchase! is deprecated and will be removed in Spree 7.0. Call Spree.payment_process_workflow instead.')
+ run_payment_workflow(Spree.payment_process_workflow, payment: self, action: :purchase)
+ end
+
+ # @deprecated Call Spree.payment_capture_workflow — removed in 7.0.
+ def capture!(amount = nil)
+ Spree::Deprecation.warn('Spree::Payment#capture! is deprecated and will be removed in Spree 7.0. Call Spree.payment_capture_workflow instead.')
+ run_payment_workflow(Spree.payment_capture_workflow, payment: self, amount: amount)
+ end
+
+ # @deprecated Call Spree.payment_void_workflow — removed in 7.0.
+ def void_transaction!
+ Spree::Deprecation.warn('Spree::Payment#void_transaction! is deprecated and will be removed in Spree 7.0. Call Spree.payment_void_workflow instead.')
+ run_payment_workflow(Spree.payment_void_workflow, payment: self)
end
# Confirms a payment already authorized or captured on the gateway side
- # (SDK / Drop-in / payment session flows) — the local state move only, no
- # gateway call.
+ # (SDK / Drop-in / payment session flows) — the local status move only,
+ # no gateway call.
+ #
+ # Deliberately not a workflow, unlike its siblings: its only caller is
+ # PaymentSession#settle_payment!, which runs inside owner.with_lock —
+ # and a workflow cannot run there (external_step refuses a
+ # workflow-opened transaction, halt! raises inside any transaction).
+ # The lock is what makes settlement exactly-once when the webhook
+ # races the customer's synchronous return, so it stays and this stays
+ # pure database work. There is no gateway call to push behind an
+ # external_step and no compensation to run, so nothing about it earns
+ # the workflow tier.
#
- # @param captured [Boolean, nil] whether the gateway reports the funds as
- # captured. Callers who know the gateway state pass it; nil falls back
- # to when the payment method charges.
+ # @param captured [Boolean, nil] whether the gateway reports the funds
+ # as captured. Callers who know the gateway state pass it; nil falls
+ # back to when the payment method charges.
def confirm!(captured: nil)
captured = payment_method&.capture_at_checkout? if captured.nil?
@@ -48,89 +82,14 @@ module Spree
end
end
- # Takes the amount in cents to capture.
- # Can be used to capture partial amounts of a payment, and will create
- # a new pending payment record for the remaining amount to capture later.
- #
- # The gateway call runs outside any lock (capture is idempotent at the
- # provider — an already-captured intent comes back as success); the
- # bookkeeping runs under the owner's row lock with a recheck, so a
- # concurrent capture — or the webhook settling the same payment —
- # records the capture event exactly once.
- def capture!(amount = nil)
- return true if completed?
-
- amount ||= money.amount_in_cents
- started_processing!
- protect_from_connection_error do
- # Capture the payment amount
- response = instrument_gateway_call(:capture, payment_method) do
- payment_method.capture(
- amount,
- response_code,
- gateway_options
- )
- end
-
- # A failed response writes no money records, so it needs no lock —
- # and handle_response raises, which inside the lock's transaction
- # would roll the failure state back.
- handle_response(response, :complete, :failure) unless response.success?
-
- already_captured = false
- remainder = nil
- owner.with_lock do
- # DB-state recheck, deliberately not a reload — reload would
- # discard the in-memory source (card numbers never persist).
- if self.class.where(id: id, state: 'completed').exists?
- already_captured = true
- else
- capture_events.create!(amount: ::Money.new(amount, currency).to_f)
- # Split before completing, so payment.completed publishes with
- # the captured amount and the order recomputes from correct rows.
- remainder = split_uncaptured_amount
- handle_response(response, :complete, :failure)
- end
- end
- return true if already_captured
-
- # Authorizes the remainder at the gateway — its own network call,
- # so it stays outside the lock.
- remainder&.authorize!
- true
- end
- end
-
- def void_transaction!
- return true if void?
- return void if response_code.blank?
-
- protect_from_connection_error do
- response = instrument_gateway_call(:void, payment_method) do
- if payment_method.payment_profiles_supported?
- # Gateways supporting payment profiles will need access to credit card object because this stores the payment profile information
- # so supply the authorization itself as well as the credit card, rather than just the authorization code
- payment_method.void(response_code, source, gateway_options)
- else
- # Standard void usage
- payment_method.void(response_code, gateway_options)
- end
- end
-
- if response.success?
- self.response_code = response.authorization
- void
- else
- gateway_error(response)
- end
- end
- end
-
+ # Settles the payment for a canceled order: releases an uncaptured
+ # authorization, refunds a captured one. The gateway decides which —
+ # payment_method.cancel routes refunds through Refunds::Create.
def cancel!
response = instrument_gateway_call(:cancel, payment_method) do
payment_method.cancel(response_code, self)
end
- handle_response(response, :void, :failure)
+ handle_response(response, :void)
end
def gateway_options
@@ -138,55 +97,11 @@ module Spree
gateway_options_class.new(self).to_hash
end
- private
-
- def process_authorization
- started_processing!
- gateway_action(source, :authorize, :pend)
- end
-
- def process_purchase
- started_processing!
- result = gateway_action(source, :purchase, :complete)
- # This won't be called if gateway_action raises a GatewayError
- capture_events.create!(amount: amount)
- end
-
- def handle_payment_preconditions
- unless block_given?
- raise ArgumentError, 'handle_payment_preconditions must be called with a block'
- end
-
- if payment_method&.source_required?
- if source
- unless processing?
- if payment_method.supports?(source) || token_based?
- yield
- else
- invalidate!
- raise Core::GatewayError, Spree.t(:payment_method_not_supported)
- end
- end
- else
- raise Core::GatewayError, Spree.t(:payment_processing_failed)
- end
- else
- yield unless processing?
- end
- end
-
- def gateway_action(source, action, success_state)
- protect_from_connection_error do
- response = instrument_gateway_call(action, payment_method) do
- payment_method.send(action, money.amount_in_cents,
- source,
- gateway_options)
- end
- handle_response(response, success_state, :failure)
- end
- end
-
- def handle_response(response, success_state, failure_state)
+ # Records a gateway response on the payment: bookkeeping (response
+ # code, AVS/CVV results) plus the status write. A failed response
+ # writes `failed` non-raising — gateway_error below is the exception
+ # this path reports, and a validation problem must not preempt it.
+ def handle_response(response, success_state, _failure_state = :failure)
if response.success?
unless response.authorization.nil?
self.response_code = response.authorization
@@ -197,9 +112,16 @@ module Spree
self.cvv_response_message = response.cvv_result['message']
end
end
- send("#{success_state}!")
+
+ case success_state
+ when :complete then complete!
+ when :pend then pend!
+ when :void then void!
+ else raise ArgumentError, "Unknown payment success state: #{success_state.inspect}"
+ end
else
- send(failure_state)
+ self.status = 'failed'
+ save
gateway_error(response)
end
end
@@ -227,6 +149,17 @@ module Spree
def token_based?
source.gateway_customer_profile_id.present? || source.gateway_payment_profile_id.present?
end
+
+ private
+
+ # Preserves the retired verbs' contract: true on success, GatewayError
+ # on failure.
+ def run_payment_workflow(workflow, **arguments)
+ result = workflow.call(**arguments)
+ raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?
+
+ true
+ end
end
end
end
diff --git a/spree/core/app/models/spree/payment_method/check.rb b/spree/core/app/models/spree/payment_method/check.rb
index 9914d95c86..5e3fd93dd1 100644
--- a/spree/core/app/models/spree/payment_method/check.rb
+++ b/spree/core/app/models/spree/payment_method/check.rb
@@ -14,12 +14,12 @@ module Spree
# Indicates whether its possible to capture the payment
def can_capture?(payment)
- ['checkout', 'pending'].include?(payment.state)
+ ['checkout', 'pending'].include?(payment.status)
end
# Indicates whether its possible to void the payment.
def can_void?(payment)
- payment.state != 'void'
+ payment.status != 'void'
end
def capture(*)
diff --git a/spree/core/app/models/spree/payment_method/store_credit.rb b/spree/core/app/models/spree/payment_method/store_credit.rb
index 094257382c..0f6b9fddd3 100644
--- a/spree/core/app/models/spree/payment_method/store_credit.rb
+++ b/spree/core/app/models/spree/payment_method/store_credit.rb
@@ -13,7 +13,7 @@ module Spree
end
def can_capture?(payment)
- ['checkout', 'pending'].include?(payment.state)
+ ['checkout', 'pending'].include?(payment.status)
end
def can_void?(payment)
diff --git a/spree/core/app/models/spree/payment_session.rb b/spree/core/app/models/spree/payment_session.rb
index 7fecf28335..417049df41 100644
--- a/spree/core/app/models/spree/payment_session.rb
+++ b/spree/core/app/models/spree/payment_session.rb
@@ -24,40 +24,7 @@ module Spree
validates :external_id, uniqueness: { scope: [:order_id, :payment_method_id] }
validates :amount, presence: true, numericality: { greater_than: 0 }
- state_machine :status, initial: :pending do
- state :pending
- state :processing
- state :completed
- state :failed
- state :canceled
- state :expired
-
- event :process do
- transition pending: :processing
- end
-
- event :complete do
- transition [:pending, :processing] => :completed
- end
-
- event :fail do
- transition [:pending, :processing] => :failed
- end
-
- event :cancel do
- transition [:pending, :processing] => :canceled
- end
-
- event :expire do
- transition [:pending, :processing] => :expired
- end
-
- after_transition to: :processing, do: :publish_processing_event
- after_transition to: :completed, do: :publish_completed_event
- after_transition to: :failed, do: :publish_failed_event
- after_transition to: :canceled, do: :publish_canceled_event
- after_transition to: :expired, do: :publish_expired_event
- end
+ include Spree::PaymentSessionTransitions
scope :not_expired, -> { where('expires_at IS NULL OR expires_at > ?', Time.current) }
scope :active, -> { not_expired.where(status: %w[pending processing]) }
@@ -144,7 +111,7 @@ module Spree
# settlement could have completed it), but reload would discard
# in-memory state like skip_source_requirement.
already_completed = settled_payment.completed? ||
- Spree::Payment.where(id: settled_payment.id, state: 'completed').exists?
+ Spree::Payment.where(id: settled_payment.id, status: 'completed').exists?
settled_payment.confirm!(captured: captured) unless already_completed
end
diff --git a/spree/core/app/models/spree/payment_setup_session.rb b/spree/core/app/models/spree/payment_setup_session.rb
index 0efa34d4b2..4efb9096f2 100644
--- a/spree/core/app/models/spree/payment_setup_session.rb
+++ b/spree/core/app/models/spree/payment_setup_session.rb
@@ -17,40 +17,7 @@ module Spree
validates :payment_method, :status, presence: true
validates :external_id, uniqueness: { scope: :payment_method_id }, allow_nil: true
- state_machine :status, initial: :pending do
- state :pending
- state :processing
- state :completed
- state :failed
- state :canceled
- state :expired
-
- event :process do
- transition pending: :processing
- end
-
- event :complete do
- transition [:pending, :processing] => :completed
- end
-
- event :fail do
- transition [:pending, :processing] => :failed
- end
-
- event :cancel do
- transition [:pending, :processing] => :canceled
- end
-
- event :expire do
- transition [:pending, :processing] => :expired
- end
-
- after_transition to: :processing, do: :publish_processing_event
- after_transition to: :completed, do: :publish_completed_event
- after_transition to: :failed, do: :publish_failed_event
- after_transition to: :canceled, do: :publish_canceled_event
- after_transition to: :expired, do: :publish_expired_event
- end
+ include Spree::PaymentSessionTransitions
scope :active, -> { where(status: %w[pending processing]) }
diff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rb
index e0f9bffa5d..de5087660c 100644
--- a/spree/core/app/models/spree/seller.rb
+++ b/spree/core/app/models/spree/seller.rb
@@ -127,10 +127,6 @@ module Spree
# Callbacks
#
before_validation :normalize_slug
- # A seller is born through plain CRUD rather than a workflow — creating one
- # is not a lifecycle transition, inviting them is — so the default lands
- # here instead of in a creating workflow, as on Spree::Fulfillment.
- after_initialize :apply_default_status, if: :new_record?
# Roles refuse to be destroyed while anyone still holds them, which is
# right when a role is deleted on its own and wrong when the whole seller
# goes: its roles govern nothing else. Dissolving the team first lets the
@@ -170,10 +166,6 @@ module Spree
self.slug = (slug.presence || name).to_s.parameterize.presence
end
- def apply_default_status
- self.status ||= self.class.default_status
- end
-
# Memberships and outstanding invitations are what make a role undeletable.
# They mean nothing once the seller is gone, so they go first.
def dissolve_team
diff --git a/spree/core/app/services/spree/carts/destroy.rb b/spree/core/app/services/spree/carts/destroy.rb
index 6fe2a14d07..d20d5bb477 100644
--- a/spree/core/app/services/spree/carts/destroy.rb
+++ b/spree/core/app/services/spree/carts/destroy.rb
@@ -34,7 +34,7 @@ module Spree
end
def void_payments(cart:)
- cart.payments.each(&:void)
+ cart.payments.each { |payment| payment.void! if payment.can_void? }
success(cart: cart)
end
diff --git a/spree/core/app/services/spree/checkout/add_store_credit.rb b/spree/core/app/services/spree/checkout/add_store_credit.rb
index c64ef7abb3..3a5d8ef727 100644
--- a/spree/core/app/services/spree/checkout/add_store_credit.rb
+++ b/spree/core/app/services/spree/checkout/add_store_credit.rb
@@ -12,7 +12,7 @@ module Spree
return failure(nil, Spree.t(:error_user_does_not_have_any_store_credits)) unless @order.customer&.store_credits&.any?
ApplicationRecord.transaction do
- existing = @order.payments.store_credits.where(state: :checkout)
+ existing = @order.payments.store_credits.where(status: :checkout)
if existing.any?
update_existing_payments(existing, remaining_total)
diff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rb
index 2edfb9b83c..b107034e9e 100644
--- a/spree/core/app/workflows/spree/carts/complete.rb
+++ b/spree/core/app/workflows/spree/carts/complete.rb
@@ -321,7 +321,7 @@ module Spree
# never on paid? — a net-terms order completes with a pending payment.
def payment_covered?(order)
order.payments.reset
- order.payments.valid.where(state: %w[pending processing completed]).sum(:amount) >= order.total
+ order.payments.valid.where(status: %w[pending processing completed]).sum(:amount) >= order.total
end
# The FINALIZE phase: the order-side completion workflow owns the
diff --git a/spree/core/app/workflows/spree/orders/cancel.rb b/spree/core/app/workflows/spree/orders/cancel.rb
index be79d70cb2..0d0210c098 100644
--- a/spree/core/app/workflows/spree/orders/cancel.rb
+++ b/spree/core/app/workflows/spree/orders/cancel.rb
@@ -125,7 +125,13 @@ module Spree
order.payments.completed.store_credits.each(&:void!)
else
order.payments.completed.each(&:cancel!)
- order.payments.incomplete.not_store_credits.each(&:void_transaction!)
+ order.payments.incomplete.not_store_credits.each do |payment|
+ # Failed and invalid payments hold nothing to release.
+ next unless payment.can_void?
+
+ result = Spree.payment_void_workflow.call(payment: payment)
+ raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?
+ end
order.payments.store_credits.pending.each(&:void!)
end
end
diff --git a/spree/core/app/workflows/spree/orders/complete.rb b/spree/core/app/workflows/spree/orders/complete.rb
index c0e24002d8..53446c40d6 100644
--- a/spree/core/app/workflows/spree/orders/complete.rb
+++ b/spree/core/app/workflows/spree/orders/complete.rb
@@ -148,7 +148,7 @@ module Spree
def payment_covered?
order.payments.reset
- order.payments.valid.where(state: %w[pending processing completed]).sum(:amount) >= order.total
+ order.payments.valid.where(status: %w[pending processing completed]).sum(:amount) >= order.total
end
end
end
diff --git a/spree/core/app/workflows/spree/payments/capture.rb b/spree/core/app/workflows/spree/payments/capture.rb
index 9d2872fb85..8f0622c0ec 100644
--- a/spree/core/app/workflows/spree/payments/capture.rb
+++ b/spree/core/app/workflows/spree/payments/capture.rb
@@ -2,13 +2,15 @@ module Spree
module Payments
# Captures an authorized payment at the gateway.
#
- # In the workflow tier because the capture is network I/O: `external_step`
- # refuses to run inside a transaction the workflow opened, so a caller
- # can no longer accidentally hold a database connection open across a
- # gateway round trip. Money movement stays in the model (the state
- # machine and capture events are unchanged) — this owns the boundary,
- # the guards and the extension points around it.
+ # Owns the flow end to end: the atomic claim, the gateway round trip
+ # (an external_step, so it can never share a workflow-opened
+ # transaction), the locked bookkeeping with its settled-concurrently
+ # recheck, the partial-capture split, and the remainder's
+ # re-authorization. Spree::Payment keeps only gateway mechanics —
+ # gateway_options, handle_response, error translation.
class Capture < Spree::Workflow
+ include Spree::InstrumentsGatewayCalls
+
hooks :validate, :before_capture, :after_capture
# @param payment [Spree::Payment] a completed payment is a no-op
@@ -16,13 +18,22 @@ module Spree
# a smaller amount splits the remainder into a new pending payment
def perform(payment:, amount: nil)
super
+ @amount = amount || payment.money.amount_in_cents
step :ensure_capturable
# Veto point — fraud holds, manual review. Before any money moves.
run_hooks :validate
run_hooks :before_capture
+ # Claiming before the gateway call is what makes a stale instance
+ # harmless: a payment another writer already settled refuses the
+ # claim, and the capture reports success without touching the
+ # gateway or recording a second capture event.
+ step :claim
+
external_step :capture_at_gateway
+ step :record_capture
+ external_step :authorize_remainder
run_hooks :after_capture
payment.publish_event('payment.captured')
@@ -31,19 +42,68 @@ module Spree
private
+ attr_reader :response, :remainder
+
# An already-captured payment returns success rather than failing:
# capture is naturally idempotent and double-submitted admin actions
- # must not surface as errors.
+ # must not surface as errors. A failed payment is capturable — the
+ # failure may have been a gateway outage, and retrying is running
+ # this workflow again.
def ensure_capturable
halt!(payment) if payment.completed?
- failure(payment, :payment_not_capturable) unless payment.pending? || payment.checkout? || payment.processing?
+ return if payment.pending? || payment.checkout? || payment.processing? || payment.failed?
+
+ failure(payment, :payment_not_capturable)
+ end
+
+ def claim
+ halt!(payment) unless payment.started_processing!
+ rescue Spree::Core::GatewayError => error
+ failure(payment, error.message)
end
def capture_at_gateway
- payment.capture!(amount)
+ @response = payment.protect_from_connection_error do
+ instrument_gateway_call(:capture, payment.payment_method) do
+ payment.payment_method.capture(@amount, payment.response_code, payment.gateway_options)
+ end
+ end
+
+ # A failed response writes no money records, so it needs no lock —
+ # handle_response records the failure and raises.
+ payment.handle_response(@response, :complete) unless @response.success?
rescue Spree::Core::GatewayError => error
failure(payment, error.message)
end
+
+ # Locked because the webhook settling the same payment races this
+ # request. The DB recheck — deliberately not a reload, which would
+ # discard the in-memory source (card numbers never persist) — makes
+ # the capture event exactly-once.
+ def record_capture
+ already_captured = false
+ payment.owner.with_lock do
+ if Spree::Payment.where(id: payment.id, status: 'completed').exists?
+ already_captured = true
+ else
+ payment.capture_events.create!(amount: ::Money.new(@amount, payment.currency).to_f)
+ # Split before completing, so payment.completed publishes with
+ # the captured amount and the order recomputes from correct rows.
+ @remainder = payment.split_uncaptured_amount
+ payment.handle_response(@response, :complete)
+ end
+ end
+ halt!(payment) if already_captured
+ end
+
+ # The remainder's authorization is its own network call, so it stays
+ # outside the lock.
+ def authorize_remainder
+ return if remainder.blank?
+
+ result = Spree.payment_process_workflow.call(payment: remainder, action: :authorize)
+ failure(remainder, result.error.value.to_s) if result.failure?
+ end
end
end
end
diff --git a/spree/core/app/workflows/spree/payments/process.rb b/spree/core/app/workflows/spree/payments/process.rb
new file mode 100644
index 0000000000..d35517e6b8
--- /dev/null
+++ b/spree/core/app/workflows/spree/payments/process.rb
@@ -0,0 +1,73 @@
+module Spree
+ module Payments
+ # Processes a checkout payment at the gateway — authorize or purchase,
+ # chosen by the payment method's capture timing unless the caller
+ # forces a verb. The storefront batch (Purchase::PaymentProcessing)
+ # calls this once per payment; Payments::Capture re-authorizes a
+ # partial capture's remainder through it.
+ class Process < Spree::Workflow
+ include Spree::InstrumentsGatewayCalls
+
+ hooks :validate, :before_process, :after_process
+
+ # @param payment [Spree::Payment]
+ # @param action [Symbol, nil] :authorize or :purchase; nil follows the
+ # payment method's capture timing
+ def perform(payment:, action: nil)
+ super
+
+ step :ensure_processable
+ run_hooks :validate
+ run_hooks :before_process
+
+ step :claim
+ external_step :process_at_gateway
+
+ run_hooks :after_process
+ success(payment.reload)
+ end
+
+ private
+
+ # The machine-era preconditions, preserved: an in-flight payment is
+ # left alone, a source-required method without a source cannot
+ # process, and an unsupported card brand invalidates the payment.
+ def ensure_processable
+ halt!(payment) if payment.processing?
+ return unless payment.payment_method&.source_required?
+
+ failure(payment, Spree.t(:payment_processing_failed)) if payment.source.blank?
+
+ unless payment.payment_method.supports?(payment.source) || payment.token_based?
+ payment.invalidate!
+ failure(payment, Spree.t(:payment_method_not_supported))
+ end
+ end
+
+ # A payment that completed concurrently — the webhook settled it while
+ # this request was in flight — is a success, not an error.
+ def claim
+ halt!(payment) unless payment.started_processing!
+ rescue Spree::Core::GatewayError => error
+ failure(payment, error.message)
+ end
+
+ def process_at_gateway
+ verb = action || (payment.payment_method&.capture_at_checkout? ? :purchase : :authorize)
+
+ response = payment.protect_from_connection_error do
+ instrument_gateway_call(verb, payment.payment_method) do
+ payment.payment_method.public_send(verb, payment.money.amount_in_cents, payment.source, payment.gateway_options)
+ end
+ end
+
+ payment.handle_response(response, verb == :purchase ? :complete : :pend)
+ # Only reached when handle_response accepted the response — a
+ # purchase moved the funds, so the capture is recorded.
+ payment.capture_events.create!(amount: payment.amount) if verb == :purchase
+ rescue Spree::Core::GatewayError => error
+ failure(payment, error.message)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/payments/void.rb b/spree/core/app/workflows/spree/payments/void.rb
index 5db50ef17e..9750f72fde 100644
--- a/spree/core/app/workflows/spree/payments/void.rb
+++ b/spree/core/app/workflows/spree/payments/void.rb
@@ -2,12 +2,12 @@ module Spree
module Payments
# Voids an authorized payment at the gateway.
#
- # In the workflow tier because the void is network I/O — the external_step
- # keeps it out of any transaction the workflow opened. Money movement
- # stays in the model (Payment#void_transaction! and the state machine are
- # unchanged); this owns the boundary, the guards and the extension points
- # around it.
+ # Owns the flow end to end; Spree::Payment keeps only gateway
+ # mechanics. The payment.voided event publishes from the void! write
+ # itself.
class Void < Spree::Workflow
+ include Spree::InstrumentsGatewayCalls
+
hooks :validate, :before_void, :after_void
# @param payment [Spree::Payment] an already-void payment is a no-op
@@ -22,7 +22,7 @@ module Spree
external_step :void_at_gateway
run_hooks :after_void
- success(payment.reload)
+ success(payment)
end
private
@@ -35,12 +35,61 @@ module Spree
failure(payment, :payment_not_voidable) unless payment.can_void?
end
- # The payment.voided event publishes from the state transition itself.
def void_at_gateway
- payment.void_transaction!
+ # Nothing ever reached the gateway, so there is nothing to release.
+ if payment.response_code.blank?
+ mark_void
+ return
+ end
+
+ response = payment.protect_from_connection_error do
+ instrument_gateway_call(:void, payment.payment_method) do
+ if payment.payment_method.payment_profiles_supported?
+ # Profile gateways need the source: it carries the stored
+ # payment profile, not just the authorization code.
+ payment.payment_method.void(payment.response_code, payment.source, payment.gateway_options)
+ else
+ payment.payment_method.void(payment.response_code, payment.gateway_options)
+ end
+ end
+ end
+
+ if response.success?
+ mark_void(authorization: response.authorization)
+ else
+ payment.gateway_error(response)
+ end
rescue Spree::Core::GatewayError => error
failure(payment, error.message)
end
+
+ # A compare-and-swap, like the session transitions: of two racing
+ # voids only the writer whose update moves the row publishes — the
+ # loser lands as idempotent success. There is no pre-gateway claim,
+ # because the gateway is the authority on whether the authorization
+ # can still be released; only the terminal write must never double.
+ # The authorization is written only when the gateway returned one —
+ # a successful void without it must not null the stored reference.
+ def mark_void(authorization: nil)
+ if payment.new_record?
+ payment.status = 'void'
+ payment.response_code = authorization if authorization.present?
+ payment.save!
+ payment.publish_event('payment.voided')
+ return
+ end
+
+ updates = { status: 'void', updated_at: Time.current }
+ updates[:response_code] = authorization if authorization.present?
+
+ claimed = Spree::Payment.where(id: payment.id).where.not(status: 'void')
+ .update_all(updates) == 1
+ return unless claimed
+
+ payment.assign_attributes(updates.except(:updated_at))
+ payment.clear_attribute_changes(updates.except(:updated_at).keys)
+ payment.publish_event('payment.voided')
+ end
end
end
end
diff --git a/spree/core/db/migrate/20260818000001_rename_spree_payments_state_to_status.rb b/spree/core/db/migrate/20260818000001_rename_spree_payments_state_to_status.rb
new file mode 100644
index 0000000000..690c7e0ce0
--- /dev/null
+++ b/spree/core/db/migrate/20260818000001_rename_spree_payments_state_to_status.rb
@@ -0,0 +1,5 @@
+class RenameSpreePaymentsStateToStatus < ActiveRecord::Migration[8.1]
+ def change
+ rename_column :spree_payments, :state, :status
+ end
+end
diff --git a/spree/core/db/sample_data/orders.rb b/spree/core/db/sample_data/orders.rb
index 4212b35f7b..8cd070d7e7 100644
--- a/spree/core/db/sample_data/orders.rb
+++ b/spree/core/db/sample_data/orders.rb
@@ -129,7 +129,7 @@ if method
source: credit_card.clone,
payment_method: method
).first_or_create!
- payment.update_columns(state: 'pending', response_code: "BGS-#{SecureRandom.hex(6)}")
+ payment.update_columns(status: 'pending', response_code: "BGS-#{SecureRandom.hex(6)}")
end
end
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index b7793440ee..8b757f2e7f 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -146,6 +146,7 @@ module Spree
address_update_service: 'Spree::Addresses::Update',
payment_create_service: 'Spree::Payments::Create',
+ payment_process_workflow: 'Spree::Payments::Process',
payment_capture_workflow: 'Spree::Payments::Capture',
payment_void_workflow: 'Spree::Payments::Void',
refund_create_workflow: 'Spree::Refunds::Create',
diff --git a/spree/core/lib/spree/testing_support/factories/payment_factory.rb b/spree/core/lib/spree/testing_support/factories/payment_factory.rb
index b0667ed7b8..943010658f 100644
--- a/spree/core/lib/spree/testing_support/factories/payment_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/payment_factory.rb
@@ -2,14 +2,14 @@ FactoryBot.define do
factory :payment, class: Spree::Payment do
order { cart.present? ? nil : create(:order, total: amount) }
amount { 45.75 }
- state { 'checkout' }
+ status { 'checkout' }
response_code { "BGS-#{SecureRandom.hex(6)}" }
payment_method { create(:credit_card_payment_method, store: (order || cart).store) }
association(:source, factory: :credit_card)
factory :payment_with_refund do
- state { 'completed' }
+ status { 'completed' }
after :create do |payment|
create(:refund, amount: 5, payment: payment)
end
diff --git a/spree/core/spec/models/concerns/spree/purchase/lifecycle_spec.rb b/spree/core/spec/models/concerns/spree/purchase/lifecycle_spec.rb
index 2c8bef2b6b..630c084103 100644
--- a/spree/core/spec/models/concerns/spree/purchase/lifecycle_spec.rb
+++ b/spree/core/spec/models/concerns/spree/purchase/lifecycle_spec.rb
@@ -24,7 +24,7 @@ RSpec.shared_examples 'a purchase lifecycle host' do
expect(new_record(completed_at: Time.current)).not_to be_can_be_deleted
record = new_record_with_line_items
- create_payment(record, state: 'completed', amount: record.total)
+ create_payment(record, status: 'completed', amount: record.total)
expect(record.reload).not_to be_can_be_deleted
end
end
diff --git a/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb b/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb
index 8a63f5740c..b8075d5a73 100644
--- a/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb
+++ b/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb
@@ -4,7 +4,7 @@ RSpec.shared_examples 'a payment processing host' do
describe '#process_payments!' do
let!(:record) { new_record_with_line_items }
let!(:payment) do
- payment = create_payment(record, amount: 10, state: payment_state)
+ payment = create_payment(record, amount: 10, status: payment_state)
record.payments << payment
payment
end
@@ -23,14 +23,14 @@ RSpec.shared_examples 'a payment processing host' do
end
it 'processes the payments' do
- expect(payment).to receive(:process!)
+ expect(Spree::Payments::Process).to receive(:call).with(payment: payment, action: nil).and_return(double(failure?: false))
expect(record.process_payments!).to be_truthy
end
# Regression spec for https://github.com/spree/spree/issues/5436
it 'raises an error if there are no payments to process' do
allow(record).to receive_messages unprocessed_payments: []
- expect(payment).not_to receive(:process!)
+ expect(Spree::Payments::Process).not_to receive(:call)
expect(record.process_payments!).to be_falsey
end
@@ -40,12 +40,12 @@ RSpec.shared_examples 'a payment processing host' do
let(:unprocessed_payments) { [] }
it 'skips processing the payments' do
- expect(payment).not_to receive(:process!)
+ expect(Spree::Payments::Process).not_to receive(:call)
expect(record.process_payments!).to be_nil
end
context 'when there is other unprocessed payment' do
- let(:other_payment) { create_payment(record, amount: 5, state: 'checkout') }
+ let(:other_payment) { create_payment(record, amount: 5, status: 'checkout') }
let(:unprocessed_payments) { [other_payment] }
before do
@@ -53,8 +53,8 @@ RSpec.shared_examples 'a payment processing host' do
end
it 'processes only the other payment' do
- expect(payment).not_to receive(:process!)
- expect(other_payment).to receive(:process!)
+ expect(Spree::Payments::Process).to receive(:call).once
+ .with(payment: other_payment, action: nil).and_return(double(failure?: false))
expect(record.process_payments!).to be_truthy
end
@@ -62,7 +62,10 @@ RSpec.shared_examples 'a payment processing host' do
end
context 'when a payment raises a GatewayError' do
- before { expect(payment).to receive(:process!).and_raise(Spree::Core::GatewayError) }
+ before do
+ expect(Spree::Payments::Process).to receive(:call)
+ .and_return(double(failure?: true, error: double(value: 'card declined')))
+ end
it 'returns false' do
expect(record.process_payments!).to be false
@@ -94,7 +97,7 @@ RSpec.shared_examples 'a payment processing host' do
before { allow(record).to receive_messages unprocessed_payments: [payment], total: 10 }
it 'processes payments with authorize!' do
- expect(payment).to receive(:authorize!)
+ expect(Spree::Payments::Process).to receive(:call).with(payment: payment, action: :authorize).and_return(double(failure?: false))
subject
end
@@ -110,7 +113,7 @@ RSpec.shared_examples 'a payment processing host' do
before { allow(record).to receive_messages unprocessed_payments: [payment], total: 10 }
it 'processes payments with purchase!' do
- expect(payment).to receive(:purchase!)
+ expect(Spree::Payments::Process).to receive(:call).with(payment: payment, action: :purchase).and_return(double(failure?: false))
subject
end
@@ -123,8 +126,8 @@ RSpec.shared_examples 'a payment processing host' do
it 'partitions payments by state' do
# Pending first — creating a new payment invalidates existing
# checkout-state payments (Payment#invalidate_old_payments).
- pending_payment = create_payment(record, amount: 5, state: 'pending')
- checkout_payment = create_payment(record, amount: 5, state: 'checkout')
+ pending_payment = create_payment(record, amount: 5, status: 'pending')
+ checkout_payment = create_payment(record, amount: 5, status: 'checkout')
expect(record.pending_payments).to contain_exactly(pending_payment)
expect(record.unprocessed_payments).to contain_exactly(checkout_payment)
diff --git a/spree/core/spec/models/concerns/spree/purchase/store_credits_spec.rb b/spree/core/spec/models/concerns/spree/purchase/store_credits_spec.rb
index 506ee2b3d0..bbc6904a23 100644
--- a/spree/core/spec/models/concerns/spree/purchase/store_credits_spec.rb
+++ b/spree/core/spec/models/concerns/spree/purchase/store_credits_spec.rb
@@ -417,10 +417,10 @@ RSpec.shared_examples 'a store credits host' do
let(:other_record_payment) { 22.0 }
before do
- create_store_credit_payment(record, state: 'completed', amount: valid_payment)
- create_store_credit_payment(record, state: 'completed', amount: valid_payment_2)
- create_store_credit_payment(record, state: 'invalid', amount: invalid_payment)
- create_store_credit_payment(new_record(user: create(:user), total: 100.00), state: 'completed', amount: other_record_payment)
+ create_store_credit_payment(record, status: 'completed', amount: valid_payment)
+ create_store_credit_payment(record, status: 'completed', amount: valid_payment_2)
+ create_store_credit_payment(record, status: 'invalid', amount: invalid_payment)
+ create_store_credit_payment(new_record(user: create(:user), total: 100.00), status: 'completed', amount: other_record_payment)
end
it 'returns the sum of the payment amounts' do
diff --git a/spree/core/spec/models/spree/credit_card_spec.rb b/spree/core/spec/models/spree/credit_card_spec.rb
index 49826eb3e3..b9c5713bd5 100644
--- a/spree/core/spec/models/spree/credit_card_spec.rb
+++ b/spree/core/spec/models/spree/credit_card_spec.rb
@@ -509,8 +509,8 @@ describe Spree::CreditCard, type: :model do
end
context 'with non-checkout payments on incomplete orders' do
- let!(:completed_payment) { create(:payment, source: card, order: incomplete_order, state: 'completed') }
- let!(:pending_payment) { create(:payment, source: card, order: incomplete_order, state: 'pending') }
+ let!(:completed_payment) { create(:payment, source: card, order: incomplete_order, status: 'completed') }
+ let!(:pending_payment) { create(:payment, source: card, order: incomplete_order, status: 'pending') }
it 'voids the payments' do
card.destroy
@@ -522,7 +522,7 @@ describe Spree::CreditCard, type: :model do
context 'with payments on completed orders' do
let!(:completed_order) { create(:completed_order_with_pending_payment, user_id: incomplete_order.user_id) }
- let!(:completed_order_payment) { create(:payment, source: card, order: completed_order, state: 'completed', amount: completed_order.total) }
+ let!(:completed_order_payment) { create(:payment, source: card, order: completed_order, status: 'completed', amount: completed_order.total) }
it 'does not modify payments on completed orders' do
card.destroy
diff --git a/spree/core/spec/models/spree/order/payment_spec.rb b/spree/core/spec/models/spree/order/payment_spec.rb
index 6e09c1489a..a0197c4fdc 100644
--- a/spree/core/spec/models/spree/order/payment_spec.rb
+++ b/spree/core/spec/models/spree/order/payment_spec.rb
@@ -86,6 +86,12 @@ module Spree
payment_1 = create(:payment, amount: 50, order: order)
payment_2 = create(:payment, amount: 50, order: order)
payment_3 = create(:payment, amount: 50, order: order)
+ # Each create invalidates its predecessors; this spec wants three
+ # live checkout payments, so restore them. The atomic claim reads
+ # the database, and refuses invalid payments — the old machine let
+ # these stale instances resurrect them, which is the race the claim
+ # closes.
+ Spree::Payment.where(id: [payment_1, payment_2, payment_3]).update_all(status: 'checkout')
allow(order).to receive(:unprocessed_payments).and_return([payment_1, payment_2, payment_3])
order.process_payments!
@@ -99,7 +105,7 @@ module Spree
it 'does not use failed payments' do
payment_1 = create(:payment, amount: 50, order: order)
- payment_2 = create(:payment, amount: 50, state: 'failed', order: order)
+ payment_2 = create(:payment, amount: 50, status: 'failed', order: order)
allow(order).to receive(:pending_payments).and_return([payment_1])
expect(payment_2).not_to receive(:process!)
@@ -160,7 +166,7 @@ module Spree
calculator.set_preference(:amount, order.fulfillments.first.cost)
calculator.save!
- order.payments << create(:payment, state: :completed, order: order, amount: order.total)
+ order.payments << create(:payment, status: :completed, order: order, amount: order.total)
return_record = create(:received_return, order: order, store: order.store)
create(:refund, amount: 10, payment: order.payments.first, originator: return_record)
@@ -176,7 +182,7 @@ module Spree
calculator.set_preference(:amount, order.fulfillments.first.cost)
calculator.save!
- order.payments << create(:payment, state: :completed, order: order, amount: order.total)
+ order.payments << create(:payment, status: :completed, order: order, amount: order.total)
create(:refund, amount: 10, payment: order.payments.first)
order.recalculate_totals!
diff --git a/spree/core/spec/models/spree/order/risk_assessment_spec.rb b/spree/core/spec/models/spree/order/risk_assessment_spec.rb
index 25709ccd6d..d4f56b51b5 100644
--- a/spree/core/spec/models/spree/order/risk_assessment_spec.rb
+++ b/spree/core/spec/models/spree/order/risk_assessment_spec.rb
@@ -66,7 +66,7 @@ describe Spree::Order, type: :model do
end
context "state == 'failed'" do
- let(:order) { FactoryBot.create(:order, payments: [FactoryBot.create(:payment, state: 'failed')]) }
+ let(:order) { FactoryBot.create(:order, payments: [FactoryBot.create(:payment, status: 'failed')]) }
it "returns true if the order has state == 'failed'" do
expect(order.is_risky?).to eq(true)
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index bbf24d806b..5fce83c648 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -206,8 +206,8 @@ describe Spree::Order, type: :model do
end
context 'with incomplete payments' do
- let!(:payment) { create(:payment, order: order, amount: order.total - 10, state: 'pending', response_code: 'abc') }
- let!(:other_payment) { create(:payment, order: order, amount: 10, state: 'checkout', response_code: 'def') }
+ let!(:payment) { create(:payment, order: order, amount: order.total - 10, status: 'pending', response_code: 'abc') }
+ let!(:other_payment) { create(:payment, order: order, amount: 10, status: 'checkout', response_code: 'def') }
it 'marks the incomplete payments as void' do
order.cancel
@@ -228,7 +228,7 @@ describe Spree::Order, type: :model do
context 'when gift card is present' do
let(:gift_card) { create(:gift_card, amount: 110) }
let(:order) { create(:completed_order_with_totals, store: store, gift_card: gift_card, total: 110) }
- let!(:payment) { create(:store_credit_payment, order: order, state: 'completed', amount: 110) }
+ let!(:payment) { create(:store_credit_payment, order: order, status: 'completed', amount: 110) }
it 'handles additional actions' do
order.cancel
@@ -242,7 +242,7 @@ describe Spree::Order, type: :model do
context 'when no gift card' do
let(:order) { create(:completed_order_with_totals, store: store) }
- let!(:payment) { create(:payment, order: order, state: 'completed', amount: 10) }
+ let!(:payment) { create(:payment, order: order, status: 'completed', amount: 10) }
it 'handles additional actions' do
order.cancel
diff --git a/spree/core/spec/models/spree/order_updater_spec.rb b/spree/core/spec/models/spree/order_updater_spec.rb
index 969264e11e..7a158f4b17 100644
--- a/spree/core/spec/models/spree/order_updater_spec.rb
+++ b/spree/core/spec/models/spree/order_updater_spec.rb
@@ -180,7 +180,7 @@ module Spree
end
it 'is authorized when a payment is only pending' do
- create(:payment, order: order, amount: order_total, state: 'pending')
+ create(:payment, order: order, amount: order_total, status: 'pending')
updater.update_payment_state
@@ -189,7 +189,7 @@ module Spree
context 'order total is greater than payment total' do
it 'is partially_paid' do
- create(:payment, order: order, amount: order_total - 1, state: 'completed')
+ create(:payment, order: order, amount: order_total - 1, status: 'completed')
updater.update_payment_state
@@ -199,7 +199,7 @@ module Spree
context 'order total equals payment total' do
it 'is paid' do
- create(:payment, order: order, amount: order_total, state: 'completed')
+ create(:payment, order: order, amount: order_total, status: 'completed')
updater.update_payment_state
@@ -220,7 +220,7 @@ module Spree
context 'and payment is refunded' do
it 'is voided' do
- payment = create(:payment, order: order, amount: order_total, state: 'completed')
+ payment = create(:payment, order: order, amount: order_total, status: 'completed')
create(:refund, payment: payment, amount: order_total)
updater.update_payment_state
diff --git a/spree/core/spec/models/spree/payment/custom_events_spec.rb b/spree/core/spec/models/spree/payment/custom_events_spec.rb
index b4206a7aa1..3d4e5c1684 100644
--- a/spree/core/spec/models/spree/payment/custom_events_spec.rb
+++ b/spree/core/spec/models/spree/payment/custom_events_spec.rb
@@ -4,7 +4,7 @@ require 'spec_helper'
RSpec.describe Spree::Payment::CustomEvents do
let(:order) { create(:order_with_line_items) }
- let(:payment) { create(:payment, order: order, state: 'pending') }
+ let(:payment) { create(:payment, order: order, status: 'pending') }
before do
allow(Spree::Events).to receive(:enabled?).and_return(true)
diff --git a/spree/core/spec/models/spree/payment_session_spec.rb b/spree/core/spec/models/spree/payment_session_spec.rb
index e36768c131..4096d2a60b 100644
--- a/spree/core/spec/models/spree/payment_session_spec.rb
+++ b/spree/core/spec/models/spree/payment_session_spec.rb
@@ -343,4 +343,29 @@ RSpec.describe Spree::PaymentSession, type: :model do
expect(payment.id).to eq(existing.id)
end
end
+
+ describe 'racing transitions' do
+ let(:session) { create(:bogus_payment_session, order: order, payment_method: payment_method, amount: 50) }
+
+ # The webhook and the customer's synchronous return race by design;
+ # the loser of the row lock must land as a no-op false with no event.
+ it 'lets exactly one of two racing writers complete the session' do
+ stale = Spree::PaymentSession.find(session.id)
+ expect(session.complete).to be(true)
+
+ events = []
+ allow(stale).to receive(:publish_event) { |name| events << name }
+
+ expect(stale.complete).to be(false)
+ expect(events).to be_empty
+ expect(stale.reload).to be_completed
+ end
+
+ it 'refuses to fail a session that already completed' do
+ Spree::PaymentSession.find(session.id).complete
+
+ expect(session.fail).to be(false)
+ expect(session.reload).to be_completed
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/payment_spec.rb b/spree/core/spec/models/spree/payment_spec.rb
index e12daa516e..148077c8a2 100644
--- a/spree/core/spec/models/spree/payment_spec.rb
+++ b/spree/core/spec/models/spree/payment_spec.rb
@@ -54,19 +54,19 @@ describe Spree::Payment, type: :model do
subject { Spree::Payment.valid }
let!(:invalid_payment) do
- create(:payment, avs_response: 'Y', cvv_response_code: 'M', cvv_response_message: '', state: 'invalid')
+ create(:payment, avs_response: 'Y', cvv_response_code: 'M', cvv_response_message: '', status: 'invalid')
end
let!(:failed_payment) do
- create(:payment, avs_response: 'Y', cvv_response_code: 'M', cvv_response_message: '', state: 'failed')
+ create(:payment, avs_response: 'Y', cvv_response_code: 'M', cvv_response_message: '', status: 'failed')
end
let!(:checkout_payment) do
- create(:payment, avs_response: 'A', cvv_response_code: 'M', cvv_response_message: '', state: 'checkout')
+ create(:payment, avs_response: 'A', cvv_response_code: 'M', cvv_response_message: '', status: 'checkout')
end
let!(:completed_payment) do
- create(:payment, avs_response: 'Y', cvv_response_code: 'N', cvv_response_message: '', state: 'completed')
+ create(:payment, avs_response: 'Y', cvv_response_code: 'N', cvv_response_message: '', status: 'completed')
end
it { is_expected.not_to include(invalid_payment) }
@@ -210,7 +210,7 @@ describe Spree::Payment, type: :model do
describe 'Callbacks' do
describe '#update_order' do
- let(:payment) { create(:payment, order: order, state: 'completed') }
+ let(:payment) { create(:payment, order: order, status: 'completed') }
context 'when destroying completed payment' do
it 'updates the order' do
@@ -254,23 +254,23 @@ describe Spree::Payment, type: :model do
# Regression test for https://github.com/spree/spree/pull/2224
context 'failure' do
it 'transitions to failed from pending state' do
- payment.state = 'pending'
+ payment.status = 'pending'
payment.failure
- expect(payment.state).to eql('failed')
+ expect(payment.status).to eql('failed')
end
it 'transitions to failed from processing state' do
- payment.state = 'processing'
+ payment.status = 'processing'
payment.failure
- expect(payment.state).to eql('failed')
+ expect(payment.status).to eql('failed')
end
end
context 'invalidate' do
- it 'transitions from checkout to invalid' do
- payment.state = 'checkout'
- payment.invalidate
- expect(payment.state).to eq('invalid')
+ it 'moves from checkout to invalid' do
+ payment.status = 'checkout'
+ payment.invalidate!
+ expect(payment.status).to eq('invalid')
end
end
@@ -296,7 +296,7 @@ describe Spree::Payment, type: :model do
it 'invalidates if payment method doesnt support source' do
expect(payment.payment_method).to receive(:supports?).with(payment.source).and_return(false)
expect { payment.process! }.to raise_error(Spree::Core::GatewayError)
- expect(payment.state).to eq('invalid')
+ expect(payment.status).to eq('invalid')
end
# Regression test for #4598
@@ -357,11 +357,10 @@ describe Spree::Payment, type: :model do
context 'when response is returned from gateway' do
it 'marks payment as failed' do
allow(gateway).to receive(:authorize).and_return(failed_response)
- expect(payment).to receive(:failure)
- expect(payment).not_to receive(:pend)
expect do
payment.authorize!
end.to raise_error(Spree::Core::GatewayError)
+ expect(payment.reload).to be_failed
end
end
@@ -401,7 +400,7 @@ describe Spree::Payment, type: :model do
end
it 'instruments the capture gateway call' do
- payment.state = 'pending'
+ payment.status = 'pending'
payment.response_code = "BGS-#{SecureRandom.hex(6)}"
allow(gateway).to receive(:capture).and_return(success_response)
@@ -451,12 +450,11 @@ describe Spree::Payment, type: :model do
context 'when response is returned from gateway' do
before do
allow(gateway).to receive(:purchase).and_return(failed_response)
- expect(payment).to receive(:failure)
- expect(payment).not_to receive(:pend)
end
it 'makes payment failed' do
expect { payment.purchase! }.to raise_error(Spree::Core::GatewayError)
+ expect(payment.reload).to be_failed
end
it 'does not log a capture event' do
@@ -600,7 +598,7 @@ describe Spree::Payment, type: :model do
context 'when payment is pending' do
before do
payment.amount = 100
- payment.state = 'pending'
+ payment.status = 'pending'
payment.response_code = "BGS-#{SecureRandom.hex(6)}"
end
@@ -672,9 +670,9 @@ describe Spree::Payment, type: :model do
context 'when response is returned from gateway' do
it 'does not make payment complete' do
allow(gateway).to receive_messages capture: failed_response
- expect(payment).to receive(:failure)
- expect(payment).not_to receive(:complete)
expect { payment.capture! }.to raise_error(Spree::Core::GatewayError)
+ expect(payment.reload).to be_failed
+ expect(payment).not_to be_completed
end
end
@@ -696,11 +694,10 @@ describe Spree::Payment, type: :model do
# Regression test for #2119
context 'when payment is completed' do
before do
- payment.state = 'completed'
+ payment.status = 'completed'
end
it 'does nothing' do
- expect(payment).not_to receive(:complete)
expect(payment.payment_method).not_to receive(:capture)
payment.capture!
end
@@ -710,7 +707,7 @@ describe Spree::Payment, type: :model do
describe '#void_transaction!' do
before do
payment.response_code = '123'
- payment.state = 'pending'
+ payment.status = 'pending'
end
context 'when profiles are supported' do
@@ -742,8 +739,8 @@ describe Spree::Payment, type: :model do
context 'when response is returned from gateway' do
it 'does not void the payment' do
allow(gateway).to receive_messages void: failed_response
- expect(payment).not_to receive(:void)
expect { payment.void_transaction! }.to raise_error(Spree::Core::GatewayError)
+ expect(payment).not_to be_void
end
end
@@ -764,7 +761,7 @@ describe Spree::Payment, type: :model do
# Regression test for #2119
context 'if payment is already voided' do
before do
- payment.state = 'void'
+ payment.status = 'void'
end
it 'does not void the payment' do
@@ -776,23 +773,23 @@ describe Spree::Payment, type: :model do
context 'if response_code is blank' do
before do
payment.response_code = nil
- payment.state = 'pending'
+ payment.status = 'pending'
end
it 'voids the payment without calling the gateway' do
expect(payment.payment_method).not_to receive(:void)
payment.void_transaction!
- expect(payment.state).to eq('void')
+ expect(payment.status).to eq('void')
end
end
end
end
context 'when already processing' do
- it 'returns nil without trying to process the source' do
- payment.state = 'processing'
+ it 'is a no-op success without trying to process the source' do
+ payment.status = 'processing'
- expect(payment.process!).to be_nil
+ expect(payment.process!).to be(true)
end
end
@@ -819,7 +816,7 @@ describe Spree::Payment, type: :model do
it 'processes successfully and transitions to pending' do
expect { payment.process! }.not_to raise_error
- expect(payment.state).to eq('pending')
+ expect(payment.status).to eq('pending')
end
context 'with auto capture' do
@@ -827,7 +824,7 @@ describe Spree::Payment, type: :model do
it 'processes successfully and transitions to completed' do
expect { payment.process! }.not_to raise_error
- expect(payment.state).to eq('completed')
+ expect(payment.status).to eq('completed')
end
end
end
@@ -859,7 +856,7 @@ describe Spree::Payment, type: :model do
describe '#save' do
context 'captured payments' do
it 'update order payment total' do
- payment = create(:payment, order: order, state: 'completed')
+ payment = create(:payment, order: order, status: 'completed')
expect(order.payment_total).to eq payment.amount
end
end
@@ -878,17 +875,11 @@ describe Spree::Payment, type: :model do
end
context 'when the payment was completed but now void' do
- let(:payment) do
- Spree::Payment.create(
- amount: 100,
- order: order,
- state: 'completed'
- )
- end
+ let(:payment) { create(:payment, order: order, amount: 100, status: 'completed') }
it 'updates order payment total' do
- payment.void
- expect(order.payment_total).to eq 0
+ payment.void!
+ expect(order.reload.payment_total).to eq 0
end
end
@@ -1237,7 +1228,7 @@ describe Spree::Payment, type: :model do
end
describe '#editable?' do
- before { payment.state = state }
+ before { payment.status = state }
context "when the state is 'checkout'" do
let(:state) { 'checkout' }
@@ -1262,7 +1253,7 @@ describe Spree::Payment, type: :model do
describe '#source' do
context 'with source required enabled' do
- let(:payment) { create(:payment, payment_method: payment_method, source: card, state: 'completed') }
+ let(:payment) { create(:payment, payment_method: payment_method, source: card, status: 'completed') }
let(:card) { create(:credit_card) }
let(:payment_method) { card.payment_method }
@@ -1363,7 +1354,7 @@ describe Spree::Payment, type: :model do
end
describe '#has_invalid_state?' do
- let(:payment) { create(:payment, state: state) }
+ let(:payment) { create(:payment, status: state) }
subject(:has_invalid_state?) { payment.has_invalid_state? }
context 'when the state is invalid' do
diff --git a/spree/core/spec/models/spree/promotion_handler/coupon_with_gift_card_spec.rb b/spree/core/spec/models/spree/promotion_handler/coupon_with_gift_card_spec.rb
index 717ff91f1d..98773888cc 100644
--- a/spree/core/spec/models/spree/promotion_handler/coupon_with_gift_card_spec.rb
+++ b/spree/core/spec/models/spree/promotion_handler/coupon_with_gift_card_spec.rb
@@ -111,7 +111,7 @@ describe Spree::PromotionHandler::Coupon, type: :model do
order.recalculate_gift_card
expect(order.payments.count).to eq(initial_payment_count)
- expect(order.payments.where(state: 'invalid').count).to eq(0)
+ expect(order.payments.where(status: 'invalid').count).to eq(0)
end
it 'does not change amount when total is unchanged' do
diff --git a/spree/core/spec/models/spree/store_credit_spec.rb b/spree/core/spec/models/spree/store_credit_spec.rb
index 9e04112c9c..b02c26cdaf 100644
--- a/spree/core/spec/models/spree/store_credit_spec.rb
+++ b/spree/core/spec/models/spree/store_credit_spec.rb
@@ -594,7 +594,7 @@ describe Spree::StoreCredit, type: :model do
subject { store_credit.can_capture?(payment) }
let(:store_credit) { create(:store_credit) }
- let(:payment) { create(:payment, state: payment_state) }
+ let(:payment) { create(:payment, status: payment_state) }
context 'pending payment' do
let(:payment_state) { 'pending' }
@@ -641,7 +641,7 @@ describe Spree::StoreCredit, type: :model do
subject { store_credit.can_void?(payment) }
let(:store_credit) { create(:store_credit) }
- let(:payment) { create(:payment, state: payment_state) }
+ let(:payment) { create(:payment, status: payment_state) }
context 'pending payment' do
let(:payment_state) { 'pending' }
@@ -665,7 +665,7 @@ describe Spree::StoreCredit, type: :model do
end
context 'when payment is completed' do
- before { payment.update_column(:state, :completed) }
+ before { payment.update_column(:status, :completed) }
it { is_expected.to be false }
end
@@ -700,7 +700,7 @@ describe Spree::StoreCredit, type: :model do
subject { store_credit.can_credit?(payment) }
let(:store_credit) { create(:store_credit) }
- let(:payment) { create(:payment, state: payment_state) }
+ let(:payment) { create(:payment, status: payment_state) }
context 'payment is not completed' do
let(:payment_state) { 'pending' }
diff --git a/spree/core/spec/services/spree/carts/destroy_spec.rb b/spree/core/spec/services/spree/carts/destroy_spec.rb
index 8399ec9a6d..d93dba9c8b 100644
--- a/spree/core/spec/services/spree/carts/destroy_spec.rb
+++ b/spree/core/spec/services/spree/carts/destroy_spec.rb
@@ -28,7 +28,7 @@ module Spree
end
it 'voids pending payments' do
- expect_any_instance_of(Spree::Payment).to receive(:void).exactly(cart.payments.count).times
+ expect_any_instance_of(Spree::Payment).to receive(:void!).exactly(cart.payments.count).times
subject
end
@@ -134,7 +134,7 @@ module Spree
context 'because a payment is completed' do
let(:cart) { create(:cart_with_line_items) }
- let!(:payment) { create(:payment, cart: cart, order: nil, state: 'completed', amount: cart.total) }
+ let!(:payment) { create(:payment, cart: cart, order: nil, status: 'completed', amount: cart.total) }
it 'returns failure' do
expect(subject.success?).to be false
diff --git a/spree/core/spec/services/spree/checkout/add_store_credit_spec.rb b/spree/core/spec/services/spree/checkout/add_store_credit_spec.rb
index d06d4563fe..aa1ddfe7ee 100644
--- a/spree/core/spec/services/spree/checkout/add_store_credit_spec.rb
+++ b/spree/core/spec/services/spree/checkout/add_store_credit_spec.rb
@@ -114,7 +114,7 @@ describe Spree::Checkout::AddStoreCredit, type: :service do
described_class.call(order: order.reload)
order.reload
- expect(order.payments.where(state: 'invalid').count).to eq(0)
+ expect(order.payments.where(status: 'invalid').count).to eq(0)
end
it 'adjusts amount when order total changes' do
diff --git a/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rb b/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rb
index 37175c7b98..1474201e04 100644
--- a/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rb
+++ b/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rb
@@ -22,7 +22,7 @@ RSpec.describe Spree::OrderStatusSubscriber do
end
it 'recomputes the owning order statuses through the single writer' do
- payment = create(:payment, order: order, cart: nil, amount: order.total, state: 'completed')
+ payment = create(:payment, order: order, cart: nil, amount: order.total, status: 'completed')
order.update_columns(payment_status: nil)
event = Spree::Event.new(name: 'payment.completed', payload: { 'id' => payment.prefixed_id }, store_id: order.store_id)
@@ -48,7 +48,7 @@ RSpec.describe Spree::OrderStatusSubscriber do
it 'rolls the order up when a payment is captured through the machine', events: true do
order = create(:order_with_line_items, store: @default_store)
order.update_columns(status: 'draft', completed_at: nil)
- payment = create(:payment, order: order, cart: nil, amount: order.total, state: 'pending')
+ payment = create(:payment, order: order, cart: nil, amount: order.total, status: 'pending')
order.update_columns(payment_status: 'none')
payment.capture!
diff --git a/spree/core/spec/workflows/spree/carts/complete_spec.rb b/spree/core/spec/workflows/spree/carts/complete_spec.rb
index 0951d5526b..59f271132f 100644
--- a/spree/core/spec/workflows/spree/carts/complete_spec.rb
+++ b/spree/core/spec/workflows/spree/carts/complete_spec.rb
@@ -292,7 +292,7 @@ module Spree
let(:order) { create(:order_with_line_items) }
it 'finalizes a draft order through the same service' do
- create(:payment, order: order, amount: order.total, state: 'pending')
+ create(:payment, order: order, amount: order.total, status: 'pending')
result = described_class.call(cart: order)
expect(result).to be_success
@@ -312,7 +312,7 @@ module Spree
it 'rolls the draft order back and re-points money records to the cart' do
# A payment that never completes: processing is a no-op, so coverage
# stays below total and the pre-capture rollback arm fires.
- allow_any_instance_of(Spree::Payment).to receive(:process!)
+ allow(Spree::Payments::Process).to receive(:call).and_return(double(failure?: false))
payment = ready_cart.payments.first
result = described_class.call(cart: ready_cart)
@@ -339,7 +339,7 @@ module Spree
end
it 'completes without capturing when the payment is authorized but pending' do
- uncovered_cart.payments.create!(payment_method: Spree::PaymentMethod.first, amount: uncovered_cart.total, state: 'pending')
+ uncovered_cart.payments.create!(payment_method: Spree::PaymentMethod.first, amount: uncovered_cart.total, status: 'pending')
result = described_class.call(cart: uncovered_cart, payment_pending: true)
diff --git a/spree/core/spec/workflows/spree/carts/recalculate_totals_spec.rb b/spree/core/spec/workflows/spree/carts/recalculate_totals_spec.rb
index 17c983b6ec..052981c3a5 100644
--- a/spree/core/spec/workflows/spree/carts/recalculate_totals_spec.rb
+++ b/spree/core/spec/workflows/spree/carts/recalculate_totals_spec.rb
@@ -21,7 +21,7 @@ module Spree
it 'nets refunds out of the payment total' do
order = create(:completed_order_with_totals, store: store)
- payment = create(:payment, order: order, amount: order.total, state: 'completed')
+ payment = create(:payment, order: order, amount: order.total, status: 'completed')
create(:refund, payment: payment, amount: 5)
described_class.call(cart: order)
diff --git a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
index ecb6edc8cc..5e061adbf8 100644
--- a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
+++ b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
@@ -377,7 +377,7 @@ module Spree
before do
payment = order.payments.first
payment.capture_events.delete_all
- payment.update_columns(state: 'pending')
+ payment.update_columns(status: 'pending')
order.update_columns(payment_total: 0, payment_state: 'balance_due')
end
@@ -427,7 +427,7 @@ module Spree
it 'refuses to hand over a mixed-tender order with an uncaptured checkout payment' do
set_capture_method('manual')
checkout_method = create(:credit_card_payment_method, store: store, capture_method: 'checkout')
- create(:payment, order: order, payment_method: checkout_method, amount: 10, state: 'pending')
+ create(:payment, order: order, payment_method: checkout_method, amount: 10, status: 'pending')
result = subject.call(fulfillment: fulfillment)
diff --git a/spree/core/spec/workflows/spree/payments/capture_spec.rb b/spree/core/spec/workflows/spree/payments/capture_spec.rb
index 712cafc505..7dd2bf6aff 100644
--- a/spree/core/spec/workflows/spree/payments/capture_spec.rb
+++ b/spree/core/spec/workflows/spree/payments/capture_spec.rb
@@ -1,36 +1,75 @@
require 'spec_helper'
RSpec.describe Spree::Payments::Capture do
- let(:payment) { create(:payment, state: 'pending', amount: 45.75) }
+ let(:store) { @default_store }
+ let(:order) { create(:order, store: store, total: 45.75) }
+ let(:gateway) do
+ gateway = store.payment_methods.create!(type: 'Spree::Gateway::Bogus', active: true)
+ allow(gateway).to receive_messages(source_required: true)
+ gateway
+ end
+ let(:card) { create(:credit_card) }
+ let(:payment) do
+ create(:payment, order: order, payment_method: gateway, source: card,
+ status: 'pending', amount: 45.75, response_code: '123')
+ end
+ let(:success_response) do
+ Spree::PaymentResponse.new(true, nil, {}, authorization: '123')
+ end
+ let(:failed_response) { Spree::PaymentResponse.new(false, 'card declined') }
before { Spree.hooks.clear! }
after { Spree.hooks.clear! }
describe 'capturing' do
- it 'captures the payment at the gateway and publishes the event' do
- expect(payment).to receive(:capture!).with(nil).and_return(true)
+ it 'captures at the gateway, records the capture event and publishes' do
+ expect(gateway).to receive(:capture).with(4575, '123', anything).and_return(success_response)
+ expect(payment).to receive(:publish_event).with('payment.completed')
expect(payment).to receive(:publish_event).with('payment.captured')
- expect(described_class.call(payment: payment)).to be_success
+ result = described_class.call(payment: payment)
+
+ expect(result).to be_success
+ expect(payment.reload).to be_completed
+ expect(payment.capture_events.sum(:amount)).to eq(45.75)
end
- it 'passes a partial amount through to the gateway' do
- expect(payment).to receive(:capture!).with(1000).and_return(true)
- allow(payment).to receive(:publish_event)
+ it 'splits a partial capture into a pending remainder and re-authorizes it' do
+ expect(gateway).to receive(:capture).with(1000, '123', anything).and_return(success_response)
+ expect(gateway).to receive(:authorize)
+ .and_return(Spree::PaymentResponse.new(true, nil, {}, authorization: '456'))
+
+ result = described_class.call(payment: payment, amount: 1000)
- described_class.call(payment: payment, amount: 1000)
+ expect(result).to be_success
+ expect(payment.reload).to be_completed
+ expect(payment.amount).to eq(10.00)
+
+ remainder = order.payments.pending.last
+ expect(remainder.amount).to eq(35.75)
end
it 'is a no-op for an already-captured payment' do
- completed = create(:payment, state: 'completed')
- expect(completed).not_to receive(:capture!)
+ completed = create(:payment, payment_method: gateway, source: card, status: 'completed')
+ expect(gateway).not_to receive(:capture)
expect(described_class.call(payment: completed)).to be_success
end
+ it 'retries a failed capture — a failure can be a transient gateway outage' do
+ payment.update_column(:status, 'failed')
+ expect(gateway).to receive(:capture).with(4575, '123', anything).and_return(success_response)
+
+ result = described_class.call(payment: payment)
+
+ expect(result).to be_success
+ expect(payment.reload).to be_completed
+ expect(payment.capture_events.sum(:amount)).to eq(45.75)
+ end
+
it 'fails without calling the gateway when the payment cannot be captured' do
- voided = create(:payment, state: 'void')
- expect(voided).not_to receive(:capture!)
+ voided = create(:payment, payment_method: gateway, source: card, status: 'void')
+ expect(gateway).not_to receive(:capture)
result = described_class.call(payment: voided)
@@ -38,19 +77,51 @@ RSpec.describe Spree::Payments::Capture do
expect(result.error.value).to eq(:payment_not_capturable)
end
- it 'surfaces a gateway error as a failure result' do
- allow(payment).to receive(:capture!).and_raise(Spree::Core::GatewayError, 'card declined')
+ it 'records the failure and surfaces a gateway decline as a failure result' do
+ allow(gateway).to receive(:capture).and_return(failed_response)
result = described_class.call(payment: payment)
expect(result).to be_failure
expect(result.error.value).to eq('card declined')
+ expect(payment.reload).to be_failed
+ expect(payment.capture_events.count).to eq(0)
+ end
+ end
+
+ describe 'racing a concurrent settlement' do
+ # The stale-instance race: the webhook settles the payment while an
+ # admin's already-loaded copy still reads pending. The claim must
+ # refuse, and the capture must succeed as a no-op — no gateway call,
+ # no second capture event, no status regression.
+ it 'reports success without touching the settled payment or the gateway' do
+ Spree::Payment.find(payment.id).tap do |settled|
+ settled.update_columns(status: 'completed')
+ settled.capture_events.create!(amount: 45.75)
+ end
+ expect(gateway).not_to receive(:capture)
+
+ result = described_class.call(payment: payment) # stale: still reads pending
+
+ expect(result).to be_success
+ expect(payment.reload).to be_completed
+ expect(payment.capture_events.count).to eq(1)
+ end
+
+ it 'fails without calling the gateway when the payment died concurrently' do
+ Spree::Payment.find(payment.id).update_columns(status: 'void')
+ expect(gateway).not_to receive(:capture)
+
+ result = described_class.call(payment: payment)
+
+ expect(result).to be_failure
+ expect(payment.reload).to be_void
end
end
describe 'hooks' do
it 'lets a validate handler veto the capture before the gateway is called' do
- expect(payment).not_to receive(:capture!)
+ expect(gateway).not_to receive(:capture)
Spree.hooks.register('payments.capture.validate') { |flow| flow.reject!('on fraud hold') }
result = described_class.call(payment: payment)
@@ -60,8 +131,7 @@ RSpec.describe Spree::Payments::Capture do
end
it 'runs after_capture once the gateway call succeeds' do
- allow(payment).to receive(:capture!).and_return(true)
- allow(payment).to receive(:publish_event)
+ allow(gateway).to receive(:capture).and_return(success_response)
captured = false
Spree.hooks.register('payments.capture.after_capture') { |_flow| captured = true }
@@ -73,14 +143,11 @@ RSpec.describe Spree::Payments::Capture do
end
it 'calls the gateway outside any transaction the workflow opened' do
- # The point of the graduation: external_step raises if the gateway call
- # would share a workflow-opened transaction.
open_transactions = nil
- allow(payment).to receive(:capture!) do
+ allow(gateway).to receive(:capture) do
open_transactions = ApplicationRecord.connection.open_transactions
- true
+ success_response
end
- allow(payment).to receive(:publish_event)
baseline = ApplicationRecord.connection.open_transactions
described_class.call(payment: payment)
diff --git a/spree/core/spec/workflows/spree/payments/process_spec.rb b/spree/core/spec/workflows/spree/payments/process_spec.rb
new file mode 100644
index 0000000000..c28fb43f11
--- /dev/null
+++ b/spree/core/spec/workflows/spree/payments/process_spec.rb
@@ -0,0 +1,116 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Payments::Process do
+ let(:store) { @default_store }
+ let(:order) { create(:order, store: store, total: 45.75) }
+ let(:gateway) do
+ gateway = store.payment_methods.create!(type: 'Spree::Gateway::Bogus', active: true)
+ allow(gateway).to receive_messages(source_required: true)
+ gateway
+ end
+ let(:card) { create(:credit_card) }
+ let(:payment) do
+ create(:payment, order: order, payment_method: gateway, source: card,
+ status: 'checkout', amount: 45.75, response_code: nil)
+ end
+ let(:success_response) do
+ Spree::PaymentResponse.new(true, nil, {}, authorization: '123')
+ end
+
+ before { Spree.hooks.clear! }
+ after { Spree.hooks.clear! }
+
+ describe 'choosing the verb' do
+ it 'authorizes when the method does not capture at checkout' do
+ allow(gateway).to receive(:capture_at_checkout?).and_return(false)
+ expect(gateway).to receive(:authorize).and_return(success_response)
+
+ expect(described_class.call(payment: payment)).to be_success
+ expect(payment.reload).to be_pending
+ expect(payment.capture_events.count).to eq(0)
+ end
+
+ it 'purchases when the method captures at checkout, recording the capture' do
+ allow(gateway).to receive(:capture_at_checkout?).and_return(true)
+ expect(gateway).to receive(:purchase).and_return(success_response)
+
+ expect(described_class.call(payment: payment)).to be_success
+ expect(payment.reload).to be_completed
+ expect(payment.capture_events.sum(:amount)).to eq(45.75)
+ end
+
+ it 'lets the caller force a verb over the capture timing' do
+ allow(gateway).to receive(:capture_at_checkout?).and_return(true)
+ expect(gateway).to receive(:authorize).and_return(success_response)
+ expect(gateway).not_to receive(:purchase)
+
+ described_class.call(payment: payment, action: :authorize)
+
+ expect(payment.reload).to be_pending
+ end
+ end
+
+ describe 'preconditions' do
+ it 'is a no-op for a payment already in flight' do
+ payment.update_column(:status, 'processing')
+ expect(gateway).not_to receive(:authorize)
+
+ expect(described_class.call(payment: payment)).to be_success
+ end
+
+ it 'fails when a source-required method has no source' do
+ payment.source = nil
+ expect(gateway).not_to receive(:authorize)
+
+ result = described_class.call(payment: payment)
+
+ expect(result).to be_failure
+ expect(result.error.value).to eq(Spree.t(:payment_processing_failed))
+ end
+
+ it 'invalidates the payment when the card brand is not supported' do
+ allow(gateway).to receive(:supports?).and_return(false)
+ allow(payment).to receive(:token_based?).and_return(false)
+
+ result = described_class.call(payment: payment)
+
+ expect(result).to be_failure
+ expect(payment.reload.status).to eq('invalid')
+ end
+ end
+
+ describe 'retrying' do
+ it 'processes a failed payment again — the failure may have been transient' do
+ payment.update_column(:status, 'failed')
+ allow(gateway).to receive(:capture_at_checkout?).and_return(false)
+ expect(gateway).to receive(:authorize).and_return(success_response)
+
+ expect(described_class.call(payment: payment)).to be_success
+ expect(payment.reload).to be_pending
+ end
+ end
+
+ describe 'racing a concurrent settlement' do
+ it 'reports success without the gateway when the webhook settled it first' do
+ Spree::Payment.find(payment.id).update_columns(status: 'completed')
+ expect(gateway).not_to receive(:authorize)
+
+ result = described_class.call(payment: payment) # stale: still reads checkout
+
+ expect(result).to be_success
+ expect(payment.reload).to be_completed
+ end
+ end
+
+ describe 'hooks' do
+ it 'lets a validate handler veto before the gateway is called' do
+ expect(gateway).not_to receive(:authorize)
+ Spree.hooks.register('payments.process.validate') { |flow| flow.reject!('review first') }
+
+ result = described_class.call(payment: payment)
+
+ expect(result).to be_failure
+ expect(result.error.to_s).to eq('review first')
+ end
+ end
+end
diff --git a/spree/core/spec/workflows/spree/payments/void_spec.rb b/spree/core/spec/workflows/spree/payments/void_spec.rb
index 8868dbba39..fcde2e671a 100644
--- a/spree/core/spec/workflows/spree/payments/void_spec.rb
+++ b/spree/core/spec/workflows/spree/payments/void_spec.rb
@@ -1,28 +1,61 @@
require 'spec_helper'
RSpec.describe Spree::Payments::Void do
- let(:payment) { create(:payment, state: 'pending', amount: 45.75) }
+ let(:store) { @default_store }
+ let(:gateway) do
+ gateway = store.payment_methods.create!(type: 'Spree::Gateway::Bogus', active: true)
+ allow(gateway).to receive_messages(source_required: true)
+ gateway
+ end
+ let(:card) { create(:credit_card) }
+ let(:payment) do
+ create(:payment, payment_method: gateway, source: card, status: 'pending',
+ amount: 45.75, response_code: '123')
+ end
+ let(:success_response) do
+ Spree::PaymentResponse.new(true, nil, {}, authorization: '456', avs_result: { code: 'D' })
+ end
+ let(:failed_response) { Spree::PaymentResponse.new(false, 'cannot void') }
before { Spree.hooks.clear! }
after { Spree.hooks.clear! }
describe 'voiding' do
- it 'voids the payment at the gateway' do
- expect(payment).to receive(:void_transaction!).and_return(true)
+ it 'voids the payment at the gateway and records the new authorization' do
+ expect(gateway).to receive(:void).with('123', card, anything).and_return(success_response)
+
+ result = described_class.call(payment: payment)
+
+ expect(result).to be_success
+ expect(payment.reload).to be_void
+ expect(payment.response_code).to eq('456')
+ end
+
+ it 'voids without the source when the gateway has no payment profiles' do
+ allow(gateway).to receive(:payment_profiles_supported?).and_return(false)
+ expect(gateway).to receive(:void).with('123', anything).and_return(success_response)
+
+ expect(described_class.call(payment: payment)).to be_success
+ end
+
+ it 'voids without calling the gateway when nothing ever reached it' do
+ payment.update_column(:response_code, nil)
+ expect(gateway).not_to receive(:void)
expect(described_class.call(payment: payment)).to be_success
+ expect(payment.reload).to be_void
end
it 'is a no-op for an already-void payment' do
- voided = create(:payment, state: 'void')
- expect(voided).not_to receive(:void_transaction!)
+ voided = create(:payment, payment_method: gateway, source: card, status: 'void')
+ expect(gateway).not_to receive(:void)
expect(described_class.call(payment: voided)).to be_success
end
it 'fails without calling the gateway when the payment cannot be voided' do
- failed = create(:payment, state: 'failed')
- expect(failed).not_to receive(:void_transaction!)
+ failed = create(:payment, payment_method: gateway, source: card, status: 'failed')
+ expect(gateway).not_to receive(:void)
result = described_class.call(payment: failed)
@@ -30,19 +63,20 @@ RSpec.describe Spree::Payments::Void do
expect(result.error.value).to eq(:payment_not_voidable)
end
- it 'surfaces a gateway error as a failure result' do
- allow(payment).to receive(:void_transaction!).and_raise(Spree::Core::GatewayError, 'cannot void')
+ it 'surfaces a gateway failure as a failure result and does not void' do
+ allow(gateway).to receive(:void).and_return(failed_response)
result = described_class.call(payment: payment)
expect(result).to be_failure
expect(result.error.value).to eq('cannot void')
+ expect(payment.reload).not_to be_void
end
end
describe 'hooks' do
it 'lets a validate handler veto the void before the gateway is called' do
- expect(payment).not_to receive(:void_transaction!)
+ expect(gateway).not_to receive(:void)
Spree.hooks.register('payments.void.validate') { |flow| flow.reject!('under review') }
result = described_class.call(payment: payment)
@@ -52,7 +86,7 @@ RSpec.describe Spree::Payments::Void do
end
it 'runs after_void once the gateway call succeeds' do
- allow(payment).to receive(:void_transaction!).and_return(true)
+ allow(gateway).to receive(:void).and_return(success_response)
voided = false
Spree.hooks.register('payments.void.after_void') { |_flow| voided = true }
diff --git a/spree/core/spec/workflows/spree/refunds/create_spec.rb b/spree/core/spec/workflows/spree/refunds/create_spec.rb
index 7c69aafc95..5c0ff3c10f 100644
--- a/spree/core/spec/workflows/spree/refunds/create_spec.rb
+++ b/spree/core/spec/workflows/spree/refunds/create_spec.rb
@@ -1,7 +1,7 @@
require 'spec_helper'
RSpec.describe Spree::Refunds::Create do
- let(:payment) { create(:payment, state: 'completed', amount: 45.75) }
+ let(:payment) { create(:payment, status: 'completed', amount: 45.75) }
before do
Spree.hooks.clear!
@@ -37,7 +37,7 @@ RSpec.describe Spree::Refunds::Create do
end
it 'refuses to refund a payment that was never captured' do
- pending_payment = create(:payment, state: 'pending')
+ pending_payment = create(:payment, status: 'pending')
result = described_class.call(payment: pending_payment)
diff --git a/spree/providers/stripe/app/models/spree_stripe/gateway/payment_setup_sessions.rb b/spree/providers/stripe/app/models/spree_stripe/gateway/payment_setup_sessions.rb
index caedb27ee8..1719ce2af0 100644
--- a/spree/providers/stripe/app/models/spree_stripe/gateway/payment_setup_sessions.rb
+++ b/spree/providers/stripe/app/models/spree_stripe/gateway/payment_setup_sessions.rb
@@ -41,13 +41,17 @@ module SpreeStripe
stripe_payment_method = stripe_setup_intent.payment_method
- setup_session.payment_source = SpreeStripe::CreateSource.new(
- stripe_payment_method_details: stripe_payment_method,
- stripe_payment_method_id: stripe_payment_method.id,
- stripe_billing_details: stripe_payment_method.billing_details,
- gateway: self,
- customer: setup_session.customer
- ).call
+ # Persisted explicitly — a status transition writes status alone,
+ # never a ride-along for other dirty attributes.
+ setup_session.update!(
+ payment_source: SpreeStripe::CreateSource.new(
+ stripe_payment_method_details: stripe_payment_method,
+ stripe_payment_method_id: stripe_payment_method.id,
+ stripe_billing_details: stripe_payment_method.billing_details,
+ gateway: self,
+ customer: setup_session.customer
+ ).call
+ )
setup_session.complete unless setup_session.completed?
else