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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Rename Shipments::Update and RecomputeStatuses to their 6.0 names
Damian Legawiecdeb15c8296fd
diff --git a/CLAUDE.md b/CLAUDE.mdindex bd91b5d4e1..097b0fc717 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -13,7 +13,7 @@ Use `/project:create-plan` and `/project:update-plan` for plan management.Active plans (6.0 target, work pending):- `6.0-multi-vendor-marketplace.md` — Open-source the marketplace core (Vendor, OrderGroup-based order splitting, commission engine with EU commission taxation, `VendorTransfer`/`VendorPayout` ledger + pluggable `PayoutProvider`) per spree/spree#13323. 6.0 headline feature; rebuilds the legacy Enterprise multi-vendor module as native models on the Cart/Order split. Basic Stripe Connect payouts (Express onboarding + on-fulfillment transfers) ship OSS in the monorepo, alongside the Stripe core gateway pulled in from the standalone `spree_stripe` repo (payment-sessions classes only, likely `spree/core` — decisions.md 2026-07-15); Enterprise keeps refund clawbacks/netting, reconciliation, KYC ops, DAC7 payout reports, facilitator taxes + Shopify/WooCommerce vendor apps.-- `6.0-cart-order-split.md` — Cart/Order model separation, dual-FK owner everywhere (`cart_id`/`order_id` exactly-one, `#owner` as method — NOT polymorphic), idempotent copy-on-completion (`Order#cart_id` unique, order-before-payment), Order state machine removed (Checkout::Requirements for steps; payment/fulfillment statuses derived-then-persisted via one recompute service). **Shipped to 6-0-dev (feature/6-0-core-rewrite Waves 1+5):** Cart owns checkout end to end, machine + `spree_orders.state` gone, `Carts::Complete` three-phase pipeline live, `Orders::RecomputeStatuses` sole status writer; only Wave 7 data migration (incomplete orders → carts) remains+- `6.0-cart-order-split.md` — Cart/Order model separation, dual-FK owner everywhere (`cart_id`/`order_id` exactly-one, `#owner` as method — NOT polymorphic), idempotent copy-on-completion (`Order#cart_id` unique, order-before-payment), Order state machine removed (Checkout::Requirements for steps; payment/fulfillment statuses derived-then-persisted via one recompute service). **Shipped to 6-0-dev (feature/6-0-core-rewrite Waves 1+5):** Cart owns checkout end to end, machine + `spree_orders.state` gone, `Carts::Complete` three-phase pipeline live, `Orders::UpdateStatuses` sole status writer; only Wave 7 data migration (incomplete orders → carts) remains- `6.0-admin-api.md` — Admin REST API conventions, auth, endpoint list (~300 endpoints)- `6.0-admin-spa.md` — React admin architecture, extension points, table registry, i18n + server-error mapping- `6.0-product-types.md` — Prototype → ProductType rename, MetafieldDefinition schema enforcementdiff --git a/docs/plans/6.0-cart-order-split.md b/docs/plans/6.0-cart-order-split.mdindex 273824f84a..ed79d5012a 100644--- a/docs/plans/6.0-cart-order-split.md+++ b/docs/plans/6.0-cart-order-split.md@@ -58,7 +58,7 @@ Every competitor treats this as load-bearing. `Spree::Carts::Complete`:**(b) Transition-triggered recalculation → recalculation-on-write.** Today tax/prices/shipment rebuilds fire *only* on state transitions (4 call sites) — an address changed in place at `payment` never re-runs tax. The Cart model recalculates explicitly on the writes that matter: address/market change → re-price, re-tax, rebuild delivery proposals (the destructive `create_proposed_shipments` behavior becomes an idempotent cart-side rebuild; the order's fulfillments are a frozen copy, never rebuilt); item changes → totals + reservations (the existing Release/Reserve/Extend dispatch in `Carts::Update` carries over). The stale memoized `tax_zone` hazard dies with the memoized order context.-**(c) Statuses → derive-then-persist (OSS platform B's hybrid, explicitly not OSS platform A's pure derivation).** OSS platform A derives payment/fulfillment status at read time and has open bugs to show for it (can't filter/sort admin order lists — #14095; status stuck after full return — #13882); the hosted market leader has the analogous `financial_status:expired` filter-index bug. Spree's admin is Ransack-heavy — pure derivation breaks order-list filtering on day one. So: `payment_status` and `fulfillment_status` are **stored, indexed string columns** (names per the normalize plan), recomputed by a single `Spree::Orders::RecomputeStatuses` service triggered from payment/fulfillment/refund/return event subscribers. One writer, many triggers. Rules that competitors learned the hard way: quantize money to currency precision **before** comparing; subtract granted/pending refunds from the total before comparing; include `overcharged` (OSS platform B) and `voided` (the hosted market leader) in the payment domain; define the returns interplay explicitly (where OSS platform A's derivation broke). The `fulfillment_status` domain (incl. `backorder`) is owned by `6.0-fulfillment-and-delivery.md`.+**(c) Statuses → derive-then-persist (OSS platform B's hybrid, explicitly not OSS platform A's pure derivation).** OSS platform A derives payment/fulfillment status at read time and has open bugs to show for it (can't filter/sort admin order lists — #14095; status stuck after full return — #13882); the hosted market leader has the analogous `financial_status:expired` filter-index bug. Spree's admin is Ransack-heavy — pure derivation breaks order-list filtering on day one. So: `payment_status` and `fulfillment_status` are **stored, indexed string columns** (names per the normalize plan), recomputed by a single `Spree::Orders::UpdateStatuses` service triggered from payment/fulfillment/refund/return event subscribers. One writer, many triggers. Rules that competitors learned the hard way: quantize money to currency precision **before** comparing; subtract granted/pending refunds from the total before comparing; include `overcharged` (OSS platform B) and `voided` (the hosted market leader) in the payment domain; define the returns interplay explicitly (where OSS platform A's derivation broke). The `fulfillment_status` domain (incl. `backorder`) is owned by `6.0-fulfillment-and-delivery.md`.### 6. Order lifecycle stays on Order, without a machine@@ -138,7 +138,7 @@ PHASE F — FINALIZE (one transaction; every step idempotent)F3. Vendor split hook (multi-vendor Phase 3): partition → child orders +OrderGroup; completion_result becomes the groupF4. order.status: 'draft' → 'placed'; cart.completed_at stamped;- completing_at cleared; RecomputeStatuses+ completing_at cleared; UpdateStatusesF5. after_commit: publish order.placed / order.completed (notify_customerhonored), digital fulfillment via FulfillmentProvider::Digital,user-account creation + newsletter subscribe (non-fatal side jobs)@@ -160,7 +160,7 @@ PHASE F — FINALIZE (one transaction; every step idempotent)**Not every payment method is an external gateway.** Offline methods — `PaymentMethod::Check`, B2B on-account/net-terms, cash on delivery, bank transfer, and anything recorded through the manual payments API — already flow through the same `process_payments!` seam but perform **no external I/O**: the method returns a local success response, and `auto_capture?` decides whether the payment lands `pending` (authorized, captured later by an admin when the invoice is settled) or `completed`. Consequences for this pipeline:- **Offline payments collapse PAYMENT into FINALIZE.** With no network call there is nothing to compensate and no partial-failure window, so the whole completion is a single transaction. The three-phase shape exists for external gateways; offline methods take the degenerate path.-- **`payment_required?` is not "must be paid now".** A net-terms order completes with `payment_total: 0` and a `pending` payment — that is a *successfully completed, unpaid* order, not a failure. Completion must gate on "a valid payment exists covering the total" (today's `pending_payments.any? && unprocessed_payments.empty?` guard), never on `paid?`. `RecomputeStatuses` reports `payment_status: none/authorized`; dunning and capture are post-completion admin/AR concerns.+- **`payment_required?` is not "must be paid now".** A net-terms order completes with `payment_total: 0` and a `pending` payment — that is a *successfully completed, unpaid* order, not a failure. Completion must gate on "a valid payment exists covering the total" (today's `pending_payments.any? && unprocessed_payments.empty?` guard), never on `paid?`. `UpdateStatuses` reports `payment_status: none/authorized`; dunning and capture are post-completion admin/AR concerns.- **Store credit and gift cards are offline by the same rule** — already true today (`recalculate_store_credit_payment` in P3, store-credit payments voided last on compensation).- **Mixed offline + external** (deposit on card, remainder on terms): any external component forces the external path; the offline components are processed inside the same phase and voided alongside on compensation.- **B2B/backoffice orders** created through the Admin API bypass this pipeline's checkout ergonomics but must reuse the same service so idempotency, inventory finalization, and reservation release stay in one place — fixing today's asymmetry where `Orders::Complete` never releases reservations.@@ -198,7 +198,7 @@ PHASE F — FINALIZE (one transaction; every step idempotent)### Status recomputation```ruby-Spree::Orders::RecomputeStatuses.call(order:) # the ONLY writer of both columns+Spree::Orders::UpdateStatuses.call(order:) # the ONLY writer of both columns# payment_status: quantized(captured + charged) vs quantized(total − granted_refunds)# → none/authorized/partially_paid/paid/partially_refunded/refunded/# overcharged/voided@@ -210,7 +210,7 @@ Triggered by subscribers on payment, refund, fulfillment, and return events —### Completion side-effect parity checklist-Everything today's `finalize!` + `after_transition to: :complete` chain does is accounted for in the flow above or explicitly relocated: adjustment freeze (→ split-adjustments order-level freeze), payment/shipment status updates (→ RecomputeStatuses), `status: 'placed'`, `completed_at`, update hooks, risk check (`considered_risky` + `order.updated`), `order.completed` event, coupon-code use, gift-card redeem, newsletter subscribe, user-account creation, digital links (→ `FulfillmentProvider::Digital`, idempotent + per-quantity — fixing the current checkout-callback's non-idempotent one-per-line-item behavior), confirmation email (already event-driven via the emails subscriber; unchanged).+Everything today's `finalize!` + `after_transition to: :complete` chain does is accounted for in the flow above or explicitly relocated: adjustment freeze (→ split-adjustments order-level freeze), payment/shipment status updates (→ UpdateStatuses), `status: 'placed'`, `completed_at`, update hooks, risk check (`considered_risky` + `order.updated`), `order.completed` event, coupon-code use, gift-card redeem, newsletter subscribe, user-account creation, digital links (→ `FulfillmentProvider::Digital`, idempotent + per-quantity — fixing the current checkout-callback's non-idempotent one-per-line-item behavior), confirmation email (already event-driven via the emails subscriber; unchanged).## Migration Path@@ -228,7 +228,7 @@ Cart model + recalculation-on-write; `Carts::Complete` rewrite (flow above); Reg### Phase 4 — remove the machine-Delete `Order::Checkout`, the state column, `checkout_flow` API, order `state_changes` writes; Ransack whitelist swap; RecomputeStatuses + subscribers; the six out-of-band `state` writers (address services etc.) become cart-recalculation triggers.+Delete `Order::Checkout`, the state column, `checkout_flow` API, order `state_changes` writes; Ransack whitelist swap; UpdateStatuses + subscribers; the six out-of-band `state` writers (address services etc.) become cart-recalculation triggers.### Phase 5 — API/SDK/dashboard/docsdiff --git a/docs/plans/6.0-core-rewrite-tasks.md b/docs/plans/6.0-core-rewrite-tasks.mdindex 09a6700ad5..1d9557c967 100644--- a/docs/plans/6.0-core-rewrite-tasks.md+++ b/docs/plans/6.0-core-rewrite-tasks.md@@ -39,7 +39,7 @@1. **Fulfillment renames before split-adjustments tables** — the typed tables are *born* with `fulfillment_id` (both plans mandate born-correct, never-migrated columns).2. **Split-adjustments + fulfillment providers before the Cart flip** — `Carts::Complete`'s copy contract (line items, addresses, fulfillments + selected rates, typed money lines) is written **once**, against final vocabulary. Flipping first would mean writing throwaway copy code for legacy shipments/polymorphic adjustments.-3. **Machine removal is its own wave after the flip** — requirements-driven checkout must be live and `RecomputeStatuses` in place before `spree_orders.state` and `Order::Checkout` are deleted.+3. **Machine removal is its own wave after the flip** — requirements-driven checkout must be live and `UpdateStatuses` in place before `spree_orders.state` and `Order::Checkout` are deleted.4. **Data rake tasks last** — every task reads legacy structures that deliberately stay in place: `spree_adjustments` (read-only through 6.0 as audit/rollback), `spree_zones` (until tax decouples), ShippingCategory tables (drop in 6.1), incomplete orders (converted to carts by `completed_at`, not `state`).Each wave must land with its engine suites green (`parallel_rspec` core + api + emails, plus dashboard tests where touched) before the next starts.@@ -209,7 +209,7 @@ Runs after Wave 2 (tables born with `fulfillment_id`). Can proceed in parallel w**Gates: core 6643/0 (parallel), api 2474/0 (parallel), emails 102/0.** One commit. Migration layout after the 2026-07-29 review consolidation: `20260728000003_create_spree_carts` fully defines spree_carts (all money/count columns with DB defaults, standardized names `discount_total`/`total_quantity`, coupon_code, gift_card_id, lock_version default 0), `20260729100001` keeps only the cross-table owner refs (cart_id on order_promotions/payment_sessions/payments/stock_reservations/coupon_codes) + `remove_column :spree_orders, :state`, `20260729100002` (order_id nullable on stock_reservations/payment_sessions), `20260729120001` renames spree_orders `promo_total`→`discount_total`, `item_count`→`total_quantity` (legacy names stay as alias_attribute bridges one release; internal code uses real names). spree_carts.market_id/channel_id are `null: false` at the DB (2026-07-29 — every store owns a bootstrap default market/channel); spree_orders keeps them nullable through 6.0 (pre-5.5 rows) — the `spree:backfill_order_markets` manifest step resolves market from store defaults (channel_id was already backfilled by the 5.4→5.5 channels step) and the NOT NULL constraints land in 6.1.- **Cart owns checkout end to end.** Full surface on `Spree::Cart` (totals + DisplayMoney incl. store-credit/gift-card money, checkout steps via Requirements, market/channel presence resolution, warnings, rebuild_fulfillments! idempotent proposal rebuild + prune_undeliverable_fulfillments!, merge!/associate_user!, store-credit quartet + `total_available_store_credit`/`could_use_store_credit?`/`total_minus_store_credits`, gift card apply/remove/redeem/recalculate ported, `update_hooks` registry unioned with Order's so legacy Order-registered hooks fire during checkout). `CartUpdater < OrderUpdater`.-- **Machine gone.** `Order::Checkout` is a lean data module (checkout_steps/current/completed via Requirements + newsletter/user-record/default-addresses). No `state` column, no `next!`/`checkout_flow`/`insert_checkout_step`/`update_from_params`. Lifecycle = `status` draft/placed/canceled + derived predicates; cancel/resume keep side effects verbatim. `Orders::RecomputeStatuses` is the sole payment/fulfillment status writer.+- **Machine gone.** `Order::Checkout` is a lean data module (checkout_steps/current/completed via Requirements + newsletter/user-record/default-addresses). No `state` column, no `next!`/`checkout_flow`/`insert_checkout_step`/`update_from_params`. Lifecycle = `status` draft/placed/canceled + derived predicates; cancel/resume keep side effects verbatim. `Orders::UpdateStatuses` is the sole payment/fulfillment status writer.- **`Carts::Complete` three-phase pipeline** (replay → lock+TTL takeover → in-lock recalc → drift guard 409 → validate → draft order + copy contract; offline payment collapses into finalize; external outside txn with Y3 compensation; finalize idempotent). Admin/B2B path `Orders::Complete` delegates into it and now honors `payment_pending:`/`notify_customer:` (kwargs restored for the admin API).- **Owner XOR everywhere** (LineItem, Payment, PaymentSession, Fulfillment, StockReservation, OrderPromotion, CouponCode, typed lines) with a uniform **`order=` cart-routing bridge** on every dual-FK model: assigning a `Spree::Cart` to the legacy `order` association routes to the cart FK (extensions assign `current_order`, which is now a Cart). `PaymentSession#owner=` lets gateways stay owner-agnostic (`Gateway::Bogus` uses it); session internals (`store` delegate, `find_or_create_payment!`, defaults) swept to owner. `Fulfillment#selected_shipping_rate_id=`/cost-recalc hooks owner-dispatched. Payment-session serializer: `order_id` reports owner (bridge), new `cart_id` attribute.- **Deprecated twins added on Cart** (`shipments`, `create_proposed_shipments`, `set_shipments_cost`) so legacy call sites keep working one release.@@ -230,7 +230,7 @@ The point of no return; biggest single wave. Everything before it exists so this### T5.2 `Carts::Complete` — three-phase pipeline- [x] **PREPARE** (one txn): replay via `completion_result(cart)` (order or order_group); `with_lock` + `completing_at` with TTL takeover; in-lock recalculation; `expected_total` drift guard (409 `cart_changed`); Validate; reservation availability check + hold extension; draft Order creation with copies (line items re-pointed, typed lines per the split-adjustments copy contract, fulfillments + selected rates, **address copies**, email/currency/locale/market/channel, guest token carried, `R` number) + unique `orders.cart_id`.- [x] **PAYMENT:** offline methods (Check, terms, COD, bank transfer, store credit, gift cards, manual) collapse into FINALIZE — single txn, nothing to compensate; external gateways outside any txn with Y3 compensation (destroy draft + copies, clear `completing_at`, 422 `payment_failed`); completion gates on "valid payment covers total", never `paid?`; store credit recalculated in P3 and voided last; `allow_checkout_on_gateway_error` external-only.-- [x] **FINALIZE** (one txn, every step idempotent): inventory finalize + unstock + reservation release (single home — fixes the admin-path asymmetry); counters behind persisted flags (coupon, gift card redeem, promo credits); vendor-split hook F3 (no-op single partition); `draft`→`placed` + `cart.completed_at` + `RecomputeStatuses`; after_commit events (`order.placed`/`order.completed`), digital fulfillment via provider, account creation/newsletter as non-fatal side jobs.+- [x] **FINALIZE** (one txn, every step idempotent): inventory finalize + unstock + reservation release (single home — fixes the admin-path asymmetry); counters behind persisted flags (coupon, gift card redeem, promo credits); vendor-split hook F3 (no-op single partition); `draft`→`placed` + `cart.completed_at` + `UpdateStatuses`; after_commit events (`order.placed`/`order.completed`), digital fulfillment via provider, account creation/newsletter as non-fatal side jobs.- [x] Resumability structural (`status: 'draft'` + `cart_id` + `completed_at: nil` = finalize pending); completion-recovery sweeper job (retries FINALIZE for stale drafts with paid coverage; alerts on persistent failure; **never auto-refunds**); webhook writer (`Payments::HandleWebhook`) converges on the same service — 30s delay becomes latency optimization only.- [x] Mutation guards: `completing_at` → 409 `cart_locked` on item/address/discount writes; `lock_version` → 409 `stale_cart`.- [x] Admin/B2B `Orders::Complete` path reuses the same service (idempotency + inventory + reservation release in one place).@@ -245,8 +245,8 @@ The point of no return; biggest single wave. Everything before it exists so this- [x] Ransack whitelist: `state` out; `status`/`payment_status`/`fulfillment_status` in.- [x] The six out-of-band `state` writers (address services etc.) become cart-recalculation triggers.-### T5.4 `RecomputeStatuses` (single writer)-- [x] `Spree::Orders::RecomputeStatuses` — the only writer of `payment_status` + `fulfillment_status`; quantize to currency precision before comparing; subtract granted/pending refunds; domains incl. `overcharged`/`voided` (payment) and `backorder` (fulfillment, owned by the fulfillment plan); triggered from payment/refund/fulfillment/return event subscribers, never inline from controllers; replaces `OrderUpdater#update_payment_state`/`update_shipment_state`.+### T5.4 `UpdateStatuses` (single writer)+- [x] `Spree::Orders::UpdateStatuses` — the only writer of `payment_status` + `fulfillment_status`; quantize to currency precision before comparing; subtract granted/pending refunds; domains incl. `overcharged`/`voided` (payment) and `backorder` (fulfillment, owned by the fulfillment plan); triggered from payment/refund/fulfillment/return event subscribers, never inline from controllers; replaces `OrderUpdater#update_payment_state`/`update_shipment_state`.### T5.5 Test support rewrite- [x] `order_walkthrough` cart-first; order/cart factories (order factories build completed orders through the real completion service or direct construction — decide pattern here); whole-suite green across engines.diff --git a/spree/admin/app/controllers/spree/admin/shipments_controller.rb b/spree/admin/app/controllers/spree/admin/shipments_controller.rbindex 6a4487b383..7f850ad845 100644--- a/spree/admin/app/controllers/spree/admin/shipments_controller.rb+++ b/spree/admin/app/controllers/spree/admin/shipments_controller.rb@@ -11,7 +11,7 @@ module Spreebefore_action :refresh_shipping_rates, only: :editdef update- @result = Spree.shipment_update_service.call(shipment: @shipment, shipment_attributes: permitted_resource_params)+ @result = Spree.fulfillment_update_service.call(fulfillment: @shipment, fulfillment_attributes: permitted_resource_params)flash[:success] = Spree.t(:successfully_updated, resource: Spree.t(:shipment)) if @result.success?redirect_back fallback_location: spree.edit_admin_order_path(@order)diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rbindex bea636016d..88918ed78b 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb@@ -42,9 +42,9 @@ module Spree# PATCH /api/v3/admin/orders/:order_id/fulfillments/:iddef updatewith_order_lock do- result = Spree.shipment_update_service.call(- shipment: @resource,- shipment_attributes: permitted_params.to_h+ result = Spree.fulfillment_update_service.call(+ fulfillment: @resource,+ fulfillment_attributes: permitted_params.to_h)if result.success?diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rbindex 7d97a47001..430c04d56b 100644--- a/spree/core/app/models/spree/fulfillment.rb+++ b/spree/core/app/models/spree/fulfillment.rb@@ -570,10 +570,6 @@ module Spreeendend- def update_attributes_and_order(params = {})- Shipments::Update.call(shipment: self, shipment_attributes: params).success?- end-# Updates various aspects of the Shipment while bypassing any callbacks. Note that this method takes an explicit reference to the# Order object. This is necessary because the association actually has a stale (and unsaved) copy of the Order and so it will not# yield the correct results.@@ -632,7 +628,7 @@ module Spreedef update_order_fulfillment_statusreturn if order.nil?- Spree::Orders::RecomputeStatuses.call(order: order)+ order.update_statuses!end# publish_shipment_shipped_event, publish_shipment_canceled_event, anddiff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 85c6412752..1dbad9cf1b 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -501,6 +501,13 @@ module SpreeSpree.order_recalculate_totals_workflow.call(order: self)end+ # Derives and persists payment_status / fulfillment_status from the+ # order's payment, refund and fulfillment records. Convenience for+ # {Spree::Orders::UpdateStatuses}, the sole status writer.+ def update_statuses!+ Spree.order_update_statuses_service.call(order: self)+ end+# @deprecated Use {#recalculate_totals!}; removed in 6.1.def update_with_updater!Spree::Deprecation.warn('Spree::Order#update_with_updater! is deprecated and will be removed in Spree 6.1. Use #recalculate_totals! instead.')@@ -689,7 +696,7 @@ module SpreeSpree::Fulfillments::AutoFulfill.call(order: self)- Spree::Orders::RecomputeStatuses.call(order: self)+ update_statuses!publish_order_placed_eventend@@ -697,7 +704,7 @@ module Spreedef fulfill!fulfillments.each { |shipment| shipment.update!(self) if shipment.persisted? }save!- Spree::Orders::RecomputeStatuses.call(order: self)+ update_statuses!end# Helper methods for checkout stepsdiff --git a/spree/core/app/models/spree/order_updater.rb b/spree/core/app/models/spree/order_updater.rbindex 1234734865..2ca506ad6a 100644--- a/spree/core/app/models/spree/order_updater.rb+++ b/spree/core/app/models/spree/order_updater.rb@@ -103,7 +103,7 @@ module Spreeend# Money only — payment_status/fulfillment_status are written exclusively- # by Spree::Orders::RecomputeStatuses, triggered from+ # by Spree::Orders::UpdateStatuses, triggered from# Spree::OrderStatusSubscriber on payment/refund/fulfillment/return# events (never inline here: those records change without any money# recalculation running, and most recalculations change no statusdiff --git a/spree/core/app/models/spree/payment.rb b/spree/core/app/models/spree/payment.rbindex f98924cc22..5d38bc1a4b 100644--- a/spree/core/app/models/spree/payment.rb+++ b/spree/core/app/models/spree/payment.rb@@ -393,7 +393,7 @@ module Spreereturn unless completed? || void? || (owner.is_a?(Spree::Order) && owner.completed?)owner.recalculate_totals!- Spree::Orders::RecomputeStatuses.call(order: owner) if owner.is_a?(Spree::Order) && owner.completed?+ owner.update_statuses! if owner.is_a?(Spree::Order) && owner.completed?enddef create_eligible_credit_eventdiff --git a/spree/core/app/services/spree/fulfillments/update.rb b/spree/core/app/services/spree/fulfillments/update.rbnew file mode 100644index 0000000000..83a702f738--- /dev/null+++ b/spree/core/app/services/spree/fulfillments/update.rb@@ -0,0 +1,48 @@+# Update a Fulfillment and make sure the owning Order's totals and+# statuses follow the fulfillment changes+module Spree+ module Fulfillments+ class Update+ prepend Spree::ServiceModule::Base++ def call(fulfillment: nil, fulfillment_attributes: nil, shipment: nil, shipment_attributes: nil)+ if shipment || shipment_attributes+ Spree::Deprecation.warn(+ 'Calling Spree::Fulfillments::Update with shipment:/shipment_attributes: keywords is deprecated ' \+ 'and will be removed in Spree 6.1. Use fulfillment:/fulfillment_attributes: instead.'+ )+ fulfillment ||= shipment+ fulfillment_attributes ||= shipment_attributes+ end+ fulfillment_attributes ||= {}++ ActiveRecord::Base.transaction do+ return failure(fulfillment) unless fulfillment.update(fulfillment_attributes)++ if fulfillment_attributes.key?(:selected_shipping_rate_id) || fulfillment_attributes.key?(:selected_delivery_rate_id)+ order = fulfillment.order++ # Changing the selected Delivery Rate won't update the cost (for now)+ # so we persist the Fulfillment#cost before calculating order delivery+ # total and updating payment status (given a change in fulfillment cost+ # might change the Order#payment_status)+ fulfillment.update_amounts++ order.recalculate_totals!++ # Update fulfillment status only after order total is updated because it+ # (via Order#paid?) affects the fulfillment status (YAY)+ fulfillment.update_columns(+ status: fulfillment.determine_state(order),+ updated_at: Time.current+ )++ # And then derive the order-level statuses from the new status+ order.update_statuses!+ end+ end+ success(fulfillment)+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/orders/recompute_statuses.rb b/spree/core/app/services/spree/orders/update_statuses.rbsimilarity index 99%rename from spree/core/app/services/spree/orders/recompute_statuses.rbrename to spree/core/app/services/spree/orders/update_statuses.rbindex 48c69e2c53..d0c324a6fa 100644--- a/spree/core/app/services/spree/orders/recompute_statuses.rb+++ b/spree/core/app/services/spree/orders/update_statuses.rb@@ -5,7 +5,7 @@ module Spree# fulfillment records and stored in indexed columns so admin filtering# keeps working. Triggered from payment/refund/fulfillment/return event# subscribers — never inline from controllers.- class RecomputeStatuses+ class UpdateStatusesprepend Spree::ServiceModule::BasePAYMENT_STATUSES = %w[none authorized partially_paid paid partially_refunded refunded overcharged voided].freezediff --git a/spree/core/app/services/spree/shipments/update.rb b/spree/core/app/services/spree/shipments/update.rbindex 9159934d66..26d1991137 100644--- a/spree/core/app/services/spree/shipments/update.rb+++ b/spree/core/app/services/spree/shipments/update.rb@@ -1,36 +1,10 @@-# Update Shipment and make sure Order states follow the shipment changesmodule Spreemodule Shipments+ # @deprecated Use {Spree::Fulfillments::Update}; removed in 6.1.class Update- prepend Spree::ServiceModule::Base-- def call(shipment:, shipment_attributes: {})- ActiveRecord::Base.transaction do- return failure(shipment) unless shipment.update(shipment_attributes)-- if shipment_attributes.key?(:selected_shipping_rate_id) || shipment_attributes.key?(:selected_delivery_rate_id)- order = shipment.order-- # Changing the selected Shipping Rate won't update the cost (for now)- # so we persist the Shipment#cost before calculating order shipment- # total and updating payment state (given a change in shipment cost- # might change the Order#payment_state)- shipment.update_amounts-- order.recalculate_totals!-- # Update shipment state only after order total is updated because it- # (via Order#paid?) affects the shipment state (YAY)- shipment.update_columns(- state: shipment.determine_state(order),- updated_at: Time.current- )-- # And then derive the order-level statuses from the new state- Spree::Orders::RecomputeStatuses.call(order: order)- end- end- success(shipment)+ def self.call(shipment:, shipment_attributes: {}, &block)+ Spree::Deprecation.warn('Spree::Shipments::Update is deprecated and will be removed in Spree 6.1. Use Spree::Fulfillments::Update instead.')+ Spree::Fulfillments::Update.call(fulfillment: shipment, fulfillment_attributes: shipment_attributes, &block)endendenddiff --git a/spree/core/app/subscribers/spree/order_status_subscriber.rb b/spree/core/app/subscribers/spree/order_status_subscriber.rbindex 7ef1e96b7a..7d89c3b0c2 100644--- a/spree/core/app/subscribers/spree/order_status_subscriber.rb+++ b/spree/core/app/subscribers/spree/order_status_subscriber.rb@@ -2,7 +2,7 @@ module Spree# The trigger side of derive-then-persist statuses: any payment, refund,# fulfillment or return-item change recomputes the owning order's# payment_status / fulfillment_status through the single writer- # (Spree::Orders::RecomputeStatuses). Synchronous so API responses right+ # (Spree::Orders::UpdateStatuses). Synchronous so API responses right# after a capture/void/fulfill already carry the fresh status. Cart-owned# records are skipped — carts have no status columns.class OrderStatusSubscriber < Spree::Subscriber@@ -17,7 +17,7 @@ module Spreeorder = order_for(event)return unless order- Spree::Orders::RecomputeStatuses.call(order: order)+ order.update_statuses!endprivatediff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rbindex e04a2ab6b8..6b07af2c42 100644--- a/spree/core/app/workflows/spree/carts/complete.rb+++ b/spree/core/app/workflows/spree/carts/complete.rb@@ -13,7 +13,7 @@ module Spree# pre-capture failure pops the armed# on_flow_failure compensation# FINALIZE (own txn) inventory + counters + draft→placed +- # cart.completed_at + RecomputeStatuses;+ # cart.completed_at + UpdateStatuses;# events after commitclass Complete < Spree::WorkflowCOMPLETING_TTL = 5.minutes@@ -78,7 +78,7 @@ module Spreeorder.finalize! unless order.completed?Spree::StockReservations::Release.call(owner: order)- Spree::Orders::RecomputeStatuses.call(order: order)+ order.update_statuses!endhalt!(order)@@ -303,7 +303,7 @@ module Spreecart.update_columns(completed_at: Time.current, completing_at: nil)endSpree::StockReservations::Release.call(owner: order)- Spree::Orders::RecomputeStatuses.call(order: order)+ order.update_statuses!mark_coupon_codes_used!(cart, order)enddiff --git a/spree/core/app/workflows/spree/carts/recalculate_totals.rb b/spree/core/app/workflows/spree/carts/recalculate_totals.rbindex 13b1a0b147..a920dd6981 100644--- a/spree/core/app/workflows/spree/carts/recalculate_totals.rb+++ b/spree/core/app/workflows/spree/carts/recalculate_totals.rb@@ -2,7 +2,7 @@ module Spreemodule Carts# Money recalculation — item counts, money totals, one update_columns# persist. Money ONLY: payment_status/fulfillment_status are written- # exclusively by Spree::Orders::RecomputeStatuses, and completed-order+ # exclusively by Spree::Orders::UpdateStatuses, and completed-order# fulfillment repricing belongs to the explicit post-placement edit# path, never to a totals refresh.#diff --git a/spree/core/app/workflows/spree/orders/cancel.rb b/spree/core/app/workflows/spree/orders/cancel.rbindex 06c8519626..4bda0a8e85 100644--- a/spree/core/app/workflows/spree/orders/cancel.rb+++ b/spree/core/app/workflows/spree/orders/cancel.rb@@ -46,7 +46,7 @@ module Spreeexternal_step :settle_paymentsstep :recompute_totals, with: -> { Spree.order_recalculate_totals_workflow }- step :recompute_statuses, with: -> { Spree::Orders::RecomputeStatuses }+ step :update_statuses, with: -> { Spree.order_update_statuses_service }order.publish_event('order.canceled', order.event_payload.merge(notify_customer: notify_customer))success(order.reload)rescue ActiveRecord::RecordInvalid, StateMachines::InvalidTransitiondiff --git a/spree/core/app/workflows/spree/orders/resume.rb b/spree/core/app/workflows/spree/orders/resume.rbindex cf4cd94642..f57f6a9e04 100644--- a/spree/core/app/workflows/spree/orders/resume.rb+++ b/spree/core/app/workflows/spree/orders/resume.rb@@ -21,7 +21,7 @@ module Spreeendorder.consider_risk- step :recompute_statuses, with: -> { Spree::Orders::RecomputeStatuses }+ step :update_statuses, with: -> { Spree.order_update_statuses_service }order.publish_event('order.resumed')success(order.reload)rescue ActiveRecord::RecordInvalid, StateMachines::InvalidTransitiondiff --git a/spree/core/db/sample_data/orders.rb b/spree/core/db/sample_data/orders.rbindex e39e4008e5..b3857c54aa 100644--- a/spree/core/db/sample_data/orders.rb+++ b/spree/core/db/sample_data/orders.rb@@ -132,7 +132,7 @@ end# Statuses are derive-then-persist; the direct writes above bypass the# event subscribers, so recompute explicitly.-orders.each { |order| Spree::Orders::RecomputeStatuses.call(order: order.reload) }+orders.each { |order| order.reload.update_statuses! }# Reimbursementfirst_complete_order = Spree::Order.complete.firstdiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex e8f05cfe33..34a90ea37b 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -559,7 +559,8 @@ module Spreereturn false unless defined?(Spree::Dependencies)Spree::Dependencies.class::INJECTION_POINTS.include?(name) ||- Spree::Dependencies.class::LEGACY_WORKFLOW_KEYS.key?(name)+ Spree::Dependencies.class::LEGACY_WORKFLOW_KEYS.key?(name) ||+ Spree::Dependencies.class::LEGACY_SERVICE_KEYS.key?(name)endenddiff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex 97ad7fe932..3dcd900e62 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -65,13 +65,12 @@ module Spreeorder_fee_destroy_service: 'Spree::Orders::Fees::Destroy',order_create_service: 'Spree::Orders::Create',order_update_service: 'Spree::Orders::Update',+ order_update_statuses_service: 'Spree::Orders::UpdateStatuses',order_updater: 'Spree::OrderUpdater',# fulfillmentfulfillment_create_service: 'Spree::Fulfillments::Create',-- # shipment- shipment_update_service: 'Spree::Shipments::Update',+ fulfillment_update_service: 'Spree::Fulfillments::Update',# tracking numberstracking_number_service: 'Spree::TrackingNumbers::BaseService',@@ -144,15 +143,24 @@ module Spreeorder_cancel_service: :order_cancel_workflow}.freeze+ # Same stash-don't-apply treatment for the 6.0 Shipment→Fulfillment+ # service rename: the new class speaks the fulfillment keyword+ # vocabulary (still accepting the old shipment keywords with a+ # warning), but a legacy override written against the old keywords is+ # not interchangeable with what the new call sites pass. Removed in 6.1.+ LEGACY_SERVICE_KEYS = {+ shipment_update_service: :fulfillment_update_service+ }.freeze+def legacy_workflow_overrides@legacy_workflow_overrides ||= {}end- LEGACY_WORKFLOW_KEYS.each do |legacy, current|+ LEGACY_WORKFLOW_KEYS.merge(LEGACY_SERVICE_KEYS).each do |legacy, current|define_method("#{legacy}=") do |value|Spree::Deprecation.warn("Spree::Dependencies##{legacy}= is deprecated and NO LONGER CONSULTED by Spree — " \- "the override was not applied. Port the class to the Spree::Workflow contract and " \+ "the override was not applied. Port the class to the #{current} contract and " \"set #{current}= instead. The #{legacy} name is removed in Spree 6.1.")legacy_workflow_overrides[legacy] = valuediff --git a/spree/core/spec/models/spree/app_dependencies_spec.rb b/spree/core/spec/models/spree/app_dependencies_spec.rbindex 0709c2f505..d2c5ae0002 100644--- a/spree/core/spec/models/spree/app_dependencies_spec.rb+++ b/spree/core/spec/models/spree/app_dependencies_spec.rb@@ -87,6 +87,21 @@ describe Spree::Core::Dependencies, type: :model doendend+ describe 'legacy service rename keys' do+ it 'stashes shipment_update_service writes without touching the fulfillment seam' do+ allow(Spree::Deprecation).to receive(:warn)++ deps.shipment_update_service = 'MyCustomShipmentUpdate'+ expect(deps.shipment_update_service).to eq('MyCustomShipmentUpdate')+ expect(deps.fulfillment_update_service).to eq('Spree::Fulfillments::Update')+ end++ it 'falls back to the fulfillment service for legacy reads with no stash' do+ allow(Spree::Deprecation).to receive(:warn)+ expect(deps.shipment_update_service).to eq('Spree::Fulfillments::Update')+ end+ end+describe 'legacy keys through the Spree top-level resolver' doit 'sets and resolves without raising, leaving the workflow seam untouched' doallow(Spree::Deprecation).to receive(:warn)diff --git a/spree/core/spec/models/spree/shipment_spec.rb b/spree/core/spec/models/spree/shipment_spec.rbindex b70e89c7bd..65761ec58e 100644--- a/spree/core/spec/models/spree/shipment_spec.rb+++ b/spree/core/spec/models/spree/shipment_spec.rb@@ -868,7 +868,7 @@ describe Spree::Shipment, type: :model doendbefore do- shipment.update_attributes_and_order selected_shipping_rate_id: shipping_rate.id+ Spree::Fulfillments::Update.call(fulfillment: shipment, fulfillment_attributes: { selected_shipping_rate_id: shipping_rate.id })endit 'updates everything around order shipment total and state' do@@ -876,7 +876,7 @@ describe Spree::Shipment, type: :model doexpect(shipment.state).to eq 'pending'# The full recalculation derives item_total from real line items# (fabricated column values don't survive it) and statuses come from- # the payment records via RecomputeStatuses.+ # the payment records via UpdateStatuses.expect(shipment.order.total.to_f).to eq(shipment.order.item_total.to_f + 10)expect(shipment.order.payment_status).to eq('none')end