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.

Record the capture-claim window as a Phase 3a constraint

Damian Legawiec5bdd3387f72a
diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.md
index 9804a0ce58..b90651ce73 100644
--- a/docs/plans/6.0-multi-vendor-marketplace.md
+++ b/docs/plans/6.0-multi-vendor-marketplace.md
@@ -731,6 +731,7 @@ Even before this lands, work touching adjacent areas should:
- **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 (**this one did not actually work until 2026-08-21** — see the shared-payment entry above: it read a captured figure that the subscriber had not yet written); `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.
+- **Claiming a share before the gateway leaves a window nothing else may settle through** (RESOLVED 2026-08-21, shipped). A parcel marks its share taken *before* charging, so two parcels cannot draw the same money — which means a share can read captured while the charge is still in flight. Cancellation now refuses to settle such a share, reporting it for manual resolution rather than releasing an authorization the gateway is about to draw on. The guard is deliberately narrow: a share claiming nothing, or one on an already-settled payment, is untouched, so net-terms and checkout-captured orders cancel unchanged. **The general shape for Phase 3a:** `captured_amount` on a split means *claimed*, not *confirmed*, and anything settling money against it — a transfer, a payout sweep — has to ask the payment whether the charge actually landed. A first attempt at this guard compared against `payment.captured_amount`, which is summed from capture *events* that a checkout-captured payment never writes, so it flagged every ordinary order; three specs caught it immediately.
- **A shared payment breaks every reader that assumed one payment means one order** (RESOLVED 2026-08-21, shipped). A review pass over the split found thirteen such readers, each verified against the code before being believed, and every one real. The instructive ones: **`order.paid` never fired for a split checkout** — it publishes from the payment's own `after_commit`, which runs *before* `payment.completed` reaches the subscriber that marks the shares captured, so the figure it read was always zero (an earlier note in this plan asserted the opposite ordering and was wrong; the trace is what settled it). Public webhook API, silently dead for marketplace orders. **Several payments each re-divided the whole basket and each rounded**, so three children owed 33.33/33.33/33.34 were credited 33.34/33.32/33.34 — the group's sum correct and two children's wrong; payments now draw down what is left. **A parcel whose halves are both worth nothing kept the full delivery charge on each**, the same double-charge fixed earlier surviving in the zero-weight path. And a grouped child's `payment_total` was summed from payments it does not own, persisting nothing paid. The pattern worth carrying into Phase 3a: **anything that reaches an order through `payment.order`, or a total through `order.payments`, is wrong on a grouped order** — and none of these failed loudly.
- **A grouped child order's money is read from its payment splits, not its payments** (RESOLVED 2026-08-20, shipped). Such an order owns no payments — the customer paid once, against the group — so `Orders::UpdateStatuses` reads captured/authorised/refunded from `payment_splits`, capture-on-dispatch draws from the group's payments **bounded by that child's remaining share** (without the bound the first seller to ship captures the whole basket), and `spree_refunds.order_id` names which child a refund puts right so `PaymentSplitRefundSubscriber` can recompute that share alone. `Refund#order` falls back to the payment and `Order#refunds` resolves either shape, so nothing outside a split checkout changes. This is the concrete argument for storing shares rather than computing proportions on read: once one seller has shipped and been captured while another has not, no proportion of the group's totals describes either.
- **The 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.