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 that commission precedence became an ordered list

Damian Legawiec796680c25a18
diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.md
index 61ca0e5980..63e0b64a37 100644
--- a/docs/plans/6.0-multi-vendor-marketplace.md
+++ b/docs/plans/6.0-multi-vendor-marketplace.md
@@ -65,17 +65,17 @@ This is the one place where the **legacy Enterprise module is ahead of the surve
**EU base (RESOLVED 2026-06-25):** commission is computed on the seller's **net (ex-VAT)** item price, and `tax_amount` is applied **on top of the commission** — the marketplace fee is a separate taxable supply from the consumer's item sale, so the two VATs never mix. The `include_tax`-style base toggle stays available for non-EU/edge merchants who want a gross base, but the EU default is net-base + fee-VAT. The **tax-on-the-fee** field is mandatory and is the headline EU feature. The commission tax *rate* is resolved through `6.0-tax-provider.md` (per-Market TaxProvider) rather than a bare `platform_fee_tax_rate` column on the vendor (RESOLVED — see Resolved Decisions).
-### 4. Commission rate resolution: layered rules, first-match-wins by priority — generalize the legacy flat rate
+### 4. Commission rate resolution: layered rules, first match wins in operator order — generalize the legacy flat rate
-The legacy module resolves a **single flat percentage** with a two-level fallback: the product's platform-fee override if set, else the vendor's default rate. That is "very simplified" — percentage only; no categories, no caps, no currency scoping. The industry pattern generalizes this into a proper `CommissionRate` + `CommissionRule` engine (priority-ordered, first-match-wins, dimension-grouped targeting rules, `percentage | fixed`, `min_amount` floor, currency gate, no-rules = global default).
+The legacy module resolves a **single flat percentage** with a two-level fallback: the product's platform-fee override if set, else the vendor's default rate. That is "very simplified" — percentage only; no categories, no caps, no currency scoping. The industry pattern generalizes this into a proper `CommissionRate` + `CommissionRule` engine (operator-ordered, first-match-wins, dimension-grouped targeting rules, `percentage | fixed`, `min_amount` floor, currency gate, no-rules = global default).
-**6.0 adopts the rule-engine shape but keeps the legacy fallback as the default ladder.** New models `Spree::CommissionRate` (priority, kind, value, currency, commission tax handling) + `Spree::CommissionRule` (polymorphic `subject` → Product / Taxon / Vendor / global). Resolution walks enabled rates by `priority DESC`, first match wins. Seed two implicit rules so existing single-rate merchants keep working: a product-scoped rate and a vendor-scoped rate, mirroring `product.platform_fee || vendor.platform_fee`.
+**6.0 adopts the rule-engine shape but keeps the legacy fallback as the default ladder.** New models `Spree::CommissionRate` (position, kind, value, currency, commission tax handling) + `Spree::CommissionRule` (polymorphic `subject` → Product / Category / Vendor / global). Resolution walks enabled rates in list order, first match wins. Seed a marketplace-wide rate at the bottom of the list so narrower rates an operator adds resolve ahead of it.
-**Rule matching is dimension-grouped: AND across dimensions, OR within a dimension.** A rate's rules are grouped by subject type (Product / Taxon / Vendor); the rate matches a line item when *every* dimension group present has at least one matching rule. `{taxon: Electronics, taxon: Cameras, vendor: X}` reads "(Electronics OR Cameras) AND vendor X" — which expresses plain lists *and* the **vendor × category pairing** today's Enterprise sells (user docs: "per vendor, per category-vendor pairing, or per individual product") with no `match_policy` knob at all. The leading surveyed OSS engine uses the same semantics, so the model is proven; where we differ deliberately is precedence — explicit operator `priority` instead of implicit most-specific-wins, which is more predictable (already RESOLVED below).
+**Rule matching is dimension-grouped: AND across dimensions, OR within a dimension.** A rate's rules are grouped by subject type (Product / Taxon / Vendor); the rate matches a line item when *every* dimension group present has at least one matching rule. `{taxon: Electronics, taxon: Cameras, vendor: X}` reads "(Electronics OR Cameras) AND vendor X" — which expresses plain lists *and* the **vendor × category pairing** today's Enterprise sells (user docs: "per vendor, per category-vendor pairing, or per individual product") with no `match_policy` knob at all. The leading surveyed OSS engine uses the same semantics, so the model is proven; where we differ deliberately is precedence — an explicit operator-ordered list instead of implicit most-specific-wins, which is more predictable (already RESOLVED below).
**`include_shipping` on the rate** (default `false`): when the resolved rate has it, the same calculation also runs against the vendor order's delivery amounts, persisting a fulfillment-scoped `CommissionLine`. The surveyed OSS competitor commissions shipping via a global-rate-only flag, and Amazon-style referral fees include it; the legacy module was items-only (its order-level "reverse fee" only prorates *item* commission on whole-order refunds — shipping is excluded from its base). Ours is per-rate — strictly more flexible than a global-only flag, and off by default so legacy behavior is preserved.
-**Precedence (RESOLVED 2026-06-25): integer-priority, not a fixed ladder.** `priority` is operator-assignable and walked `DESC`, first match wins. Core **seeds default priorities** so the product-scoped rate beats the vendor-scoped rate out of the box — simple merchants never touch priorities, advanced merchants reorder freely. No hardcoded product > taxon > vendor > global ladder.
+**Precedence (RESOLVED 2026-06-25; reshaped 2026-08-17 — `acts_as_list`, shipped): an ordered list, not a fixed ladder.** Rates carry `position` via `acts_as_list scope: :store_id` and are walked top-down, first match wins — so the order an operator sees in the table *is* the precedence, and reordering is dragging a row rather than reasoning about an integer. **New rates are created at the top** (`add_new_at: :top`): a rate exists to say something more specific than what is already there, and appending would file it behind the catch-all that matches everything. Seeds put a disabled marketplace-wide rate at the bottom, which makes the product-then-category-then-seller order merchants asked for fall out for free without hardcoding it. Ordering is deliberately **not** derived from how specific a rate's rules look: a rate may name a product, a category and a seller at once, so there is no single dimension to sort on, and "narrowest wins" guesses at an intent the operator can simply state.
### 5. One payment, recorded as a per-seller split — adopt the explicit split-payment record
@@ -407,7 +407,7 @@ class Spree::CommissionRate < Spree.base_class
belongs_to :store, class_name: 'Spree::Store'
has_many :commission_rules, class_name: 'Spree::CommissionRule', dependent: :destroy
- # name, code (unique per store), enabled (bool), priority (int)
+ # name, code (unique per store), enabled (bool), position (int, acts_as_list)
# kind : string — 'percentage' | 'fixed'
# value : decimal — percent (e.g. 10.0) or flat amount
# currency : string — REQUIRED when kind == 'fixed', ignored when 'percentage' (RESOLVED)
@@ -428,7 +428,7 @@ class Spree::CommissionRule < Spree.base_class
end
```
-**Resolution** (`Spree::Commissions::ResolveRate` service): load enabled `CommissionRate`s for the store ordered by `priority DESC` — the currency gate applies **only to `fixed` rates** (a fixed rate must match the order currency; `percentage` rates are currency-agnostic and always pass) — and return the first whose rules match the line item: rules grouped by `subject_type`, every present group needs ≥1 match (Decision 4). A rate with no rules is the global default. Seed default rates so `product.platform_fee || vendor.platform_fee` behavior is preserved without configuration — including the legacy store-preference default (30%) as the seeded global rate. This also untangles the three legacy meanings of `platform_fee` (store preference / vendor column / product override) into one model.
+**Resolution** (`Spree::Commissions::ResolveRate` service): load enabled `CommissionRate`s for the store in list order (`position ASC`) — the currency gate applies **only to `fixed` rates** (a fixed rate must match the order currency; `percentage` rates are currency-agnostic and always pass) — and return the first whose rules match the line item: rules grouped by `subject_type`, every present group needs ≥1 match (Decision 4). A rate with no rules is the global default (`CommissionRate#global?`) — and because resolution stops at the first match, one placed above a targeted rate makes it unreachable, which is why the seeded default sits at the bottom and the admin surfaces the flag. `Spree::Seeds::CommissionRates` seeds exactly one such rate, **disabled and at zero**: a marketplace that has not set its terms should charge nothing rather than a number core invented. This also untangles the three legacy meanings of `platform_fee` (store preference / vendor column / product override) into one model.
**Calculation** (`Spree::Commissions::CalculateLine` service) — ports the legacy per-item fee calculation, generalized:
@@ -677,7 +677,7 @@ Even before this lands, work touching adjacent areas should:
- **Basic Stripe Connect execution → OSS (boundary amendment)** (RESOLVED 2026-07-15). Express onboarding + on-fulfillment transfers ship in the monorepo alongside the pulled-in Stripe gateway, for demo/adoption parity with the surveyed competitor — "money moves automatically" is the demo that sells, and transfers are inseparable from basic onboarding (a `Stripe::Transfer` needs a connected account). Enterprise repositions on money **operations**: automatic refund clawbacks (prorated transfer reversals + negative-balance netting), KYC/account-health workflows, ledger⇄Stripe reconciliation, payout reports incl. DAC7, facilitator taxes. Ledger reversal rows stay OSS in every mode — only the pullback execution is paid. Supersedes #13323's "execution stays Enterprise" framing (amendment by the issue author; update the issue). See `decisions.md` 2026-07-15.
- **`Spree::Vendor` name ownership → marketplace seller; inventory-operations' procurement model renamed `Spree::Supplier`** (RESOLVED 2026-07-14). See the Key Decisions entry and `decisions.md` 2026-07-14.
- **Commission is not a `Spree::Fee`** (RESOLVED 2026-07-14). `Fee` is buyer-facing and rolls into order totals; `CommissionLine` is an off-order platform↔vendor ledger. See Decision 2.
-- **Commission rule matching → dimension-grouped (AND across subject types, OR within one)** (RESOLVED 2026-07-14). Expresses plain lists and the vendor × taxon pairings today's Enterprise sells, with no `match_policy` knob; same semantics as the leading surveyed OSS engine, but precedence stays explicit operator `priority` rather than implicit specificity. See Decision 4.
+- **Commission rule matching → dimension-grouped (AND across subject types, OR within one)** (RESOLVED 2026-07-14). Expresses plain lists and the vendor × taxon pairings today's Enterprise sells, with no `match_policy` knob; same semantics as the leading surveyed OSS engine, but precedence stays the operator's own ordering rather than implicit specificity. See Decision 4.
- **Commission on delivery revenue → `include_shipping` on the rate** (RESOLVED 2026-07-14). Per-rate flag, default off (legacy was items-only); a fulfillment-scoped `CommissionLine` (nullable `fulfillment_id`, exactly-one-of with `line_item_id`). Matches the surveyed OSS competitor (global-only there) and Amazon referral-fee behavior. See Decision 4.
- **Split payment record → `Spree::PaymentSplit` + `payments.order_group_id`** (RESOLVED 2026-07-14). One gateway payment on the group, one split row per child order; no cloned `Payment` rows. See Decision 5 + Design Details.
- **Vendor teams → reuse `Role`/`RoleUser`/`Invitation` with `resource: vendor`** (RESOLVED 2026-07-14). The polymorphic rails already exist in core (Invitation's docstring names Vendor); no `VendorUser` model. See Vendor identity & teams.
@@ -686,7 +686,7 @@ Even before this lands, work touching adjacent areas should:
- **Fund ledger → two levels: `Spree::VendorTransfer` (per-order, on-fulfillment) + `Spree::VendorPayout` (per-interval settlement), both generic in core + pluggable `PayoutProvider` (system no-op in core; basic StripeConnect with the monorepo Stripe gateway per the 2026-07-15 amendment, extended by Enterprise with the money operations)** (RESOLVED 2026-06-25). See Decision 9. Transfer credits the vendor balance on fulfillment; payout sweeps unsettled transfers into a scheduled bank settlement (transfers `belong_to` their payout — auditable). `vendor.balance(currency) = Σ completed transfers − Σ completed payouts` per currency. Splits the legacy gateway-namespaced transfer ledger (which conflated the two and outsourced settlement to Stripe) into core ledger + provider execution along the OSS/Enterprise seam.
- **Commission VAT base → net item price, VAT added on top of the fee** (RESOLVED 2026-06-25). For EU, commission is computed on the seller's **net (ex-VAT)** item price; the commission `tax_amount` (Decision 3) is then applied **on top of the commission** as a separate B2B service supply — the marketplace fee is a distinct taxable event from the consumer's item sale, so the two VATs never mix. The `include_tax` toggle stays available for non-EU/edge merchants who genuinely want a gross base, but the EU default is net-base + fee-VAT. This makes the marketplace's commission invoice to the seller stand on its own (correct for EU invoicing + remittance).
- **Store-credit/gift-card payout → payment-source-agnostic** (RESOLVED 2026-06-25). The `VendorTransfer` amount (which rolls up into the payout) is `(vendor's sale value) − (commission owed)`, **independent of how the customer paid**. Store credit / gift cards are the platform's funding concern, not the vendor's — the vendor is owed their full cut of the sale regardless. This **drops the legacy store-credit dual-basis** from the amount calculation; that branch existed only to reconcile the old store-credit funding model and does not belong in the payout basis. (The platform still tracks its own store-credit liability separately — that's orthogonal to what the vendor receives.)
-- **Commission precedence → integer priority + seeded defaults** (RESOLVED 2026-06-25). `CommissionRate.priority` is operator-assignable, walked `DESC`, first match wins (Decision 4). Core **seeds default priorities** so a product-scoped rate beats a vendor-scoped rate out of the box — simple merchants never touch the knob; advanced merchants reorder freely. No hardcoded semantic ladder.
+- **Commission precedence → an operator-ordered list** (RESOLVED 2026-06-25 as integer priority; **reshaped 2026-08-17 to `acts_as_list`, shipped**). `CommissionRate` carries `position` (`acts_as_list scope: :store_id, add_new_at: :top`) and resolution walks it top-down, first match wins (Decision 4). The list on screen is the precedence, so reordering is dragging rather than assigning numbers; new rates land at the top so they take effect on creation instead of behind the catch-all. `Spree::Seeds::CommissionRates` puts one disabled marketplace-wide rate at the bottom, which yields the product > category > seller order merchants asked for without hardcoding a ladder. No specificity inference — a rate can name all three dimensions at once, so there is nothing to infer from.
- **Commission rate currency → required for fixed, ignored for percentage** (RESOLVED 2026-06-25). A `kind: 'fixed'` rate **must** carry a `currency` (a flat "2" is meaningless without one); a `kind: 'percentage'` rate ignores currency (10% applies in any currency). Enforced by a model validation: `validates :currency, presence: true, if: -> { kind == 'fixed' }`. See the `CommissionRate` model.
- **Payout vs transfer trigger → transfer on-fulfillment, payout on-interval** (RESOLVED 2026-06-25). These are the two distinct events of Decision 9: a `VendorTransfer` becomes due **on-fulfillment** (the vendor earned it); a `VendorPayout` settles on the vendor's **scheduled interval** (`payouts_schedule_interval`). The earlier "on-ship vs on-deliver vs scheduled" framing was a category error — it conflated the two. Core's `system` provider honors `manual` settlement natively; Enterprise implements daily/weekly/biweekly/monthly.