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.

Fix refunds on split-checkout orders

Damian Legawiec50d7d78e9a8a
diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.md
index 317b861200..03e3b98a3d 100644
--- a/docs/plans/6.0-multi-vendor-marketplace.md
+++ b/docs/plans/6.0-multi-vendor-marketplace.md
@@ -185,7 +185,7 @@ Two questions were re-examined against the shipped auth (PR #14380) and RBAC (PR
**Principal — `Spree.admin_user_class`, no `SellerUser` model.** The platform is two-principal after #14380: `Customer` buys, `AdminUser` operates a back office — and a seller's team operates a back office. That one class now carries the entire auth stack (`has_secure_password`, lockout, password policy, `generates_token_for :password_reset`, `UserIdentity` SSO linking, invitation acceptance, refresh-token cookie flow); a third principal would duplicate every one of those (and every future MFA/passkey improvement) as a second security surface. The RBAC rails already assume it: `RoleUser` (`user: Spree.admin_user_class`, `resource: seller`, store binding derived from the seller), `Invitation` (`resource: seller`), and `Spree::Ability#staff_roles` deliberately excluding seller-resourced assignments as belonging to "their own panel's ability". One human, one login, several hats: an `AdminUser` may hold a store role and a seller role at once (the operator's own first-party seller; a merchant selling on two marketplaces run on two stores). A seller member is **not** store staff — membership is by *resource type*, never by `store_id`.
-**Surface — a third v3 branch, `/api/v3/seller/…`, beside `store` and `admin`.** The plan's earlier line ("seller users hit the same admin API with seller-scoped abilities — no separate seller routes") is superseded: it relied on `PermissionSets::SellerUser` with `seller_id: user.seller_ids` hash conditions, and #14412 removed permission sets with no bridge — the catalog is flat `read_*`/`write_*` keys with no conditions, and the RBAC plan already re-decided on 2026-08-08 that "seller-panel endpoints scope-fetch through `current_seller` exactly as admin endpoints scope through `current_store`". Reusing the ~300 admin endpoints would mean per-principal forks in every `scope`/`find_resource`/incidental lookup (`stock_location_id`, `reason_id`, `variant_id` on line-item writes) — each miss a cross-seller read or write inside the same store — plus per-principal field masking in serializers. A seller branch is ~20 controllers, each written scope-first (`current_seller.products`, `current_seller.orders`, …): **IDOR by construction**, the same way store isolation works on the admin branch today (controller scoping only — the ability layer has no tenancy conditions). What a seller may not do (publish to channels, edit orders, refund, approve itself, create stock locations) is an endpoint that does not exist, not an ability rule. Do **not** subclass admin controllers into the seller namespace — inherited `current_store.*` lookups are precisely the leak; share workflows and permitted-param lists, never controllers.
+**Surface — a third v3 branch, `/api/v3/seller/…`, beside `store` and `admin`.** The plan's earlier line ("seller users hit the same admin API with seller-scoped abilities — no separate seller routes") is superseded: it relied on `PermissionSets::SellerUser` with `seller_id: user.seller_ids` hash conditions, and #14412 removed permission sets with no bridge — the catalog is flat `read_*`/`write_*` keys with no conditions, and the RBAC plan already re-decided on 2026-08-08 that "seller-panel endpoints scope-fetch through `current_seller` exactly as admin endpoints scope through `current_store`". Reusing the ~300 admin endpoints would mean per-principal forks in every `scope`/`find_resource`/incidental lookup (`stock_location_id`, `reason_id`, `variant_id` on line-item writes) — each miss a cross-seller read or write inside the same store — plus per-principal field masking in serializers. A seller branch is ~20 controllers, each written scope-first (`current_seller.products`, `current_seller.orders`, …): **IDOR by construction**, the same way store isolation works on the admin branch today (controller scoping only — the ability layer has no tenancy conditions). What a seller may not do (publish to channels, edit orders, take payments, approve itself, create stock locations) is an endpoint that does not exist, not an ability rule. (**Amended 2026-09-03** — `refund` was in that list and should not have been: the legacy module granted vendors `Refund`, `Reimbursement`, `CustomerReturn` and `ReturnAuthorization` on their own orders, so a seller refunding their own return is behavior being opened up, not new latitude. See `6.0-seller-order-management.md` Decision 1; the group's `Payment` stays the operator's.) Do **not** subclass admin controllers into the seller namespace — inherited `current_store.*` lookups are precisely the leak; share workflows and permitted-param lists, never controllers.
**Isolation is enforced at the token layer, not only at membership.** Three requirements, all mandatory (they answer the two concrete objections to a shared model — "staff must be SSO-only while sellers use passwords" and "what happens when a seller token hits the Admin API"):
@@ -719,7 +719,7 @@ A third v3 branch, `/api/v3/seller/…`, anchored by `Spree::Api::V3::Seller::Ba
- **Auth & context:** `POST /seller/auth/login|refresh|logout`, password reset — `Spree.seller_authentication_strategies`, `seller_api` JWT audience, audience-stamped refresh token + own cookie. `X-Spree-Seller-Id` selects the seller; membership = `role_users` on `resource: seller`; a header naming a seller the caller does not belong to is 403; `Spree::Current.store` is set from `current_seller.store`. `GET /seller/me` — user + seller memberships + `permission_keys` for the selected seller. Invitation acceptance stays on the existing `/admin/invitation_acceptances` (it is store-agnostic and already handles `resource: seller`).
- **Own resources:** `GET/PATCH /seller/profile` (name, about, branding uploads, billing/returns addresses, `payouts_schedule_interval`, ToS acceptance, holiday mode), `GET /seller/onboarding_tasks` + `POST /seller/onboarding/submit_for_review`, `GET /seller/team` + team invitations (`RoleGrantGuard`-bounded to seller-audience roles), `GET /seller/balance`, `GET /seller/transfers`, `GET /seller/payouts` (read-only ledger).
- **Catalog:** products (+ nested variants, prices, media, stock items) — every lookup through `current_seller.products`; create force-stamps `seller_id`; approval state per the store's seller-product preference. No channel publication, and no categories/collections/tags at all — filing a listing is the operator's, done at review (2026-08-26). A seller does assign a **product type** and a **delivery profile** (2026-09-01): the type is what hands them option types and the profile template, the profile is what makes their goods quotable, and read-only `GET /seller/product_types` and `GET /seller/delivery_profiles` back the two pickers.
-- **Orders:** the seller's child orders (`current_seller.orders`), fulfillments with `Fulfillments::Fulfill`/`Cancel`/`UpdateTracking`, returns/claims on those orders. **No** refunds, order edits, approvals, payments — the seller sees its `payment_split`, never the group's `Payment`.
+- **Orders:** the seller's child orders (`current_seller.orders`), fulfillments with `Fulfillments::Fulfill`/`Cancel`/`UpdateTracking`, returns/exchanges/claims on those orders — **including refunding their own return** (amended 2026-09-03; the legacy module allowed it, and the amount is bounded three times over: by `Return#refundable_total`, by `Refund#order_is_covered_by_payment`, and by `Refunds::Create#refundable_share`, which caps a grouped payment at this child's captured share). **No** order edits, approvals, payments or delivery confirmation — the seller sees its `payment_split`, never the group's `Payment`, and marking goods received is the buyer's word, not the sender's. Full surface: `6.0-seller-order-management.md`.
- **Delivery:** profiles are read-only vocabulary (shipped 2026-09-01); the seller's own delivery methods (`seller_id` = self) with read-only zones under a profile, and shared marketplace methods listed read-only with `editable: false` — Decision 13, shipped 2026-09-01.
- **Exports/imports:** the seller's own runs on the `Spree::Export`/`Import` pipeline, scoped by `seller_id`.
- **Serializers:** `Spree::Api::V3::Seller::*Serializer < V3::*Serializer` (the store serializer) plus an explicit list of operational fields — never a subclass of the admin serializer, so nothing leaks by inheritance. Own typelizer output and a generated `docs/api-reference/seller.yaml` from `spree/api/spec/integration/spree/api/v3/seller/`.
diff --git a/docs/plans/6.0-seller-order-management.md b/docs/plans/6.0-seller-order-management.md
new file mode 100644
index 0000000000..ddc9dbda7d
--- /dev/null
+++ b/docs/plans/6.0-seller-order-management.md
@@ -0,0 +1,202 @@
+# Seller Order Management
+
+**Status:** Draft — designed, nothing built
+**Target:** Spree 6.0
+**Depends on:** `6.0-multi-vendor-marketplace.md` (Seller identity, the `/api/v3/seller` branch, order splitting, the fund ledger — all shipped), `6.0-returns-exchanges-claims.md` (Return/Exchange/Claim + their fifteen workflows — shipped), `6.0-fulfillment-and-delivery.md` (Fulfillment status model, `Fulfillments::Fulfill`/`Cancel`/`Resume` — shipped), `6.0-admin-spa.md` (panel composition, the three-package split)
+**Author:** Damian Legawiec
+**Last updated:** 2026-09-03
+
+## Summary
+
+The seller panel's order screens are a hand-rolled minimum — a flat list of items, one tracking input, and a cancel button — while the operator dashboard grew a full order surface: a fulfillments card with carrier-aware tracking, partial fulfillment and splitting, and cards for returns, exchanges and claims. A seller running their own back office needs the same operations on their own orders, because on a marketplace the seller *is* the merchant of record for their child order: they pack it, post it, take the goods back and make the customer whole.
+
+This plan rebuilds the seller order views to match the dashboard's, and adds the seller-branch endpoints they need. It is deliberately a port of an existing, proven surface rather than a new design: the operator dashboard's components are the reference, and the seller panel reproduces their structure and vocabulary with an operator-only subset removed.
+
+## Key Decisions (do not deviate without discussion)
+
+### 1. A seller may refund their own orders — restoring legacy behavior, and this amends the marketplace plan
+
+`6.0-multi-vendor-marketplace.md` says twice that a seller gets no refunds — "What a seller may not do (publish to channels, edit orders, **refund**, approve itself…) is an endpoint that does not exist" (Decision 10) and "**No** refunds, order edits, approvals, payments" (the Phase 4 scope note). **Both are wrong about the module they are opening up, and this plan supersedes them on that one point.**
+
+The legacy Enterprise multi-vendor module granted vendors the whole money-back surface, scoped to their own orders, in `SpreeMultiVendor::PermissionSets::VendorUser#apply_returns_permissions`:
+
+```ruby
+can :create, Spree::Refund
+can :manage, Spree::Refund, payment: { order: { vendor_id: @vendor_ids } }
+can :create, Spree::Reimbursement
+can :manage, Spree::Reimbursement, order: { vendor_id: @vendor_ids }
+can :manage, Spree::ReturnAuthorization, order: { vendor_id: @vendor_ids }
+can :manage, Spree::CustomerReturn, stock_location: { vendor_id: @vendor_ids }
+can :manage, Spree::ReturnItem, inventory_unit: { order: { vendor_id: @vendor_ids } }
+can :read, Spree::RefundReason
+can :read, Spree::ReimbursementType
+```
+
+`Reimbursement` was 5.x's money-back mechanism and `Refund` is the gateway refund itself. The module shipped no return screens of its own — vendors reached the stock admin order tabs, narrowed by that permission set. So refunding is **shipped Enterprise behavior a marketplace operator already relies on**, not new latitude, and opening the marketplace core without it would be a regression for every migrating customer.
+
+The commercial logic agrees. A seller is merchant of record for their child order (the marketplace plan's own transfer-basis decision: consumer tax and shipping revenue are theirs). The party who owes the customer their money back is the party who took it. Routing every seller refund through the operator makes the operator a ticket queue for other people's customer service, which is exactly the cost a marketplace exists to avoid.
+
+**What bounds it is arithmetic, not permission.** Three bounds hold, and all three are already in the code:
+
+- `Returns::Refund` refuses an amount above `return_record.refundable_total` (`refund_total - refunded_total`), and a return belongs to exactly one seller's order — so a seller can only ask for what their own order's returned units are worth.
+- `Spree::Refund#order_is_covered_by_payment` validates *which* child a refund names — on a grouped payment the `order_id` is required and must be named by one of the payment's splits.
+- `Spree::Refunds::Create#refundable_share` caps the amount at that child's captured share, counting refunds from the rows rather than the split's subscriber-written figure (so two refunds landing together cannot each see an unrefunded share) and re-checking under the payment's row lock. It is the only path that creates a `Spree::Refund` anywhere in the codebase, so nothing bypasses it.
+
+Legacy needed none of this because each sub-order carried its own real `Payment` row, so `credit_allowed` was already per-vendor. In 6.0 payments hang off the `OrderGroup` and the split is what attributes money to a child — `refundable_share` is where that lands.
+
+**Prerequisite (Decision 1a, revised 2026-09-03).** The bound was never the problem; *reaching the payment at all* was. `Returns::Refund`, `Claims::Resolve` and `Exchanges::Fulfill` all drained `order.payments.completed`, which is empty on a grouped child — so all three failed with `:no_refundable_payments` on exactly the orders a seller refunds, and no spec covered the grouped case in any of them. They now share `Spree::RefundsOrderPayments`, which refunds through the order's `payment_splits` when grouped (skipping a share mid-capture, as `Orders::Cancel` does) and through `order.payments` when not. This is a correctness fix for **operators** too — refunds, claims and exchanges were broken on every marketplace order — so it lands as its own commit ahead of any seller work.
+
+The reversal path needs nothing new either: a refund on a fulfilled order already writes a negative `SellerTransfer` (`kind: 'refund_reversal'`, bounded by `reversible_amount`) through the shipped subscriber, so a seller refunding themselves correctly reduces their own payout.
+
+**Still not the seller's:** the group's `Payment` (capture, void, adding a payment), order edits, approvals, and refunds on an order that is not theirs. Those remain endpoints that do not exist.
+
+### 2. The seller panel reproduces the dashboard's structure, minus operator-only cards
+
+The order page becomes the same two-column `ResourceLayout` the dashboard uses, with the same card vocabulary in the same order. What a seller sees is a subset, decided per card by whether the seller owns the question:
+
+| Card | Seller | Why |
+|---|---|---|
+| Fulfillments (tracking, partial fulfill, split, cancel/resume) | yes | the seller packs and posts |
+| Returns / Exchanges / Claims | yes | the seller takes the goods back and makes it right |
+| Order summary (totals) | yes | already serialized, never rendered today |
+| Items, both addresses, customer note | yes | merchant of record |
+| Customer (name only) | yes, without email | see Decision 3 |
+| Payments, tax lines, discounts, fees | no | the marketplace's money surface |
+| Purchase order, internal note, tags, marketplace card, digital links, custom fields, metadata | no | operator bookkeeping |
+
+The panel keeps composing from `@spree/dashboard-ui` and `@spree/dashboard-core` and does **not** import from `@spree/dashboard` — the operator app is not a library, and its components are wired to `adminClient`. Where a component is genuinely identical modulo its SDK, it is reimplemented against `sellerClient()` rather than parameterised across the two, because the two clients return different types and a shared generic component would have to be generic over both.
+
+### 3. The customer's email stays hidden, and no new endpoint may leak it
+
+`Seller::OrderSerializer` withholds the buyer's email deliberately, with the reasoning recorded in the class: it is the one contact detail that lets a marketplace's customer be taken off it, and packing, posting and invoicing need only the phone on the shipping address. `Spree::Exports::Orders::SELLER_OMITTED_HEADERS` drops it from the CSV for the same reason.
+
+That rule now has to survive three new nested resources. Returns, exchanges and claims all reach `order.customer` transitively, so **the seller serializers for them are declared from `V3::BaseSerializer`, never subclassed from their admin counterparts**, and none of them expands a customer.
+
+### 4. Reasons are read-only on the seller branch
+
+Creating a return or a claim wants a reason, and the vocabulary (`Spree::ReturnReason`, `Spree::ClaimReason`) is the marketplace's to define — a `Spree::NamedType` the operator curates. Sellers get `GET /seller/return_reasons` and `GET /seller/claim_reasons`, index only, active rows, exactly as they already get `product_types` and `delivery_profiles`. No CRUD: a seller inventing private reasons would fragment the operator's reporting dimension.
+
+### 5. Controllers are written scope-first, never subclassed from admin
+
+The marketplace plan's Decision 10 is binding here: "Do **not** subclass admin controllers into the seller namespace — inherited `current_store.*` lookups are precisely the leak; share workflows and permitted-param lists, never controllers." Every new controller roots at `current_seller_orders` and reaches its records through the order, so a foreign id is a 404 by construction rather than a 403 by rule.
+
+The workflows are shared unchanged — `Spree.return_*_workflow`, `Spree.claim_*_workflow`, `Spree.exchange_*_workflow`, `Spree.fulfillment_*_workflow` — so hooks, emails, tax credits and ledger reversals fire identically whoever triggers them.
+
+### 6. No new permission keys
+
+`Spree::Return`, `Spree::Exchange` and `Spree::Claim` are already subjects of the `orders` catalog resource, and `orders` is already `audiences: %i[seller]`. So `read_orders`/`write_orders` gate all of this, and the seeded default seller role (which holds `write_orders`) needs no change. `Spree::Refund` is a subject of the separate `refunds` resource, which is **not** seller-grantable — but a seller refunds *through* `Returns::Refund` on their own return, not through the refunds endpoint, so no key changes there either. Adding `refunds` to the seller audience would open `/admin`-shaped refund creation and is explicitly not part of this.
+
+### 7. Seller users are already the right principal
+
+`Return#created_by`, `Exchange#created_by` and `Claim#created_by` are typed `Spree.admin_user_class`, and a seller's team member **is** an `AdminUser` (marketplace plan, Decision 10 — one class, several hats). So attribution works with no model change; a return a seller files records that seller's user.
+
+## Design Details
+
+### API surface added to `/api/v3/seller`
+
+Nested under the seller's own order, mirroring the admin routes minus the money-surface ones:
+
+```ruby
+resources :orders, only: [:index, :show] do
+ member { patch :cancel }
+
+ resources :fulfillments, only: [:index, :show], controller: 'orders/fulfillments' do
+ member do
+ patch :fulfill
+ patch :update # tracking number + carrier
+ patch :cancel
+ patch :resume
+ patch :split
+ patch :mark_delivered
+ end
+ end
+
+ resources :returns, only: [:index, :show, :create], controller: 'orders/returns' do
+ member { patch :approve; patch :receive; patch :refund; patch :cancel }
+ end
+
+ resources :exchanges, only: [:index, :show, :create], controller: 'orders/exchanges' do
+ member { patch :approve; patch :receive; patch :fulfill; patch :cancel }
+ end
+
+ resources :claims, only: [:index, :show, :create], controller: 'orders/claims' do
+ member { patch :approve; patch :resolve; patch :deny; patch :cancel }
+ end
+end
+
+resources :return_reasons, only: [:index]
+resources :claim_reasons, only: [:index]
+resources :tracking_carriers, only: [:index]
+```
+
+Deliberately absent from the fulfillments member list: `purchase_label`. Carrier accounts live on the store-scoped `Spree::Integration` and a seller method is internal-rate/manual-fulfillment only (marketplace plan, Decision 13), so a seller buys no labels in 6.0.
+
+`update` on a fulfillment is narrowed to tracking: the admin endpoint also moves a parcel between stock locations and re-picks a delivery rate, and a seller's origin move is a different question that is not in this cut. Permitted params are `tracking` and `tracking_carrier` only.
+
+### Serializers
+
+New, all declared from `V3::BaseSerializer` and none expanding a customer: `Seller::ReturnSerializer`, `Seller::ReturnLineItemSerializer`, `Seller::ExchangeSerializer`, `Seller::ExchangeLineItemSerializer`, `Seller::ClaimSerializer`, `Seller::ClaimLineItemSerializer`, `Seller::ReasonSerializer` (one, serving both vocabularies — a reason is `id`/`name`/`active`).
+
+`Seller::FulfillmentSerializer` gains nothing: it already carries `tracking`, `tracking_carrier`, `tracking_url`, `tracking_status`, `fulfilled_at`, `delivery_method_name` and `stock_location_name`, all of which the current UI ignores.
+
+`Seller::OrderSerializer` gains the money fields the summary card needs that it does not already have (`shipping_total`, `promo_total`, `additional_tax_total`, `included_tax_total` and their `display_` twins), plus `canceled_at`. It does **not** gain `email`, `customer`, `payments`, `fees` or `discounts`.
+
+### Panel structure
+
+```
+pages/order.tsx → composition only, like the dashboard's route
+components/orders/order-header.tsx → PageHeader + cancel in destructiveItems
+components/orders/fulfillments-card.tsx
+components/orders/fulfillment-fulfill-form.tsx
+components/orders/fulfillment-tracking-dialog.tsx
+components/orders/fulfillment-split-dialog.tsx
+components/orders/fulfillment-item-list.tsx
+components/orders/order-items-card.tsx
+components/orders/order-summary-card.tsx
+components/orders/order-customer-card.tsx → name + addresses, no email
+components/orders/returns-card.tsx
+components/orders/post-sale-cards.tsx → exchanges + claims
+components/orders/post-sale-create-dialogs.tsx → create return/exchange/claim, resolve claim
+hooks/use-order.ts, use-fulfillments.ts, use-returns.ts, use-post-sale.ts, use-reasons.ts
+```
+
+The seller panel has no `hooks/` directory today — every page inlines `useQuery`. This introduces one, matching the dashboard's convention, because eleven mutations across four resources inlined into cards is how the current page became unmaintainable.
+
+### Orders list
+
+Largely already right (it has the export button, quick filters and the status vocabularies). Two additions: a `status` quick filter so canceled orders can be found, and row selection is deliberately still **not** added — the dashboard's orders table has no bulk actions either.
+
+## Migration Path
+
+0. **Grouped-order refunds (Decision 1a), not additive.** `Spree::RefundsOrderPayments` + `PaymentSplit#refundable_amount`, adopted by `Returns::Refund`, `Claims::Resolve` and `Exchanges::Fulfill`, with a spec covering the grouped case for all three. Ships first and separately — it corrects operator refunds as well, and the seller endpoint cannot work without it.
+1. **Backend, additive only.** Routes, six controllers (`orders/returns`, `orders/exchanges`, `orders/claims`, `return_reasons`, `claim_reasons`, `tracking_carriers`), seven serializers, the fulfillments controller's four new member actions. Specs per controller: a happy path, a cross-seller 404, and the money bound on refund.
+2. **SDK.** `seller-sdk` gains `orders.returns`, `orders.exchanges`, `orders.claims`, `returnReasons`, `claimReasons`, `trackingCarriers`, and the new fulfillment verbs. Regenerate types (`typelizer:generate`).
+3. **Panel.** Port the components in the order listed above; the fulfillments card first, since it is what a seller touches daily.
+4. **OpenAPI + i18n.** Integration specs for the new endpoints, `swaggerize`, and every new key into all six locale files.
+
+No data migration: everything here is additive, and no existing column, route or serializer field changes meaning.
+
+## Constraints on Current Work
+
+- **Never subclass an admin controller into the seller namespace.** Root at `current_seller_orders` and reach nested records through the order.
+- **A seller serializer is never a subclass of an admin or store one.** Declare from `V3::BaseSerializer`; a subclass inherits fields (email, payments, cost price) that the seller branch must not carry.
+- **No new seller endpoint may expose the buyer's email**, directly or through an expansion. If a new surface needs to contact the customer, it uses the phone on the shipping address.
+- **Money moves only through the shared workflows**, never a hand-rolled refund. `Refunds::Create` owns the per-child ceiling, the row lock and the gateway credit; a call site that writes a `Spree::Refund` another way is a cross-seller money bug.
+- **`payment.credit_allowed` is group-wide on a grouped payment** — it sums refunds across every child order, so it is never a per-seller ceiling. The child's share is `PaymentSplit#refundable_amount`.
+- **Never read `order.payments` on a path that may see a grouped order** — it is empty there. Use `order.payment_splits` (or `Order#settlement_payments` where a payment list is genuinely wanted); a new post-sale money path uses `Spree::RefundsOrderPayments`.
+- **Do not add `refunds`, `payments` or `commissions` to the seller audience** in the permission catalog. A seller refunds through their own return, and that is the only path.
+- **No label purchase on the seller branch** while carrier credentials are store-scoped.
+- The marketplace plan's "no refunds" lines are superseded by Decision 1 here; update them rather than re-deriving the old conclusion.
+
+## Open Questions
+
+1. **Should a seller see the customer's name at all?** This plan says yes (it is on the addresses regardless, and a packing slip carries it), but a stricter marketplace might want initials only. Deferred: it is a serializer field, changeable without restructuring.
+2. **Exchange fulfillment origin.** `Exchanges::Fulfill` builds replacement fulfillments; which of the seller's stock locations they draw from is currently the order's default. Worth revisiting when seller pickup lands.
+3. **Cross-order returns list for sellers.** The operator has read-only `/returns`, `/exchanges`, `/claims` pages. A seller arguably wants the same "what is open right now" view; left out of this cut because the per-order cards answer the daily question first.
+
+## References
+
+- `docs/plans/6.0-multi-vendor-marketplace.md` — Decision 10 (the seller branch), Decision 13 (seller delivery), Phase 3/3a (split + ledger). **Amended by Decision 1 above.**
+- `docs/plans/6.0-returns-exchanges-claims.md` — the three models and their fifteen workflows.
+- `docs/plans/6.0-fulfillment-and-delivery.md` — fulfillment status model, partial fulfillment, tracking axis.
+- Legacy Enterprise module, `SpreeMultiVendor::PermissionSets::VendorUser` — the source of truth for what a vendor could already do.
diff --git a/spree/core/app/models/concerns/spree/refunds_order_payments.rb b/spree/core/app/models/concerns/spree/refunds_order_payments.rb
new file mode 100644
index 0000000000..72553e64b2
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/refunds_order_payments.rb
@@ -0,0 +1,94 @@
+# frozen_string_literal: true
+
+module Spree
+ # Gives a post-sale workflow one way to put money back on an order.
+ #
+ # Returns, claims and exchanges all owe the customer money for the same
+ # reason — goods that are going back, or were never right — and all three
+ # drained `order.payments` to pay it. That reads nothing on a marketplace
+ # order: a split checkout takes one charge against the {Spree::OrderGroup},
+ # so a child order holds no payments of its own and every one of the three
+ # failed with "no refundable payments" on the orders a seller is most likely
+ # to be refunding.
+ #
+ # What a child order holds instead is a {Spree::PaymentSplit} per group
+ # payment — its own authorised, captured and refunded share. Refunding
+ # through the share is what keeps one seller's refund from spending a
+ # sibling's captured money, and it is the same shape
+ # {Spree::Orders::Cancel} already settles a canceled child order with.
+ module RefundsOrderPayments
+ extend ActiveSupport::Concern
+
+ private
+
+ # Puts `amount` back on `order`, newest payment first, until it is covered.
+ #
+ # A split-tender order needs more than one refund, so this drains rather
+ # than picking one payment. Every row goes through
+ # {Spree::Refunds::Create}, which owns the row-locked balance check, the
+ # gateway credit, the declined-row compensation, the refund hooks and the
+ # `payment.refunded` event — so nothing here talks to a gateway itself.
+ #
+ # @param order [Spree::Order] the order being put right
+ # @param amount [BigDecimal] how much to give back
+ # @param originator [Spree::Return, Spree::Claim, Spree::Exchange]
+ # @param refunder [Object, nil] whoever is issuing it
+ # @return [Array<Spree::Refund>] the refunds written, newest payment first
+ def refund_order_payments(order:, amount:, originator:, refunder: nil)
+ remaining = amount.to_d
+ refunds = []
+
+ refundable_shares(order).each do |payment, refundable|
+ break unless remaining.positive?
+
+ creditable = [refundable.to_d, remaining].min
+ next unless creditable.positive?
+
+ result = Spree.refund_create_workflow.call(
+ payment: payment,
+ amount: creditable,
+ order: order,
+ reason: Spree::RefundReason.return_processing_reason(originator.store),
+ refunder: refunder,
+ originator: originator
+ )
+ yield(result) if result.failure?
+
+ refunds << result.value
+ remaining -= creditable
+ end
+
+ refunds
+ end
+
+ # What each of the order's completed payments can still give back to *this*
+ # order.
+ #
+ # On an ordinary order that is the payment's own balance. On a child of a
+ # split checkout it is that child's share: `credit_allowed` sums the
+ # refunds of every child against the whole charge, so measuring one
+ # seller's refund by it would let them draw on headroom their sibling's
+ # sale is holding.
+ #
+ # A share mid-capture is skipped rather than guessed at — a parcel reserves
+ # what it is about to draw before asking the gateway, so a share can read
+ # captured while the charge is still in flight, and refunding through it
+ # would hand back money nobody has taken yet. {Spree::Orders::Cancel}
+ # leaves the same case for the operator.
+ #
+ # @param order [Spree::Order]
+ # @return [Array<Array(Spree::Payment, BigDecimal)>]
+ def refundable_shares(order)
+ unless order.grouped?
+ return order.payments.completed.map { |payment| [payment, payment.credit_allowed.to_d] }
+ end
+
+ order.payment_splits.includes(:payment).filter_map do |split|
+ next if split.capture_in_flight?
+ next unless split.payment&.completed?
+
+ [split.payment, split.refundable_amount]
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/payment_split.rb b/spree/core/app/models/spree/payment_split.rb
index 8f5875bf1d..f338cdaf91 100644
--- a/spree/core/app/models/spree/payment_split.rb
+++ b/spree/core/app/models/spree/payment_split.rb
@@ -48,6 +48,20 @@ module Spree
captured_amount - refunded_amount
end
+ # The most this child order can still be given back from this payment.
+ #
+ # Counted from the refund rows rather than from {#refunded_amount}, which a
+ # subscriber writes after the fact: two refunds landing together would each
+ # read a share that still looked unrefunded. {Spree::Refunds::Create}
+ # re-checks the same figure under the payment's lock before any money
+ # moves — this is what a caller uses to decide how much to ask for.
+ #
+ # @return [BigDecimal]
+ def refundable_amount
+ already_refunded = Spree::Refund.where(payment_id: payment_id, order_id: order_id).sum(:amount)
+ captured_amount - already_refunded
+ end
+
# What is left of this share for a parcel to draw on.
#
# Counts money already taken and money another parcel has reserved but not
diff --git a/spree/core/app/workflows/spree/claims/resolve.rb b/spree/core/app/workflows/spree/claims/resolve.rb
index f3c07dd240..15ed1a6ba0 100644
--- a/spree/core/app/workflows/spree/claims/resolve.rb
+++ b/spree/core/app/workflows/spree/claims/resolve.rb
@@ -6,6 +6,8 @@ module Spree
# so the caller's intent is explicit at the call site and an admin can
# decide at resolution time rather than at claim creation.
class Resolve < Spree::Workflow
+ include Spree::RefundsOrderPayments
+
hooks :validate, :before_settle, :after_resolve
attr_reader :refunds, :fulfillments
@@ -142,28 +144,12 @@ module Spree
end
def refund_at_gateway
- remaining = @amount_to_refund
- claim.order.payments.completed.each do |payment|
- break unless remaining.positive?
-
- creditable = [payment.credit_allowed.to_d, remaining].min
- next unless creditable.positive?
-
- # One refund path for the whole system: Refunds::Create owns the
- # row-lock balance check, the gateway credit, the declined-row
- # compensation, the refund hooks and the payment.refunded event.
- result = Spree.refund_create_workflow.call(
- payment: payment,
- amount: creditable,
- reason: Spree::RefundReason.return_processing_reason(claim.store),
- refunder: resolver,
- originator: claim
- )
- failure(claim, result.error.value) if result.failure?
-
- @refunds << result.value
- remaining -= creditable
- end
+ @refunds = refund_order_payments(
+ order: claim.order,
+ amount: @amount_to_refund,
+ originator: claim,
+ refunder: resolver
+ ) { |result| failure(claim, result.error.value) }
failure(claim, :no_refundable_payments) if @refunds.empty?
end
diff --git a/spree/core/app/workflows/spree/exchanges/fulfill.rb b/spree/core/app/workflows/spree/exchanges/fulfill.rb
index ff591e1bf4..a639f793d6 100644
--- a/spree/core/app/workflows/spree/exchanges/fulfill.rb
+++ b/spree/core/app/workflows/spree/exchanges/fulfill.rb
@@ -8,6 +8,8 @@ module Spree
# for the merchant to collect — charging a stored card without a fresh
# authorization is not something core should do silently.
class Fulfill < Spree::Workflow
+ include Spree::RefundsOrderPayments
+
hooks :validate, :before_settle, :after_fulfill
# Fulfillments created for the replacement items.
@@ -124,28 +126,12 @@ module Spree
end
def refund_at_gateway
- remaining = credit_amount
- exchange.order.payments.completed.each do |payment|
- break unless remaining.positive?
-
- creditable = [payment.credit_allowed.to_d, remaining].min
- next unless creditable.positive?
-
- # One refund path for the whole system: Refunds::Create owns the
- # row-lock balance check, the gateway credit, the declined-row
- # compensation, the refund hooks and the payment.refunded event.
- result = Spree.refund_create_workflow.call(
- payment: payment,
- amount: creditable,
- reason: Spree::RefundReason.return_processing_reason(exchange.store),
- refunder: refunder,
- originator: exchange
- )
- failure(exchange, result.error.value) if result.failure?
-
- @refunds << result.value
- remaining -= creditable
- end
+ @refunds = refund_order_payments(
+ order: exchange.order,
+ amount: credit_amount,
+ originator: exchange,
+ refunder: refunder
+ ) { |result| failure(exchange, result.error.value) }
end
def mark_fulfilled
diff --git a/spree/core/app/workflows/spree/returns/refund.rb b/spree/core/app/workflows/spree/returns/refund.rb
index 0fe333bfdc..98e186f1ed 100644
--- a/spree/core/app/workflows/spree/returns/refund.rb
+++ b/spree/core/app/workflows/spree/returns/refund.rb
@@ -8,6 +8,8 @@ module Spree
# a pure database write outside the transaction would open a window where
# a crash leaves a refunded return with no credit issued.
class Refund < Spree::Workflow
+ include Spree::RefundsOrderPayments
+
hooks :validate, :before_refund, :after_refund
# Refunds created by this run — hook handlers read them.
@@ -112,32 +114,14 @@ module Spree
end
# Each refund row commits, then Refund#perform! credits it at the
- # gateway — explicitly, never from a callback. Payments are drained
- # newest-first until the amount is covered — a split-tender order needs
- # more than one refund.
+ # gateway — explicitly, never from a callback.
def refund_at_gateway
- remaining = @amount_to_refund
- return_record.order.payments.completed.each do |payment|
- break unless remaining.positive?
-
- creditable = [payment.credit_allowed.to_d, remaining].min
- next unless creditable.positive?
-
- # One refund path for the whole system: Refunds::Create owns the
- # row-lock balance check, the gateway credit, the declined-row
- # compensation, the refund hooks and the payment.refunded event.
- result = Spree.refund_create_workflow.call(
- payment: payment,
- amount: creditable,
- reason: Spree::RefundReason.return_processing_reason(return_record.store),
- refunder: refunder,
- originator: return_record
- )
- failure(return_record, result.error.value) if result.failure?
-
- @refunds << result.value
- remaining -= creditable
- end
+ @refunds = refund_order_payments(
+ order: return_record.order,
+ amount: @amount_to_refund,
+ originator: return_record,
+ refunder: refunder
+ ) { |result| failure(return_record, result.error.value) }
failure(return_record, :no_refundable_payments) if @refunds.empty?
end
diff --git a/spree/core/spec/workflows/spree/grouped_order_refunds_spec.rb b/spree/core/spec/workflows/spree/grouped_order_refunds_spec.rb
new file mode 100644
index 0000000000..902bdce520
--- /dev/null
+++ b/spree/core/spec/workflows/spree/grouped_order_refunds_spec.rb
@@ -0,0 +1,156 @@
+require 'spec_helper'
+
+# A marketplace basket is taken with one charge against the order group, so a
+# child order holds no payments of its own — only its share of the group's.
+# Every post-sale workflow that gives money back has to refund through that
+# share: reading `order.payments` finds nothing, and measuring against the
+# whole payment lets one seller's refund spend a sibling's captured money.
+RSpec.describe 'refunding a child order of a split checkout' do
+ let(:store) { @default_store }
+ let(:group) { create(:order_group, store: store) }
+
+ # Two sellers' orders under one group, each paid for by its own share of a
+ # single completed payment. Created before the payment, whose amount the
+ # group's own total bounds.
+ let!(:order) { grouped_order(number_suffix: 1) }
+ let!(:sibling) { grouped_order(number_suffix: 2) }
+
+ let!(:payment) do
+ create(:payment, order: nil, cart: nil, order_group: group, amount: 200, status: 'completed')
+ end
+
+ let!(:split) do
+ create(:payment_split, payment: payment, order: order,
+ authorized_amount: 100, captured_amount: 100)
+ end
+ let!(:sibling_split) do
+ create(:payment_split, payment: payment, order: sibling,
+ authorized_amount: 100, captured_amount: 100)
+ end
+
+ def grouped_order(number_suffix:)
+ create(:shipped_order, store: store, line_items_count: 1).tap do |placed|
+ placed.update_columns(order_group_id: group.id, number: "#{group.number}-#{number_suffix}")
+ placed.reload
+ group.orders.reload
+ end
+ end
+
+ # The gateway is not the subject here — that a refund row is written against
+ # the right share is.
+ before do
+ allow_any_instance_of(Spree::Refund).to receive(:perform!).and_return(true)
+ allow_any_instance_of(Spree::Order).to receive(:tax_provider).
+ and_return(instance_double(Spree::TaxProvider::Internal, refund: nil, void: nil, estimate: nil))
+ end
+
+ describe Spree::Returns::Refund do
+ let(:return_record) do
+ Spree::Returns::Create.call(
+ order: order,
+ items: [{ fulfillment_item: order.fulfillment_items.first, quantity: 1 }]
+ ).value
+ end
+
+ before do
+ Spree::Returns::Approve.call(return_record: return_record)
+ Spree::Returns::Receive.call(return_record: return_record)
+ end
+
+ # The regression: `order.payments` is empty on a grouped child, so this
+ # used to fail with :no_refundable_payments and a seller could not refund
+ # a marketplace order at all.
+ it 'refunds through the order group payment' do
+ result = described_class.call(return_record: return_record, amount: 10)
+
+ expect(result).to be_success
+ refund = Spree::Refund.find_by(originator: return_record)
+ expect(refund).to be_present
+ expect(refund.payment).to eq(payment)
+ end
+
+ it 'attributes the refund to the child order being put right' do
+ described_class.call(return_record: return_record, amount: 10)
+
+ expect(Spree::Refund.find_by(originator: return_record).order).to eq(order)
+ end
+
+ it 'leaves the sibling share untouched' do
+ expect {
+ described_class.call(return_record: return_record, amount: 10)
+ }.not_to change { Spree::Refund.where(order_id: sibling.id).count }.from(0)
+ end
+
+ # The share is the ceiling, not the payment: this order was captured 100 of
+ # the payment's 200, so asking for more than 100 must not reach into the
+ # sibling's half even though the payment itself could cover it.
+ it 'refuses more than this order captured, however much the payment holds' do
+ split.update!(captured_amount: 5)
+
+ result = described_class.call(return_record: return_record, amount: 50)
+
+ expect(result).to be_failure
+ expect(Spree::Refund.where(order_id: order.id)).to be_empty
+ end
+
+ # A parcel reserves what it is about to draw before asking the gateway, so
+ # a share can read captured while the charge is still in flight. Refunding
+ # through it would hand back money nobody has taken.
+ it 'skips a share whose capture is still in flight' do
+ split.update!(claimed_amount: 100)
+
+ result = described_class.call(return_record: return_record, amount: 10)
+
+ expect(result).to be_failure
+ expect(result.error.value).to eq(:no_refundable_payments)
+ end
+ end
+
+ describe Spree::Claims::Resolve do
+ let(:claim) do
+ Spree::Claims::Create.call(
+ order: order,
+ items: [{ line_item: order.line_items.first, quantity: 1 }]
+ ).value
+ end
+
+ before { Spree::Claims::Approve.call(claim: claim) }
+
+ it 'refunds through the order group payment' do
+ result = described_class.call(claim: claim, resolution: 'refund',
+ refund_method: 'original_payment', amount: 10)
+
+ expect(result).to be_success
+ expect(Spree::Refund.find_by(originator: claim)&.payment).to eq(payment)
+ end
+ end
+
+ describe Spree::Exchanges::Fulfill do
+ let(:variant) { create(:variant) }
+ let(:exchange) do
+ Spree::Exchanges::Create.call(
+ order: order,
+ items: [{
+ fulfillment_item: order.fulfillment_items.first,
+ quantity: 1,
+ new_variant: variant
+ }]
+ ).value
+ end
+
+ before do
+ Spree::Exchanges::Approve.call(exchange: exchange)
+ Spree::Exchanges::Receive.call(exchange: exchange)
+ end
+
+ # Only owes money when the replacement is cheaper than what came back.
+ it 'refunds a price difference through the order group payment' do
+ allow_any_instance_of(Spree::Exchange).to receive(:price_difference).and_return(-10)
+
+ result = described_class.call(exchange: exchange, refund_method: 'original_payment')
+
+ expect(result).to be_success
+ expect(Spree::Refund.where(originator: exchange).map(&:payment).uniq).to eq([payment])
+ end
+ end
+end