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
Fix: orders from a multi-seller checkout reported nothing paid (#14673)
Łukasz Adamczyke5356bf61621
diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.mdindex 63a707766b..abf6e562be 100644--- a/docs/plans/6.0-multi-vendor-marketplace.md+++ b/docs/plans/6.0-multi-vendor-marketplace.md@@ -801,6 +801,7 @@ Even before this lands, work touching adjacent areas should:- **A share records what it reserved separately from what the gateway took** (RESOLVED 2026-08-21, shipped). `spree_payment_splits.claimed_amount` beside `captured_amount`: a parcel reserves what it is about to draw *before* charging, so two parcels cannot reach for the same money, and that reservation becomes captured only once the charge lands. `undrawn_amount` (authorized − captured − claimed) is what a parcel may take, and `capture_in_flight?` is a plain read of the row. Cancellation refuses to settle a share mid-charge, reporting it for manual resolution rather than releasing an authorization about to be drawn or refunding money nobody took. **Two earlier attempts got this wrong, and both are the reason the column exists.** Overloading `captured_amount` for the claim meant `carry_splits_to` — which runs *during* the capture — saw the claim as taken and carried the full share onto the remainder payment, paying that order twice. Inferring the in-flight state from the payment failed twice over: `payment.captured_amount` sums capture *events*, which a checkout-captured payment never writes (so every ordinary order looked mid-capture), and `payment.completed?` is set by whichever sibling captured first, so a second seller's genuine in-flight claim looked settled and was refunded. **The rule for Phase 3a:** the split row is the only thing that knows the difference between reserved and confirmed — a transfer or payout sweep must read `captured_amount`, never `authorized_amount` minus arithmetic, and never ask the shared payment.- **A shared payment breaks every reader that assumed one payment means one order** (RESOLVED 2026-08-21, shipped). A review pass over the split found thirteen such readers, each verified against the code before being believed, and every one real. The instructive ones: **`order.paid` never fired for a split checkout** — it publishes from the payment's own `after_commit`, which runs *before* `payment.completed` reaches the subscriber that marks the shares captured, so the figure it read was always zero (an earlier note in this plan asserted the opposite ordering and was wrong; the trace is what settled it). Public webhook API, silently dead for marketplace orders. **Several payments each re-divided the whole basket and each rounded**, so three children owed 33.33/33.33/33.34 were credited 33.34/33.32/33.34 — the group's sum correct and two children's wrong; payments now draw down what is left. **A parcel whose halves are both worth nothing kept the full delivery charge on each**, the same double-charge fixed earlier surviving in the zero-weight path. And a grouped child's `payment_total` was summed from payments it does not own, persisting nothing paid. The pattern worth carrying into Phase 3a: **anything that reaches an order through `payment.order`, or a total through `order.payments`, is wrong on a grouped order** — and none of these failed loudly.- **A grouped child order's money is read from its payment splits, not its payments** (RESOLVED 2026-08-20, shipped). Such an order owns no payments — the customer paid once, against the group — so `Orders::UpdateStatuses` reads captured/authorised/refunded from `payment_splits`, capture-on-dispatch draws from the group's payments **bounded by that child's remaining share** (without the bound the first seller to ship captures the whole basket), and `spree_refunds.order_id` names which child a refund puts right so `PaymentSplitRefundSubscriber` can recompute that share alone. `Refund#order` falls back to the payment and `Order#refunds` resolves either shape, so nothing outside a split checkout changes. This is the concrete argument for storing shares rather than computing proportions on read: once one seller has shipped and been captured while another has not, no proportion of the group's totals describes either.+- **The share rows keep a grouped child's `payment_total` true, rather than any writer remembering to** (RESOLVED 2026-09-17, shipped). The entry above records a grouped child's `payment_total` as one of the thirteen readers found and fixed; it was fixed only halfway, and V-3649 is what the other half looked like. `Carts::SplitBySeller` re-sums each child *before* `OrderGroups::AllocatePayments` writes the shares, so every child persisted nothing paid; `refresh_payment_total!` — the only other writer, and the one every payment event reaches — sums `spree_payments` by `order_id` and would have written the same zero had it ever run, which on a grouped child it does not, because `payment.owner` is the group. The result was an order reading **Payment total 0.00 and its whole total outstanding beside a Paid badge** on the admin summary panel, the seller panel and the customer's own order payload, with the Payments card next to it showing the correct share — the badge derives from the shares, the money did not. `Spree::Order` now overrides the concern's private `settled_payments_arel` so a grouped order sums `captured_amount − refunded_amount` over its shares, in the same single scalar subquery the plain path uses, and `Spree::PaymentSplit` refreshes its order's total on save and on destroy. **Deliberately one hook on the row rather than a call at each writer:** allocation at checkout, capture on dispatch, an authorisation settling afterwards, a refund and a payment being torn down all move a share, and the pattern this plan already warns about — none of these failing loudly — is exactly what a fifth call site eventually forgotten looks like. Synchronous rather than `after_commit`, because the checkout response is rendered from the orders the allocation leaves behind. Fixing the column rather than the readers is what makes `outstanding_balance`, `amount_due`, `paid?`, all three order serializers and any Ransack filter or report over the column right at once; `net_captured_total` stays the live read for callers about to move money, since the column trails the rows by one refresh. No backfill ships with it: order grouping is 6.0 work still in development, so there is no released data carrying the wrong figure.- **The shared catalog ships as variant attributes plus one selection service** (RESOLVED 2026-08-16, shipped — Decision 11's Phase 1b). `spree_variants.seller_id` and `spree_variants.delivery_profile_id`, both nullable, and **two modes that never mix**: on an *owned* product (`products.seller_id` set) every variant is that seller's and ships as the product does — no other seller can create a variant there, so the variant's own columns carry no meaning and are kept blank by a normalizer; on a *master* product (`products.seller_id` nil, the shared catalog) each seller's row names its own seller and how it ships, falling back to the master's profile. The resolved answer is a plain read on the model (`resolved_seller`, `resolved_delivery_profile` — product's if owned, else the row's; no memo, no inheritance chain), and the API carries **one field each** (`seller_id`, `delivery_profile_id`), read resolved and written to the column, so a storefront never learns which mode it is in and a read-then-write round trip on an owned product changes nothing (the write is a no-op there). This deliberately departs from `Variant#tax_category`'s override-the-reader shape, and supersedes an earlier cut that modelled the seller as an inheritance-with-override and grew a second `own_*` name on the API to keep the round-trip safe — the domain has no override to model, so it needed neither. `Variant#digital?` moved onto the variant's own profile with it, which is what lets a download and its printed edition sit on one product. Condition is an `OptionType` shipped as **sample data, not a seed** (`db/sample_data/options.rb`, beside color; values new/refurbished/used): nothing in core keys on the word — the buy box groups by whatever option values it is given — so it is a merchant's choice, not an install prerequisite, and a store that sells only new goods never finds it on a fresh install, so it splits a product the way any axis does and the buy box keys on the option combination — a new buy box and a used one, at no extra cost. **The buy box is `Spree::Products::SelectBuyBox`** behind `Spree.product_buy_box_service`: computed on every read and never stored (it turns on price, stock and who is selling today, none of which hold still), ranking first-party ahead of sellers then cheapest, refusing to feature a seller who is suspended, onboarding or away, and still naming a variant when nothing is buyable so the page has a price to render. `purchasable?`/`in_stock?`/`backorderable?` now answer through the winner rather than `variants.any?` — a product is not purchasable because a suspended seller happens to hold stock — and `default_variant` prefers a first-party listing, since the headline price, SKU and the Omnibus `prior_price` are compliance claims about the operator's own pricing. **SKU uniqueness is scoped to the resolved seller** via a hand-written validation rather than a `scope:` option, because Rails' uniqueness validator reads the raw column and would have merged two sellers who each own a whole product into the nil scope. Cross-store binding is refused on the model (`seller`/`delivery_profile` must belong to the product's store), matching the pair already on Product. **Three pre-existing faults were fixed with it, each with a regression spec proven against the old code:** `Product#variants=`'s full-replacement delete was left as-is on the operator's path — the operator writes every seller's variants on a master — and the guard against a seller wiping a rival's rows lives at the seller branch, not the model (see "Writes never destroy another seller's variants" above), `Stock::Splitter::DeliveryProfile` and `Stock::Coordinator` re-keyed their memoisation off `product_id`, and `with_option_value_ids` now requires **one variant** to satisfy every axis (a `HAVING COUNT(DISTINCT option_type_id)` over one grouped subquery) instead of asking the product about each axis separately — "Blue AND XL" had matched a product selling a blue small beside a red XL, a live storefront bug independent of marketplaces. **Both search providers were fixed together**, since a filter's meaning is part of the provider contract and fixing one would have made results change when an operator installs the search gem: the Meilisearch document is per product, so its option values are a union across variants that cannot answer a per-variant question — the presenter now also emits `option_value_combination_ids` (one token per *combination* of values seen on the same variant) and a multi-axis filter asks for a whole combination, with single-axis filters and the disjunctive-facet queries unchanged. Whole combinations rather than pairs, because every pair holding on *some* variant is not the same as one variant holding them all — three variants (blue, XL, used), (blue, S, new) and (red, XL, new) satisfy each pair of "blue AND XL AND new" while none carries all three. Token count is exponential in the axis count, so it is capped (`MAX_COMBINATION_AXES`) and filters naming more axes fall back to the pairwise approximation. **The upgrade needs a reindex** — existing documents lack the field, so a multi-axis filter matches nothing until then; `search_reindex` is in the 5.6→6.0 manifest for exactly this and is a no-op on the database provider.- **Seller lifecycle → four workflows, never a writable `status`** (RESOLVED 2026-08-16, shipped). `Spree::Sellers::Invite` / `Approve` / `Suspend` / `Reject` (seams `seller_invite_workflow` and siblings), each with `validate` + `after_*` hooks and its own `seller.*` event. The Admin API exposes them as member actions (`POST invite`, `PATCH approve|suspend|reject`) and deliberately omits `status` from `permitted_params` — a PATCH that moved a seller would skip the mail, the payout provisioning and the extension hooks, which is exactly what `6.0-service-workflows.md` keeps out of a column write. Guards admit more than the linear path: `Approve` also lifts a suspension (clearing holiday mode with it) and revives a rejected applicant; `Suspend` is for a seller already on the marketplace while `Reject` is for one that never traded, so rejecting an approved seller is refused. Suspension and rejection reasons live in `metadata` rather than columns — each is a note about one event, and the next one has its own. Creation stays plain CRUD (it is not a lifecycle transition), so the default status is applied in an `after_initialize` on the model, as on `Spree::Fulfillment`.- **Lifecycle emails are seller-facing, event-driven, and skip the invitation** (RESOLVED 2026-08-16, shipped). `Spree::SellerMailer` (approved/suspended/rejected) in `spree_emails`, fired by `Spree::SellerEmailSubscriber` off the `seller.*` events the workflows already publish — nothing mails from a workflow step, so mail is one listener among several rather than something a transition waits on. Three departures from the legacy module: **no `seller.invited` email** (inviting creates an `Invitation`, which already mails the invitee — a second message would be the same news to the same address), **no marketplace-staff copies** (the legacy module mailed every store admin on approval and onboarding; staff read status in the dashboard, and per-admin fan-out across many sellers is the kind of noise merchants switch off — staff notifications ride the event/webhook surface), and **suspension/rejection reasons never appear in the email** (the operator's note is an internal record; the seller is asked to get in touch). Gated on a new `send_seller_transactional_emails` Store preference rather than the consumer one — sellers are a different audience, and silencing customer receipts must not silence seller mail. Onboarding started/completed emails wait for the onboarding task registry.diff --git a/spree/core/app/models/concerns/spree/purchase/totals.rb b/spree/core/app/models/concerns/spree/purchase/totals.rbindex efad64bdcd..9340d5c7ae 100644--- a/spree/core/app/models/concerns/spree/purchase/totals.rb+++ b/spree/core/app/models/concerns/spree/purchase/totals.rb@@ -35,8 +35,10 @@ module Spree# unsaved changes — callers legitimately hold dirty attributes while# a payment is destroyed (cart teardown, order merging), and this# must never disturb their in-memory state.+ # updated_at moves with it, or the API validates a cached response+ # against an unchanged timestamp and serves the pre-payment figure.settled = settled_payments_arel- self.class.where(id: id).update_all(payment_total: settled)+ self.class.where(id: id).update_all(payment_total: settled, updated_at: Time.current)self.payment_total = self.class.where(id: id).pick(:payment_total)enddiff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 10d72364ca..4c6980a2a4 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -746,12 +746,8 @@ module Spree# What has been captured against this order, net of refunds.#- # An order placed in a split checkout owns no payments, so its own- # +payment_total+ stays at zero however much the customer paid — the- # figure comes from its share of the group's payments instead, the same- # way {Spree::Orders::UpdateStatuses} derives +payment_status+. The- # group's own total will not do: once one seller has been captured and- # another has not, no proportion of it describes either.+ # Read from the share rows rather than the +payment_total+ they are summed+ # into, since a caller about to move money needs what they say now.## @return [BigDecimal]def net_captured_total@@ -1248,6 +1244,21 @@ module Spreeprivate+ # An order placed in a split checkout owns no payments, so its money is+ # the sum of its shares of the group's instead — the same source+ # {Spree::Orders::UpdateStatuses} derives payment_status from.+ #+ # @return [Arel::Nodes::NamedFunction]+ def settled_payments_arel+ return super unless grouped?++ splits = Spree::PaymentSplit.arel_table+ net = splits.project(splits[:captured_amount].sum - splits[:refunded_amount].sum).+ where(splits[:order_id].eq(id))++ Arel::Nodes::NamedFunction.new('COALESCE', [Arel::Nodes::Grouping.new(net), Arel.sql('0')])+ end+def ensure_can_be_deletedreturn true if can_be_deleted?diff --git a/spree/core/app/models/spree/payment_split.rb b/spree/core/app/models/spree/payment_split.rbindex 0e93a85672..d2e4779001 100644--- a/spree/core/app/models/spree/payment_split.rb+++ b/spree/core/app/models/spree/payment_split.rb@@ -33,6 +33,12 @@ module Spreevalidates :currency, presence: truevalidates :order_id, uniqueness: { scope: [:payment_id, *spree_base_uniqueness_scope] }+ #+ # Callbacks+ #+ after_save :refresh_order_payment_total, if: :settled_money_moved?+ after_destroy :refresh_order_payment_total, if: :held_settled_money?+## Scopes#@@ -86,5 +92,23 @@ module Spreedef capture_in_flight?claimed_amount.positive?end++ private++ # Here rather than at each of the five writers that move a share, because a+ # column refreshed at five call sites will eventually be refreshed at four.+ def refresh_order_payment_total+ order&.refresh_payment_total!+ end++ # Reserving money or moving an authorisation reports no differently, and+ # locking the order for it would invert {Spree::Payment#carry_splits_to}.+ def settled_money_moved?+ saved_change_to_captured_amount? || saved_change_to_refunded_amount?+ end++ def held_settled_money?+ captured_amount.positive? || refunded_amount.positive?+ endendenddiff --git a/spree/core/app/services/spree/order_groups/allocate_payments.rb b/spree/core/app/services/spree/order_groups/allocate_payments.rbindex 9bf752e544..cf768be393 100644--- a/spree/core/app/services/spree/order_groups/allocate_payments.rb+++ b/spree/core/app/services/spree/order_groups/allocate_payments.rb@@ -87,6 +87,9 @@ module Spreenext if split.persisted?share = Spree::Money::Rounding.from_minor_units(shares[index], currency)+ # So re-summing its payment total on save reuses this instance rather+ # than loading a second copy of the row per share.+ split.order = ordersplit.currency = payment.currencysplit.authorized_amount = sharesplit.captured_amount = captured ? share : 0diff --git a/spree/core/app/workflows/spree/carts/recalculate_totals.rb b/spree/core/app/workflows/spree/carts/recalculate_totals.rbindex 5d6ae750ef..2f9e7326a4 100644--- a/spree/core/app/workflows/spree/carts/recalculate_totals.rb+++ b/spree/core/app/workflows/spree/carts/recalculate_totals.rb@@ -137,7 +137,9 @@ module Spree# @return [BigDecimal]def paid_so_farif cart.is_a?(Spree::Order) && cart.grouped?- return cart.payment_splits.to_a.sum(&:net_captured_amount)+ # Reloaded: a share moved since this instance loaded them would be+ # re-summed at its old figure and persisted back over the correction.+ return cart.payment_splits.reload.to_a.sum(&:net_captured_amount)endcart.payments.completed.includes(:refunds).inject(0) do |sum, payment|diff --git a/spree/core/spec/models/spree/fulfillment/grouped_capture_spec.rb b/spree/core/spec/models/spree/fulfillment/grouped_capture_spec.rbindex f9a91749e6..c5ce6f681f 100644--- a/spree/core/spec/models/spree/fulfillment/grouped_capture_spec.rb+++ b/spree/core/spec/models/spree/fulfillment/grouped_capture_spec.rb@@ -77,4 +77,20 @@ RSpec.describe Spree::Fulfillment, 'capture on dispatch in a split checkout' doexpect(seller_order.reload.payment_status).to eq('paid')end++ # Without this a dispatched order reads as paid while still showing its whole+ # total outstanding, which is the badge above disagreeing with the money.+ it "carries what it drew onto the order's payment total, and no sibling's" do+ expect { dispatch(seller_order, worth: 40) }.+ to change { seller_order.reload.payment_total }.from(0).to(40)++ expect(first_party_order.reload.payment_total).to be_zero+ end++ # Reserving money is not taking it, and locking the order from inside the+ # share's lock would deadlock two sellers dispatching at once.+ it 'leaves the payment total alone while a claim is merely reserved' do+ expect { seller_split.update!(claimed_amount: 10) }.+ not_to change { seller_order.reload.payment_total }+ endenddiff --git a/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rb b/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rbindex 3ec9a18fee..d750faa968 100644--- a/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rb+++ b/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rb@@ -58,26 +58,57 @@ RSpec.describe Spree::PaymentSplitSubscriber, :events, type: :model doexpect(seller_split.reload.refunded_amount).to eq(15)end- # order.paid is public webhook API, and it is published from the payment's- # own after_commit — which runs before the subscriber marks the shares- # captured, so the figure it reads has to count this payment's share itself.- it 'declares each child paid when the shared payment settles' do- pending_payment = create(:payment, order: nil, cart: nil, order_group: group,- amount: 100, status: 'pending')- create(:payment_split, payment: pending_payment, order: seller_order, authorized_amount: 40)- create(:payment_split, payment: pending_payment, order: first_party_order, authorized_amount: 60)- seller_split.destroy!- first_party_split.destroy!-- published = []- allow(Spree::Events).to receive(:publish).and_wrap_original do |original, name, *rest|- published << name- original.call(name, *rest)+ # A share moved without re-summing would leave the order claiming money back+ # that the customer already has.+ it "takes the refund off that order's payment total and no sibling's" do+ refund!(seller_order, 15)++ expect(seller_order.reload.payment_total).to eq(25)+ expect(seller_order.amount_due).to eq(15)+ expect(first_party_order.reload.payment_total).to eq(60)+ end++ # An authorisation taken at checkout and settled once the sellers ship, so+ # the shares are on the books before any money is.+ context 'when the shared payment settles after placement' do+ let!(:pending_payment) do+ create(:payment, order: nil, cart: nil, order_group: group, amount: 100, status: 'pending')+ end++ before do+ create(:payment_split, payment: pending_payment, order: seller_order, authorized_amount: 40)+ create(:payment_split, payment: pending_payment, order: first_party_order, authorized_amount: 60)+ seller_split.destroy!+ first_party_split.destroy!end- pending_payment.complete!+ # order.paid is public webhook API, and it is published from the payment's+ # own after_commit — which runs before the subscriber marks the shares+ # captured, so the figure it reads has to count this payment's share itself.+ it 'declares each child paid' do+ published = []+ allow(Spree::Events).to receive(:publish).and_wrap_original do |original, name, *rest|+ published << name+ original.call(name, *rest)+ end++ pending_payment.complete!++ expect(published.count { |name| name == 'order.paid' }).to eq(2)+ end++ it "carries the settled money onto each child's payment total" do+ expect { pending_payment.complete! }.+ to change { seller_order.reload.payment_total }.from(0).to(40).+ and change { first_party_order.reload.payment_total }.from(0).to(60)+ end+ end- expect(published.count { |name| name == 'order.paid' }).to eq(2)+ # Tearing a payment down takes its shares with it, so the order it paid for+ # is left holding nothing.+ it "takes a destroyed share off the order's payment total" do+ expect { payment.destroy! }.+ to change { seller_order.reload.payment_total }.from(40).to(0)endit 'leaves an ungrouped order alone' dodiff --git a/spree/core/spec/workflows/spree/carts/complete_split_spec.rb b/spree/core/spec/workflows/spree/carts/complete_split_spec.rbindex a28915c8eb..def97b5dd3 100644--- a/spree/core/spec/workflows/spree/carts/complete_split_spec.rb+++ b/spree/core/spec/workflows/spree/carts/complete_split_spec.rb@@ -496,6 +496,15 @@ module Spreeendend+ it 'leaves each child reporting its share as paid' do+ group.orders.each do |order|+ expect(order.reload.payment_total).to eq(order.total)+ expect(order.amount_due).to be_zero+ expect(order.outstanding_balance).to be_zero+ expect(order).to be_paid+ end+ end+# A gift card becomes a store-credit payment beside the card charge, and# both divide the same way — one attribution rule for every source, no# priority ordering. A seller's order is therefore not "paid by card" or