Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Let an operator read the seller ledger and settle what is owed
Damian Legawiec935c4dd0a7ef
diff --git a/docs/plans/6.0-admin-api.md b/docs/plans/6.0-admin-api.mdindex b42a525395..1dba0dcc33 100644--- a/docs/plans/6.0-admin-api.md+++ b/docs/plans/6.0-admin-api.md@@ -709,9 +709,9 @@ Per `6.0-multi-vendor-marketplace.md`. Seller prefix is `sel_` (matches the lega- [ ] `PATCH /api/v3/admin/commission_rates/:id` — saves rate fields + nested `rules: []` in one round-trip (PriceList-style)- [ ] `DELETE /api/v3/admin/commission_rates/:id`- [ ] `GET /api/v3/admin/commission_lines` — read-only snapshot ledger (filter by seller/order)-- [ ] `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)+- [x] `GET /api/v3/admin/seller_transfers` — read-only earnings ledger (filter by seller/payout/status; `read_payouts`)+- [x] `GET /api/v3/admin/seller_payouts` / `GET /:id`+- [x] `PATCH /api/v3/admin/seller_payouts/:id/complete` — manual settlement (system provider; `write_payouts`)- [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.mdindex 61bffe097c..dadc94b749 100644--- a/docs/plans/6.0-multi-vendor-marketplace.md+++ b/docs/plans/6.0-multi-vendor-marketplace.md@@ -1,6 +1,6 @@# Multi-Vendor Marketplace (Open Source Core)-**Status:** In Progress — 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)+**Status:** In Progress — 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), Phase 3 (order splitting — `OrderGroup`, `PaymentSplit`, the split inside `Carts::Complete`, 2026-08-20), Phase 3a (the two-level fund ledger, 2026-08-22) and Phase 3b (OSS Stripe Connect payouts, 2026-08-22) implemented; Phase 4 (dashboards) remains, along with the seller-facing onboarding screens**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@@ -722,9 +722,9 @@ This is **new OSS code**, not a rename of existing core — there is no in-place- **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. 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.+ - **Phase 3a — fund ledger. IMPLEMENTED 2026-08-22.** The two-level `SellerTransfer` (on-fulfillment) + `SellerPayout` (scheduled sweep) + `PayoutProvider::System` + `seller.balance(currency)`, sequenced after the split because the transfer basis needs child orders to exist. **What shipped and why it took the shape it did:** a seller earns on **fulfilment**, not payment — `SellerTransferSubscriber` answers `order.fulfilled` (only; the legacy `order.shipped` is deliberately not subscribed) and `SellerTransfers::Create` writes `order.total − commission_lines.sum(:total)`, less `additional_tax_total` when the seller is `platform`-remitted, floored at zero. Its guards are the interesting part: an order with **no** fulfillments reads as `fully_fulfilled?` (vacuously true), so the emptiness is checked explicitly, and a seller whose provider `requires_payout_account?` but who holds none is skipped rather than credited money nothing can send. A refund writes a **reversal row** (`kind: 'refund_reversal'`, linked by `reversed_from`) bounded by `reversible_amount`, so a twice-refunded order can never claw back more than was credited; the earning row is never edited. A partial unique index on `(order_id) WHERE kind = 'earning'` makes double-crediting a database error rather than a race (MySQL takes a `CASE WHEN` generated column instead). `SellerPayouts::Sweep` claims unsettled transfers **by stamping them inside one transaction**, so two concurrent runs cannot batch the same earning, and restates its own amount if it claimed fewer rows than it counted; it refuses a batch below the seller's minimum or one a reversal has pushed negative. `SellerPayouts::Complete` is the only thing that debits a balance, because a settlement is a claim about the outside world — an operator says the bank transfer went out, or a provider's webhook says the money landed. Admin API: read-only `/admin/seller_transfers` and `/admin/seller_payouts` plus `PATCH /seller_payouts/:id/complete`, under a new `payouts` permission resource (separate from `commissions` — they are opposite directions of the same relationship, and a finance operator often needs one without the other; closed to the seller audience).- **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 3b — OSS Stripe Connect provider. IMPLEMENTED 2026-08-22** in `spree/providers/stripe`. `SpreeStripe::PayoutProvider` transfers on fulfilment naming the customer's own charge as `source_transaction` (so the money settles with that charge rather than out of the platform's balance — a marketplace should not have to float its sellers), with an idempotency key derived from the ledger row. `pay!` deliberately **sends nothing**: money on a connected account is settled to the seller's bank by Stripe on that account's own schedule, so a payout is confirmed by webhook exactly as the built-in provider's is confirmed by an operator. `reverse!` is ledger-only in OSS. **Connect settings live on the Stripe payment method, not in an integration of their own** — it is the same Stripe account either way, and a transfer signed with a different key than the charge cannot name that charge as its funding source, so a second copy of the credentials could only drift out of agreement with the first. **Two webhook endpoints, and this is not a detail.** Stripe's `connect` flag is a *scope selector*, not an additive one: an endpoint receives events from the platform's own account **or** from its connected accounts, never both. Adding `account.updated` to the payment endpoint would not widen it — it would switch it over, and the payment webhooks would silently stop arriving. So a marketplace registers a second endpoint with its own signing secret, served by a new provider-agnostic `POST /api/v3/webhooks/payouts/:payment_method_id` route beside the payments one, and it is registered only once the store actually has sellers. `account.updated` writes `payouts_enabled_at` — and **clears it** when Stripe withdraws the capability, since a seller whose documents expire stops being payable and the ledger must stop crediting them. Not yet built: the Express onboarding UI (`create_connect_account_link` exists and is specced; the seller-facing screen belongs with the onboarding work) and payout-schedule mapping onto the connected account.- **Phase 4 — Dashboards.** **The order surfaces landed early with Phase 3 (2026-08-21)**, since a split checkout is unreadable without them: the orders table gained optional `seller` and `order_group` columns (both `default: false`, so a store selling only its own goods never sees them) with Ransack filters behind them, and the order page gained a marketplace card naming the seller — linked to their profile — and, when the order was one of several, the purchase it belonged to with a link back to the list filtered to its siblings. The card renders nothing on an ordinary order. Deliberately **no order-group screen of its own**: the group is the shared payment and the identity of the purchase, and what an operator acts on is always an order, so the group appears as a filter and a link rather than a page. `orders.seller_id`/`order_group_id` joined the Ransack allowlist (without which a filter silently matches nothing); the serializer carries **ids only**, with the seller's name coming from `?expand=seller` requested by the column while it is visible — a denormalized `seller_name` was tried and dropped as a second copy of something the association already answers. The order group is deliberately **not** expandable from an order: its serializer renders the orders it holds, so expanding it from one of them would render that order inside itself, and a client wanting the group has `/order_groups/:id`. Remaining: (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.**Phases 1–2 have no dependency on the Cart/Order split** — they can be built (even shipped behind a preview flag in a 5.x release) while the split refactor lands, de-risking the 6.0 timeline.@@ -775,6 +775,7 @@ Even before this lands, work touching adjacent areas should:- **Seller principal → `Spree::AdminUser` (`Spree.admin_user_class`), no `SellerUser` model** (RESOLVED 2026-08-15). Reuse the whole shipped auth stack and the RBAC rails (`RoleUser`/`Invitation` on `resource: seller`); membership is by resource type, never `store_id`. Isolation guaranteed at the token layer: own `seller_api` JWT audience, own `Spree.seller_authentication_strategies` + `/seller/auth/*` (so staff can be SSO-only while sellers use passwords; the seller login refuses non-members), `spree_refresh_tokens.audience`. See Decision 10 + `decisions.md` 2026-08-15.- **Seller API → dedicated `/api/v3/seller` branch, `current_seller` scope-fetching; sellers never call the Admin API** (RESOLVED 2026-08-15). Supersedes the 2026-07-14 "seller users hit the same admin API with seller-scoped abilities" wording — permission sets with tenancy conditions no longer exist (RBAC, PR #14412), and the RBAC plan's 2026-08-08 direction already named `current_seller` endpoints. Own serializer branch off the store serializers, own OpenAPI spec, no subclassing of admin controllers. See Decision 10.- **Store credit / gift cards split across child orders → group-level payments, prorated through `PaymentSplit` like any other payment** (RESOLVED 2026-08-15). A store-credit or gift-card payment is a `Payment` on the `OrderGroup` exactly like the gateway payment; every group payment gets one `PaymentSplit` row per child order, prorated by child totals with the same largest-remainder rule as order-level discounts. One attribution rule for every payment source, no priority ordering, no special-casing — and it composes with the resolved payment-source-agnostic transfer basis (the seller's earning never depends on how the buyer paid). Confirmed against the shipped `Carts::Complete` pipeline (payments attach before the split runs).+- **One payout provider per store, chosen by a preference** (RESOLVED 2026-08-22). `Store#preferred_payout_provider` names it, `payout_provider_instance` resolves it, and blank means core's record-only `System`. Concurrent providers were considered and rejected: a seller's account reference is meaningful only relative to one provider (a Stripe `acct_…` means nothing to another), so supporting two at once turns that column into a per-provider map and adds the provider to the grouping key of the balance, the sweep and every reconciliation — a real tax on every marketplace for a case few will meet. The two realistic needs are served without it: a **migration** between providers works because each ledger row carries its own `provider`, so history stays truthful while new rows use the new one; and **per-seller providers**, if ever needed, are a nullable column on the seller falling back to the store's, the same override shape `payouts_schedule_interval` already uses. The nearer problem is not two providers but one that cannot pay every seller — Stripe Connect refuses unsupported countries — which is what `payouts_enabled_at` and the sweep's skip are for. The surveyed OSS marketplace reaches the same conclusion and enforces it harder: its payout module raises unless **exactly one** provider is registered, and its seller payout account is an untyped JSON blob with no provider column at all, so its schema could not tell two providers apart even with the guard removed. Its ledger is also one level — one order is one payout row, with no batching — so there is no prior art to copy for the two-level shape either.- **Payout minimum threshold → core; rolling reserve / holdback → Enterprise** (RESOLVED 2026-08-15). `spree_sellers.minimum_payout_amount` (decimal, nullable; nil ⇒ store preference `default_minimum_payout_amount`) — the sweep skips a seller whose `balance(currency)` is below the threshold and carries the balance to the next period. A percentage holdback with a release window is money-operations policy (chargeback buffer) and stays Enterprise, so core does not grow a third ledger row kind.- **Marketplace-facilitator remittance → `spree_sellers.tax_remittance` (`seller` | `platform`, default `seller`), honored by core's transfer basis** (RESOLVED 2026-08-15). `platform` ⇒ `transfer.amount = total − tax_total − commission`; `seller` keeps `total − commission`. Core owns the ledger math so it is provider-independent; *deciding* when a seller is `platform`-remitted (US facilitator nexus, EU deemed-supplier scenarios) stays Enterprise "automatic taxes", which simply sets the column. Amends the Decision 9 note that this mode is "not core": the flag and the math are core, the policy is not.- **Seller-scoped promotions → post-6.0** (RESOLVED 2026-08-15 as deferred; shape recorded under Open Questions).diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 7e098a1d5c..b2621b16b4 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -313,9 +313,11 @@ import type {ReturnReason,Role,Seller,+ SellerPayout,SellerRequirement,SellerRequirementSubmission,SellerTeamMember,+ SellerTransfer,StockLevel,StockLocation,StockMovement,@@ -2710,6 +2712,73 @@ export class AdminClient {}),}+ // ============================================+ // Seller fund ledger+ // ============================================++ /**+ * Read-only view of `Spree::SellerTransfer` — what one order earned one+ * seller, credited when the goods went out. There is no write path: a+ * refund writes a reversal, which is another row rather than an edit.+ */+ readonly sellerTransfers = {+ list: (+ params?: ListParams & Record<string, unknown>,+ options?: RequestOptions,+ ): Promise<PaginatedResponse<SellerTransfer>> =>+ this.request<PaginatedResponse<SellerTransfer>>('GET', '/seller_transfers', {+ ...options,+ params: params ? transformListParams(params) : undefined,+ }),++ get: (+ id: string,+ params?: { expand?: string[] },+ options?: RequestOptions,+ ): Promise<SellerTransfer> =>+ this.request<SellerTransfer>('GET', `/seller_transfers/${id}`, {+ ...options,+ params: getParams(params),+ }),+ }++ /**+ * `Spree::SellerPayout` — one settlement to one seller. Created by the+ * sweep on that seller's own schedule rather than by a caller, so there is+ * no create or update. `complete` is what the built-in provider waits for:+ * the operator saying the bank transfer went out.+ */+ readonly sellerPayouts = {+ list: (+ params?: ListParams & Record<string, unknown>,+ options?: RequestOptions,+ ): Promise<PaginatedResponse<SellerPayout>> =>+ this.request<PaginatedResponse<SellerPayout>>('GET', '/seller_payouts', {+ ...options,+ params: params ? transformListParams(params) : undefined,+ }),++ get: (+ id: string,+ params?: { expand?: string[] },+ options?: RequestOptions,+ ): Promise<SellerPayout> =>+ this.request<SellerPayout>('GET', `/seller_payouts/${id}`, {+ ...options,+ params: getParams(params),+ }),++ complete: (+ id: string,+ data?: { reference?: string },+ options?: RequestOptions,+ ): Promise<SellerPayout> =>+ this.request<SellerPayout>('PATCH', `/seller_payouts/${id}/complete`, {+ ...options,+ body: data,+ }),+ }+// ============================================// Gift cards (admin-issued)// ============================================diff --git a/packages/admin-sdk/src/types/generated/SellerPayout.ts b/packages/admin-sdk/src/types/generated/SellerPayout.tsnew file mode 100644index 0000000000..9bdfe9f99c--- /dev/null+++ b/packages/admin-sdk/src/types/generated/SellerPayout.ts@@ -0,0 +1,23 @@+// Typelizer digest 7c09631fd08c09c04fed787a9cbd4530+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++interface SellerPayout {+ id: string;+ status: string;+ currency: string;+ provider: string;+ reference: string | null;+ metadata: unknown;+ period_start: string | null;+ period_end: string | null;+ created_at: string;+ updated_at: string;+ amount: string;+ display_amount: string;+ seller_id: string;+ seller_name: string | null;+ transfers_count: number;+}++export default SellerPayout;diff --git a/packages/admin-sdk/src/types/generated/SellerTransfer.ts b/packages/admin-sdk/src/types/generated/SellerTransfer.tsnew file mode 100644index 0000000000..96e15fda0f--- /dev/null+++ b/packages/admin-sdk/src/types/generated/SellerTransfer.ts@@ -0,0 +1,25 @@+// Typelizer digest 7928486b3b38f323dd0632633c484146+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++interface SellerTransfer {+ id: string;+ kind: string;+ status: string;+ currency: string;+ provider: string;+ reference: string | null;+ metadata: unknown;+ created_at: string;+ updated_at: string;+ amount: string;+ display_amount: string;+ seller_id: string;+ order_id: string | null;+ payout_id: string | null;+ reversed_from_id: string | null;+ seller_name: string | null;+ order_number: string | null;+}++export default SellerTransfer;diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.tsindex 1644eac040..d105227c81 100644--- a/packages/admin-sdk/src/types/generated/index.ts+++ b/packages/admin-sdk/src/types/generated/index.ts@@ -83,11 +83,13 @@ export type { default as ReturnLineItem } from './ReturnLineItem'export type { default as ReturnReason } from './ReturnReason'export type { default as Return } from './Return'export type { default as Role } from './Role'+export type { default as SellerPayout } from './SellerPayout'export type { default as SellerRequirement } from './SellerRequirement'export type { default as SellerRequirementStatus } from './SellerRequirementStatus'export type { default as SellerRequirementSubmission } from './SellerRequirementSubmission'export type { default as Seller } from './Seller'export type { default as SellerTeamMember } from './SellerTeamMember'+export type { default as SellerTransfer } from './SellerTransfer'export type { default as SetupTask } from './SetupTask'export type { default as State } from './State'export type { default as StockLevel } from './StockLevel'diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.tsindex 209f30a831..261483ef70 100644--- a/packages/admin-sdk/src/types/index.ts+++ b/packages/admin-sdk/src/types/index.ts@@ -92,10 +92,12 @@ export type { default as ReturnLineItem } from './generated/ReturnLineItem'export type { default as ReturnReason } from './generated/ReturnReason'export type { default as Role } from './generated/Role'export type { default as Seller } from './generated/Seller'+export type { default as SellerPayout } from './generated/SellerPayout'export type { default as SellerRequirement } from './generated/SellerRequirement'export type { default as SellerRequirementStatus } from './generated/SellerRequirementStatus'export type { default as SellerRequirementSubmission } from './generated/SellerRequirementSubmission'export type { default as SellerTeamMember } from './generated/SellerTeamMember'+export type { default as SellerTransfer } from './generated/SellerTransfer'export type { default as SetupTask } from './generated/SetupTask'export type { default as State } from './generated/State'export type { default as StockLevel } from './generated/StockLevel'diff --git a/spree/api/app/controllers/spree/api/v3/admin/seller_payouts_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/seller_payouts_controller.rbnew file mode 100644index 0000000000..68702cd1db--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/seller_payouts_controller.rb@@ -0,0 +1,57 @@+module Spree+ module Api+ module V3+ module Admin+ # Settlements to sellers — what has been sent, and what is still owed.+ #+ # A payout is created by the sweep on the seller's own schedule rather+ # than by a caller, so there is no create or update here. The one thing+ # an operator does to a payout is say it landed, which is what the+ # built-in provider expects: it records the settlement and waits to be+ # told the bank transfer went out.+ class SellerPayoutsController < ResourceController+ scoped_resource :payouts++ before_action :set_resource, only: [:complete]++ # PATCH /api/v3/admin/seller_payouts/:id/complete+ #+ # What the built-in provider waits for: the operator saying the bank+ # transfer went out, with the reference it went out under.+ def complete+ result = Spree.seller_payout_complete_workflow.call(+ seller_payout: @resource,+ reference: params[:reference]+ )++ if result.success?+ render json: serialize_resource(result.value)+ else+ render_result_error(result)+ end+ end++ protected++ def model_class+ Spree::SellerPayout+ end++ def serializer_class+ Spree.api.admin_seller_payout_serializer+ end++ # Reached through the store's own sellers: a payout carries no store+ # of its own, and the seller is what ties it to one.+ def scope+ super.where(seller_id: current_store.sellers.select(:id))+ end++ def collection_includes+ [:seller, :transfers]+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/seller_transfers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/seller_transfers_controller.rbnew file mode 100644index 0000000000..be10f7f45c--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/seller_transfers_controller.rb@@ -0,0 +1,36 @@+module Spree+ module Api+ module V3+ module Admin+ # What each seller has earned, order by order.+ #+ # Read-only, enforced by the routes: a transfer records money that+ # moved. Correcting one is a reversal — another row, written by the+ # refund that caused it — rather than an edit.+ class SellerTransfersController < ResourceController+ scoped_resource :payouts++ protected++ def model_class+ Spree::SellerTransfer+ end++ def serializer_class+ Spree.api.admin_seller_transfer_serializer+ end++ # Reached through the store's own sellers: a transfer carries no+ # store of its own, and the seller is what ties it to one.+ def scope+ super.where(seller_id: current_store.sellers.select(:id))+ end++ def collection_includes+ [:seller, :order, :payout]+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/webhooks/payouts_controller.rb b/spree/api/app/controllers/spree/api/v3/webhooks/payouts_controller.rbnew file mode 100644index 0000000000..3ed6180879--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/webhooks/payouts_controller.rb@@ -0,0 +1,56 @@+module Spree+ module Api+ module V3+ module Webhooks+ # Marketplace events about sellers: POST /api/v3/webhooks/payouts/:payment_method_id.+ #+ # Separate from the payments endpoint because providers scope the two+ # separately. Events originating in a seller's own account — whether+ # they may be paid, whether a payout reached their bank — arrive on+ # their own subscription with their own signing secret, so verifying+ # them against the payment endpoint's secret would reject every one.+ #+ # Addressed to the payment method because a marketplace pays sellers+ # out of the account it charges their customers from: the same+ # credentials, and so the same record.+ #+ # Handled inline rather than handed to a job, like the carrier+ # endpoint: marking a seller payable or a payout settled is a couple of+ # database writes, well inside any sender's timeout.+ class PayoutsController < ActionController::API+ include ActionController::RateLimiting+ include Spree::Core::ControllerHelpers::Store++ # Must render — instance_exec'd in a before_action, where only+ # render/redirect halts the chain.+ RATE_LIMIT_RESPONSE = -> {+ response.headers['Retry-After'] = '60'+ render json: { error: { code: 'rate_limit_exceeded', message: 'Too many requests' } },+ status: :too_many_requests+ }++ rate_limit to: 120, within: 1.minute,+ store: Rails.cache,+ by: -> { request.remote_ip },+ with: RATE_LIMIT_RESPONSE++ def create+ payment_method = current_store.payment_methods.find_by_prefix_id!(params[:payment_method_id])+ return head :not_found unless payment_method.respond_to?(:handle_payout_webhook)++ payment_method.handle_payout_webhook(request.raw_post, request.headers)++ head :ok+ rescue Spree::PaymentMethod::WebhookSignatureError+ head :unauthorized+ rescue ActiveRecord::RecordNotFound+ head :not_found+ rescue StandardError => e+ Rails.error.report(e, source: 'spree.webhooks.payouts')+ head :ok+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/seller_payout_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/seller_payout_serializer.rbnew file mode 100644index 0000000000..9e40ff1d23--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/seller_payout_serializer.rb@@ -0,0 +1,39 @@+module Spree+ module Api+ module V3+ module Admin+ # Serializes Spree::SellerPayout — one settlement to one seller.+ #+ # Created by the sweep rather than by a caller, so the API offers no+ # create or update. The one thing an operator does to a payout is say+ # it landed, which is its own member action.+ class SellerPayoutSerializer < V3::BaseSerializer+ typelize seller_id: :string,+ seller_name: 'string | null',+ status: :string,+ provider: :string,+ amount: :string,+ currency: :string,+ reference: 'string | null',+ period_start: 'string | null',+ period_end: 'string | null',+ transfers_count: :number,+ display_amount: :string++ attributes :status, :currency, :provider, :reference, :metadata,+ period_start: :iso8601, period_end: :iso8601,+ created_at: :iso8601, updated_at: :iso8601++ attribute(:amount) { |payout| payout.amount&.to_s }+ attribute(:display_amount) { |payout| payout.display_amount.to_s }+ attribute(:seller_id) { |payout| payout.seller&.prefixed_id }+ attribute(:seller_name) { |payout| payout.seller&.name }++ # How many earnings this settlement covers, so a list answers "what+ # is in this deposit" without loading every transfer.+ attribute(:transfers_count) { |payout| payout.transfers.size }+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/seller_transfer_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/seller_transfer_serializer.rbnew file mode 100644index 0000000000..e3984c58e4--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/seller_transfer_serializer.rb@@ -0,0 +1,43 @@+module Spree+ module Api+ module V3+ module Admin+ # Serializes Spree::SellerTransfer — what one order earned one seller.+ #+ # Read-only: a transfer records money that moved, or is moving. What+ # corrects it is a reversal, which is another row rather than an edit.+ class SellerTransferSerializer < V3::BaseSerializer+ typelize seller_id: :string,+ order_id: 'string | null',+ payout_id: 'string | null',+ reversed_from_id: 'string | null',+ seller_name: 'string | null',+ order_number: 'string | null',+ kind: :string,+ status: :string,+ provider: :string,+ amount: :string,+ currency: :string,+ reference: 'string | null',+ display_amount: :string++ attributes :kind, :status, :currency, :provider, :reference, :metadata,+ created_at: :iso8601, updated_at: :iso8601++ # A string, so the figure a seller is paid round-trips exactly.+ attribute(:amount) { |transfer| transfer.amount&.to_s }+ attribute(:display_amount) { |transfer| transfer.display_amount.to_s }++ %i[seller order payout reversed_from].each do |association|+ attribute(:"#{association}_id") { |transfer| transfer.public_send(association)&.prefixed_id }+ end++ # Both readable without expanding, since a ledger table is read row+ # by row and these are what identify a row to an operator.+ attribute(:seller_name) { |transfer| transfer.seller&.name }+ attribute(:order_number) { |transfer| transfer.order&.number }+ end+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 841aeaf7a6..c800efe0af 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -531,6 +531,18 @@ Spree::Core::Engine.add_routes doendresources :commission_lines, only: [:index, :show]+ # The fund ledger — what sellers earned, and what has been sent them.+ # Both are written by fulfilment and by the sweep rather than by a+ # caller, so both are read-only. The one thing an operator does is say+ # a settlement landed, which the built-in provider depends on: it+ # records what to send and waits to be told it went.+ resources :seller_transfers, only: [:index, :show]+ resources :seller_payouts, only: [:index, :show] do+ member do+ patch :complete+ end+ end+# 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]@@ -785,6 +797,13 @@ Spree::Core::Engine.add_routes donamespace :webhooks dopost 'payments/:payment_method_id', to: 'payments#create', as: :payment_webhookpost 'fulfillments/:integration_id', to: 'fulfillments#create', as: :fulfillment_webhook+ # Marketplace events about sellers rather than about a payment —+ # whether a seller may be paid, and whether a payout reached their+ # bank. A separate endpoint because providers scope these separately:+ # events originating in a seller's own account arrive on a different+ # subscription, with a different signing secret, than the+ # marketplace's own payment events.+ post 'payouts/:payment_method_id', to: 'payouts#create', as: :payout_webhookendendenddiff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex 5d638a945a..36652284f4 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -186,6 +186,8 @@ module Spreeadmin_commission_rate_serializer: 'Spree::Api::V3::Admin::CommissionRateSerializer',admin_commission_rule_serializer: 'Spree::Api::V3::Admin::CommissionRuleSerializer',admin_commission_line_serializer: 'Spree::Api::V3::Admin::CommissionLineSerializer',+ admin_seller_transfer_serializer: 'Spree::Api::V3::Admin::SellerTransferSerializer',+ admin_seller_payout_serializer: 'Spree::Api::V3::Admin::SellerPayoutSerializer',admin_address_serializer: 'Spree::Api::V3::Admin::AddressSerializer',admin_channel_serializer: 'Spree::Api::V3::Admin::ChannelSerializer',admin_order_routing_rule_serializer: 'Spree::Api::V3::Admin::OrderRoutingRuleSerializer',diff --git a/spree/api/spec/controllers/spree/api/v3/admin/seller_payouts_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/seller_payouts_controller_spec.rbnew file mode 100644index 0000000000..9b3f954e46--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/seller_payouts_controller_spec.rb@@ -0,0 +1,67 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::SellerPayoutsController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let(:seller) { create(:seller, :approved, store: store, name: 'Sparks Audio') }+ let!(:payout) { create(:seller_payout, seller: seller, amount: 120, currency: 'USD') }++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ it 'lists what a seller is owed' do+ get :index, as: :json++ expect(response).to have_http_status(:ok)+ row = json_response['data'].first+ expect(row['id']).to start_with('vpo_')+ expect(row['seller_name']).to eq('Sparks Audio')+ expect(row['amount']).to eq('120.0')+ expect(row['display_amount']).to eq('$120.00')+ expect(row['status']).to eq('pending')+ end++ it "hides another marketplace's settlements" do+ create(:seller_payout, seller: create(:seller, store: create(:store)))++ get :index, as: :json++ expect(json_response['data'].map { |row| row['id'] }).to contain_exactly(payout.prefixed_id)+ end++ it 'counts the earnings a settlement covers' do+ create(:seller_transfer, :completed, seller: seller, payout: payout)+ create(:seller_transfer, :completed, seller: seller, payout: payout)++ get :index, as: :json++ expect(json_response['data'].first['transfers_count']).to eq(2)+ end+ end++ describe 'PATCH #complete' do+ it 'records that the money landed' do+ patch :complete, params: { id: payout.prefixed_id, reference: 'BACS-9912' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['status']).to eq('completed')+ expect(payout.reload.reference).to eq('BACS-9912')+ end++ it "404s on another marketplace's settlement" do+ other = create(:seller_payout, seller: create(:seller, store: create(:store)))++ patch :complete, params: { id: other.prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'writes' do+ it 'offers no create — a settlement is produced by the sweep' do+ expect { post :create, params: { amount: 5 }, as: :json }.to raise_error(ActionController::UrlGenerationError)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/seller_transfers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/seller_transfers_controller_spec.rbnew file mode 100644index 0000000000..f8344f21fc--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/seller_transfers_controller_spec.rb@@ -0,0 +1,66 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::SellerTransfersController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let(:seller) { create(:seller, :approved, store: store, name: 'Sparks Audio') }+ let(:order) { create(:order, store: store, seller: seller) }+ let!(:transfer) do+ create(:seller_transfer, seller: seller, order: order, amount: 42.5, currency: 'USD')+ end++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ it 'lists what a seller earned' do+ get :index, as: :json++ expect(response).to have_http_status(:ok)+ row = json_response['data'].first+ expect(row['id']).to start_with('vtr_')+ expect(row['seller_name']).to eq('Sparks Audio')+ expect(row['order_number']).to eq(order.number)+ expect(row['amount']).to eq('42.5')+ expect(row['display_amount']).to eq('$42.50')+ expect(row['kind']).to eq('earning')+ end++ it "hides another marketplace's ledger" do+ other_store = create(:store)+ other_seller = create(:seller, store: other_store)+ create(:seller_transfer, seller: other_seller, order: create(:order, store: other_store, seller: other_seller))++ get :index, as: :json++ expect(json_response['data'].map { |row| row['id'] }).to contain_exactly(transfer.prefixed_id)+ end+ end++ describe 'GET #show' do+ it 'returns one transfer' do+ get :show, params: { id: transfer.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['id']).to eq(transfer.prefixed_id)+ end++ it "404s on another marketplace's transfer" do+ other_store = create(:store)+ other_seller = create(:seller, store: other_store)+ other = create(:seller_transfer, seller: other_seller,+ order: create(:order, store: other_store, seller: other_seller))++ get :show, params: { id: other.prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'writes' do+ it 'offers none — a transfer records money that moved' do+ expect { post :create, params: { amount: 5 }, as: :json }.to raise_error(ActionController::UrlGenerationError)+ end+ end+enddiff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rbindex 024c60e566..37cc47ef44 100644--- a/spree/core/lib/spree/core/permission_configuration.rb+++ b/spree/core/lib/spree/core/permission_configuration.rb@@ -403,6 +403,16 @@ module Spree[Spree::CommissionRate, Spree::CommissionRule, Spree::CommissionLine]})+ # What the marketplace owes its sellers, and what it has sent them.+ # Separate from `commissions` because they are opposite directions of the+ # same relationship, and a finance operator often needs one without the+ # other. Closed to the seller audience: a seller reads their own earnings+ # through their own branch, scope-fetched, never through a key that could+ # reach the whole ledger.+ register_resource(:payouts, group: :access, subjects: -> {+ [Spree::SellerTransfer, Spree::SellerPayout]+ })+# A seller editing their own record: profile, branding, addresses,# onboarding.#