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.

Split a checkout across the sellers it bought from

Damian Legawiec1c40d79ea2ce
diff --git a/docs/plans/6.0-admin-api.md b/docs/plans/6.0-admin-api.md
index e01f542272..b42a525395 100644
--- a/docs/plans/6.0-admin-api.md
+++ b/docs/plans/6.0-admin-api.md
@@ -712,7 +712,7 @@ Per `6.0-multi-vendor-marketplace.md`. Seller prefix is `sel_` (matches the lega
- [ ] `GET /api/v3/admin/seller_transfers` — read-only earnings ledger (filter by seller/payout/status)
- [ ] `GET /api/v3/admin/seller_payouts` / `GET /:id`
- [ ] `POST /api/v3/admin/seller_payouts/:id/complete` — manual settlement (system provider)
-- [ ] `GET /api/v3/admin/order_groups` / `GET /:id` — the multi-order transaction container
+- [x] `GET /api/v3/admin/order_groups` / `GET /:id` — the multi-order transaction container (read-only; `read_orders`)
API key scopes: `read_sellers` / `write_sellers`, `read_commissions` / `write_commissions`, `read_payouts` / `write_payouts`.
diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.md
index 2012364adf..f41fb99b3b 100644
--- a/docs/plans/6.0-multi-vendor-marketplace.md
+++ b/docs/plans/6.0-multi-vendor-marketplace.md
@@ -1,10 +1,10 @@
# Multi-Vendor Marketplace (Open Source Core)
-**Status:** Design complete (2026-08-15 — auth/API surface + the last blocking questions settled). Phase 0 (admin-branch hardening), Phase 1 (seller identity, teams, lifecycle workflows, mail, the seller API branch), Phase 1b (the shared catalog — Decision 11) and Phase 2 (commission engine) implemented; Phase 3 (order splitting + fund ledger) next, gated on the Cart/Order split
+**Status:** Design complete (2026-08-15 — auth/API surface + the last blocking questions settled). Phase 0 (admin-branch hardening), Phase 1 (seller identity, teams, lifecycle workflows, mail, the seller API branch), Phase 1b (the shared catalog — Decision 11), Phase 2 (commission engine) and Phase 3 (order splitting — `OrderGroup`, `PaymentSplit`, the split inside `Carts::Complete`, 2026-08-20) implemented; Phase 3a (the two-level fund ledger) next, then Phase 3b (OSS Stripe Connect) and Phase 4 (dashboards)
**Target:** Spree 6.0 (the "Marketplace" release)
**Depends on:** `6.0-cart-order-split.md` (Cart/Order split + dual-FK `LineItem` owner (`cart_id`/`order_id`, `#owner` method) — **expanded 2026-07-27; Phase 3 design can now freeze against it**), `6.0-6.1-split-adjustments.md` (TaxLine/Discount/Fee replace polymorphic Adjustment), `6.0-order-routing.md` (per-seller stock location), `6.0-fulfillment-and-delivery.md` (Fulfillment/DeliveryMethod vocabulary, per-seller delivery selection), `6.0-admin-spa.md` (seller panel composition), `6.0-admin-api.md` (Marketplace endpoints), `6.0-platform-auth.md` (`Spree::AdminUser` is the seller principal; strategy registries + JWT audiences — shipped in PR #14380), `6.0-admin-rbac.md` (permission catalog, `RoleUser` resource typing, seller audience direction — shipped in PR #14412)
**Author:** Damian + Claude
-**Last updated:** 2026-08-17
+**Last updated:** 2026-08-20
## Summary
@@ -696,7 +696,9 @@ This is **new OSS code**, not a rename of existing core — there is no in-place
- **Phase 0 — admin-branch hardening (ships first, no Seller model needed). IMPLEMENTED 2026-08-16.** Tighten `AdminAuthentication#current_user_member_of_store?` to `resource_type: 'Spree::Store'` + regression spec; `spree_refresh_tokens.audience` written at mint and enforced on refresh (admin + store surfaces stamp their own); `Role#audience` + the audience marker on `register_resource` (Decision 10 / RBAC plan). **Shipped as:** `audience` on refresh tokens (nullable; `for_audience` scope narrowing every refresh **and** logout lookup on both surfaces — ending a session belongs to the surface that started it; legacy NULL-audience rows match no surface and are rejected on refresh, costing their holders one login) and on roles (`null: false`, backfilled `staff`, immutable after create, `Spree::Role::AUDIENCES` the vocabulary); the catalog takes `audiences:` naming the audiences **beyond staff** a resource opens up, with `grantable_keys(audience)` (unknown audience ⇒ empty, never raises) — a generalization of the originally-planned `seller_grantable` boolean, so a third panel needs no schema change (decisions.md 2026-08-16); `orders`/`fulfillments`/`products`/`stock`/`dashboard` opened to `seller`. **Roles became store-owned** (`spree_roles.store_id`, `null: false`, via `SingleStoreResource`): they were global reference data, so two stores could never each define a "Manager" and the marketplace would have inherited that. Names are unique per `(store, name, audience)` — `Spree::UniqueName`'s global uniqueness is deliberately not used on Role — so one store holds a staff "Manager" beside a seller "Manager", and another store holds its own. `admin` is now one immutable role **per store** (`default_admin_role(store)`; `Seeds::Roles` moved after `Seeds::Stores`, since a role cannot exist before its store). The upgrade fans every existing role out per store and re-points assignments and invitations at the copy for the store they already named, so no grant changes hands. The audience bound is enforced **twice**: `Spree::Role` validates it on write, and `Spree::Ability` re-filters through `grantable_keys(role.audience)` at activation, since a catalog that changes after the role was saved would otherwise leave stale keys live. The staff surface is closed to foreign-audience roles at both ends — `Admin::RolesController#scope` lists only `Spree::Role.staff`, and `RoleGrantGuard` rejects assigning a non-staff role to store staff (invitations + admin_users). `Spree::Ability` takes `resource:` (defaults to the store) and reads `role_users` on it — the `admin` super-role and the implicit-admin fallback apply **only** on a store resource, and the staff baseline narrows `read Spree::Store` to the one store a non-store panel operates under. **The ability answers capability, never tenancy:** a seller holding `write_orders` gets `can :manage, Spree::Order` on the model class exactly as an admin does; which records it may touch is `current_seller` scope-fetching in the controller, so a seller-branch controller that authorizes without scope-fetching reads store-wide.
- **Phase 1 — Seller identity.** `Spree::Seller` model (see Seller identity & teams: lifecycle, branding, ToS acceptance, holiday mode), onboarding task registry + core tasks, seller teams via `RoleUser`/`Invitation` (`resource: seller`) + `UserRoles#sellers`, self-serve application endpoint, core `Spree::SellerMailer` lifecycle emails (see Seller notifications), product ownership (`products.seller_id` + approval preference), Admin API Marketplace/sellers endpoints + Store API seller profiles, seller CSV import/export on the `Spree::Import` pipeline. **Phase 1b — the shared catalog (Decision 11). IMPLEMENTED 2026-08-16:** `variants.seller_id` + `variants.delivery_profile_id`, condition as an OptionType, the ownership filter on `Product#variants=`, first-party `default_variant` priority, the same-variant fix to option filtering, and the buy-box selection service the product rollups then answer through — see the Resolved Decisions entry for what shipped. Sequenced here rather than later because the split's partition key (Phase 3) and the commission line's identity (Phase 2) both read the seller off a line item, and on a shared product only the variant can answer. **The Seller API branch anchor** (`Seller::BaseController`/`ResourceController`, `seller_api` audience, `Spree.seller_authentication_strategies`, `/seller/auth/*`, `/seller/me`, `/seller/profile`, onboarding, team, seller-scope guard, `Spree::Ability` `resource:` option) + the seeded default seller role. Products/orders/fulfillments on the seller branch follow as each domain lands (products in Phase 1, orders/fulfillments/ledger reads in Phase 3). No splitting yet.
- **Phase 2 — Commission engine.** `CommissionRate` + `CommissionRule` + `CommissionLine`, resolution + calculation services (dimension-grouped matching, min/max clamps, `include_shipping`), commission-tax field, admin UI for rates. Compute-only (attach to single-seller orders, no split).
- - **Phase 3 — Order splitting + fund ledger.** `OrderGroup`, `Carts::SplitBySeller` inside `Carts::Complete`, per-seller delivery selection at checkout, `PaymentSplit`, derived group status, reversals, the two-level `SellerTransfer` (on-fulfillment) + `SellerPayout` (scheduled sweep) + `PayoutProvider::System` + `seller.balance(currency)`. **Gated on `6.0-cart-order-split.md` and `6.0-6.1-split-adjustments.md` landing first** — and cart-order-split is today a one-page stub: it must be expanded (checkout/delivery-selection/payment flow on Cart) before this phase's design can freeze. Flagging early: the 6.0 headline feature sits downstream of the two biggest unstarted refactors.
+ - **Phase 3 — Order splitting. IMPLEMENTED 2026-08-20** (the fund ledger follows as Phase 3a). `Spree::OrderGroup` + `Spree::PaymentSplit`, the split as named steps inside `Carts::Complete` (`Carts::PartitionBySeller` → `Carts::SplitBySeller` → `OrderGroups::AllocatePayments`), derived group status, per-child refund attribution. **What shipped and why it took the shape it did:** the split runs in FINALIZE, after payment, and **adopts the paid draft order as the group's first child** rather than building N fresh orders and discarding it — that order is what the payment was taken against and what carries the unique `cart_id` replay anchor, so destroying it would orphan money and break resumption; the remaining partitions become siblings and the rows are **moved, never re-copied** (every line item, fulfillment and typed money row was costed once inside the completion lock — re-deriving would ask the pricing and tax engines a question already answered). The group takes the order's number and children suffix off it (`R1001-1`, `R1001-2`), so a customer keeps the reference they saw at checkout. `completion_result` is now `cart.order_group || cart.order` and the workflow returns whichever exists. **A parcel split between sellers divides its delivery cost** by the value each half carries (largest-remainder) — cloning the fulfillment kept the full cost on both halves and charged the customer twice, caught by a totals spec; order-level fees prorate the same way with their tax lines following. Per-seller commission needed **no commission-engine change at all**: each child publishes its own `order.placed`, which `OrderCommissionSubscriber` already answers, and the service already skips nil-seller lines so the first-party child is correctly uncommissioned. **Payments moved up to the group** (`payments.order_group_id`, `order_id` nil; `Payment#owner` extended, `exactly_one_owner` now three-way) with one `PaymentSplit` per (payment, child) prorated by child totals — so a mixed store-credit checkout never overstates gateway exposure on one seller's order. Consequences that had to ship with it: `Orders::UpdateStatuses` reads a grouped child's money from its splits rather than `order.payments` (which is empty there); capture-on-dispatch draws from the group's payments **bounded by that child's remaining share**, so the first seller to ship cannot capture the whole basket; `spree_refunds.order_id` names which child a refund puts right (`Refund#order` falls back to the payment, `Order#refunds` resolves either shape) and `PaymentSplitRefundSubscriber` recomputes only that child's `refunded_amount`; `Spree::OrderGroup` answers the payment-owner contract (`payment_total`, store credits, addresses via `Purchase::Addresses`) and counts as a purchase in `Storefront::AccessPolicy` so a guest can see what they bought. API: the Store completion response returns the group with orders nested (the customer sees **one purchase**, not three), the gateway-race retry resolves a group id, and read-only `GET /admin/order_groups` ships with `OrderGroup`/`PaymentSplit` added to the `orders`/`payments` catalog subjects.
+ - **Phase 3a — fund ledger (next).** The two-level `SellerTransfer` (on-fulfillment) + `SellerPayout` (scheduled sweep) + `PayoutProvider::System` + `seller.balance(currency)`. Sequenced after the split because the transfer basis is `child_order.total − commission_lines.sum(:total)`, which needs child orders and their captured shares to exist.
+ - **Note for the second splitting consumer (recorded 2026-08-20).** `Carts::SplitBySeller` is seller-specific in exactly **three lines** — the `seller_id` stamped on the adopted order and on each sibling, and the `line_items.where(seller_id:)` that selects a partition's rows. Everything else (group construction, number suffixing, parcel division and its delivery-cost apportionment, typed-line re-homing, order-level fee proration, the `resum_only` re-total) is partition-agnostic. When split-by-location or B2B split-by-company-location lands, the move is to lift those three lines into a registered splitter (`Spree.order_splitters`, following `Spree.stock_splitters`/`Spree.adjusters`) and rename the rest to `Orders::Split`, **not** to copy the file. Deliberately not done now, per the standing rule that a flow generalizes when it has a second consumer rather than speculatively — but the analysis is recorded so the second consumer does not have to redo it.
- **Phase 3b — OSS Stripe provider** (after Phase 3, alongside the Stripe gateway pull-in: the payment-sessions-API gateway classes come into the monorepo from the standalone `spree_stripe` repo, likely into `spree/core`, leaving the legacy v2-API/storefront code behind): Express onboarding link in the seller dashboard, `account.updated` status webhook, `transfer!` on fulfillment with `source_transaction`, payout-schedule mapping + payout webhooks. Ledger-only `reverse!`.
- **Phase 4 — Dashboards.** (a) Operator marketplace screens in `@spree/dashboard`: Sellers list/detail (lifecycle actions, branding, commission + payout settings, ledger-derived lifetime revenue/commission), Commission Rates settings page, Payouts review queue (owed balances, itemized payouts, mark-paid), OrderGroup rendering on order screens, and a "needs attention" queue on the dashboard home (sellers `ready_for_review` + pending seller products — a lightweight unified review inbox). (b) Seller panel: compose `@spree/dashboard-ui` + `@spree/dashboard-core` into a seller-scoped panel (per `6.0-admin-spa.md` — the package split exists precisely for this) talking to the Seller API branch (own login page + `seller_api` tokens; `PermissionProvider` fed by `/seller/me`). Seller roles come from the operator's roles editor filtered to the seller audience; the operator's Sellers detail screen assigns them. Surfaces the seller's products, orders + fulfillment actions, and the balance + transfer/payout ledger (earned/settled) read-only for OSS.
@@ -720,6 +722,14 @@ Even before this lands, work touching adjacent areas should:
## Resolved Decisions
+- **The split adopts the paid order rather than replacing it, and moves rows rather than copying them** (RESOLVED 2026-08-20, shipped). Completion builds one draft order holding the whole basket so it can be paid as one; the split then makes that order the group's first child and hands the other partitions' rows to new siblings. The alternative — build N fresh orders and destroy the original — was written first and rejected on two counts: the original is the record the payment was taken against and the row carrying the unique `cart_id` that makes completion replayable, so destroying it orphans money and breaks resumption. Rows **move** (`update_all` on the owner FK) rather than being re-copied from the cart, because everything was costed once inside the completion lock and re-deriving would ask the pricing and tax engines a question already answered — possibly getting a different one. The group takes the order's number so the customer keeps the reference they saw at checkout, and children suffix off it (`R1001-1`), following the same reads-its-parent shape as fulfillment and payment numbers.
+- **Splitting a parcel between sellers divides everything hanging off it** (RESOLVED 2026-08-20, shipped). A fulfillment holding two sellers' goods becomes two, and the cost the customer was quoted is apportioned between them by the value each half carries (largest-remainder), never copied onto both. The first implementation cloned the fulfillment wholesale and charged delivery twice — the group totalled more than the customer paid, caught by a totals spec rather than by review. The honest reading is that one quote for one parcel no longer describes two; a marketplace wanting each seller quoted separately gets that by giving sellers their own delivery methods, which packs their goods separately from the start and leaves nothing to divide. **Three things divide with it**, each missed on the first pass because a divided parcel is the only case where a row's owner keeps its id while its contents change: the parcel's own tax lines, discounts and fees (re-pointing by `fulfillment_id` finds nothing for the clone, so the source kept tax on a charge it no longer bore and the sibling shipped untaxed), the **selected delivery rate** (a fulfillment restates its cost from its rate whenever amounts refresh, so leaving the rate whole quietly restored the full charge on both halves the next time anything touched them), and the **stock reservations** on the moving line items (scoped by `order_id` at release, so one child would have released everyone's and each sibling none).
+- **Per-seller commission needed no commission-engine change** (RESOLVED 2026-08-20, verified). Each child order publishes its own `order.placed`, which `OrderCommissionSubscriber` already answers, and `Commissions::CommissionOrder` already partitions by `line_item.seller_id` and skips nil-seller lines — so the seller children are commissioned and the first-party child correctly is not, with no marketplace branch anywhere in the engine. This is the payoff of the Phase 2 decision to key commission on the line item's own seller snapshot rather than on the order.
+- **The seller is asked about through a concern, so the container stays neutral** (RESOLVED 2026-08-20, shipped). `OrderGroup#sellers`, `#seller_count` and `#includes_first_party?` live in `Spree::Marketplace::OrderGroup`, included into the model rather than written on it, and `PaymentSplit` carries no seller reader at all (its order answers). Decision 8 says the group is a domain-neutral primitive whose other three planned consumers — split-by-location, split-by-availability, B2B split-by-company-location — have no seller, and "first party" means nothing to any of them. The readers are genuinely useful to a marketplace operator and the admin serializer renders them; keeping them in a concern is what lets both be true. Worth doing on the boundary rather than later, since the moment those fields ship they are client-visible API.
+- **The split must say "re-sum, don't regenerate" explicitly** (RESOLVED 2026-08-20, shipped). `Carts::RecalculateTotals` takes `resum_only:`, and the split passes it. The freeze was previously inferred from `completed?`, which is `completed_at.present?` — and the children are still **drafts** when they are re-summed, so the guard did not fire: the promotion adjuster deleted the discounts just moved onto each child and re-tested one seller's subset against a threshold the whole basket met, and the tax provider deleted the moved tax lines and re-derived them from today's rates. The service's own docstring claimed it was avoiding exactly this. A lifecycle predicate was the wrong instrument for an intent the caller knows and the record does not; the parameter states it. Pinned by a spec asserting an order-level £6 promotion survives the split intact (£3 per child, group total equal to what was charged) — the failure was silent and money-visible, and only a totals assertion catches it.
+- **A shared payment is bounded, re-allocated and refunded per child — never voided wholesale** (RESOLVED 2026-08-20, shipped). Four consequences of one payment covering several orders, each of which fails silently in a different direction: a partial capture forks the payment (`split_uncaptured_amount`), so the remainder must **carry the uncaptured shares with it** or the sellers who have not shipped point at an authorization that no longer holds their money; `Orders::Cancel` on a grouped child **refunds that child's captured share** instead of voiding the payment, since voiding would release the siblings' authorization and un-pay sellers still shipping; `Payment#owner` being an `OrderGroup` means `gateway_options` asks it for `ship_total`/`additional_tax_total`/`discount_total`/`last_ip_address`, so the group answers all of them by roll-up (without which **every** post-placement gateway call on a split checkout raised); and every refund now carries `order_id` (stamped from the payment when it can answer, named by the caller when it cannot), which is what lets `Order#refunds` stay one plain association and the admin refunds endpoint keep working.
+- **Every post-placement money path needs its own grouped case, and each one fails silently without it** (RESOLVED 2026-08-21, shipped). The split itself was well covered while the paths that run *after* it were not, and that is where the defects clustered — six of them, none raising at checkout. Dispatch capture claims the share **before** the gateway, inside its lock (claiming after meant a partial capture forked the payment while the share still read uncaptured, carried the full amount onto the remainder, and let the same order capture twice); `Carts::Complete`'s pre-payment compensation refuses to run once a group exists (its guards read `order.payments`, which a split has moved to the group, so it would have destroyed a paid order); `Orders::Cancel` honours `refund_payments` on the grouped path exactly as on the plain one (it had refunded unconditionally, so an operator cancelling with the default got a live gateway refund they never asked for) and reads what the order was paid from its shares; `Refunds::Create` bounds a refund by the named order's share, so refunding one seller cannot spend a sibling's captured money; `payment.paid` publishes `order.paid` per settled child, since a grouped payment has no single order and the event is public webhook API; `split_uncaptured_amount` uses a bang, since a silent failure would leave the group holding more money than was charged; and `Refund#update_order` re-sums the order the refund names rather than the payment's (nil on a shared payment, so every refund on a split checkout raised). Two of these were found only by *writing the specs* — the grouped dispatch and grouped refund batteries each failed on their first run against code that had already passed review. **The lesson for Phase 3a:** a ledger built on captured shares must be specced against dispatch, refund and cancellation of a *grouped* order, not only against the split, and the bound on what one order may take must count the rows rather than trust a figure a subscriber updates after the fact.
+- **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 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/packages/admin-sdk/src/types/generated/OrderGroup.ts b/packages/admin-sdk/src/types/generated/OrderGroup.ts
new file mode 100644
index 0000000000..58014de639
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/OrderGroup.ts
@@ -0,0 +1,30 @@
+// Typelizer digest 96ea3509ad3da7179d72f90f0b6cc28c
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {Address, Order, Payment} from '@/types'
+
+interface OrderGroup {
+ id: string;
+ number: string;
+ email: string | null;
+ currency: string;
+ total: string | null;
+ display_total: string | null;
+ item_total: string | null;
+ display_item_total: string | null;
+ fulfillment_status: string | null;
+ payment_status: string | null;
+ completed_at: string | null;
+ billing_address: Address | null;
+ shipping_address: Address | null;
+ orders: Array<Order>;
+ customer_id: string | null;
+ cart_id: string | null;
+ seller_count: number;
+ includes_first_party: boolean;
+ created_at: string;
+ updated_at: string;
+ payments: Array<Payment>;
+}
+
+export default OrderGroup;
diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.ts
index 17de3548c1..fa5750a79f 100644
--- a/packages/admin-sdk/src/types/generated/index.ts
+++ b/packages/admin-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 7d7db5f9ff5c3c46e23f7b85fa3d86e2
+// Typelizer digest f6fb43d9d2c744ab64ce66d6aa31356b
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { default as Address } from './Address'
@@ -56,6 +56,7 @@ export type { default as Media } from './Media'
export type { default as NewsletterSubscriber } from './NewsletterSubscriber'
export type { default as OptionType } from './OptionType'
export type { default as OptionValue } from './OptionValue'
+export type { default as OrderGroup } from './OrderGroup'
export type { default as OrderRoutingRule } from './OrderRoutingRule'
export type { default as Order } from './Order'
export type { default as PaymentMethod } from './PaymentMethod'
diff --git a/packages/sdk/src/types/generated/OrderGroup.ts b/packages/sdk/src/types/generated/OrderGroup.ts
new file mode 100644
index 0000000000..97758f4d47
--- /dev/null
+++ b/packages/sdk/src/types/generated/OrderGroup.ts
@@ -0,0 +1,23 @@
+// Typelizer digest 0a85f07d08e1250fdea39daf216cec07
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {Address, Order} from '@/types'
+
+interface OrderGroup {
+ id: string;
+ number: string;
+ email: string | null;
+ currency: string;
+ total: string | null;
+ display_total: string | null;
+ item_total: string | null;
+ display_item_total: string | null;
+ fulfillment_status: string | null;
+ payment_status: string | null;
+ completed_at: string | null;
+ billing_address: Address | null;
+ shipping_address: Address | null;
+ orders: Array<Order>;
+}
+
+export default OrderGroup;
diff --git a/packages/sdk/src/types/generated/index.ts b/packages/sdk/src/types/generated/index.ts
index 49ad4210f6..e80c109d3a 100644
--- a/packages/sdk/src/types/generated/index.ts
+++ b/packages/sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest c6033982878e42f3a5015ec1552f31bd
+// Typelizer digest 1a5d67d59598c76d62738f81d67e6d1b
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { default as Address } from './Address'
@@ -37,6 +37,7 @@ export type { default as Media } from './Media'
export type { default as NewsletterSubscriber } from './NewsletterSubscriber'
export type { default as OptionType } from './OptionType'
export type { default as OptionValue } from './OptionValue'
+export type { default as OrderGroup } from './OrderGroup'
export type { default as Order } from './Order'
export type { default as PaymentMethod } from './PaymentMethod'
export type { default as Payment } from './Payment'
diff --git a/packages/sdk/src/zod/generated/OrderGroup.ts b/packages/sdk/src/zod/generated/OrderGroup.ts
new file mode 100644
index 0000000000..1d551db9d7
--- /dev/null
+++ b/packages/sdk/src/zod/generated/OrderGroup.ts
@@ -0,0 +1,23 @@
+// This file is auto-generated. Do not edit directly.
+import { z } from 'zod';
+import { AddressSchema } from './Address';
+import { OrderSchema } from './Order';
+
+export const OrderGroupSchema = z.object({
+ id: z.string(),
+ number: z.string(),
+ email: z.string().nullable(),
+ currency: z.string(),
+ total: z.string().nullable(),
+ display_total: z.string().nullable(),
+ item_total: z.string().nullable(),
+ display_item_total: z.string().nullable(),
+ fulfillment_status: z.string().nullable(),
+ payment_status: z.string().nullable(),
+ completed_at: z.string().nullable(),
+ billing_address: AddressSchema.nullable(),
+ shipping_address: AddressSchema.nullable(),
+ orders: z.array(OrderSchema),
+});
+
+export type OrderGroup = z.infer<typeof OrderGroupSchema>;
diff --git a/packages/sdk/src/zod/generated/index.ts b/packages/sdk/src/zod/generated/index.ts
index 09014946af..67c027a351 100644
--- a/packages/sdk/src/zod/generated/index.ts
+++ b/packages/sdk/src/zod/generated/index.ts
@@ -36,6 +36,7 @@ export { NewsletterSubscriberSchema, type NewsletterSubscriber } from './Newslet
export { OptionTypeSchema, type OptionType } from './OptionType';
export { OptionValueSchema, type OptionValue } from './OptionValue';
export { OrderSchema, type Order } from './Order';
+export { OrderGroupSchema, type OrderGroup } from './OrderGroup';
export { PaymentSchema, type Payment } from './Payment';
export { PaymentMethodSchema, type PaymentMethod } from './PaymentMethod';
export { PaymentSessionSchema, type PaymentSession } from './PaymentSession';
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb b/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb
index cf7e897aaa..6b6b398617 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb
@@ -45,9 +45,18 @@ module Spree
render json: Spree.api.cart_serializer.new(@cart, params: serializer_params).to_h, status: status
end
- # Render the order as JSON using the order serializer (for complete action).
+ # Render what the checkout produced (for the complete action).
+ #
+ # A checkout spanning several sellers produced a group of orders rather
+ # than one order, and the group is what the customer bought — so it is
+ # what comes back, with the per-seller orders nested inside it. A
+ # storefront that knows nothing about groups still finds every order it
+ # needs there.
def render_order(status: :ok)
- render json: Spree.api.order_serializer.new(@cart.reload, params: serializer_params).to_h, status: status
+ record = @cart.reload
+ serializer = record.is_a?(Spree::OrderGroup) ? Spree.api.order_group_serializer : Spree.api.order_serializer
+
+ render json: serializer.new(record, params: serializer_params).to_h, status: status
end
# Return the cart token from the request headers.
diff --git a/spree/api/app/controllers/spree/api/v3/admin/order_groups_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/order_groups_controller.rb
new file mode 100644
index 0000000000..4a2fa72a4e
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/order_groups_controller.rb
@@ -0,0 +1,43 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # The multi-order transaction container — what a customer bought in one
+ # checkout when it was fulfilled by more than one seller.
+ #
+ # Read-only, enforced by the routes: a group records a checkout that
+ # already happened, and everything an operator can act on lives on the
+ # orders inside it or on the payment it holds.
+ class OrderGroupsController < ResourceController
+ scoped_resource :orders
+
+ protected
+
+ def model_class
+ Spree::OrderGroup
+ end
+
+ def serializer_class
+ Spree.api.admin_order_group_serializer
+ end
+
+ def scope
+ super.where(store_id: current_store.id)
+ end
+
+ # Everything both serializers touch. The group's figures are summed
+ # from its children and its payments are rendered in full, so a page
+ # of groups that did not preload them would issue a query per row for
+ # each.
+ def collection_includes
+ [
+ :customer, :ship_address, :bill_address,
+ { payments: %i[payment_method source] },
+ { orders: %i[market gift_card] }
+ ]
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/refunds_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/refunds_controller.rb
index 55f00a7f31..fdc2ab13a7 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/refunds_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/refunds_controller.rb
@@ -14,7 +14,7 @@ module Spree
# prevent. Refund#perform! is a no-op on a credited refund, so a
# double submit cannot credit twice.
def create
- payment = @parent.payments.accessible_by(current_ability, :update).find_by_prefix_id!(params[:payment_id])
+ payment = settlement_payments.accessible_by(current_ability, :update).find_by_prefix_id!(params[:payment_id])
# Scoped to the store, not just the ability — a reason id from
# another store must 404, not attach.
reason = current_store.refund_reasons.accessible_by(current_ability, :show).find_by_prefix_id!(params[:refund_reason_id]) if params[:refund_reason_id].present?
@@ -26,7 +26,11 @@ module Spree
payment: payment,
amount: params[:amount],
reason: reason,
- refunder: try_spree_current_user
+ refunder: try_spree_current_user,
+ # Names which order is being refunded. Only matters when the
+ # payment is shared by a split checkout, where it covers several
+ # and the payment cannot say which one this is for.
+ order: @parent
)
if result.success?
@@ -46,8 +50,17 @@ module Spree
Spree.api.admin_refund_serializer
end
+ # Every refund names the order it put right, so this reads the same
+ # for an ordinary order and for one placed in a split checkout,
+ # whose payments belong to its group rather than to itself.
def scope
- Spree::Refund.where(payment_id: @parent.payment_ids)
+ Spree::Refund.where(order_id: @parent.id)
+ end
+
+ # The payments that can settle this order — its own, or its group's
+ # when it was placed alongside others.
+ def settlement_payments
+ @parent.settlement_payments
end
def collection_includes
diff --git a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
index 710b7f7eae..8fbeb26169 100644
--- a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb
@@ -127,11 +127,12 @@ module Spree
)
end
rescue ActiveRecord::RecordNotFound
- # Gateway-race retry with the ORDER id: the webhook completed the
- # cart and the client re-posts with the id it got back. Foreign
- # prefixes never decode against carts, so this only fires for
- # order_ ids (or genuinely unknown ids, which 404 below).
- @cart = current_store.orders.complete.find_by_prefix_id!(params[:id])
+ # Gateway-race retry with the id the client got back: the webhook
+ # completed the cart and the client re-posts. Foreign prefixes never
+ # decode against carts, so this only fires for an order or group id
+ # (or a genuinely unknown one, which 404s below). A split checkout
+ # handed the client a group, so both have to resolve here.
+ @cart = find_completed_result!
authorize_storefront_read!(@cart, token: cart_token)
render_order
@@ -139,6 +140,17 @@ module Spree
protected
+ # The completed result behind an id the client is retrying with —
+ # either the single order a plain checkout produced, or the group a
+ # split one did.
+ #
+ # @return [Spree::Order, Spree::OrderGroup]
+ def find_completed_result!
+ current_store.orders.complete.find_by_prefix_id!(params[:id])
+ rescue ActiveRecord::RecordNotFound
+ current_store.order_groups.find_by_prefix_id!(params[:id])
+ end
+
def model_class
Spree::Order
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/order_group_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/order_group_serializer.rb
new file mode 100644
index 0000000000..9d3e7fb652
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/order_group_serializer.rb
@@ -0,0 +1,50 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Serializes Spree::OrderGroup for the back office — the checkout that
+ # produced several orders, and what ties them together.
+ #
+ # Extends the store serializer, so what a customer sees stays in one
+ # place and this adds only what an operator needs on top: the payment
+ # shares, and the timestamps every admin surface carries.
+ class OrderGroupSerializer < V3::OrderGroupSerializer
+ typelize customer_id: 'string | null',
+ cart_id: 'string | null',
+ seller_count: :number,
+ includes_first_party: :boolean,
+ created_at: :string, updated_at: :string
+
+ attribute :customer_id do |group|
+ group.customer&.prefixed_id
+ end
+
+ attribute :cart_id do |group|
+ Spree::Cart.prefixed_id_for(group.cart_id)
+ end
+
+ # How many sellers this checkout reached — the operator's headline
+ # question about a group, and cheaper than counting the orders client
+ # side once a group is large.
+ attribute :seller_count do |group|
+ group.seller_count
+ end
+
+ attribute :includes_first_party do |group|
+ group.includes_first_party?
+ end
+
+ attributes :created_at, :updated_at
+
+ # Re-declared against the admin serializers. Inheriting the store
+ # ones would render a customer-facing record inside a back-office
+ # response, which is the one thing an admin serializer must never do.
+ one :billing_address, resource: proc { Spree.api.admin_address_serializer }
+ one :shipping_address, resource: proc { Spree.api.admin_address_serializer }
+ many :orders, resource: proc { Spree.api.admin_order_serializer }
+ many :payments, resource: proc { Spree.api.admin_payment_serializer }
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/order_group_serializer.rb b/spree/api/app/serializers/spree/api/v3/order_group_serializer.rb
new file mode 100644
index 0000000000..357ec96d06
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/order_group_serializer.rb
@@ -0,0 +1,59 @@
+module Spree
+ module Api
+ module V3
+ # Store API Order Group Serializer
+ #
+ # What the customer bought in one checkout, when it was fulfilled by more
+ # than one seller. They made one purchase and paid once, so this is what
+ # their order history shows them — with the per-seller orders nested
+ # inside it, each carrying its own items, delivery and tracking.
+ class OrderGroupSerializer < BaseSerializer
+ typelize number: :string, email: [:string, nullable: true], currency: :string,
+ total: [:string, nullable: true], display_total: [:string, nullable: true],
+ item_total: [:string, nullable: true], display_item_total: [:string, nullable: true],
+ fulfillment_status: [:string, nullable: true], payment_status: [:string, nullable: true],
+ completed_at: [:string, nullable: true],
+ billing_address: { nullable: true }, shipping_address: { nullable: true }
+
+ attributes :number, :email, :currency
+
+ attribute :total do |group|
+ group.total.to_s
+ end
+
+ attribute :display_total do |group|
+ group.display_total.to_s
+ end
+
+ attribute :item_total do |group|
+ group.item_total.to_s
+ end
+
+ attribute :display_item_total do |group|
+ group.display_item_total.to_s
+ end
+
+ # Rolled up across the children rather than stored, so it can never
+ # disagree with the orders it describes.
+ attribute :fulfillment_status do |group|
+ group.fulfillment_status
+ end
+
+ attribute :payment_status do |group|
+ group.payment_status
+ end
+
+ attribute :completed_at do |group|
+ group.created_at
+ end
+
+ one :billing_address, resource: proc { Spree.api.address_serializer }
+ one :shipping_address, resource: proc { Spree.api.address_serializer }
+
+ # The whole point of the group: the customer sees one purchase, and the
+ # seller orders inside it are how it will arrive.
+ many :orders, resource: proc { Spree.api.order_serializer }
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index e0f90e4bac..acfac72f57 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -479,6 +479,10 @@ Spree::Core::Engine.add_routes do
end
resources :commission_lines, only: [:index, :show]
+ # What one checkout produced when it reached several sellers. Read-only:
+ # everything an operator acts on lives on the orders inside it.
+ resources :order_groups, only: [:index, :show]
+
# Business customers. Branches and their buyers are created under their
# parent and then addressed directly, so a caller holding a branch id
# does not have to know which company it belongs to.
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index 6efb91bbf7..30585cd3c9 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -16,6 +16,7 @@ module Spree
option_value_serializer: 'Spree::Api::V3::OptionValueSerializer',
cart_serializer: 'Spree::Api::V3::CartSerializer',
order_serializer: 'Spree::Api::V3::OrderSerializer',
+ order_group_serializer: 'Spree::Api::V3::OrderGroupSerializer',
line_item_serializer: 'Spree::Api::V3::LineItemSerializer',
payment_serializer: 'Spree::Api::V3::PaymentSerializer',
payment_session_serializer: 'Spree::Api::V3::PaymentSessionSerializer',
@@ -109,6 +110,7 @@ module Spree
admin_customer_serializer: 'Spree::Api::V3::Admin::CustomerSerializer',
admin_newsletter_subscriber_serializer: 'Spree::Api::V3::Admin::NewsletterSubscriberSerializer',
admin_order_serializer: 'Spree::Api::V3::Admin::OrderSerializer',
+ admin_order_group_serializer: 'Spree::Api::V3::Admin::OrderGroupSerializer',
admin_product_serializer: 'Spree::Api::V3::Admin::ProductSerializer',
admin_product_type_serializer: 'Spree::Api::V3::Admin::ProductTypeSerializer',
admin_product_type_custom_field_definition_serializer: 'Spree::Api::V3::Admin::ProductTypeCustomFieldDefinitionSerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/order_groups_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/order_groups_controller_spec.rb
new file mode 100644
index 0000000000..bc92fd846a
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/order_groups_controller_spec.rb
@@ -0,0 +1,61 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::OrderGroupsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let(:seller) { create(:seller, :approved, store: store, name: 'Sparks Audio') }
+ let!(:group) { create(:order_group, store: store) }
+ let!(:first_party_order) { create(:order, store: store, order_group: group, total: 30) }
+ let!(:seller_order) { create(:order, store: store, order_group: group, seller: seller, total: 20) }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ it 'lists the store’s groups' do
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].size).to eq(1)
+ expect(json_response['data'].first['number']).to eq(group.number)
+ end
+
+ it 'does not list another store’s groups' do
+ create(:order_group, store: create(:store))
+
+ get :index
+
+ expect(json_response['data'].size).to eq(1)
+ end
+ end
+
+ describe 'GET #show' do
+ it 'reports what the checkout came to and who it reached' do
+ get :show, params: { id: group.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(BigDecimal(json_response['total'])).to eq(50)
+ expect(json_response['seller_count']).to eq(1)
+ expect(json_response['includes_first_party']).to be(true)
+ end
+
+ it 'nests the orders it holds' do
+ get :show, params: { id: group.prefixed_id }
+
+ numbers = json_response['orders'].map { |order| order['number'] }
+ expect(numbers).to contain_exactly(first_party_order.number, seller_order.number)
+ end
+ end
+
+ # Read-only by routing: a group records a checkout that already happened.
+ describe 'writes' do
+ it 'has no create route' do
+ expect { post :create, params: {} }.to raise_error(ActionController::UrlGenerationError)
+ end
+
+ it 'has no destroy route' do
+ expect { delete :destroy, params: { id: group.prefixed_id } }.to raise_error(ActionController::UrlGenerationError)
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts_split_checkout_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts_split_checkout_spec.rb
new file mode 100644
index 0000000000..6470278054
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts_split_checkout_spec.rb
@@ -0,0 +1,78 @@
+require 'spec_helper'
+
+# What a customer gets back when their basket held several sellers' goods: one
+# purchase, with the per-seller orders inside it.
+RSpec.describe Spree::Api::V3::Store::CartsController, 'split checkout', type: :controller do
+ render_views
+
+ include_context 'API v3 Store'
+
+ let(:seller) { create(:seller, :approved, store: store) }
+
+ before do
+ request.headers['X-Spree-Api-Key'] = api_key.token
+ request.headers['Authorization'] = "Bearer #{jwt_token}"
+ create(:shipping_method) if Spree::DeliveryMethod.none?
+ end
+
+ # A basket of the operator's own goods plus one seller's — the mixed case.
+ let(:cart) do
+ cart = create(:cart_with_line_items, customer: user, store: store, line_items_count: 2)
+ cart.update!(email: user.email, ship_address: create(:address), bill_address: create(:address))
+
+ seller_line = cart.line_items.reload.last
+ seller_line.variant.update!(seller: seller)
+ seller_line.update_columns(seller_id: seller.id)
+
+ cart.rebuild_fulfillments!
+ cart.set_fulfillments_cost
+ cart.reload.recalculate_totals!
+ create(:payment, cart: cart, amount: cart.reload.total).tap(&:create_payment_profile)
+ cart
+ end
+
+ it 'answers with the group rather than one of the orders' do
+ post :complete, params: { id: cart.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to start_with('ogrp_')
+ expect(json_response['orders'].size).to eq(2)
+ end
+
+ it 'shows the customer one total for the purchase' do
+ post :complete, params: { id: cart.prefixed_id }
+
+ expect(BigDecimal(json_response['total'])).to eq(cart.reload.total)
+ end
+
+ it 'nests each seller’s order with its own items and total' do
+ post :complete, params: { id: cart.prefixed_id }
+
+ orders = json_response['orders']
+ expect(orders.map { |order| order['items'].size }).to all(eq(1))
+ expect(orders.sum { |order| BigDecimal(order['total']) }).to eq(cart.reload.total)
+ end
+
+ it 'lets the client retry with the group id it was given' do
+ post :complete, params: { id: cart.prefixed_id }
+ group_id = json_response['id']
+
+ post :complete, params: { id: group_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(group_id)
+ end
+
+ it 'leaves an unsplit checkout answering with a bare order' do
+ plain = create(:cart_with_line_items, customer: user, store: store)
+ plain.update!(email: user.email, ship_address: create(:address), bill_address: create(:address))
+ plain.rebuild_fulfillments!
+ plain.set_fulfillments_cost
+ create(:payment, cart: plain, amount: plain.reload.total).tap(&:create_payment_profile)
+
+ post :complete, params: { id: plain.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to start_with('or_')
+ end
+end
diff --git a/spree/core/app/models/concerns/spree/marketplace/order_group.rb b/spree/core/app/models/concerns/spree/marketplace/order_group.rb
new file mode 100644
index 0000000000..9f5fe093fa
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/marketplace/order_group.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+module Spree
+ module Marketplace
+ # What a marketplace wants to know about one checkout's group of orders.
+ #
+ # {Spree::OrderGroup} is deliberately domain-neutral — "N orders placed
+ # together as one customer transaction" — because the same container serves
+ # split-by-location, split-by-availability and B2B split-by-company-location,
+ # none of which involve a seller
+ # (docs/plans/6.0-multi-vendor-marketplace.md, Decision 8). So the seller is
+ # asked about here rather than there, and the primitive keeps meaning the
+ # same thing for its other consumers.
+ module OrderGroup
+ extend ActiveSupport::Concern
+
+ # @return [ActiveRecord::Relation<Spree::Seller>] the sellers this
+ # checkout reached; the operator's own goods contribute none
+ def sellers
+ store.sellers.where(id: orders.filter_map(&:seller_id).uniq)
+ end
+
+ # @return [Integer]
+ def seller_count
+ orders.filter_map(&:seller_id).uniq.size
+ end
+
+ # @return [Boolean] whether any child order carries no seller — the
+ # operator's own goods, bought alongside sellers' in one checkout
+ def includes_first_party?
+ orders.any? { |order| order.seller_id.nil? }
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rb
index a63096d0a4..5dc1ab31f5 100644
--- a/spree/core/app/models/spree/cart.rb
+++ b/spree/core/app/models/spree/cart.rb
@@ -88,6 +88,9 @@ module Spree
has_many :payment_sessions, class_name: 'Spree::PaymentSession', inverse_of: :cart, dependent: :destroy
has_many :stock_reservations, class_name: 'Spree::StockReservation', inverse_of: :cart, dependent: :destroy
has_one :order, class_name: 'Spree::Order', inverse_of: :cart
+ # A cart spanning more than one seller completes into a group of orders
+ # instead of a single one — exactly one of these two is ever set.
+ has_one :order_group, class_name: 'Spree::OrderGroup', inverse_of: :cart
alias items line_items
diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rb
index f1d01bd16b..4f97fc0e50 100644
--- a/spree/core/app/models/spree/fulfillment.rb
+++ b/spree/core/app/models/spree/fulfillment.rb
@@ -447,9 +447,16 @@ module Spree
# Read through +owner+ rather than +order+: a fulfillment can still belong
# to a cart, and both carry pending_payments.
#
+ # An order placed in a split checkout has no payments of its own — the
+ # customer paid once, against the group — so the pool comes from there
+ # instead. What this parcel may draw from it is still bounded by its own
+ # order's share; see {#process_order_payments}.
+ #
# @return [Array<Spree::Payment>]
def payments_to_capture_on_dispatch
- Array(owner&.pending_payments).select { |payment| payment.payment_method&.capture_on_dispatch? }
+ pool = grouped_owner? ? owner.settlement_payments.pending : Array(owner&.pending_payments)
+
+ Array(pool).select { |payment| payment.payment_method&.capture_on_dispatch? }
end
def process_order_payments
@@ -473,11 +480,8 @@ module Spree
payment.amount
end
- cents = (capturable_amount * 100).to_i
- 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
+ captured = capture_from(payment, capturable_amount)
+ shipment_to_pay -= captured
end
end
@@ -750,6 +754,72 @@ module Spree
private
+ # @return [Boolean] whether this parcel's order shares its payment with
+ # others placed in the same checkout
+ # Draws one parcel's worth from a payment and reports what it took.
+ #
+ # A payment shared by a split checkout is only ever drawn on up to this
+ # order's own share of it — without the bound, the first seller to ship
+ # would capture against the whole basket and leave nothing authorised for
+ # the rest. The bound is read and written **inside the share's lock**, so
+ # two parcels of the same order dispatching at once cannot both read the
+ # same remaining share and each capture it.
+ #
+ # @return [BigDecimal] what was actually captured
+ def capture_from(payment, capturable_amount)
+ return capture_at_gateway(payment, capturable_amount) unless grouped_owner?
+
+ split = owner.payment_split_for(payment)
+ return 0 if split.nil?
+
+ # Claimed before the gateway, and in its own short transaction rather
+ # than one held across the network call. Two reasons the claim comes
+ # first: two parcels of the same order dispatching at once would
+ # otherwise both read the same remaining share, and capturing part of a
+ # shared payment forks the remainder, carrying each order's
+ # still-uncaptured share across — a share not yet marked taken would be
+ # carried over in full and paid to this order twice.
+ bounded = claim_share(split, capturable_amount)
+ return 0 if bounded <= 0
+
+ begin
+ capture_at_gateway(payment, bounded)
+ rescue StandardError
+ # The money never moved, so the claim must not stand.
+ split.with_lock { split.update!(captured_amount: split.captured_amount - bounded) }
+ raise
+ end
+
+ bounded
+ end
+
+ # @return [BigDecimal] how much of the share this parcel may take, marked
+ # as taken; zero when nothing is left
+ def claim_share(split, capturable_amount)
+ split.with_lock do
+ bounded = [capturable_amount, split.authorized_amount - split.captured_amount].min
+ next 0 if bounded <= 0
+
+ split.update!(captured_amount: split.captured_amount + bounded)
+ bounded
+ end
+ end
+
+ # @return [BigDecimal] the amount captured, so callers can draw it down
+ def capture_at_gateway(payment, amount)
+ return 0 if amount <= 0
+
+ units = Spree::Money::Rounding.to_minor_units(amount, payment.currency)
+ result = Spree.payment_capture_workflow.call(payment: payment, amount: units)
+ raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?
+
+ amount
+ end
+
+ def grouped_owner?
+ owner.is_a?(Spree::Order) && owner.grouped?
+ end
+
# Inlined from the removed ShipmentHandler (its name-constantize factory
# could never match a real subclass); FulfillmentProvider takes over the
# type-specific mechanics in the provider wave.
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index a1f7c20716..de8167d886 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -149,6 +149,13 @@ module Spree
# The cart this order was completed from (unique — the completion
# idempotency key). Backoffice draft orders have no cart.
belongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :order
+ # The checkout this order was placed in, when it was placed alongside
+ # others — one per seller on a marketplace. A single-seller or first-party
+ # only checkout produces a bare order and no group.
+ belongs_to :order_group, class_name: 'Spree::OrderGroup', optional: true, inverse_of: :orders
+ # Whose sale this is. Nil on the operator's own goods, including the
+ # first-party child of a mixed marketplace checkout.
+ belongs_to :seller, class_name: 'Spree::Seller', optional: true
belongs_to :created_by, class_name: "::#{Spree.admin_user_class}", optional: true
belongs_to :approver, class_name: "::#{Spree.admin_user_class}", optional: true
belongs_to :canceler, class_name: "::#{Spree.admin_user_class}", optional: true
@@ -171,7 +178,11 @@ module Spree
has_many :return_line_items, through: :returns, class_name: 'Spree::ReturnLineItem', source: :return_line_items
has_many :variants, through: :line_items
has_many :products, through: :variants
- has_many :refunds, through: :payments
+ # Every refund names the order it puts right — its own payments' refunds
+ # stamp it automatically, and a refund against a payment shared by a split
+ # checkout names the one child being refunded. Keyed on that column rather
+ # than walked through payments, which a grouped order does not own.
+ has_many :refunds, class_name: 'Spree::Refund', inverse_of: :order, dependent: :nullify
# Typed adjustment rows owned by this order (line-, fulfillment- and
# order-level). See docs/plans/6.0-6.1-split-adjustments.md.
@@ -187,6 +198,10 @@ module Spree
# ledger the order merely hosts. See docs/plans/6.0-multi-vendor-marketplace.md.
has_many :commission_lines, class_name: 'Spree::CommissionLine', dependent: :destroy, inverse_of: :order
+ # This order's share of the payments made against its group. Empty on an
+ # ungrouped order, whose payments are its own (see #settlement_payments).
+ has_many :payment_splits, class_name: 'Spree::PaymentSplit', dependent: :destroy, inverse_of: :order
+
has_many :line_item_tax_lines, through: :line_items, source: :tax_lines
has_many :line_item_discounts, through: :line_items, source: :discounts
@@ -557,6 +572,34 @@ module Spree
end
+ # The payments that settle this order.
+ #
+ # An order placed in a split checkout has none of its own: the customer
+ # made one payment for the whole basket, against the group. Anything asking
+ # what money exists for this order — capture on dispatch, refunds, the
+ # admin payments panel — reads it here, and reads its own share of it from
+ # {#payment_splits}.
+ #
+ # @return [ActiveRecord::Relation<Spree::Payment>]
+ def settlement_payments
+ order_group_id.present? ? order_group.payments : payments
+ end
+
+ # @return [Boolean] whether this order was placed alongside others in one
+ # checkout, and therefore shares their payment
+ def grouped?
+ order_group_id.present?
+ end
+
+
+ # This order's share of one payment made against its group.
+ #
+ # @param payment [Spree::Payment]
+ # @return [Spree::PaymentSplit, nil]
+ def payment_split_for(payment)
+ payment_splits.find_by(payment_id: payment.id)
+ end
+
def name
if (address = bill_address || ship_address)
address.full_name
diff --git a/spree/core/app/models/spree/order_group.rb b/spree/core/app/models/spree/order_group.rb
new file mode 100644
index 0000000000..636ba33ed1
--- /dev/null
+++ b/spree/core/app/models/spree/order_group.rb
@@ -0,0 +1,218 @@
+# frozen_string_literal: true
+
+module Spree
+ # N orders placed together as one customer checkout.
+ #
+ # Deliberately domain-neutral. Multi-vendor is its first consumer — a mixed
+ # cart splits into one order per seller — but the same container serves
+ # split-by-fulfillment-location, split-by-availability and B2B
+ # split-by-company-location, none of which involve a seller. The seller
+ # therefore lives on the child order and never here
+ # (docs/plans/6.0-multi-vendor-marketplace.md, Decision 8).
+ #
+ # The group owns what the customer experienced once: the payment they made,
+ # the addresses they entered, the contact email. Children own what varies per
+ # seller: line items, fulfillments, totals, and their own money lines.
+ #
+ # Status is derived across the children rather than stored, because a column
+ # would be a second source of truth for something the children already
+ # answer, and it would need re-writing on every child transition.
+ class OrderGroup < Spree.base_class
+ has_prefix_id :ogrp
+
+ include Spree::Metadata
+ include Spree::SingleStoreResource
+ # The same number rules an order follows — the group's number seeds its
+ # children's, so a difference in case or length would show up between a
+ # group and the orders named after it.
+ include Spree::NumberIdentifier
+ # A payment is validated and sized against whatever it was made against, so
+ # the group has to answer the same store-credit questions a cart or an
+ # order does — it is what the customer paid.
+ include Spree::Purchase::StoreCredits
+
+ # Shares the order counter rather than running one of its own: a group and
+ # an order are both things a customer calls "my order", and two counters
+ # behind one `R` prefix would eventually issue the same string for both.
+ # In practice the split copies the number from the order it adopts, so this
+ # only fires for a group created some other way.
+ has_spree_number prefix: 'R', key: :order
+
+ publishes_lifecycle_events
+
+ #
+ # Associations
+ #
+ belongs_to :store, class_name: 'Spree::Store'
+ belongs_to :customer, class_name: "::#{Spree.customer_class}", optional: true
+ # The cart this group was completed from — unique, and the replay key that
+ # makes a retried completion return this group instead of building another.
+ belongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :order_group
+
+ # restrict_with_error, never cascade: these are completed orders, and a
+ # container going away is not a reason to lose them.
+ has_many :orders, class_name: 'Spree::Order', inverse_of: :order_group, dependent: :restrict_with_error
+ has_many :payments, class_name: 'Spree::Payment', inverse_of: :order_group, dependent: :restrict_with_error
+ has_many :payment_splits, through: :payments, class_name: 'Spree::PaymentSplit', source: :payment_splits
+
+ # Brings the ship/bill pair with the shipping_address/billing_address
+ # aliases every other purchase surface reads them by.
+ #
+ # Only the associations and aliases apply here. The concern's checkout
+ # helpers — shipping_address_required?, assign_default_addresses! — reach
+ # for line items, fulfillments and digital goods, none of which a group
+ # has: they belong to its children, which answer those questions for
+ # themselves. A group's addresses are copies made when the checkout
+ # divided, so nothing asks it to work them out.
+ include Spree::Purchase::Addresses
+ # What a marketplace asks about a group. Kept out of the class itself so
+ # this stays the neutral primitive its other consumers need.
+ include Spree::Marketplace::OrderGroup
+
+ #
+ # Validations
+ #
+ validates :currency, presence: true
+
+ #
+ # Scopes
+ #
+ self.whitelisted_ransackable_attributes = %w[number email currency created_at]
+ self.whitelisted_ransackable_associations = %w[orders customer]
+
+ extend Spree::DisplayMoney
+ money_methods :total, :item_total
+
+ # What the customer was charged for the whole checkout, and what it was
+ # charged for — the sums of what each child independently computed. Never
+ # prorated downward: the children are the record, these are the roll-up,
+ # and a gateway asking what it is charging for gets the whole basket
+ # because the whole basket is what the one charge covers.
+ #
+ # Summed in Ruby rather than by SQL aggregate: anything reading these has
+ # the children loaded already (a serializer renders them, a gateway call
+ # reads four of these in a row), and an aggregate per figure would issue a
+ # query each time even against rows sitting in memory.
+ ROLLED_UP_TOTALS = %i[
+ total item_total delivery_total additional_tax_total included_tax_total
+ discount_total fee_total
+ ].freeze
+
+ ROLLED_UP_TOTALS.each do |figure|
+ define_method(figure) do
+ rolled_up_totals[figure]
+ end
+ end
+
+ alias ship_total delivery_total
+
+ # Where the checkout was made from, carried on the children because they
+ # are what the checkout produced.
+ #
+ # @return [String, nil]
+ def last_ip_address
+ orders.first&.last_ip_address
+ end
+
+ # @return [String, nil] the group's fulfillment position, in the same
+ # vocabulary a single order uses, rolled up across children
+ def fulfillment_status
+ roll_up(orders.map(&:fulfillment_status)) do |statuses|
+ # Canceled siblings do not make the group canceled — a recalled parcel
+ # does not describe the purchase while another is still coming.
+ live = statuses - ['canceled']
+ next 'canceled' if live.empty?
+
+ live.one? ? live.first : 'partial'
+ end
+ end
+
+ # The payment is shared, but each child reports its own share of it — so
+ # this rolls those up rather than reading the payment, and a checkout with
+ # one seller shipped and another not says so.
+ #
+ # @return [String, nil]
+ def payment_status
+ roll_up(orders.map(&:payment_status))
+ end
+
+ #
+ # The payment-owner contract. A payment reads these off whatever it was
+ # made against — the group answers them by rolling up its children rather
+ # than from columns of its own, since the children are the record of what
+ # was sold and this is only the container they were bought in.
+ #
+
+ # @return [BigDecimal] completed payments on this group, less their refunds
+ def payment_total
+ @payment_total ||= begin
+ settled = payments.select { |payment| payment.status == 'completed' }
+ settled.sum(&:amount) - Spree::Refund.where(payment_id: settled.map(&:id)).sum(:amount)
+ end
+ end
+
+ # Nothing to persist — payment_total is derived here — but the payment path
+ # calls this after settling, so it must exist, and it must forget what it
+ # last worked out or a settled payment would go unnoticed.
+ #
+ # @return [BigDecimal]
+ def refresh_payment_total!
+ forget_derived_money
+ payment_total
+ end
+
+ # Drops the memoized roll-ups. Money moves through the children and their
+ # payments, not through this record, so nothing here is dirtied by a write
+ # that changes what it reports.
+ def forget_derived_money
+ @rolled_up_totals = nil
+ @payment_total = nil
+ end
+
+ # @return [BigDecimal] still to collect across the whole checkout
+ def outstanding_balance
+ total - payment_total
+ end
+
+ # @return [Boolean]
+ def paid?
+ total.positive? && payment_total >= total
+ end
+
+ # A group only ever exists because a checkout finished, so it is completed
+ # by construction. Store-credit reporting asks, to tell what was applied
+ # from what could still be.
+ #
+ # @return [Boolean]
+ def completed?
+ true
+ end
+
+ def number_store
+ store
+ end
+
+ private
+
+ # One pass over the children for every figure, so reading four of them
+ # costs what reading one does.
+ def rolled_up_totals
+ @rolled_up_totals ||= orders.to_a.each_with_object(Hash.new(BigDecimal(0))) do |order, totals|
+ ROLLED_UP_TOTALS.each { |figure| totals[figure] += order.public_send(figure).to_d }
+ end
+ end
+
+ # Collapses the children's answers into one word: nothing to say, the one
+ # they agree on, or a mixture. What a mixture means is the caller's, since
+ # only it knows which of its values absorb the others.
+ #
+ # @return [String, nil]
+ def roll_up(statuses)
+ statuses = statuses.compact.uniq
+ return if statuses.empty?
+ return statuses.first if statuses.one?
+
+ block_given? ? yield(statuses) : 'partial'
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/payment.rb b/spree/core/app/models/spree/payment.rb
index 2a58be7916..0bf6a13b40 100644
--- a/spree/core/app/models/spree/payment.rb
+++ b/spree/core/app/models/spree/payment.rb
@@ -28,8 +28,13 @@ module Spree
with_options inverse_of: :payments do
belongs_to :order, class_name: 'Spree::Order', touch: true, optional: true
belongs_to :cart, class_name: 'Spree::Cart', optional: true
+ # A grouped checkout's payment belongs to the group: there is one charge
+ # for the whole basket, and the per-order shares are payment_splits.
+ belongs_to :order_group, class_name: 'Spree::OrderGroup', optional: true
belongs_to :payment_method, -> { with_deleted }, class_name: 'Spree::PaymentMethod'
end
+
+ has_many :payment_splits, class_name: 'Spree::PaymentSplit', dependent: :destroy, inverse_of: :payment
belongs_to :source, polymorphic: true
validate :exactly_one_owner
@@ -344,10 +349,38 @@ module Spree
status: 'pending',
capture_on_dispatch: true
)
- update(amount: captured_amount)
+ carry_splits_to(remainder)
+ # Bang: a silent failure here would leave this payment at its full amount
+ # beside a remainder that also exists, so the group would hold more money
+ # than the customer was ever charged.
+ update!(amount: captured_amount)
remainder
end
+ # Hands each order's still-uncaptured share over to the remainder payment.
+ #
+ # A shared payment covers several orders, so capturing one seller's share
+ # shrinks a payment the others are still relying on. Their shares have to
+ # move to the remainder with the money, or the sellers who have not shipped
+ # would be left pointing at an authorization that no longer holds their
+ # amount — unable to capture, and reading as unpaid forever.
+ def carry_splits_to(remainder)
+ return unless grouped?
+
+ payment_splits.each do |split|
+ outstanding = split.authorized_amount - split.captured_amount
+ next if outstanding <= 0
+
+ Spree::PaymentSplit.create!(
+ payment: remainder,
+ order_id: split.order_id,
+ currency: split.currency,
+ authorized_amount: outstanding
+ )
+ split.update!(authorized_amount: split.captured_amount)
+ end
+ end
+
def editable?
checkout? || pending?
end
@@ -395,9 +428,20 @@ module Spree
has_invalid_status?
end
- # @return [Spree::Cart, Spree::Order, nil]
+ # What this payment was made against — a cart mid-checkout, a single order,
+ # or the group a split checkout produced. Everything reading totals,
+ # currency or gateway options goes through here rather than through #order,
+ # which is nil on a grouped payment.
+ #
+ # @return [Spree::Cart, Spree::Order, Spree::OrderGroup, nil]
def owner
- order || cart
+ order || cart || order_group
+ end
+
+ # @return [Boolean] whether this payment covers several orders placed in one
+ # checkout, in which case its per-order shares are {#payment_splits}
+ def grouped?
+ order_group_id.present?
end
# Bridge for legacy callers assigning +current_order+ (now a Spree::Cart)
@@ -451,7 +495,7 @@ module Spree
end
def exactly_one_owner
- errors.add(:base, Spree.t('errors.messages.exactly_one_of_cart_or_order')) unless [order, cart].compact.one?
+ errors.add(:base, Spree.t('errors.messages.exactly_one_of_cart_or_order')) unless [order, cart, order_group].compact.one?
end
def set_amount
diff --git a/spree/core/app/models/spree/payment/custom_events.rb b/spree/core/app/models/spree/payment/custom_events.rb
index 57b8fd87f5..3fe236d80e 100644
--- a/spree/core/app/models/spree/payment/custom_events.rb
+++ b/spree/core/app/models/spree/payment/custom_events.rb
@@ -27,6 +27,11 @@ module Spree
def publish_payment_paid_event
publish_event('payment.paid')
+ # A payment shared by a split checkout belongs to no single order, so
+ # each child is asked about its own share. order.paid is a public
+ # webhook; a marketplace order must announce itself paid like any other.
+ return publish_grouped_paid_events if grouped?
+
# order is nil for a cart-owned payment — checkout is still in
# flight, so there is no order to declare paid yet.
return if order.nil?
@@ -46,6 +51,19 @@ module Spree
settled = order.payments.completed.includes(:refunds).sum { |payment| payment.amount - payment.refunds.sum(:amount) }
settled >= order.total.to_d
end
+
+ # Declares each child of a split checkout paid once its own shares cover
+ # its total — which is not all at once, since one seller can be captured
+ # on dispatch while another is still waiting.
+ def publish_grouped_paid_events
+ payment_splits.includes(:order).each do |split|
+ child = split.order
+ next if child.nil? || child.total.to_d <= 0
+
+ settled = child.payment_splits.sum { |row| row.captured_amount - row.refunded_amount }
+ child.publish_event('order.paid') if settled >= child.total.to_d
+ end
+ end
end
end
end
diff --git a/spree/core/app/models/spree/payment_split.rb b/spree/core/app/models/spree/payment_split.rb
new file mode 100644
index 0000000000..8cabd33706
--- /dev/null
+++ b/spree/core/app/models/spree/payment_split.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+module Spree
+ # One child order's share of one payment made against an order group.
+ #
+ # A grouped checkout takes a single charge — the customer authorised one
+ # amount, and creating N gateway charges would change what they agreed to.
+ # The per-seller bookkeeping is these rows: each child order's authorised,
+ # captured and refunded share of that one payment.
+ #
+ # Durable rather than computed on read, because the shares stop being
+ # proportional the moment anything partial happens: one seller ships and is
+ # captured while another has not, one child is refunded and its siblings are
+ # not. A proportion recomputed from current totals cannot express that
+ # history; a row can.
+ #
+ # Every payment on the group gets its own set of rows — the gateway charge,
+ # the store credit, the gift card — so a child's shares across all of them
+ # sum to that child's total, whatever the customer paid with.
+ class PaymentSplit < Spree.base_class
+ has_prefix_id :paysp
+
+ #
+ # Associations
+ #
+ belongs_to :payment, class_name: 'Spree::Payment', inverse_of: :payment_splits
+ belongs_to :order, class_name: 'Spree::Order', inverse_of: :payment_splits
+
+ #
+ # Validations
+ #
+ validates :authorized_amount, :captured_amount, :refunded_amount, numericality: true
+ validates :currency, presence: true
+ validates :order_id, uniqueness: { scope: [:payment_id, *spree_base_uniqueness_scope] }
+
+ #
+ # Scopes
+ #
+ self.whitelisted_ransackable_attributes = %w[currency authorized_amount captured_amount refunded_amount]
+ self.whitelisted_ransackable_associations = %w[payment order]
+
+ extend Spree::DisplayMoney
+ money_methods :authorized_amount, :captured_amount, :refunded_amount
+
+ # @return [BigDecimal] what this child still has captured against it after
+ # refunds — the figure a seller's earnings are computed from
+ def net_captured_amount
+ captured_amount - refunded_amount
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/refund.rb b/spree/core/app/models/spree/refund.rb
index d237d20ce3..7906c2d7e8 100644
--- a/spree/core/app/models/spree/refund.rb
+++ b/spree/core/app/models/spree/refund.rb
@@ -12,6 +12,11 @@ module Spree
publishes_lifecycle_events
belongs_to :payment, inverse_of: :refunds
+ # Which order is being put right. A refund against an ordinary payment
+ # takes the payment's order automatically; one against a payment shared by
+ # a split checkout must name the child order it applies to, since the
+ # payment covers several and only one of them is being refunded.
+ belongs_to :order, class_name: 'Spree::Order', optional: true, inverse_of: :refunds
belongs_to :reason, class_name: 'Spree::RefundReason', foreign_key: :refund_reason_id
belongs_to :refunder, class_name: Spree.admin_user_class.to_s, optional: true
# What triggered this refund — a Spree::Return today, later an Exchange
@@ -29,7 +34,12 @@ module Spree
attr_reader :response
- delegate :order, :currency, to: :payment
+ delegate :currency, to: :payment
+
+ # A refund always knows its order, so every reader — the scopes, the
+ # ledger, the split's share — can rely on the column rather than walking
+ # back through a payment that may belong to several orders.
+ before_validation :assign_order_from_payment, on: :create
def amount=(amount)
self[:amount] = Spree::LocalizedNumber.parse(amount)
@@ -82,6 +92,13 @@ module Spree
private
+ # A payment belonging to one order answers this for itself; a payment
+ # shared by a split checkout cannot, so the caller has to have said which
+ # order it is refunding.
+ def assign_order_from_payment
+ self.order_id ||= payment&.order_id
+ end
+
# return a payment response object if successful or else raise an error
def process!(credit_cents)
refund_total_in_cents = calculate_refund_amount(credit_cents)
@@ -123,8 +140,11 @@ module Spree
end
end
+ # Re-sums the order this refund put right. Read through the refund's own
+ # order rather than the payment's: a payment shared by a split checkout
+ # belongs to no single order, and it is this one order's money that moved.
def update_order
- payment.order.recalculate_totals!
+ order&.recalculate_totals!
end
end
end
diff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rb
index 4471a5de6a..11e567b397 100644
--- a/spree/core/app/models/spree/seller.rb
+++ b/spree/core/app/models/spree/seller.rb
@@ -97,6 +97,13 @@ module Spree
# be worse than no record at all.
has_many :commission_lines, class_name: 'Spree::CommissionLine', dependent: nil
+ # This seller's own orders — the child orders a split checkout produced,
+ # and whole orders on a single-seller checkout. Left alone when the seller
+ # goes, for the same reason as commission lines: a completed sale outlives
+ # the party that made it.
+ has_many :orders, class_name: 'Spree::Order', dependent: nil
+ has_many :payment_splits, through: :orders, class_name: 'Spree::PaymentSplit', source: :payment_splits
+
# What this seller has done about the marketplace's requirements — their
# attestations, the documents they uploaded, what the operator made of
# them. Goes with the seller, since it means nothing without them.
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 3b79c85687..cf6037e35e 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -128,6 +128,7 @@ module Spree
#
has_many :carts, class_name: 'Spree::Cart', inverse_of: :store, dependent: :destroy
has_many :orders, class_name: 'Spree::Order'
+ has_many :order_groups, class_name: 'Spree::OrderGroup'
has_many :line_items, through: :orders, class_name: 'Spree::LineItem'
has_many :digital_links, through: :line_items, class_name: 'Spree::DigitalLink'
has_many :fulfillments, through: :orders, class_name: 'Spree::Fulfillment'
diff --git a/spree/core/app/models/spree/storefront/access_policy.rb b/spree/core/app/models/spree/storefront/access_policy.rb
index c088d48c1a..cb475d5266 100644
--- a/spree/core/app/models/spree/storefront/access_policy.rb
+++ b/spree/core/app/models/spree/storefront/access_policy.rb
@@ -112,12 +112,15 @@ module Spree
purchase.token.present? && token == purchase.token
end
+ # An order group is a purchase for access purposes: it carries the same
+ # customer and guest token, and a guest who split their basket across
+ # sellers has to be able to see what they bought.
def purchase?(record)
- record.is_a?(Spree::Cart) || record.is_a?(Spree::Order)
+ record.is_a?(Spree::Cart) || record.is_a?(Spree::Order) || record.is_a?(Spree::OrderGroup)
end
def purchase_class?(klass)
- klass <= Spree::Cart || klass <= Spree::Order
+ klass <= Spree::Cart || klass <= Spree::Order || klass <= Spree::OrderGroup
end
# --- everything else: ownership ---
diff --git a/spree/core/app/services/spree/carts/partition_by_seller.rb b/spree/core/app/services/spree/carts/partition_by_seller.rb
new file mode 100644
index 0000000000..dac161e6e7
--- /dev/null
+++ b/spree/core/app/services/spree/carts/partition_by_seller.rb
@@ -0,0 +1,71 @@
+module Spree
+ module Carts
+ # Decides how a purchase divides into orders, and refreshes the line items
+ # whose answer has gone stale.
+ #
+ # The partition key is the line item's own +seller_id+, denormalised from
+ # the variant at add-to-cart. It has to be revalidated before the split
+ # because ownership can change while items sit in a cart — a seller takes
+ # over a listing, an operator brings one in-house — and partitioning on a
+ # stale snapshot would file the sale under a seller who no longer sells it.
+ #
+ # Items with no seller are the operator's own goods, and they form a
+ # partition of their own rather than being folded into anyone else's. That
+ # is what makes a mixed basket — some first-party stock, some from two
+ # sellers — divide into three orders, one of which is a perfectly ordinary
+ # first-party order carrying no seller and no commission.
+ class PartitionBySeller
+ prepend Spree::ServiceModule::Base
+
+ # @param purchase [Spree::Cart, Spree::Order] whatever owns the line items
+ # being divided; the completion passes the paid draft order
+ # @return [Spree::ServiceModule::Result] value is an Array of
+ # Spree::Carts::SellerPartition, first party first and then by seller id,
+ # so a checkout divides the same way twice running
+ def call(purchase:)
+ line_items = purchase.line_items.includes(variant: :product).to_a
+ refresh_stale_sellers(line_items)
+
+ partitions = line_items.group_by(&:seller_id).map do |seller_id, items|
+ SellerPartition.new(seller_id: seller_id, line_items: items)
+ end
+
+ success(partitions.sort_by { |partition| [partition.seller_id.nil? ? 0 : 1, partition.seller_id.to_i] })
+ end
+
+ private
+
+ # Re-reads each line's seller from the variant it points at. Writes only
+ # the rows that actually moved, and through update_columns: this runs
+ # inside completion, and touching a line item would re-enter recalculation
+ # for a change that alters no money. The in-memory rows are updated with
+ # it, so the grouping above sees the refreshed answer without re-reading.
+ def refresh_stale_sellers(line_items)
+ line_items.each do |line_item|
+ current = line_item.variant&.resolved_seller_id
+ next if current == line_item.seller_id
+
+ line_item.update_columns(seller_id: current, updated_at: Time.current)
+ end
+ end
+ end
+
+ # One order's worth of a divided purchase.
+ class SellerPartition
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+
+ # Nil on the operator's own goods, which form a partition like any other.
+ attribute :seller_id, :integer
+ attr_accessor :line_items
+
+ # What this partition's items are worth before delivery, taxes and
+ # order-level money — the weight order-level rows prorate by.
+ #
+ # @return [BigDecimal]
+ def item_total
+ line_items.sum(&:amount)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/carts/split_by_seller.rb b/spree/core/app/services/spree/carts/split_by_seller.rb
new file mode 100644
index 0000000000..6021c96043
--- /dev/null
+++ b/spree/core/app/services/spree/carts/split_by_seller.rb
@@ -0,0 +1,379 @@
+module Spree
+ module Carts
+ # Divides the paid draft order into one order per seller, under a group.
+ #
+ # Called by {Spree::Carts::Complete} when a checkout spans more than one
+ # partition. The order this receives is the one the completion already
+ # built and took payment against, holding the whole basket: this narrows it
+ # to its own seller's items and moves the rest onto new sibling orders.
+ #
+ # Moving rather than re-copying is deliberate. Every line item, fulfillment
+ # and typed money row was costed once, during completion, inside the lock —
+ # re-deriving any of it here would ask the pricing and tax engines a
+ # question whose answer is already recorded, and risk a different one. The
+ # rows travel; only their owner changes.
+ #
+ # Per-seller totals are then computed independently, never prorated down
+ # from the basket. The one exception is money that was never attached to an
+ # item — an order-level fee such as a payment surcharge — which is
+ # apportioned by item value, because there is nothing else to attach it to.
+ class SplitBySeller
+ prepend Spree::ServiceModule::Base
+
+ # What a sibling order inherits from the order the checkout was taken
+ # against — the facts about the purchase itself, which are true of every
+ # order it produced.
+ #
+ # Deliberately an allowlist rather than an `except`: money columns, the
+ # cart link, placement timestamps and the number are all per-order, and a
+ # blocklist would carry every future column onto siblings by default.
+ # Adding a column here is a decision that it describes the checkout
+ # rather than one seller's part of it.
+ CARRIED_TO_SIBLING = %w[
+ email currency locale market_id channel_id company_location_id
+ customer_id token accept_marketing preferred_stock_location_id
+ customer_note last_ip_address
+ ].freeze
+
+ # @param cart [Spree::Cart]
+ # @param order [Spree::Order] the paid draft order, adopted as the
+ # group's first child rather than replaced — it is the record the
+ # payment was taken against
+ # @param partitions [Array<Spree::Carts::SellerPartition>] ordered, first
+ # party first
+ # @return [Spree::ServiceModule::Result] value is the Spree::OrderGroup
+ def call(cart:, order:, partitions:)
+ group = nil
+ # Every apportionment here divides money in this one currency.
+ @currency = order.currency
+
+ ApplicationRecord.transaction do
+ group = build_group(cart, order)
+ first, *rest = partitions
+
+ orders = [adopt_order(order, group, first)]
+ rest.each_with_index do |partition, index|
+ orders << hand_off(order, group, partition, index + 2)
+ end
+
+ distribute_order_level_fees(order, orders, partitions)
+ orders.each { |child| resum_totals(child) }
+ end
+
+ # Handed over with the children loaded: everything downstream reads
+ # them — placement, tax filing, the response — and the group's own
+ # figures are summed from them.
+ group.orders.load
+
+ success(group)
+ end
+
+ private
+
+ # The group takes the number the order was already given, so the customer
+ # keeps the reference they saw at checkout, and the children number off
+ # it: R1001-1, R1001-2. The cart_id moves up too — the group is what that
+ # cart completed into, and it becomes the replay anchor.
+ def build_group(cart, order)
+ order.update_columns(cart_id: nil)
+
+ group = cart.store.order_groups.create!(
+ cart: cart,
+ customer: cart.customer,
+ number: order.number,
+ currency: cart.currency,
+ email: cart.email,
+ token: cart.token,
+ ship_address: cart.ship_address&.dup,
+ bill_address: cart.bill_address&.dup
+ )
+ group
+ end
+
+ # Files the paid order under the group as its first child. Its own
+ # partition's rows simply stay where they are.
+ def adopt_order(order, group, partition)
+ order.update_columns(
+ order_group_id: group.id,
+ seller_id: partition.seller_id,
+ number: "#{group.number}-1"
+ )
+ order.reload
+ end
+
+ # Builds a sibling and moves one partition's rows onto it. Ownership is
+ # rewritten in place — update_columns rather than saves — so nothing
+ # re-runs the callbacks that would recost a line item whose price was
+ # settled during completion.
+ def hand_off(source_order, group, partition, index)
+ sibling = source_order.store.orders.create!(
+ source_order.attributes.slice(*CARRIED_TO_SIBLING).merge(
+ 'order_group_id' => group.id,
+ 'seller_id' => partition.seller_id,
+ 'number' => "#{group.number}-#{index}",
+ 'status' => 'draft',
+ # Copies, not the same rows: each order has to be able to have its
+ # address corrected without moving a sibling's parcel.
+ 'ship_address' => source_order.ship_address&.dup,
+ 'bill_address' => source_order.bill_address&.dup
+ )
+ )
+
+ line_item_ids = move_line_items(source_order, sibling, partition)
+ move_stock_reservations(sibling, line_item_ids)
+ divided = move_fulfillments(source_order, sibling, line_item_ids)
+ move_typed_lines(sibling, line_item_ids, divided)
+ copy_promotions(source_order, sibling)
+ copy_tax_identifier(source_order, sibling)
+
+ sibling.reload
+ end
+
+ # @return [Array<Integer>] the ids of the line items now owned by the sibling
+ def move_line_items(source_order, sibling, partition)
+ scope = source_order.line_items.where(seller_id: partition.seller_id)
+ ids = scope.pluck(:id)
+ Spree::LineItem.where(id: ids).update_all(order_id: sibling.id, updated_at: Time.current)
+ ids
+ end
+
+ # The stock a line item is holding follows it, or the child that keeps
+ # the item would release someone else's reservation on completion and
+ # leave its own held until they expire.
+ def move_stock_reservations(sibling, line_item_ids)
+ Spree::StockReservation.where(line_item_id: line_item_ids).
+ update_all(order_id: sibling.id, updated_at: Time.current)
+ end
+
+ # A fulfillment follows its items. One holding items from several
+ # partitions is split in two — the moving items get a new fulfillment on
+ # the sibling carrying the same delivery choice, and the rest stay put —
+ # which keeps a parcel's contents and the rate quoted for it together.
+ #
+ # @return [Hash{Integer => Array(Integer, Array<Integer>)}] original
+ # fulfillment id → its replacement's id and the weights the two halves
+ # divide by, for the parcels that had to be divided. Whole-parcel moves
+ # are absent: they keep their id, so the rows hanging off them need no
+ # rewriting. The weights travel because everything a divided parcel
+ # apportions — its cost, its tax, its discounts — divides by the same
+ # two numbers, and they cost a query each to work out.
+ def move_fulfillments(source_order, sibling, line_item_ids)
+ fulfillments = source_order.fulfillments.reload.includes(fulfillment_items: :line_item).to_a
+
+ fulfillments.each_with_object({}) do |fulfillment, divided|
+ items = fulfillment.fulfillment_items.to_a
+ moving = items.select { |item| line_item_ids.include?(item.line_item_id) }
+ next if moving.empty?
+
+ if moving.size == items.size
+ fulfillment.update_columns(order_id: sibling.id, address_id: sibling.ship_address_id)
+ Spree::FulfillmentItem.where(id: moving.map(&:id)).update_all(order_id: sibling.id)
+ next
+ end
+
+ replacement = clone_fulfillment(fulfillment, sibling)
+ Spree::FulfillmentItem.where(id: moving.map(&:id)).
+ update_all(fulfillment_id: replacement.id, order_id: sibling.id)
+
+ weights = [items - moving, moving].map { |half| to_minor_units(items_value(half)) }
+ divide_delivery_cost(fulfillment, replacement, weights)
+ divided[fulfillment.id] = [replacement.id, weights]
+ end
+ end
+
+ # One parcel becoming two must not charge for delivery twice: the
+ # customer was quoted one cost for one shipment, so it is divided between
+ # the halves by what each now carries rather than copied onto both.
+ #
+ # This is the honest reading of a quote that no longer describes what is
+ # being shipped. A marketplace that wants each seller to be quoted
+ # separately gets that by giving sellers their own delivery methods, which
+ # packs their goods into their own parcel from the start — at which point
+ # nothing here has to divide anything.
+ def divide_delivery_cost(original, replacement, weights)
+ total_cost = original.cost.to_d
+ return if total_cost.zero? || weights.sum <= 0
+
+ shares = Spree::Adjusters::LargestRemainder.largest_remainder_shares(to_minor_units(total_cost), weights)
+
+ apply_divided_cost(original, from_minor_units(shares[0]))
+ apply_divided_cost(replacement, from_minor_units(shares[1]))
+ end
+
+ # The rate is written down with the parcel. A fulfillment's cost is
+ # restated from its selected rate whenever its amounts are refreshed, so
+ # leaving the rate at the undivided figure would quietly restore the full
+ # delivery charge on both halves the next time anything touched them.
+ def apply_divided_cost(fulfillment, cost)
+ fulfillment.selected_delivery_rate&.update_columns(cost: cost, updated_at: Time.current)
+ fulfillment.update_columns(cost: cost, updated_at: Time.current)
+ end
+
+ # @param items [Array<Spree::FulfillmentItem>]
+ # @return [BigDecimal] what those items are worth
+ def items_value(items)
+ items.sum do |item|
+ line_item = item.line_item
+ next 0 if line_item.nil? || line_item.quantity.to_i.zero?
+
+ line_item.amount * item.quantity.to_d / line_item.quantity
+ end
+ end
+
+ def clone_fulfillment(fulfillment, sibling)
+ attributes = fulfillment.attributes.except('id', 'cart_id', 'number', 'created_at', 'updated_at')
+ replacement = sibling.fulfillments.create!(
+ attributes.merge('order_id' => sibling.id, 'address_id' => sibling.ship_address_id)
+ )
+
+ if (selected = fulfillment.selected_delivery_rate)
+ rate_attributes = selected.attributes.except('id', 'created_at', 'updated_at')
+ replacement.delivery_rates.create!(rate_attributes.merge('fulfillment_id' => replacement.id))
+ end
+
+ replacement
+ end
+
+ # Tax lines, discounts and fees follow whatever they hang off. Rows
+ # attached to nothing are order-level and are apportioned separately.
+ #
+ # A parcel that moved whole keeps its id, so its rows move with a plain
+ # re-point. A parcel that was divided leaves its rows behind on an
+ # original that now carries only part of the goods — they have to be
+ # divided too, or the source over-taxes a halved parcel and the sibling
+ # ships with no delivery tax at all.
+ #
+ # @param divided [Hash{Integer => Array(Integer, Array<Integer>)}] what
+ # {#move_fulfillments} reported about the parcels it had to divide
+ def move_typed_lines(sibling, line_item_ids, divided = {})
+ moved_fulfillment_ids = sibling.fulfillments.reload.pluck(:id) - divided.values.map(&:first)
+
+ [Spree::TaxLine, Spree::Discount, Spree::Fee].each do |klass|
+ klass.where(line_item_id: line_item_ids).update_all(order_id: sibling.id, updated_at: Time.current)
+
+ next unless klass.column_names.include?('fulfillment_id')
+
+ klass.where(fulfillment_id: moved_fulfillment_ids).update_all(order_id: sibling.id, updated_at: Time.current)
+ divided.each do |original_id, (replacement_id, weights)|
+ divide_fulfillment_rows(klass, original_id, replacement_id, weights, sibling)
+ end
+ end
+ end
+
+ # Splits one parcel's money rows between the two halves it became, by
+ # what each half now carries — the same basis its delivery cost was
+ # divided on, so the tax still describes the charge.
+ def divide_fulfillment_rows(klass, original_id, replacement_id, weights, sibling)
+ return if weights.sum <= 0
+
+ klass.where(fulfillment_id: original_id).find_each do |row|
+ apportion_row(row, weights, [{}, { 'order_id' => sibling.id, 'fulfillment_id' => replacement_id }])
+ end
+ end
+
+ def copy_promotions(source_order, sibling)
+ source_order.order_promotions.find_each do |order_promotion|
+ sibling.order_promotions.find_or_create_by!(promotion_id: order_promotion.promotion_id)
+ end
+ end
+
+ # The buyer's tax registration is a snapshot, and each order has to be
+ # explainable on its own — so every child receives a copy of it.
+ def copy_tax_identifier(source_order, sibling)
+ identifier = source_order.tax_identifier
+ return if identifier.nil?
+
+ attributes = identifier.attributes.except('id', 'order_id', 'customer_id', 'company_id', 'cart_id',
+ 'created_at', 'updated_at')
+ sibling.create_tax_identifier!(attributes)
+ end
+
+ # An order-level fee was charged for the checkout as a whole, so it is
+ # apportioned across the children by what each is worth. Largest-remainder
+ # so the shares add back up to what the customer was charged, and the
+ # fee's own tax follows the share it was charged on.
+ def distribute_order_level_fees(source_order, orders, partitions)
+ fees = Spree::Fee.where(order_id: source_order.id, line_item_id: nil, fulfillment_id: nil).to_a
+ return if fees.empty?
+
+ weights = partitions.map { |partition| to_minor_units(partition.item_total) }
+ return if weights.sum <= 0
+
+ fees.each { |fee| distribute_fee(fee, orders, weights) }
+ end
+
+ def distribute_fee(fee, orders, weights)
+ targets = orders.map { |order| { 'order_id' => order.id } }
+ placed_fees = apportion_row(fee, weights, targets)
+
+ Spree::TaxLine.where(fee_id: fee.id).find_each do |tax_line|
+ # A fee's tax follows the share it was charged on, so each copy is
+ # attached to the fee that landed on the same order.
+ tax_targets = placed_fees.map do |placed_fee|
+ { 'order_id' => placed_fee&.order_id, 'fee_id' => placed_fee&.id } if placed_fee
+ end
+
+ apportion_row(tax_line, weights, tax_targets)
+ end
+ end
+
+ # Divides one money row across several owners.
+ #
+ # The row itself takes the first share — restating it rather than
+ # destroying and recreating keeps whatever else points at it — and each
+ # remaining share becomes a copy carrying that owner's attributes. Shares
+ # come from largest-remainder, so together they still add up to the
+ # amount the customer was charged.
+ #
+ # @param targets [Array<Hash, nil>] the attributes each share is written
+ # with, index-aligned with the weights; a nil target skips its share
+ # @return [Array<ActiveRecord::Base, nil>] the row now holding each share
+ def apportion_row(row, weights, targets)
+ shares = Spree::Adjusters::LargestRemainder.largest_remainder_shares(to_minor_units(row.amount), weights)
+
+ shares.each_with_index.map do |share, index|
+ target = targets[index]
+ next if target.nil?
+ next if index.positive? && share.zero?
+
+ placed = index.zero? ? row : copy_row(row, target)
+ placed.update_columns(amount: from_minor_units(share), updated_at: Time.current)
+ placed
+ end
+ end
+
+ # @return [ActiveRecord::Base] a new row like this one, on another owner
+ def copy_row(row, attributes)
+ row.class.create!(
+ row.attributes.except('id', 'cart_id', 'created_at', 'updated_at').merge(attributes)
+ )
+ end
+
+ # Each child re-sums the rows it now owns. Deliberately the totals
+ # workflow rather than arithmetic here: it is the single home for what an
+ # order's money adds up to, and a second implementation would be a second
+ # answer.
+ #
+ # resum_only, because the children are still drafts and would otherwise
+ # be money-regenerated: the promotion adjuster would delete the discounts
+ # just moved onto them and recompute against one seller's subset (an
+ # order-level threshold the whole basket met, most children would fail),
+ # and the tax provider would delete the moved tax lines and re-derive them
+ # from today's rates. The checkout already answered both questions against
+ # the whole basket, and the customer has already paid that answer.
+ def resum_totals(order)
+ Spree.order_recalculate_totals_workflow.call(order: order.reload, resum_only: true)
+ end
+
+ # Apportionment works in the currency's smallest whole unit, so shares
+ # divide exactly and add back up to the charge they came from.
+ def to_minor_units(amount)
+ Spree::Money::Rounding.to_minor_units(amount, @currency)
+ end
+
+ def from_minor_units(units)
+ Spree::Money::Rounding.from_minor_units(units, @currency)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/coupon_codes/coupon_codes_handler.rb b/spree/core/app/services/spree/coupon_codes/coupon_codes_handler.rb
index 72755bc21c..1a8b5c45e4 100644
--- a/spree/core/app/services/spree/coupon_codes/coupon_codes_handler.rb
+++ b/spree/core/app/services/spree/coupon_codes/coupon_codes_handler.rb
@@ -18,8 +18,21 @@ module Spree
private
+ # Which promotions this checkout actually used.
+ #
+ # Read across the whole group when the order is one of several placed
+ # together: the codes all sit on the first child, while the discount a
+ # code bought may have landed on any of them. Asking only this order
+ # would find no discount for a code that discounted a sibling, and
+ # release a single-use code back for somebody to spend again.
def find_current_promotions_ids
- order.discounts.promotion.where.not(promotion_id: nil).distinct.pluck(:promotion_id)
+ scope = if order.respond_to?(:grouped?) && order.grouped?
+ Spree::Discount.where(order_id: order.order_group.orders.select(:id))
+ else
+ order.discounts
+ end
+
+ scope.promotion.where.not(promotion_id: nil).distinct.pluck(:promotion_id)
end
def use_all_current(promotion_ids)
diff --git a/spree/core/app/services/spree/order_groups/allocate_payments.rb b/spree/core/app/services/spree/order_groups/allocate_payments.rb
new file mode 100644
index 0000000000..70ed0ad678
--- /dev/null
+++ b/spree/core/app/services/spree/order_groups/allocate_payments.rb
@@ -0,0 +1,89 @@
+module Spree
+ module OrderGroups
+ # Re-points a split checkout's payments onto the group and records each
+ # child order's share of them.
+ #
+ # The customer authorised one amount for one basket, so the charge stays
+ # singular and the per-seller figures are bookkeeping. Every payment on the
+ # group gets its own set of shares — the card, the store credit, the gift
+ # card — apportioned by what each child is worth, with largest-remainder so
+ # a child's shares across all payments add back up to that child's total. A
+ # mixed store-credit checkout therefore never overstates what the gateway is
+ # exposed to on any one seller's order.
+ #
+ # Idempotent: the shares are found-or-created on the unique
+ # (payment, order) index, so a replayed completion writes nothing new.
+ class AllocatePayments
+ prepend Spree::ServiceModule::Base
+
+ # @param group [Spree::OrderGroup]
+ # @return [Spree::ServiceModule::Result] value is the group
+ def call(group:)
+ orders = group.orders.order(:id).to_a
+ return success(group) if orders.empty?
+
+ ApplicationRecord.transaction do
+ claim_payments(group)
+ weights = orders.map { |order| Spree::Money::Rounding.to_minor_units(order.total, group.currency) }
+
+ group.payments.reload.each do |payment|
+ allocate(payment, orders, weights)
+ end
+ end
+
+ success(group)
+ end
+
+ private
+
+ # The payments were made against the cart and re-pointed onto the child
+ # orders as they were built; a split checkout moves them up to the group,
+ # where the single charge actually belongs.
+ #
+ # Payment sessions deliberately stay where they are. A session is the
+ # external gateway's own record of one authorisation attempt, keyed to
+ # the reference the provider holds — moving it would fork a reference
+ # that has to keep resolving, and nothing about the split changes what
+ # the gateway authorised.
+ def claim_payments(group)
+ order_ids = group.orders.select(:id)
+ Spree::Payment.where(order_id: order_ids).update_all(order_id: nil, order_group_id: group.id)
+ group.payments.reset
+ end
+
+ # A share records what this order can draw on, and what it already has.
+ #
+ # The captured figure matters as much as the authorised one: a checkout
+ # paid by a method that charges up front arrives here with the payment
+ # already completed, and a share showing nothing captured would report
+ # every child of a fully paid checkout as merely authorised. So a
+ # completed payment's shares are born captured, and one still pending is
+ # captured later, as each seller dispatches.
+ def allocate(payment, orders, weights)
+ # A basket worth nothing — fully discounted, wholly gift-carded — has
+ # nothing to divide by. Every child still gets a share saying so,
+ # rather than none at all, so each reads as settled instead of waiting
+ # on money that was never owed.
+ weights = Array.new(orders.size, 1) if weights.sum <= 0
+
+ currency = payment.currency
+ shares = Spree::Adjusters::LargestRemainder.largest_remainder_shares(
+ Spree::Money::Rounding.to_minor_units(payment.amount, currency), weights
+ )
+ captured = payment.completed?
+
+ orders.each_with_index do |order, index|
+ split = Spree::PaymentSplit.find_or_initialize_by(payment_id: payment.id, order_id: order.id)
+ next if split.persisted?
+
+ share = Spree::Money::Rounding.from_minor_units(shares[index], currency)
+ split.currency = payment.currency
+ split.authorized_amount = share
+ split.captured_amount = captured ? share : 0
+ split.save!
+ end
+ end
+
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/orders/update_statuses.rb b/spree/core/app/services/spree/orders/update_statuses.rb
index be75cc2f34..c45fed70d2 100644
--- a/spree/core/app/services/spree/orders/update_statuses.rb
+++ b/spree/core/app/services/spree/orders/update_statuses.rb
@@ -28,9 +28,7 @@ module Spree
currency = ::Money::Currency.find(order.currency) || ::Money::Currency.find('USD')
precision = currency.exponent
- captured = quantize(order.payments.valid.completed.sum(:amount), precision)
- authorized = quantize(order.payments.valid.pending.sum(:amount), precision)
- refunded = quantize(order.refunds.sum(:amount), precision)
+ captured, authorized, refunded = money_for(order).map { |amount| quantize(amount, precision) }
target = quantize(order.total, precision) - refunded
net_captured = captured - refunded
@@ -53,6 +51,34 @@ module Spree
end
end
+ # What has been authorised, captured and refunded against this order.
+ #
+ # An order placed in a split checkout owns no payments — the customer
+ # made one payment against the group — so its figures come from its share
+ # of them. That is precisely what a payment split records, and it is why
+ # the shares are stored rather than recomputed: once one seller has
+ # shipped and been captured while another has not, no proportion of the
+ # group's totals can describe either.
+ #
+ # @return [Array(BigDecimal, BigDecimal, BigDecimal)] captured,
+ # authorized and refunded, in that order
+ def money_for(order)
+ unless order.order_group_id.present?
+ return [
+ order.payments.valid.completed.sum(:amount),
+ order.payments.valid.pending.sum(:amount),
+ order.refunds.sum(:amount)
+ ]
+ end
+
+ splits = order.payment_splits.to_a
+ captured = splits.sum(&:captured_amount)
+
+ # Authorized means still to draw: what the shares allow, less what has
+ # already been taken against them.
+ [captured, splits.sum(&:authorized_amount) - captured, splits.sum(&:refunded_amount)]
+ end
+
# Rolls the fulfillments up into one word for filtering and display.
#
# Canceled fulfillments are ignored unless they are all there is: an
diff --git a/spree/core/app/subscribers/spree/payment_split_subscriber.rb b/spree/core/app/subscribers/spree/payment_split_subscriber.rb
new file mode 100644
index 0000000000..1f2940f0a6
--- /dev/null
+++ b/spree/core/app/subscribers/spree/payment_split_subscriber.rb
@@ -0,0 +1,60 @@
+# frozen_string_literal: true
+
+module Spree
+ # Keeps a split checkout's per-order shares in step with the money.
+ #
+ # Two things move a share after it is written. A refund puts one seller's
+ # order right, and must touch only that order's share: the customer's money
+ # comes back out of the one charge either way, but what each seller owes and
+ # is owed does not move because a sibling refunded. And a payment completing
+ # captures the whole basket at once — an authorisation settled after
+ # placement — which every child shares in proportionally.
+ #
+ # Synchronous, like the commission subscriber, because a share is what an
+ # order's payment status is derived from: an order that still read as
+ # unpaid until a job ran would be showing the wrong thing to the merchant
+ # and to the seller.
+ class PaymentSplitSubscriber < Spree::Subscriber
+ subscribes_to 'refund.created', 'payment.completed', async: false
+
+ on 'refund.created', :handle_refund
+ on 'payment.completed', :handle_capture
+
+ def handle_refund(event)
+ refund = Spree::Refund.find_by_prefix_id(event.payload['id'])
+ return unless refund
+
+ order = refund.order
+ return if order.nil? || !order.grouped?
+
+ split = order.payment_split_for(refund.payment)
+ return if split.nil?
+
+ # Recomputed from the refunds rather than incremented, so a replayed
+ # event cannot count the same money twice.
+ refunded = Spree::Refund.where(payment_id: refund.payment_id, order_id: order.id).sum(:amount)
+ split.update!(refunded_amount: refunded)
+
+ # Deliberately re-derived here even though OrderStatusSubscriber also
+ # answers refund.created: subscriber order is not guaranteed, and a
+ # status derived before this share was written would describe the refund
+ # as not having happened.
+ Spree::Orders::UpdateStatuses.call(order: order)
+ end
+
+ # The whole payment settled, so every share it covers is captured in full.
+ # A share already carrying a larger captured figure is left alone — a
+ # dispatch captured it first, and that is the more specific record.
+ def handle_capture(event)
+ payment = Spree::Payment.find_by_prefix_id(event.payload['id'])
+ return if payment.nil? || !payment.grouped?
+
+ payment.payment_splits.includes(:order).each do |split|
+ next if split.captured_amount >= split.authorized_amount
+
+ split.update!(captured_amount: split.authorized_amount)
+ Spree::Orders::UpdateStatuses.call(order: split.order) if split.order
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rb
index b107034e9e..7344ec22a6 100644
--- a/spree/core/app/workflows/spree/carts/complete.rb
+++ b/spree/core/app/workflows/spree/carts/complete.rb
@@ -21,7 +21,8 @@ module Spree
hooks :validate, :before_finalize, :after_finalize
# Hook handlers read this plus the argument readers.
- attr_reader :order
+ # +order_group+ is set only when the cart spanned more than one seller.
+ attr_reader :order, :order_group
# @param cart [Spree::Cart, Spree::Order] a draft order funnels into
# the same finalize semantics
@@ -53,7 +54,9 @@ module Spree
run_hooks :before_finalize
step :finalize_completion
run_hooks :after_finalize
- success(order)
+ # A split checkout answers with the group: it is what the customer
+ # bought, and the orders inside it are how it will be fulfilled.
+ success(order_group || order)
rescue ActiveRecord::RecordNotUnique
# Concurrent completion lost the unique orders.cart_id race —
# re-enter: the replay step returns the winner's order (or the TTL
@@ -76,17 +79,29 @@ module Spree
# (idempotent, and the only healer for the crash window between the
# order commit and the cart stamp).
def replay_completed
- order = completion_result(cart)
- return if order.nil?
+ result = completion_result(cart)
+ return if result.nil?
+
+ return replay_group(result) if result.is_a?(Spree::OrderGroup)
- halt!(order) if order.canceled?
+ halt!(result) if result.canceled?
- if !order.placed? && order.payment_required? && !payment_covered?(order)
+ if !result.placed? && result.payment_required? && !payment_covered?(result)
failure(cart, code: 'payment_failed', message: Spree.t(:payment_processing_failed))
end
+ finalize!(cart, result)
+ halt!(result)
+ end
+
+ # The split already ran, so the money and the division are settled — what
+ # may not have finished is placing the children. Re-running finalize
+ # against the group picks up wherever it stopped.
+ def replay_group(group)
+ @order_group = group
+ @order = group.orders.first
finalize!(cart, order)
- halt!(order)
+ halt!(group)
end
def guard_concurrent_completion
@@ -143,6 +158,11 @@ module Spree
# or completion could still finalize.
def rollback_draft_order
return if order.nil?
+ # Once the checkout has divided, this is no longer a lone draft that can
+ # be thrown away: its money sits on the group and its siblings hold the
+ # rest of the basket. A failure after that point resumes through the
+ # sweeper like any other finalize failure.
+ return if order_group.present?
return if order.payments.valid.completed.any? || payment_covered?(order)
ApplicationRecord.transaction do
@@ -155,10 +175,10 @@ module Spree
end
end
- # Exactly one of cart.order (single partition) or, later, the
- # multi-seller order group.
+ # Exactly one of these is ever set: the bare order a single-partition
+ # cart completed into, or the group a multi-seller one did.
def completion_result(cart)
- cart.order
+ cart.order_group || cart.order
end
# P7 — the copy contract: the order receives copies (line items with
@@ -326,20 +346,93 @@ module Spree
# The FINALIZE phase: the order-side completion workflow owns the
# placement side effects; the two cart-side stamps follow.
+ #
+ # A cart spanning several sellers divides here rather than earlier: the
+ # customer authorised one amount against one basket, so the money is
+ # taken first and the bookkeeping follows it. A crash between the two
+ # resumes like any other finalize failure.
def finalize!(cart, order)
@order = order
- step :complete_order, with: -> { Spree.order_complete_workflow }
+ step :split_by_seller
+ step :allocate_payment_splits
+ step :complete_orders
step :complete_cart
step :mark_coupon_codes_used
external_step :commit_tax
end
+ # Divides the paid draft order into one order per seller, under a group.
+ # A cart of one partition — all first-party, or all one seller — is left
+ # exactly as it is: no group, no splits, and the order it already built
+ # is the order the customer gets.
+ #
+ # The draft order built in PREPARE becomes the group's first child rather
+ # than being replaced. It is the record the payment was taken against and
+ # the row carrying the unique cart_id that makes completion replayable,
+ # so it is kept and narrowed to its own partition; the remaining
+ # partitions become new siblings beside it.
+ def split_by_seller
+ @order_group = cart.order_group
+ return if order_group.present?
+ return if order.placed?
+
+ partitions = Spree::Carts::PartitionBySeller.call(purchase: order).value
+ return if partitions.size < 2
+
+ result = Spree::Carts::SplitBySeller.call(cart: cart, order: order, partitions: partitions)
+ failure(cart, code: 'split_failed', message: result.error) if result.failure?
+
+ @order_group = result.value
+ @order = order_group.orders.first
+ end
+
+ def allocate_payment_splits
+ return if order_group.nil?
+
+ Spree::OrderGroups::AllocatePayments.call(group: order_group)
+ end
+
+ # Places what the checkout produced — the children of a split, or the one
+ # order otherwise. Each child publishes its own order.placed, which is
+ # what gets every seller their own commission lines with no marketplace
+ # code in the commission engine.
+ #
+ # A split checkout's payments were already taken against the whole basket
+ # and moved onto the group, so the children place without processing them
+ # again. One purchase means one confirmation email: the first child
+ # carries the notification and its siblings place silently.
+ def complete_orders
+ split = order_group.present?
+
+ placed_orders.each_with_index do |child, index|
+ result = Spree.order_complete_workflow.call(
+ order: child,
+ payment_pending: split,
+ notify_customer: split && !index.zero? ? false : nil
+ )
+ failure(cart, code: 'completion_failed', message: result.error) if result.failure?
+ end
+
+ order_group&.publish_event('order_group.completed')
+ end
+
# Tells the tax engine the sale is final. A no-op for the built-in
# provider, whose rows are already the record; external engines file the
# document that a tax return is later built from. Outside the
# transaction — a remote call must not hold the completion open.
+ #
+ # Every order of a split checkout is filed, not just the first: each is a
+ # separate sale with its own tax, and an unfiled sibling is a hole in the
+ # merchant's return that only surfaces at filing time.
def commit_tax
- order.tax_provider.commit(order)
+ placed_orders.each { |placed| placed.tax_provider.commit(placed) }
+ end
+
+ # What this checkout produced: the children of a split, or the one order
+ # otherwise. The single answer to "which orders came out of here", so
+ # placement and tax filing can never disagree about the set.
+ def placed_orders
+ order_group.present? ? order_group.orders.to_a : [order]
end
def complete_cart
diff --git a/spree/core/app/workflows/spree/carts/recalculate_totals.rb b/spree/core/app/workflows/spree/carts/recalculate_totals.rb
index afa63fa2cf..29d2f6f6c0 100644
--- a/spree/core/app/workflows/spree/carts/recalculate_totals.rb
+++ b/spree/core/app/workflows/spree/carts/recalculate_totals.rb
@@ -23,7 +23,14 @@ module Spree
attr_reader :tax_line_context
# @param cart [Spree::Cart, Spree::Order]
- def perform(cart:)
+ # @param resum_only [Boolean] re-sum the rows the record already carries
+ # without regenerating them. A placed order is frozen by its own
+ # lifecycle, but an order can also hold rows that must not be
+ # re-derived before it is placed — the seller split moves already-costed
+ # rows onto child orders that are still drafts, and re-running the
+ # promotion and tax engines against one seller's subset would answer a
+ # question the checkout already answered against the whole basket.
+ def perform(cart:, resum_only: false)
super
step :reset_association_caches
@@ -121,7 +128,7 @@ module Spree
end
def money_frozen?
- cart.is_a?(Spree::Order) && cart.completed?
+ resum_only || (cart.is_a?(Spree::Order) && cart.completed?)
end
# Pass one of the two-pass recalculation: persist per-adjustable
diff --git a/spree/core/app/workflows/spree/orders/cancel.rb b/spree/core/app/workflows/spree/orders/cancel.rb
index f10d77180d..7062e4e4c4 100644
--- a/spree/core/app/workflows/spree/orders/cancel.rb
+++ b/spree/core/app/workflows/spree/orders/cancel.rb
@@ -41,7 +41,7 @@ module Spree
@decided_at = canceled_at || Time.current
@amount_to_refund = refund_amount
- @amount_to_refund ||= order.payment_total if refund_payments
+ @amount_to_refund ||= amount_paid if refund_payments
ApplicationRecord.transaction do
step :record_cancellation
@@ -121,6 +121,8 @@ module Spree
# never refunded; everything else cancels captured payments (void or
# refund at the gateway's discretion) and voids what never completed.
def settle_payments
+ return settle_grouped_payments if order.grouped?
+
if order.gift_card.present? && order.covered_by_store_credit?
order.payments.completed.store_credits.each(&:void!)
else
@@ -136,6 +138,53 @@ module Spree
end
end
+ # Canceling one order of a split checkout gives back that order's money
+ # and nothing else: the payment is shared, so voiding it would release
+ # the siblings' authorization too and un-pay sellers who are still
+ # shipping. What comes back is this order's own share — refunded where it
+ # has been captured, and simply written down where it has not, since
+ # there is nothing to give back until it is drawn.
+ #
+ # Deliberately not "void the payment when every sibling is canceled too":
+ # that reads the siblings' state to decide what to do with shared money,
+ # and being wrong about it releases an authorization a seller is still
+ # relying on. Writing the share down leaves the payment voidable by
+ # whoever cancels last, which reaches the same end without the risk.
+ # What this order has actually been paid. An order placed in a split
+ # checkout holds no payments of its own — the customer paid once, against
+ # the group — so its position is the sum of its shares.
+ #
+ # @return [BigDecimal]
+ def amount_paid
+ return order.payment_total unless order.grouped?
+
+ order.payment_splits.sum(&:net_captured_amount)
+ end
+
+ def settle_grouped_payments
+ remaining = @amount_to_refund
+
+ order.payment_splits.includes(:payment).each do |split|
+ # Release what this order had reserved but never drew, always — the
+ # authorization is no longer for anything.
+ split.update!(authorized_amount: split.captured_amount)
+
+ # Give money back only when the caller asked for it, and only up to
+ # what they asked for, exactly as the ungrouped path does.
+ next unless refund_payments
+
+ refundable = [split.net_captured_amount, remaining].compact.min
+ next if refundable <= 0
+
+ result = Spree.refund_create_workflow.call(
+ payment: split.payment, amount: refundable, order: order, refunder: canceler
+ )
+ raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?
+
+ remaining -= refundable if remaining
+ end
+ end
+
# Reverses the filed tax document. The canceled sale must stop appearing
# in the merchant's tax liability.
def void_tax
diff --git a/spree/core/app/workflows/spree/orders/recalculate_totals.rb b/spree/core/app/workflows/spree/orders/recalculate_totals.rb
index 2dc8aa2393..520dafa185 100644
--- a/spree/core/app/workflows/spree/orders/recalculate_totals.rb
+++ b/spree/core/app/workflows/spree/orders/recalculate_totals.rb
@@ -4,8 +4,8 @@ module Spree
# this side (the calculator resolves polymorphically through the
# model's #updater).
class RecalculateTotals < Spree::Carts::RecalculateTotals
- def perform(order:)
- super(cart: order)
+ def perform(order:, resum_only: false)
+ super(cart: order, resum_only: resum_only)
end
end
end
diff --git a/spree/core/app/workflows/spree/refunds/create.rb b/spree/core/app/workflows/spree/refunds/create.rb
index ef1e1ff301..47ce500077 100644
--- a/spree/core/app/workflows/spree/refunds/create.rb
+++ b/spree/core/app/workflows/spree/refunds/create.rb
@@ -22,7 +22,11 @@ module Spree
# @param refunder [Object, nil] the admin issuing the refund
# @param originator [Object, nil] what triggered the refund — a
# Spree::Return, Exchange or Claim; nil for a manual refund
- def perform(payment:, amount: nil, reason: nil, refunder: nil, originator: nil)
+ # @param order [Spree::Order, nil] which order is being put right.
+ # Required only when the payment is shared by a split checkout, where
+ # it covers several orders and the payment cannot say which one this
+ # refund is for; otherwise the payment's own order is taken.
+ def perform(payment:, amount: nil, reason: nil, refunder: nil, originator: nil, order: nil)
super
step :ensure_refundable
@@ -49,11 +53,34 @@ module Spree
end
def ensure_amount_within_balance
- return if @amount_to_refund.to_d.positive? && @amount_to_refund.to_d <= payment.credit_allowed.to_d
+ amount = @amount_to_refund.to_d
+ return if amount.positive? && amount <= payment.credit_allowed.to_d && amount <= refundable_share
failure(payment, :refund_amount_exceeds_balance)
end
+ # What the named order may take back from this payment.
+ #
+ # A payment shared by a split checkout holds several orders' money, and
+ # the whole-payment balance says nothing about whose. Without this bound,
+ # refunding one seller's order for more than it was paid would quietly
+ # spend a sibling's captured share — the money would go back to the
+ # customer, and the other seller would find nothing left to draw.
+ #
+ # @return [BigDecimal] the payment's own balance when it is not shared
+ def refundable_share
+ return payment.credit_allowed.to_d unless payment.grouped?
+
+ split = order && payment.payment_splits.find_by(order_id: order.id)
+ return 0 if split.nil?
+
+ # Refunds already written are counted from the rows rather than from
+ # the split's own figure, which a subscriber updates after the fact —
+ # two refunds in quick succession must not each see an unrefunded share.
+ already_refunded = Spree::Refund.where(payment_id: payment.id, order_id: order.id).sum(:amount)
+ split.captured_amount - already_refunded
+ end
+
# The row is what reserves the balance — credit_allowed sums refund rows —
# so creation serializes on the payment's row lock. Without it the
# balance validation is check-then-act, and two concurrent refunds would
@@ -62,13 +89,22 @@ module Spree
payment.with_lock do
@refund = payment.refunds.create!(
amount: @amount_to_refund,
- reason: reason || Spree::RefundReason.return_processing_reason(payment.order&.store),
+ order: order || payment.order,
+ reason: reason || Spree::RefundReason.return_processing_reason(refund_store),
refunder: refunder,
originator: originator
)
end
end
+ # The store the default reason belongs to. A payment shared by a split
+ # checkout has no order of its own, so it is asked through whichever
+ # order is being refunded — and failing that the current store, since a
+ # store-less reason would be created global and reused everywhere.
+ def refund_store
+ (order || payment.order)&.store || payment.owner&.store || Spree::Current.store
+ end
+
def credit_at_gateway
refund.perform!
rescue Spree::Core::GatewayError => error
diff --git a/spree/core/db/migrate/20260820000001_create_spree_order_groups.rb b/spree/core/db/migrate/20260820000001_create_spree_order_groups.rb
new file mode 100644
index 0000000000..9dc1802f16
--- /dev/null
+++ b/spree/core/db/migrate/20260820000001_create_spree_order_groups.rb
@@ -0,0 +1,33 @@
+class CreateSpreeOrderGroups < ActiveRecord::Migration[8.1]
+ def change
+ create_table :spree_order_groups do |t|
+ t.references :store, null: false
+ t.references :customer, index: true # guest checkouts have no customer
+ # The cart this group was completed from. Unique for the same reason
+ # orders.cart_id is: it is the completion idempotency key, so a replayed
+ # completion finds the group instead of building a second one.
+ t.references :cart, index: { unique: true }
+
+ t.string :number, null: false
+ t.string :currency, null: false
+ # Guest checkouts carry the contact address here, as the order does.
+ t.string :email
+ t.string :token
+
+ t.references :ship_address
+ t.references :bill_address
+
+ if t.respond_to?(:jsonb)
+ t.jsonb :metadata
+ else
+ t.json :metadata
+ end
+
+ t.timestamps
+ end
+
+ add_index :spree_order_groups, :number, unique: true
+ add_index :spree_order_groups, [:store_id, :created_at]
+ add_index :spree_order_groups, :token
+ end
+end
diff --git a/spree/core/db/migrate/20260820000002_add_order_group_to_spree_orders_and_payments.rb b/spree/core/db/migrate/20260820000002_add_order_group_to_spree_orders_and_payments.rb
new file mode 100644
index 0000000000..56b7887d51
--- /dev/null
+++ b/spree/core/db/migrate/20260820000002_add_order_group_to_spree_orders_and_payments.rb
@@ -0,0 +1,14 @@
+class AddOrderGroupToSpreeOrdersAndPayments < ActiveRecord::Migration[8.1]
+ def change
+ # Which seller sold this order, and which checkout it was placed in. Both
+ # nullable: a store selling only its own goods never sets either, and the
+ # first-party child of a mixed checkout carries a group but no seller.
+ add_reference :spree_orders, :seller, index: true
+ add_reference :spree_orders, :order_group, index: true
+
+ # A grouped checkout's payment belongs to the group rather than to any one
+ # child order — there is one charge, and the per-order shares are
+ # spree_payment_splits rows. An ungrouped order keeps payments.order_id.
+ add_reference :spree_payments, :order_group, index: true
+ end
+end
diff --git a/spree/core/db/migrate/20260820000003_create_spree_payment_splits.rb b/spree/core/db/migrate/20260820000003_create_spree_payment_splits.rb
new file mode 100644
index 0000000000..7df7233e15
--- /dev/null
+++ b/spree/core/db/migrate/20260820000003_create_spree_payment_splits.rb
@@ -0,0 +1,21 @@
+class CreateSpreePaymentSplits < ActiveRecord::Migration[8.1]
+ def change
+ create_table :spree_payment_splits do |t|
+ t.references :payment, null: false, index: false
+ t.references :order, null: false
+
+ # This child order's share of that one payment. Captures and refunds on a
+ # child update its own row and never a sibling's — which is the whole
+ # reason the share is a record rather than a proportion computed on read.
+ t.decimal :authorized_amount, precision: 10, scale: 2, null: false, default: 0
+ t.decimal :captured_amount, precision: 10, scale: 2, null: false, default: 0
+ t.decimal :refunded_amount, precision: 10, scale: 2, null: false, default: 0
+ t.string :currency, null: false
+
+ t.timestamps
+ end
+
+ # One share per (payment, order), so a replayed split cannot write a second.
+ add_index :spree_payment_splits, [:payment_id, :order_id], unique: true
+ end
+end
diff --git a/spree/core/db/migrate/20260820000004_add_order_to_spree_refunds.rb b/spree/core/db/migrate/20260820000004_add_order_to_spree_refunds.rb
new file mode 100644
index 0000000000..a2bd6b39b7
--- /dev/null
+++ b/spree/core/db/migrate/20260820000004_add_order_to_spree_refunds.rb
@@ -0,0 +1,29 @@
+class AddOrderToSpreeRefunds < ActiveRecord::Migration[8.1]
+ def change
+ # Which order this refund is against.
+ #
+ # A refund used to reach its order through its payment, which works while
+ # one payment belongs to one order. In a split checkout the payment belongs
+ # to the group and covers several orders, so the refund has to say which
+ # one it is putting right — the seller's books, the commission reversal and
+ # the payment share all have to agree on the answer.
+ #
+ # Nullable, and backfilled from the payment for existing rows: every refund
+ # written before this column belongs to a payment that belongs to exactly
+ # one order, so the answer is already in the data.
+ add_reference :spree_refunds, :order, index: true
+
+ reversible do |direction|
+ direction.up do
+ execute <<~SQL.squish
+ UPDATE #{Spree::Refund.table_name}
+ SET order_id = (
+ SELECT order_id FROM #{Spree::Payment.table_name}
+ WHERE #{Spree::Payment.table_name}.id = #{Spree::Refund.table_name}.payment_id
+ )
+ WHERE order_id IS NULL
+ SQL
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index cc6c3e8914..c112f7ac13 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -532,6 +532,7 @@ module Spree
Spree::OrderPlacedSubscriber,
Spree::OrderCommissionSubscriber,
Spree::OrderStatusSubscriber,
+ Spree::PaymentSplitSubscriber,
Spree::ExportSubscriber,
Spree::ReportSubscriber,
Spree::InvitationEmailSubscriber,
diff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rb
index 3a7d10cd62..0ef963f24f 100644
--- a/spree/core/lib/spree/core/permission_configuration.rb
+++ b/spree/core/lib/spree/core/permission_configuration.rb
@@ -278,11 +278,11 @@ module Spree
# rubocop:disable Metrics/MethodLength
def register_default_resources
register_resource(:orders, group: :orders, audiences: %i[seller], subjects: -> {
- [Spree::Order, Spree::LineItem, Spree::TaxLine, Spree::Discount, Spree::Fee,
+ [Spree::Order, Spree::OrderGroup, Spree::LineItem, Spree::TaxLine, Spree::Discount, Spree::Fee,
Spree::Return, Spree::Exchange, Spree::Claim, Spree::TaxIdentifier,
Spree::CustomField]
})
- register_resource(:payments, group: :orders, subjects: -> { [Spree::Payment] })
+ register_resource(:payments, group: :orders, subjects: -> { [Spree::Payment, Spree::PaymentSplit] })
register_resource(:fulfillments, group: :orders, audiences: %i[seller], subjects: -> { [Spree::Fulfillment] })
register_resource(:refunds, group: :orders, subjects: -> { [Spree::Refund] })
register_resource(:gift_cards, group: :orders, subjects: -> {
diff --git a/spree/core/lib/spree/money.rb b/spree/core/lib/spree/money.rb
index a6404ba0bf..b8923d8279 100644
--- a/spree/core/lib/spree/money.rb
+++ b/spree/core/lib/spree/money.rb
@@ -49,6 +49,30 @@ module Spree
def quantize(amount, precision)
BigDecimal(amount.to_s).round(precision, BigDecimal::ROUND_HALF_UP)
end
+
+ # An amount as a whole number of the currency's smallest unit — cents for
+ # most currencies, whole yen for one written without decimals.
+ #
+ # Apportionment works in these units because integers divide exactly:
+ # shares computed from them can be made to sum to the original, which is
+ # what keeps a divided charge equal to the one the customer agreed to.
+ # Hardcoding a hundredth here instead would give a yen sale a hundred
+ # times its weight and hand back a figure with decimals the currency does
+ # not have.
+ #
+ # @param amount [Numeric, String, nil]
+ # @param currency [String, ::Money::Currency, nil]
+ # @return [Integer]
+ def to_minor_units(amount, currency)
+ (BigDecimal(amount.to_s) * (10**precision(currency))).round.to_i
+ end
+
+ # @param units [Integer] whole minor units, as {#to_minor_units} returns
+ # @param currency [String, ::Money::Currency, nil]
+ # @return [BigDecimal]
+ def from_minor_units(units, currency)
+ BigDecimal(units) / (10**precision(currency))
+ end
end
include Comparable
diff --git a/spree/core/lib/spree/testing_support/factories/order_group_factory.rb b/spree/core/lib/spree/testing_support/factories/order_group_factory.rb
new file mode 100644
index 0000000000..0484fae745
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/order_group_factory.rb
@@ -0,0 +1,29 @@
+FactoryBot.define do
+ factory :order_group, class: Spree::OrderGroup do
+ store { Spree::Store.default || create(:store) }
+ customer
+ currency { 'USD' }
+ email { customer&.email }
+
+ trait :with_orders do
+ transient do
+ sellers_count { 2 }
+ end
+
+ after(:create) do |group, evaluator|
+ evaluator.sellers_count.times do |index|
+ create(
+ :order,
+ store: group.store,
+ order_group: group,
+ seller: create(:seller, :approved, store: group.store),
+ number: "#{group.number}-#{index + 1}",
+ customer: group.customer,
+ currency: group.currency
+ )
+ end
+ group.orders.reload
+ end
+ end
+ end
+end
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 943010658f..bcc79dc108 100644
--- a/spree/core/lib/spree/testing_support/factories/payment_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/payment_factory.rb
@@ -1,11 +1,11 @@
FactoryBot.define do
factory :payment, class: Spree::Payment do
- order { cart.present? ? nil : create(:order, total: amount) }
+ order { (cart || order_group).present? ? nil : create(:order, total: amount) }
amount { 45.75 }
status { 'checkout' }
response_code { "BGS-#{SecureRandom.hex(6)}" }
- payment_method { create(:credit_card_payment_method, store: (order || cart).store) }
+ payment_method { create(:credit_card_payment_method, store: (order || cart || order_group).store) }
association(:source, factory: :credit_card)
factory :payment_with_refund do
diff --git a/spree/core/lib/spree/testing_support/factories/payment_split_factory.rb b/spree/core/lib/spree/testing_support/factories/payment_split_factory.rb
new file mode 100644
index 0000000000..e8fbecd56e
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/payment_split_factory.rb
@@ -0,0 +1,10 @@
+FactoryBot.define do
+ factory :payment_split, class: Spree::PaymentSplit do
+ payment
+ order
+ currency { 'USD' }
+ authorized_amount { BigDecimal(10) }
+ captured_amount { BigDecimal(0) }
+ refunded_amount { BigDecimal(0) }
+ end
+end
diff --git a/spree/core/spec/lib/spree/money_spec.rb b/spree/core/spec/lib/spree/money_spec.rb
index e92d29815d..0933b2c758 100644
--- a/spree/core/spec/lib/spree/money_spec.rb
+++ b/spree/core/spec/lib/spree/money_spec.rb
@@ -180,4 +180,36 @@ describe Spree::Money do
expect(money.as_json(options)).to eq('$10.00')
end
end
+
+ # Apportionment divides money in whole minor units, because integers divide
+ # exactly and can be made to add back up to the amount they came from.
+ describe Spree::Money::Rounding do
+ describe '.to_minor_units' do
+ it 'counts cents for a currency written in them' do
+ expect(described_class.to_minor_units(BigDecimal('12.34'), 'USD')).to eq(1234)
+ end
+
+ it 'counts whole yen, which are written without decimals' do
+ expect(described_class.to_minor_units(BigDecimal('1234'), 'JPY')).to eq(1234)
+ end
+
+ it 'counts thousandths for a three-decimal currency' do
+ expect(described_class.to_minor_units(BigDecimal('1.234'), 'BHD')).to eq(1234)
+ end
+
+ it 'rounds half up rather than truncating' do
+ expect(described_class.to_minor_units(BigDecimal('0.005'), 'USD')).to eq(1)
+ end
+ end
+
+ describe '.from_minor_units' do
+ it 'is the inverse for each currency' do
+ { 'USD' => '12.34', 'JPY' => '1234', 'BHD' => '1.234' }.each do |currency, amount|
+ units = described_class.to_minor_units(BigDecimal(amount), currency)
+
+ expect(described_class.from_minor_units(units, currency)).to eq(BigDecimal(amount))
+ end
+ end
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/fulfillment/grouped_capture_spec.rb b/spree/core/spec/models/spree/fulfillment/grouped_capture_spec.rb
new file mode 100644
index 0000000000..f9a91749e6
--- /dev/null
+++ b/spree/core/spec/models/spree/fulfillment/grouped_capture_spec.rb
@@ -0,0 +1,80 @@
+require 'spec_helper'
+
+# Dispatching a parcel in a split checkout draws on a payment several orders
+# share, so what it may take is bounded by this order's own recorded share.
+RSpec.describe Spree::Fulfillment, 'capture on dispatch in a split checkout' do
+ let(:store) { @default_store }
+ let(:seller) { create(:seller, :approved, store: store) }
+ let(:group) { create(:order_group, store: store) }
+
+ let!(:seller_order) { create(:order, store: store, order_group: group, seller: seller, total: 40) }
+ let!(:first_party_order) { create(:order, store: store, order_group: group, total: 60) }
+
+ let(:payment_method) { create(:check_payment_method, store: store, capture_method: 'on_dispatch') }
+ let(:payment) do
+ create(:payment, order: nil, cart: nil, order_group: group, amount: 100,
+ status: 'pending', payment_method: payment_method)
+ end
+
+ let!(:seller_split) do
+ create(:payment_split, payment: payment, order: seller_order, authorized_amount: 40)
+ end
+ let!(:first_party_split) do
+ create(:payment_split, payment: payment, order: first_party_order, authorized_amount: 60)
+ end
+
+ # A parcel worth more than this order's share of the shared payment.
+ def dispatch(order, worth:)
+ fulfillment = create(:fulfillment, order: order, cart: nil)
+ allow(fulfillment).to receive(:final_price_with_items).and_return(BigDecimal(worth))
+ fulfillment.send(:process_order_payments)
+ fulfillment
+ end
+
+ before { payment }
+
+ it 'captures no more than the order’s own share' do
+ dispatch(seller_order, worth: 100)
+
+ expect(captured_for(seller_order)).to eq(40)
+ end
+
+ # A partial capture forks the payment, and the uncaptured shares move to the
+ # remainder with the money — so an order's position is the sum of its shares
+ # across every payment the group holds, not one row.
+ def captured_for(order)
+ order.payment_splits.sum(:captured_amount)
+ end
+
+ def authorized_for(order)
+ order.payment_splits.sum(:authorized_amount)
+ end
+
+ it 'leaves the sibling’s money untouched and still capturable' do
+ dispatch(seller_order, worth: 100)
+
+ expect(captured_for(first_party_order)).to eq(0)
+ expect(authorized_for(first_party_order)).to eq(60)
+ end
+
+ it 'lets each order capture its own share in turn' do
+ dispatch(seller_order, worth: 40)
+ dispatch(first_party_order, worth: 60)
+
+ expect(captured_for(seller_order)).to eq(40)
+ expect(captured_for(first_party_order)).to eq(60)
+ end
+
+ it 'takes nothing more once the share is used up' do
+ dispatch(seller_order, worth: 40)
+
+ expect { dispatch(seller_order, worth: 40) }.not_to change { captured_for(seller_order) }
+ end
+
+ it 'reports the order as paid once its share is captured' do
+ dispatch(seller_order, worth: 40)
+ Spree::Orders::UpdateStatuses.call(order: seller_order)
+
+ expect(seller_order.reload.payment_status).to eq('paid')
+ end
+end
diff --git a/spree/core/spec/models/spree/order_group_spec.rb b/spree/core/spec/models/spree/order_group_spec.rb
new file mode 100644
index 0000000000..deeb76f585
--- /dev/null
+++ b/spree/core/spec/models/spree/order_group_spec.rb
@@ -0,0 +1,81 @@
+require 'spec_helper'
+
+RSpec.describe Spree::OrderGroup, type: :model do
+ let(:store) { @default_store }
+ let(:group) { create(:order_group, store: store) }
+ let(:seller) { create(:seller, :approved, store: store) }
+
+ it_behaves_like 'metadata'
+
+ describe 'derived money' do
+ before do
+ create(:order, store: store, order_group: group, total: 30, item_total: 25)
+ create(:order, store: store, order_group: group, seller: seller, total: 20, item_total: 18)
+ end
+
+ it 'totals what the children came to' do
+ expect(group.reload.total).to eq(50)
+ expect(group.item_total).to eq(43)
+ end
+ end
+
+ describe '#fulfillment_status' do
+ it 'is nil while no child has one' do
+ create(:order, store: store, order_group: group)
+
+ expect(group.reload.fulfillment_status).to be_nil
+ end
+
+ it 'reports the shared status when the children agree' do
+ 2.times { create(:order, store: store, order_group: group, fulfillment_status: 'unfulfilled') }
+
+ expect(group.reload.fulfillment_status).to eq('unfulfilled')
+ end
+
+ it 'reports partial when they disagree' do
+ create(:order, store: store, order_group: group, fulfillment_status: 'fulfilled')
+ create(:order, store: store, order_group: group, fulfillment_status: 'unfulfilled')
+
+ expect(group.reload.fulfillment_status).to eq('partial')
+ end
+
+ # A recalled parcel does not describe the whole purchase.
+ it 'ignores a canceled child while another is live' do
+ create(:order, store: store, order_group: group, fulfillment_status: 'canceled')
+ create(:order, store: store, order_group: group, fulfillment_status: 'fulfilled')
+
+ expect(group.reload.fulfillment_status).to eq('fulfilled')
+ end
+
+ it 'is canceled only when every child is' do
+ 2.times { create(:order, store: store, order_group: group, fulfillment_status: 'canceled') }
+
+ expect(group.reload.fulfillment_status).to eq('canceled')
+ end
+ end
+
+ describe '#sellers' do
+ it 'names the sellers it reached, first-party contributing none' do
+ create(:order, store: store, order_group: group)
+ create(:order, store: store, order_group: group, seller: seller)
+
+ expect(group.reload.sellers).to contain_exactly(seller)
+ expect(group).to be_includes_first_party
+ end
+ end
+
+ describe 'children' do
+ it 'refuses to be destroyed while it holds orders' do
+ create(:order, store: store, order_group: group)
+
+ expect(group.reload.destroy).to be false
+ expect(group.errors[:base]).to be_present
+ end
+ end
+
+ describe 'numbering' do
+ it 'takes an order-style number' do
+ expect(group.number).to start_with('R')
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/payment_split_spec.rb b/spree/core/spec/models/spree/payment_split_spec.rb
new file mode 100644
index 0000000000..299e8ca8c4
--- /dev/null
+++ b/spree/core/spec/models/spree/payment_split_spec.rb
@@ -0,0 +1,45 @@
+require 'spec_helper'
+
+RSpec.describe Spree::PaymentSplit, type: :model do
+ let(:store) { @default_store }
+ let(:group) { create(:order_group, store: store) }
+ # The order exists before the payment: a payment is sized against what it is
+ # paying for, and an empty group is worth nothing.
+ let!(:order) { create(:order, store: store, order_group: group, total: 60) }
+ let(:payment) { create(:payment, order: nil, cart: nil, order_group: group, amount: 40) }
+
+ describe 'one share per order and payment' do
+ it 'refuses a second share for the same pair' do
+ create(:payment_split, payment: payment, order: order)
+ duplicate = build(:payment_split, payment: payment, order: order)
+
+ expect(duplicate).not_to be_valid
+ end
+
+ it 'allows the same order a share of a second payment' do
+ create(:payment_split, payment: payment, order: order)
+ other_payment = create(:payment, order: nil, cart: nil, order_group: group, amount: 10)
+
+ expect(build(:payment_split, payment: other_payment, order: order)).to be_valid
+ end
+ end
+
+ describe '#net_captured_amount' do
+ it 'is what is left after refunds' do
+ split = create(:payment_split, payment: payment, order: order, captured_amount: 20, refunded_amount: 5)
+
+ expect(split.net_captured_amount).to eq(15)
+ end
+ end
+
+ # Whose sale a share belongs to is asked through its order — the split
+ # itself stays neutral, since the same container serves splits that have no
+ # seller at all.
+ it 'reaches its seller through the order it settles' do
+ seller = create(:seller, :approved, store: store)
+ seller_order = create(:order, store: store, order_group: group, seller: seller)
+ split = create(:payment_split, payment: payment, order: seller_order)
+
+ expect(split.order.seller).to eq(seller)
+ end
+end
diff --git a/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rb b/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rb
new file mode 100644
index 0000000000..3bfb90a604
--- /dev/null
+++ b/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rb
@@ -0,0 +1,67 @@
+require 'spec_helper'
+
+# Refunding one seller's order in a split checkout must leave its siblings
+# alone: the customer's money comes back out of the one charge either way, but
+# what each seller is owed does not move because a neighbour refunded.
+RSpec.describe Spree::PaymentSplitSubscriber, :events, type: :model do
+ let(:store) { @default_store }
+ let(:seller) { create(:seller, :approved, store: store) }
+ let(:group) { create(:order_group, store: store) }
+
+ let!(:seller_order) { create(:order, store: store, order_group: group, seller: seller, total: 40) }
+ let!(:first_party_order) { create(:order, store: store, order_group: group, total: 60) }
+
+ let(:payment) do
+ create(:payment, order: nil, cart: nil, order_group: group, amount: 100, status: 'completed')
+ end
+
+ let!(:seller_split) do
+ create(:payment_split, payment: payment, order: seller_order,
+ authorized_amount: 40, captured_amount: 40)
+ end
+ let!(:first_party_split) do
+ create(:payment_split, payment: payment, order: first_party_order,
+ authorized_amount: 60, captured_amount: 60)
+ end
+
+ def refund!(order, amount)
+ create(:refund, payment: payment, order: order, amount: amount)
+ end
+
+ it 'records the refund against only that order’s share' do
+ refund!(seller_order, 15)
+
+ expect(seller_split.reload.refunded_amount).to eq(15)
+ expect(first_party_split.reload.refunded_amount).to eq(0)
+ end
+
+ it 'reports the refunded order as refunded and leaves the sibling’s share alone' do
+ Spree::Orders::UpdateStatuses.call(order: first_party_order)
+
+ refund!(seller_order, 40)
+
+ expect(seller_order.reload.payment_status).to eq('refunded')
+ expect(first_party_order.reload.payment_status).to eq('paid')
+ expect(first_party_split.reload.refunded_amount).to eq(0)
+ end
+
+ it 'reports a part refund as partially refunded' do
+ refund!(seller_order, 10)
+
+ expect(seller_order.reload.payment_status).to eq('partially_refunded')
+ end
+
+ it 'totals several refunds on one order rather than counting the last' do
+ refund!(seller_order, 10)
+ refund!(seller_order, 5)
+
+ expect(seller_split.reload.refunded_amount).to eq(15)
+ end
+
+ it 'leaves an ungrouped order alone' do
+ plain_order = create(:order, store: store, total: 20)
+ plain_payment = create(:payment, order: plain_order, amount: 20, status: 'completed')
+
+ expect { create(:refund, payment: plain_payment, amount: 5) }.not_to raise_error
+ end
+end
diff --git a/spree/core/spec/workflows/spree/carts/complete_split_spec.rb b/spree/core/spec/workflows/spree/carts/complete_split_spec.rb
new file mode 100644
index 0000000000..aa8ab8a5ed
--- /dev/null
+++ b/spree/core/spec/workflows/spree/carts/complete_split_spec.rb
@@ -0,0 +1,294 @@
+require 'spec_helper'
+
+module Spree
+ # The marketplace half of completion: a basket holding several sellers' goods
+ # becomes one order per seller, under a group that holds the single payment.
+ describe Carts::Complete, 'splitting by seller' do
+ let(:store) { @default_store }
+ let(:seller) { create(:seller, :approved, store: store, name: 'Sparks Audio') }
+ let(:other_seller) { create(:seller, :approved, store: store, name: 'Quill Books') }
+
+ # A cart of three items, whose sellers the caller decides.
+ def cart_for(*sellers)
+ cart = create(:cart_ready_for_delivery, store: store, line_items_count: sellers.size)
+ cart.line_items.reload.each_with_index do |line_item, index|
+ assigned = sellers[index]
+ line_item.variant.update!(seller: assigned)
+ line_item.update_columns(seller_id: assigned&.id)
+ end
+ cart.reload.recalculate_totals!
+ create(:payment, cart: cart, order: nil, payment_method: Spree::PaymentMethod.first, amount: cart.reload.total)
+ cart.reload
+ end
+
+ describe 'the gate' do
+ it 'leaves an all-first-party cart as a bare order' do
+ result = described_class.call(cart: cart_for(nil, nil))
+
+ expect(result).to be_success
+ expect(result.value).to be_a(Spree::Order)
+ expect(result.value.order_group).to be_nil
+ expect(Spree::OrderGroup.count).to eq(0)
+ end
+
+ it 'leaves a single-seller cart as a bare order carrying the seller' do
+ result = described_class.call(cart: cart_for(seller, seller))
+
+ expect(result.value).to be_a(Spree::Order)
+ expect(Spree::OrderGroup.count).to eq(0)
+ expect(result.value.line_items.map(&:seller_id).uniq).to eq([seller.id])
+ end
+
+ it 'splits a cart holding two sellers' do
+ result = described_class.call(cart: cart_for(seller, other_seller))
+
+ expect(result).to be_success
+ expect(result.value).to be_a(Spree::OrderGroup)
+ expect(result.value.orders.count).to eq(2)
+ end
+
+ # The mixed basket: the operator's own goods bought alongside a seller's.
+ it 'splits first-party items into their own order' do
+ result = described_class.call(cart: cart_for(nil, seller))
+ group = result.value
+
+ expect(group.orders.count).to eq(2)
+ expect(group.orders.map(&:seller_id)).to match_array([nil, seller.id])
+ expect(group).to be_includes_first_party
+ end
+
+ it 'splits a basket of first-party plus two sellers three ways' do
+ result = described_class.call(cart: cart_for(nil, seller, other_seller))
+ group = result.value
+
+ expect(group.orders.count).to eq(3)
+ expect(group.orders.map(&:seller_id)).to match_array([nil, seller.id, other_seller.id])
+ end
+ end
+
+ describe 'what each child order holds' do
+ let(:cart) { cart_for(nil, seller, other_seller) }
+ let(:group) { described_class.call(cart: cart).value }
+
+ it 'gives every child only its own seller’s items' do
+ group.orders.each do |order|
+ expect(order.line_items.map(&:seller_id).uniq).to eq([order.seller_id])
+ expect(order.line_items).to be_present
+ end
+ end
+
+ it 'accounts for every line item exactly once' do
+ moved = group.orders.flat_map { |order| order.line_items.map(&:id) }
+
+ expect(moved.size).to eq(cart.line_items.count)
+ expect(moved.uniq.size).to eq(moved.size)
+ end
+
+ it 'computes each child’s totals from its own rows' do
+ group.orders.each do |order|
+ expect(order.total).to be > 0
+ expect(order.item_total).to eq(order.line_items.sum(&:amount))
+ end
+ end
+
+ it 'places every child' do
+ expect(group.orders.map(&:status).uniq).to eq(['placed'])
+ end
+
+ it 'numbers the children off the group' do
+ expect(group.orders.map(&:number)).to match_array(
+ [1, 2, 3].map { |index| "#{group.number}-#{index}" }
+ )
+ end
+
+ it 'gives each child its own addresses rather than sharing rows' do
+ address_ids = group.orders.map(&:ship_address_id)
+
+ expect(address_ids.compact.uniq.size).to eq(address_ids.size)
+ end
+ end
+
+ # The hardest case: the cart packed everything into one parcel, so the
+ # split has to divide the parcel itself — and the delivery the customer was
+ # quoted for it, which must not be charged twice.
+ describe 'a parcel holding several sellers’ goods' do
+ let(:cart) { cart_for(nil, seller, seller) }
+ let(:group) { described_class.call(cart: cart).value }
+
+ it 'gives each child its own parcel' do
+ expect(cart.fulfillments.count).to eq(1)
+ expect(group.orders.map { |order| order.fulfillments.count }).to all(eq(1))
+ end
+
+ it 'divides the delivery charge rather than duplicating it' do
+ expect(group.orders.sum(&:delivery_total)).to eq(cart.reload.delivery_total)
+ end
+
+ it 'keeps the customer’s total exactly what they paid' do
+ expect(group.total).to eq(cart.reload.total)
+ expect(group.total).to eq(group.payments.sum(:amount))
+ end
+
+ it 'carries the chosen delivery rate onto both parcels' do
+ rates = group.orders.flat_map { |order| order.fulfillments.map(&:selected_delivery_rate) }
+
+ expect(rates).to all(be_present)
+ end
+
+ it 'leaves no row pointing at an order that no longer owns it' do
+ order_ids = group.orders.map(&:id)
+
+ expect(Spree::FulfillmentItem.where.not(order_id: order_ids)).to be_empty
+ expect(Spree::LineItem.where(order_id: nil, cart_id: nil)).to be_empty
+ end
+
+ # A fulfillment restates its cost from its selected rate whenever its
+ # amounts refresh, so a rate left at the undivided figure would quietly
+ # restore the full delivery charge on both halves.
+ it 'writes the divided cost down onto the rate as well' do
+ group.orders.each do |order|
+ order.fulfillments.each do |fulfillment|
+ expect(fulfillment.selected_delivery_rate.cost).to eq(fulfillment.cost)
+ end
+ end
+ end
+
+ it 'survives a later amounts refresh without doubling the delivery charge' do
+ before_total = group.orders.sum(&:delivery_total)
+ group.orders.each { |order| order.fulfillments.each(&:update_amounts) }
+
+ expect(group.orders.map(&:reload).sum(&:delivery_total)).to eq(before_total)
+ end
+
+ # Reservations are released by order, so a line item's hold has to travel
+ # with it — otherwise one child releases everyone's and the siblings hold
+ # stock until it expires.
+ it 'moves each line item’s stock reservation to the order that keeps it' do
+ group.orders.each do |order|
+ reserved_line_item_ids = Spree::StockReservation.where(order_id: order.id).pluck(:line_item_id).compact
+
+ expect(reserved_line_item_ids - order.line_items.ids).to be_empty
+ end
+ end
+ end
+
+ # The children are still drafts when they are re-summed, so nothing may
+ # re-derive their money: the promotion adjuster would delete the discounts
+ # just moved onto them and re-test one seller's subset against a threshold
+ # the whole basket met, and the tax provider would re-estimate from today's
+ # rates. The customer has already paid the answer the checkout gave.
+ describe 'money the checkout already settled' do
+ let(:promotion) do
+ create(:promotion, :with_order_adjustment, store: store,
+ weighted_order_adjustment_amount: 6, code: 'SAVE6')
+ end
+
+ let(:cart) do
+ promotion
+ built = cart_for(nil, seller)
+ built.coupon_code = 'SAVE6'
+ Spree::PromotionHandler::Coupon.new(built).apply
+ built.reload.recalculate_totals!
+ built.payments.each { |payment| payment.update!(amount: built.reload.total) }
+ built.reload
+ end
+
+ it 'keeps an order-level discount instead of re-competing it per child' do
+ paid = cart.total
+ group = described_class.call(cart: cart).value
+
+ expect(group.total).to eq(paid)
+ expect(group.orders.sum(&:discount_total)).to eq(-6)
+ expect(group.orders.map { |order| order.discounts.count }).to all(eq(1))
+ end
+ end
+
+ describe 'the payment' do
+ let(:cart) { cart_for(nil, seller) }
+ let(:group) { described_class.call(cart: cart).value }
+
+ it 'moves onto the group rather than any one order' do
+ expect(group.payments.count).to eq(1)
+ expect(group.orders.flat_map(&:payments)).to be_empty
+ end
+
+ it 'records one share per child order' do
+ expect(group.payment_splits.count).to eq(2)
+ end
+
+ it 'shares out exactly what was charged' do
+ payment = group.payments.first
+ shares = group.payment_splits.sum(:authorized_amount)
+
+ expect(shares).to eq(payment.amount)
+ end
+
+ it 'gives each child a share matching its own total' do
+ group.orders.each do |order|
+ share = order.payment_splits.sum(:authorized_amount)
+ expect(share).to eq(order.total)
+ end
+ end
+
+ # A share that recorded nothing captured would report every child of a
+ # fully paid checkout as merely authorised — two unpaid-looking orders
+ # for money that is already in the bank.
+ it 'records the share as captured when the payment already settled' do
+ expect(group.payments.first).to be_completed
+
+ group.orders.each do |order|
+ expect(order.payment_splits.sum(:captured_amount)).to eq(order.total)
+ expect(order.payment_status).to eq('paid')
+ end
+ end
+ end
+
+ # The commission engine listens for order.placed, which every child
+ # publishes on its own — so a split checkout charges each seller with no
+ # marketplace code in the commission engine at all.
+ describe 'commission', :events do
+ let(:cart) { cart_for(nil, seller) }
+
+ before { create(:commission_rate, store: store, kind: 'percentage', value: 10, enabled: true) }
+
+ it 'charges the seller’s order and leaves first-party alone' do
+ group = described_class.call(cart: cart).value
+
+ seller_order = group.orders.find_by(seller: seller)
+ first_party_order = group.orders.find_by(seller_id: nil)
+
+ expect(seller_order.commission_lines).to be_present
+ expect(first_party_order.commission_lines).to be_empty
+ end
+ end
+
+ describe 'replay' do
+ let(:cart) { cart_for(seller, other_seller) }
+
+ it 'returns the same group rather than splitting twice' do
+ first = described_class.call(cart: cart).value
+ second = described_class.call(cart: cart.reload).value
+
+ expect(second.id).to eq(first.id)
+ expect(Spree::OrderGroup.count).to eq(1)
+ expect(Spree::Order.count).to eq(2)
+ end
+ end
+
+ describe 'the group' do
+ let(:group) { described_class.call(cart: cart_for(nil, seller)).value }
+
+ it 'totals what the children came to' do
+ expect(group.total).to eq(group.orders.sum(&:total))
+ end
+
+ it 'names the sellers it reached' do
+ expect(group.sellers).to contain_exactly(seller)
+ end
+
+ it 'is the cart’s completion result' do
+ expect(group.cart.order_group).to eq(group)
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/workflows/spree/orders/cancel_grouped_spec.rb b/spree/core/spec/workflows/spree/orders/cancel_grouped_spec.rb
new file mode 100644
index 0000000000..6d30bcc487
--- /dev/null
+++ b/spree/core/spec/workflows/spree/orders/cancel_grouped_spec.rb
@@ -0,0 +1,69 @@
+require 'spec_helper'
+
+# Cancelling one order of a split checkout must give back that order's money
+# and nothing else: the payment is shared, so releasing it wholesale would
+# un-pay the sellers still shipping.
+RSpec.describe Spree::Orders::Cancel, 'an order placed in a split checkout' do
+ let(:store) { @default_store }
+ let(:seller) { create(:seller, :approved, store: store) }
+ let(:group) { create(:order_group, store: store) }
+
+ let!(:seller_order) do
+ create(:order, store: store, order_group: group, seller: seller, total: 40, status: 'placed',
+ completed_at: Time.current)
+ end
+ let!(:first_party_order) do
+ create(:order, store: store, order_group: group, total: 60, status: 'placed', completed_at: Time.current)
+ end
+
+ let(:payment) do
+ create(:payment, order: nil, cart: nil, order_group: group, amount: 100, status: 'completed')
+ end
+
+ let!(:seller_split) do
+ create(:payment_split, payment: payment, order: seller_order, authorized_amount: 40, captured_amount: 40)
+ end
+ let!(:first_party_split) do
+ create(:payment_split, payment: payment, order: first_party_order, authorized_amount: 60, captured_amount: 60)
+ end
+
+ before { payment }
+
+ # The default. An operator cancelling an order is not thereby asking to move
+ # money — that is a separate decision, and the plain path already treats it
+ # as one.
+ context 'without refund_payments' do
+ it 'refunds nothing' do
+ expect { described_class.call(order: seller_order) }.not_to change { Spree::Refund.count }
+ end
+
+ it 'still releases what the order had reserved but never drew' do
+ seller_split.update!(captured_amount: 10)
+
+ described_class.call(order: seller_order)
+
+ expect(seller_split.reload.authorized_amount).to eq(10)
+ end
+ end
+
+ context 'with refund_payments' do
+ it 'gives back what this order was actually paid' do
+ described_class.call(order: seller_order, refund_payments: true)
+
+ expect(Spree::Refund.where(order_id: seller_order.id).sum(:amount)).to eq(40)
+ end
+
+ it 'leaves the sibling’s money alone' do
+ described_class.call(order: seller_order, refund_payments: true)
+
+ expect(Spree::Refund.where(order_id: first_party_order.id)).to be_empty
+ expect(first_party_split.reload.captured_amount).to eq(60)
+ end
+
+ it 'honours an explicit smaller amount' do
+ described_class.call(order: seller_order, refund_payments: true, refund_amount: 15)
+
+ expect(Spree::Refund.where(order_id: seller_order.id).sum(:amount)).to eq(15)
+ end
+ end
+end
diff --git a/spree/core/spec/workflows/spree/refunds/create_grouped_spec.rb b/spree/core/spec/workflows/spree/refunds/create_grouped_spec.rb
new file mode 100644
index 0000000000..458ff8adc1
--- /dev/null
+++ b/spree/core/spec/workflows/spree/refunds/create_grouped_spec.rb
@@ -0,0 +1,55 @@
+require 'spec_helper'
+
+# A payment shared by a split checkout holds several orders' money, so what one
+# of them may take back is bounded by its own share — not by the payment's
+# balance, which says nothing about whose money is left in it.
+RSpec.describe Spree::Refunds::Create, 'against a shared payment' do
+ let(:store) { @default_store }
+ let(:seller) { create(:seller, :approved, store: store) }
+ let(:group) { create(:order_group, store: store) }
+
+ let!(:seller_order) { create(:order, store: store, order_group: group, seller: seller, total: 40) }
+ let!(:first_party_order) { create(:order, store: store, order_group: group, total: 60) }
+
+ let(:payment) do
+ create(:payment, order: nil, cart: nil, order_group: group, amount: 100, status: 'completed')
+ end
+
+ let!(:seller_split) do
+ create(:payment_split, payment: payment, order: seller_order, authorized_amount: 40, captured_amount: 40)
+ end
+ let!(:first_party_split) do
+ create(:payment_split, payment: payment, order: first_party_order, authorized_amount: 60, captured_amount: 60)
+ end
+
+ before { payment }
+
+ it 'refunds up to the order’s own share' do
+ result = described_class.call(payment: payment, amount: 40, order: seller_order)
+
+ expect(result).to be_success
+ expect(result.value.amount).to eq(40)
+ end
+
+ it 'refuses to spend a sibling’s money, even though the payment holds it' do
+ result = described_class.call(payment: payment, amount: 70, order: seller_order)
+
+ expect(result).to be_failure
+ expect(payment.reload.refunds).to be_empty
+ end
+
+ it 'refuses once the order’s share is already refunded' do
+ described_class.call(payment: payment, amount: 40, order: seller_order)
+ seller_split.reload
+
+ result = described_class.call(payment: payment, amount: 5, order: seller_order)
+
+ expect(result).to be_failure
+ end
+
+ it 'stamps the refund with the order it put right' do
+ refund = described_class.call(payment: payment, amount: 10, order: seller_order).value
+
+ expect(refund.order).to eq(seller_order)
+ end
+end