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
Fix: an admin-raised order charged a seller commission and credited them nothing (#14677)
Łukasz Adamczykb6fa9c60ecd3
diff --git a/docs/developer/core-concepts/sellers.mdx b/docs/developer/core-concepts/sellers.mdxindex 4b6d95d0a0..cd50a046ae 100644--- a/docs/developer/core-concepts/sellers.mdx+++ b/docs/developer/core-concepts/sellers.mdx@@ -255,8 +255,29 @@ Two details worth knowing:<Warning>A storefront must handle the possibility of an order group. Completing a cart may yield one order or several, and a customer's order history should show the group as one purchase rather than confronting them with three orders they don't remember placing separately.++A back office must handle it too: an order raised from the admin divides the same way, so completing one may answer with a group instead of an order.</Warning>+<CodeGroup>++```typescript Admin SDK+import { isOrderGroup } from '@spree/admin-sdk'++const result = await client.orders.complete('or_UkLWZg9DAJ')++// One order per seller when the order held several sellers' goods.+const orders = isOrderGroup(result) ? result.orders : [result]+```++```bash cURL+curl -X PATCH https://your-store.com/api/v3/admin/orders/or_UkLWZg9DAJ/complete \+ -H "X-Spree-API-Key: sk_xxx" \+ -H "Content-Type: application/json"+```++</CodeGroup>+## CommissionCommission is what the marketplace charges for the sale — configured as **rates**, and recorded per sale as immutable **commission lines**.diff --git a/docs/plans/6.0-cart-order-split.md b/docs/plans/6.0-cart-order-split.mdindex ca2e4e5a4b..fd84330c09 100644--- a/docs/plans/6.0-cart-order-split.md+++ b/docs/plans/6.0-cart-order-split.md@@ -2,7 +2,7 @@**Status:** Implemented via the core-rewrite waves (Waves 1+5, 2026-07-29) — `Spree::Cart` owns checkout end to end, the Order state machine and `spree_orders.state` are gone, the `Carts::Complete` three-phase pipeline is live and `Orders::UpdateStatuses` is the sole status writer. Wave 7's data migration (incomplete orders → carts) landed with the rest. **Remaining: Phase 6 cleanup only, scoped to 6.1** (drop the deprecation aliases and the migration task; `null: false` on `spree_orders.market_id`/`channel_id`)**Target:** Spree 6.0-**Depends on:** API v3 conventions. **Gates (they depend on this plan):** `6.0-6.1-split-adjustments.md` (typed-line owner), `6.0-fulfillment-and-delivery.md` (fulfillment/rate owner), `6.0-multi-vendor-marketplace.md` Phase 3 (split fires inside `Carts::Complete`), `6.0-normalize-state-to-status.md` (Order.state removed here). This was the most upstream 6.0 refactor; all four gated plans have since shipped on top of it.+**Depends on:** API v3 conventions. **Gates (they depend on this plan):** `6.0-6.1-split-adjustments.md` (typed-line owner), `6.0-fulfillment-and-delivery.md` (fulfillment/rate owner), `6.0-multi-vendor-marketplace.md` Phase 3 (seller attribution fires inside `Orders::Complete`, the one finalize home — moved there 2026-09-17, V-3643), `6.0-normalize-state-to-status.md` (Order.state removed here). This was the most upstream 6.0 refactor; all four gated plans have since shipped on top of it.**Author:** Damian + Claude**Last updated:** 2026-08-27diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.mdindex abf6e562be..a8b961b1ab 100644--- a/docs/plans/6.0-multi-vendor-marketplace.md+++ b/docs/plans/6.0-multi-vendor-marketplace.md@@ -771,7 +771,7 @@ This is **new OSS code**, not a rename of existing core — there is no in-placeEven before this lands, work touching adjacent areas should:-- **Cart/Order split (`6.0-cart-order-split.md`)**: keep `cart.complete!`/`Spree::Carts::Complete` as the single completion entry point — the seller split hooks in there. Do not reintroduce an order-level `after_transition` extension surface; multi-vendor must not depend on one. When fleshing out the checkout flow on Cart, design delivery selection **per package** (packages come from order routing) — the multi-vendor checkout needs one delivery choice per seller package before completion, and payments must be attachable to an `OrderGroup`, not only to an `Order`.+- **Cart/Order split (`6.0-cart-order-split.md`)**: seller attribution hooks into `Spree::Orders::Complete`, the one finalize home both entry points share — **not** into `Carts::Complete`, which admin and B2B drafts never reach (amended 2026-09-17, V-3643; this line previously named `Carts::Complete` and that is what let an admin-raised order be commissioned while the ledger could never credit anyone). Do not reintroduce an order-level `after_transition` extension surface; multi-vendor must not depend on one. When fleshing out the checkout flow on Cart, design delivery selection **per package** (packages come from order routing) — the multi-vendor checkout needs one delivery choice per seller package before completion, and payments must be attachable to an `OrderGroup`, not only to an `Order`.- **Rich text sanitization (`6.0-rich-text-descriptions.md`)**: sellers are the marketplace's lower-trust writers, and today they are protected by the 5.x-only Enterprise gem's `Spree::SanitizeConcern` (`sanitize :description, :meta_description, if: -> { seller_id.present? }`). That gem does not carry into 6.0 — this plan rewrites its functionality as core models — so **core must own the sanitization before seller-authored content lands here**. Core's `SanitizableRichText` (shipped 5.6.2) sanitizes on write rather than deriving `sanitized_*` on read, which is the stronger form. Three obligations for this plan: (1) apply it to every seller-writable rich text field (`Seller#about`, seller-authored product descriptions); (2) keep seller-facing write paths — the seller dashboard, seller CSV/feed imports, bulk maintenance jobs — on save-backed writers, since the concern is a `before_save` and does not cover `update_columns`/`update_all`/raw SQL (anything that must bypass callbacks calls `Spree::RichTextSanitizer.sanitize` explicitly); (3) do **not** ship a 6.0 allowlist weaker than the Enterprise scrubber sellers have on 5.x — that one prunes `script`/`style` element bodies entirely.- **Split adjustments (`6.0-6.1-split-adjustments.md`)**: `TaxLine` and `Discount` stay strictly line-item- or fulfillment-attached (order-level discounts distribute to line items at application time), so they re-home unambiguously to one child order during the split. `Fee` may additionally be **order-level** (payment surcharge, COD — resolved 2026-07-27); at split, order-level fees prorate across child orders by item totals (largest-remainder), tax lines following the fee. Do **not** add a commission/marketplace `Fee` kind — commission is `Spree::CommissionLine`, off-order (Decision 2); `Fee` stays buyer-facing.- **Inventory operations (`6.0-inventory-operations.md`)**: the procurement model is `Spree::Supplier` — never reuse `Spree::Seller` (reserved for marketplace sellers) for purchase-order sources. See `decisions.md` 2026-07-14.@@ -793,6 +793,7 @@ Even before this lands, work touching adjacent areas should:- **Splitting a parcel between sellers divides everything hanging off it** (RESOLVED 2026-08-20, shipped). A fulfillment holding two sellers' goods becomes two, and the cost the customer was quoted is apportioned between them by the value each half carries (largest-remainder), never copied onto both. The first implementation cloned the fulfillment wholesale and charged delivery twice — the group totalled more than the customer paid, caught by a totals spec rather than by review. The honest reading is that one quote for one parcel no longer describes two; a marketplace wanting each seller quoted separately gets that by giving sellers their own delivery methods, which packs their goods separately from the start and leaves nothing to divide. **Three things divide with it**, each missed on the first pass because a divided parcel is the only case where a row's owner keeps its id while its contents change: the parcel's own tax lines, discounts and fees (re-pointing by `fulfillment_id` finds nothing for the clone, so the source kept tax on a charge it no longer bore and the sibling shipped untaxed), the **selected delivery rate** (a fulfillment restates its cost from its rate whenever amounts refresh, so leaving the rate whole quietly restored the full charge on both halves the next time anything touched them), and the **stock reservations** on the moving line items (scoped by `order_id` at release, so one child would have released everyone's and each sibling none).- **Per-seller commission needed no commission-engine change** (RESOLVED 2026-08-20, verified). Each child order publishes its own `order.placed`, which `OrderCommissionSubscriber` already answers, and `Commissions::CommissionOrder` already partitions by `line_item.seller_id` and skips nil-seller lines — so the seller children are commissioned and the first-party child correctly is not, with no marketplace branch anywhere in the engine. This is the payoff of the Phase 2 decision to key commission on the line item's own seller snapshot rather than on the order.- **A promotion is redeemed by a checkout, not by an order** (RESOLVED 2026-08-21, shipped). `Promotion#credits_count` counted distinct `order_id`s carrying its discount rows, so a split checkout — which leaves a row on every child — spent a `usage_limit` two or three times over on one customer's single redemption, and a promotion capped at 100 uses ran out early for everyone. Counting now collapses on `COALESCE(orders.order_group_id, orders.id)`, so a group's children are one use between them and an ungrouped order is itself; `adjusted_credits_count` and `used_by?` exclude the asking order's **whole group** rather than just the order, via `Order#sibling_order_ids` (`[id]` when ungrouped). Coupon codes and the one-use-per-customer rule were checked and need nothing — a code's `used` flag lives on the code, and `used_by?` answers a boolean. The adjacent lesson: anything counting "how many times has this been used" must ask what a *use* is, because the split turned one of them into several without changing any of those call sites.+- **Seller attribution belongs to the one finalize home, so an admin-raised order divides like a checkout** (RESOLVED 2026-09-17, shipped). The stamp and the split lived in `Carts::Complete` alone, while commission is charged off `order.placed` — published by `Orders::Complete`, which both entry points share. An order raised in the back office therefore came out commissioned against a seller by name with `orders.seller_id` NULL, so `SellerTransfers::Create` could never credit them and their own order list never showed the sale; a mixed basket commissioned two sellers and divided into nothing. This is the same oversight as the single-seller checkout entry below, one level up: that one fixed the case, not the cause. `Orders::Complete` now owns the division outright — partition, then stamp one seller or divide into a group, apportion the payment and place the siblings — running it after payment and before placement. `Carts::Complete` divides nothing: FINALIZE makes one call and reads the group back, losing two steps and its per-child loop. `Carts::SplitBySeller` takes `cart:` as optional, since `build_group` was its only cart-coupled method and the order carries every fact it reads. The admin completion endpoint answers with the group when one was made, as the Store API already did, and the dashboard redirects to the orders list filtered to it rather than leaving the operator on a page that is now one seller's fragment of what they completed. **Refusing multi-seller admin orders was considered and rejected**: a customer asking a merchant to place an order across sellers is ordinary, and refusing would have left them hand-raising one order per seller. The grouped-order money paths the entry below this one records — bounded dispatch capture, per-child refunds, cancellation, the status rollup — are keyed on `order_group_id` and not on how the group was made, so an admin-raised group inherits all of them.- **A single-seller checkout stamps its order with the seller** (RESOLVED 2026-08-21, shipped). The split gate returns early on one partition, which was right about not making a group and wrong about doing nothing: the line items carried `seller_id` (so commission worked) while `orders.seller_id` stayed null — and that column is what `Seller#orders` and the seller branch's `current_seller.orders` read, so a seller's own order list would have been empty for every basket bought only from them. The single-partition path now stamps the order before returning.- **The seller is asked about through a concern, so the container stays neutral** (RESOLVED 2026-08-20, shipped). `OrderGroup#sellers`, `#seller_count` and `#includes_first_party?` live in `Spree::Marketplace::OrderGroup`, included into the model rather than written on it, and `PaymentSplit` carries no seller reader at all (its order answers). Decision 8 says the group is a domain-neutral primitive whose other three planned consumers — split-by-location, split-by-availability, B2B split-by-company-location — have no seller, and "first party" means nothing to any of them. The readers are genuinely useful to a marketplace operator and the admin serializer renders them; keeping them in a concern is what lets both be true. Worth doing on the boundary rather than later, since the moment those fields ship they are client-visible API.- **The split must say "re-sum, don't regenerate" explicitly** (RESOLVED 2026-08-20, shipped). `Carts::RecalculateTotals` takes `resum_only:`, and the split passes it. The freeze was previously inferred from `completed?`, which is `completed_at.present?` — and the children are still **drafts** when they are re-summed, so the guard did not fire: the promotion adjuster deleted the discounts just moved onto each child and re-tested one seller's subset against a threshold the whole basket met, and the tax provider deleted the moved tax lines and re-derived them from today's rates. The service's own docstring claimed it was avoiding exactly this. A lifecycle predicate was the wrong instrument for an intent the caller knows and the record does not; the parameter states it. Pinned by a spec asserting an order-level £6 promotion survives the split intact (£3 per child, group total equal to what was charged) — the failure was silent and money-visible, and only a totals assertion catches it.diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex bcd740dc26..6881cb8693 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -9,6 +9,17 @@ Rejected: correcting only the dialog's pre-fill, which leaves the Admin API, the**Consequences:** No API shape changes and no dashboard change at all — both panels already read `refundable_total`, and it is now right. The values move: after a partial receipt `refund_total`, `display_refund_total` and `refundable_total` all drop to what arrived, on the Admin, Seller and Store serializers alike, so the returns card and the customer's own return page stop quoting a figure nobody will be paid. An over-large amount is now a 422 `refund_exceeds_balance` where it used to succeed, which is a behaviour change for any integration that was passing the announced total deliberately. The seller clawback needed no change: it scales off the refund, so a correct refund makes it correct. The phantom outstanding balance on a refunded order (V-3562) is untouched and still open.**Plans amended:** `6.0-returns-exchanges-claims.md` (Return and ReturnLineItem snippets, the `Returns::Refund` workflow row).+## 2026-09-17: Seller attribution belongs to the one finalize home, so an admin-raised order divides like a checkout++**Context:** An order raised from the admin charged a seller commission and credited that seller nothing. Reproduced from a clean install: a $549.99 order for a seller's product completed `paid`, wrote a commission line of $82.50 against the seller by name, and left `orders.seller_id` NULL — so `SellerTransfers::Create` halted on the blank column and the seller's own order list never showed the sale. A mixed basket commissioned both sellers and divided into nothing. The cause is that the stamp and the split were steps in `Carts::Complete`, while commission is charged off `order.placed`, published by `Orders::Complete` — the home `6.0-cart-order-split.md` designates for everything that happens when an order becomes placed, "serving both checkout and admin/B2B drafts". Two halves of one money path read two different columns, for exactly the orders that skip the cart. The 2026-08-21 entry on single-seller checkouts is the same oversight one level down: it fixed the case, not the cause (V-3643).++**Decision:** Attribution moves into `Spree::Orders::Complete`, which owns it alone. It partitions by seller after payment and before placement, then either stamps one seller onto the order or divides it into a group, apportions the payment and places the siblings the division produced. `Carts::Complete` no longer divides anything: its FINALIZE phase makes one call and reads the group back off the result, losing two steps and its per-child loop. An intermediate shape put the logic in a service both workflows called; it was removed as shallow indirection, and two homes for one decision was the shape that caused this bug. `Carts::SplitBySeller` takes `cart:` as optional — `build_group` was its only cart-coupled method and the order carries every fact it read. The admin completion endpoint answers with the group when one was made, following the Store API, and the dashboard redirects to the orders list filtered to that group.++Rejected: refusing to complete a multi-seller admin order. A customer asking a merchant to place an order spanning sellers is ordinary trade, and refusing would have left merchants hand-raising one order per seller with separate payments and reference numbers. The risk that argued for refusing — the six silent defects in post-placement money paths recorded on 2026-08-21 — does not apply, because those paths key on `order_group_id` and not on how the group was made, so an admin-raised group inherits every one of their fixes.++**Consequences:** `PATCH /api/v3/admin/orders/:id/complete` may now answer with an order group instead of an order; `@spree/admin-sdk` types it `Order | OrderGroup` and exports `isOrderGroup` to narrow it, since the payload carries no type discriminator of its own. An admin order spanning sellers now produces child orders numbered off the group (`R1007-1`), which is a visible change to what an operator gets back. Two adjacent defects were found and deliberately left: `Orders::AddItem` never calls `Orders::BuildFulfillments`, so create-then-add-items leaves an order with no fulfillments that can never be fulfilled (and therefore never credits its seller, which fires on `order.fulfilled`); and `Admin::Orders::PaymentsController` scopes to the order's own payments, so its index is empty for a grouped child and `show`/`capture`/`void` answer 404 — `Admin::Orders::RefundsController` reads `settlement_payments` and shows the shape a fix would take. Both are pre-existing and reach split checkouts too. The sibling fault, a grouped child reporting `payment_total: 0` beside a correct `payment_status: paid`, was fixed separately in #14673.++**Plans amended:** `6.0-multi-vendor-marketplace.md` (Constraints on Current Work, Resolved Decisions), `6.0-cart-order-split.md` (the Gates line).## 2026-09-16: Two catalogs on one company charge the best of them, and every order line says which agreement priced itdiff --git a/packages/admin-sdk/examples/orders/complete.ts b/packages/admin-sdk/examples/orders/complete.tsindex 98fb5925b9..c1621d2c21 100644--- a/packages/admin-sdk/examples/orders/complete.ts+++ b/packages/admin-sdk/examples/orders/complete.ts@@ -1,4 +1,4 @@-import { createAdminClient } from '@spree/admin-sdk'+import { createAdminClient, isOrderGroup } from '@spree/admin-sdk'const client = createAdminClient({baseUrl: 'https://your-store.com',@@ -6,10 +6,13 @@ const client = createAdminClient({})// region:example-const order = await client.orders.complete('or_UkLWZg9DAJ', {+const result = await client.orders.complete('or_UkLWZg9DAJ', {notify_customer: true,})+// An order holding several sellers' goods becomes one order per seller.+const orders = isOrderGroup(result) ? result.orders : [result]+// endregion:example-export { order }+export { orders }diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex c79c44e3d6..5dbb9648e1 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -1422,12 +1422,20 @@ export class AdminClient {delete: (id: string, options?: RequestOptions): Promise<void> =>this.request<void>('DELETE', `/orders/${id}`, options),+ /**+ * An order holding several sellers' goods divides into one order per+ * seller, and the group it produced is what comes back — narrow the result+ * with `isOrderGroup`.+ */complete: (id: string,params?: OrderCompleteParams,options?: RequestOptions,- ): Promise<Order> =>- this.request<Order>('PATCH', `/orders/${id}/complete`, { ...options, body: params }),+ ): Promise<Order | OrderGroup> =>+ this.request<Order | OrderGroup>('PATCH', `/orders/${id}/complete`, {+ ...options,+ body: params,+ }),cancel: (id: string, params?: OrderCancelParams, options?: RequestOptions): Promise<Order> =>this.request<Order>('PATCH', `/orders/${id}/cancel`, { ...options, body: params }),diff --git a/packages/admin-sdk/src/index.ts b/packages/admin-sdk/src/index.tsindex 2169b8dce2..a91391cb85 100644--- a/packages/admin-sdk/src/index.ts+++ b/packages/admin-sdk/src/index.ts@@ -29,6 +29,9 @@ export { AdminClient } from './admin-client'export type { AdminClientConfig, Client } from './client'export { createAdminClient } from './client'+// Narrows what completing an order answered with.+export { isOrderGroup } from './order-group'+// Param types (request bodies)export type * from './params'// Runtime helpers exported from params.ts alongside their related types.diff --git a/packages/admin-sdk/src/order-group.ts b/packages/admin-sdk/src/order-group.tsnew file mode 100644index 0000000000..ea51b7007b--- /dev/null+++ b/packages/admin-sdk/src/order-group.ts@@ -0,0 +1,13 @@+import type Order from './types/generated/Order'+import type OrderGroup from './types/generated/OrderGroup'++/**+ * Whether a completion answered with the group a multi-seller order divided+ * into, rather than with one order.+ *+ * Keyed on `seller_count`, which only the group carries — the payload has no+ * type discriminator of its own.+ */+export function isOrderGroup(result: Order | OrderGroup): result is OrderGroup {+ return 'seller_count' in result+}diff --git a/packages/admin-sdk/tests/orders.test.ts b/packages/admin-sdk/tests/orders.test.tsindex d6101626f9..e23d3e830c 100644--- a/packages/admin-sdk/tests/orders.test.ts+++ b/packages/admin-sdk/tests/orders.test.ts@@ -1,5 +1,6 @@import { HttpResponse, http } from 'msw'import { describe, expect, it } from 'vitest'+import { isOrderGroup } from '../src'import { API_PREFIX, createTestClient, paginated } from './helpers'import { server } from './mocks/server'@@ -276,4 +277,39 @@ describe('orders', () => {expect(hit).toBe(true)})})+ // An order holding several sellers' goods divides on completion, and the+ // group it produced is what comes back.+ describe('complete', () => {+ it('answers with the order when it holds one seller', async () => {+ server.use(+ http.patch(`${API_PREFIX}/orders/order_abc123/complete`, () =>+ HttpResponse.json(sampleOrder),+ ),+ )++ const result = await createTestClient().orders.complete('order_abc123')++ expect(isOrderGroup(result)).toBe(false)+ expect(result.id).toBe('order_abc123')+ })++ it('answers with the group when the order divided', async () => {+ server.use(+ http.patch(`${API_PREFIX}/orders/order_abc123/complete`, () =>+ HttpResponse.json({+ id: 'ogrp_abc123',+ number: 'R123456789',+ seller_count: 2,+ orders: [sampleOrder, { ...sampleOrder, id: 'order_def456' }],+ }),+ ),+ )++ const result = await createTestClient().orders.complete('order_abc123')++ expect(isOrderGroup(result)).toBe(true)+ if (!isOrderGroup(result)) throw new Error('expected a group')+ expect(result.orders.map((child) => child.id)).toEqual(['order_abc123', 'order_def456'])+ })+ })})diff --git a/packages/dashboard/src/components/spree/orders/order-header.tsx b/packages/dashboard/src/components/spree/orders/order-header.tsxindex adb33bbe78..2a95a6c9c9 100644--- a/packages/dashboard/src/components/spree/orders/order-header.tsx+++ b/packages/dashboard/src/components/spree/orders/order-header.tsx@@ -1,4 +1,4 @@-import type { Order } from '@spree/admin-sdk'+import { isOrderGroup, type Order } from '@spree/admin-sdk'import {adminClient,Can,@@ -13,6 +13,7 @@ import {DropdownMenuItem,RelativeTime,StatusBadge,+ toastManager,useConfirm,} from '@spree/dashboard-ui'import {@@ -29,6 +30,7 @@ import { useState } from 'react'import { useTranslation } from 'react-i18next'import { orderQueryKey, useDeleteOrder } from '../../../hooks/use-order'import { spreeJsonLinkResolver } from '../../../lib/json-link-resolver'+import { orderGroupSearch } from '../../../lib/order-group-search'import { OrderCancelDialog } from './order-cancel-dialog'export function OrderHeader({ order }: { order: Order }) {@@ -45,8 +47,35 @@ export function OrderHeader({ order }: { order: Order }) {const completeMutation = useResourceMutation({mutationFn: () => adminClient.orders.complete(orderId),invalidate: [orderQueryKey(orderId)],- successMessage: t('admin.orders.detail.messages.completed'),+ // Announced here instead, because what to say depends on whether the order+ // divided.+ successMessage: false,errorMessage: t('admin.orders.detail.errors.complete_failed'),+ onSuccess: (result) => {+ if (!isOrderGroup(result)) {+ toastManager.add({ type: 'success', title: t('admin.orders.detail.messages.completed') })+ return+ }++ toastManager.add({+ type: 'success',+ // The orders it produced, not seller_count — a basket mixing the+ // operator's own goods with a seller's makes two orders and names one+ // seller.+ title: t('admin.orders.detail.messages.completed_as_group', {+ count: result.orders.length,+ }),+ })+ // The order divided into one per seller, so this page now shows only+ // part of what was completed. Replaced rather than pushed: going back+ // would land on that same partial view.+ navigate({+ to: '/$storeId/orders',+ params: { storeId },+ search: orderGroupSearch(result.id),+ replace: true,+ })+ },})const approveMutation = useResourceMutation({mutationFn: () => adminClient.orders.approve(orderId),diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex a7423ff129..20b38aab84 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -2911,6 +2911,11 @@"canceled": "تم إلغاء الطلب","captured": "القبض على الدفع","completed": "اكتمل الطلب",+ "completed_as_group_few": "اكتمل الطلب كـ {{count}} طلبات منفصلة",+ "completed_as_group_many": "اكتمل الطلب كـ {{count}} طلبًا منفصلًا",+ "completed_as_group_one": "اكتمل الطلب كطلب منفصل واحد",+ "completed_as_group_other": "اكتمل الطلب كـ {{count}} طلبات منفصلة",+ "completed_as_group_two": "اكتمل الطلب كطلبين منفصلين","confirmation_sent": "تم إرسال التأكيد","deleted": "تم حذف مسودة الطلب","voided": "تم إلغاء الدفع"diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex dc18648f51..c816408510 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -2894,6 +2894,8 @@"canceled": "Auftrag storniert","captured": "Zahlung eingezogen","completed": "Auftrag abgeschlossen",+ "completed_as_group_one": "Auftrag als {{count}} separater Auftrag abgeschlossen",+ "completed_as_group_other": "Auftrag als {{count}} separate Aufträge abgeschlossen","confirmation_sent": "Bestätigung gesendet","deleted": "Auftragsentwurf gelöscht","voided": "Zahlung storniert"diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 046e318dee..9b1f2f2ea5 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -2894,6 +2894,8 @@"canceled": "Order canceled","captured": "Payment captured","completed": "Order completed",+ "completed_as_group_one": "Order completed as {{count}} separate order",+ "completed_as_group_other": "Order completed as {{count}} separate orders","confirmation_sent": "Confirmation sent","deleted": "Draft order deleted","voided": "Payment voided"diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex 61482f5528..3a83f06021 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -2634,6 +2634,8 @@"canceled": "Pedido cancelado","captured": "Pago capturado","completed": "Pedido completado",+ "completed_as_group_one": "Pedido completado como {{count}} pedido separado",+ "completed_as_group_other": "Pedido completado como {{count}} pedidos separados","confirmation_sent": "Confirmación enviada","deleted": "Pedido borrador eliminado","voided": "Pago anulado"diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 3cebcb5a7a..3ed5dcfb9a 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -2894,6 +2894,8 @@"canceled": "Commande annulée","captured": "Paiement capturé","completed": "Commande finalisée",+ "completed_as_group_one": "Commande finalisée en {{count}} commande distincte",+ "completed_as_group_other": "Commande finalisée en {{count}} commandes distinctes","confirmation_sent": "Confirmation envoyée","deleted": "Commande brouillon supprimée","voided": "Paiement annulé"diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex d4004ea207..311246ead8 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -2920,6 +2920,10 @@"canceled": "Zamówienie anulowane","captured": "Płatność pobrana","completed": "Zamówienie sfinalizowane",+ "completed_as_group_few": "Zamówienie sfinalizowane jako {{count}} osobne zamówienia",+ "completed_as_group_many": "Zamówienie sfinalizowane jako {{count}} osobnych zamówień",+ "completed_as_group_one": "Zamówienie sfinalizowane jako {{count}} osobne zamówienie",+ "completed_as_group_other": "Zamówienie sfinalizowane jako {{count}} osobnych zamówień","confirmation_sent": "Potwierdzenie wysłane","deleted": "Robocza wersja zamówienia została usunięta","voided": "Płatność unieważniona"diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex d4cd9dc065..c7f2336884 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -2886,6 +2886,8 @@"canceled": "订单已取消","captured": "付款已收取","completed": "订单已完成",+ "completed_as_group_one": "订单已完成,拆分为 {{count}} 个独立订单",+ "completed_as_group_other": "订单已完成,拆分为 {{count}} 个独立订单","confirmation_sent": "确认信息已发送","deleted": "订单草稿已删除","voided": "付款已作废"diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rbindex ca946761fa..177db222f4 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb@@ -52,6 +52,10 @@ module Spreeend# PATCH /api/v3/admin/orders/:id/complete+ #+ # An order holding several sellers' goods divides into one order per+ # seller, so the group is what comes back — the orders it produced+ # are nested inside it.def completewith_order_lock doresult = Spree.order_complete_service.call(@@ -61,7 +65,7 @@ module Spree)if result.success?- render json: serialize_resource(@resource.reload)+ render json: serialize_completion(result.value)elserender_service_error(@resource.errors.presence || result.error, code: ERROR_CODES[:order_cannot_complete])end@@ -149,6 +153,28 @@ module SpreeSpree.api.admin_order_serializerend+ # Completion answers with whatever it produced: one order, or the+ # group a multi-seller order divided into.+ #+ # The group is rendered whole rather than through `filter_fields`: a+ # `fields` list names an order's attributes, and narrowing a group by+ # it can drop the very keys that say it is one.+ def serialize_completion(record)+ return serialize_resource(record.reload) unless record.is_a?(Spree::OrderGroup)++ Spree.api.admin_order_group_serializer.new(completed_group(record), params: serializer_params).to_h+ end++ # Every child is rendered in full, so its associations are loaded once+ # here rather than per order.+ def completed_group(group)+ Spree::OrderGroup.includes(+ :customer, :ship_address, :bill_address,+ { payments: %i[payment_method source] },+ { orders: [:seller, :market, :gift_card, :customer, { line_items: { variant: :prices } }] }+ ).find(group.id)+ end+# Override scope — Order uses SingleStoreResource (for_store).# Variant prices and each line's price list are named here rather# than via scope_includes, which this override bypasses; thediff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rbindex d7ecb43536..f9b3ab8c78 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb@@ -950,6 +950,55 @@ RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller doexpect(body['error']['message']).to eq('Order is canceled')endend++ # An order holding several sellers' goods divides on completion, so the+ # operator is answered with the purchase rather than one part of it.+ context 'when the order divides between sellers' do+ let(:seller) { create(:seller, :approved, store: store) }+ let(:other_seller) { create(:seller, :approved, store: store) }+ let!(:order) do+ draft = create(:order_ready_to_ship, store: store, line_items_count: 2)+ draft.update_columns(status: 'draft', completed_at: nil, payment_status: nil)+ draft.line_items.reload.each_with_index do |line_item, index|+ assigned = index.zero? ? seller : other_seller+ line_item.variant.update!(seller: assigned)+ line_item.update_columns(seller_id: assigned.id)+ end+ draft.reload+ end++ it 'answers with the group and the orders it produced' do+ patch :complete, params: { id: order.prefixed_id, payment_pending: true }, as: :json++ expect(response).to have_http_status(:ok)+ body = JSON.parse(response.body)+ expect(body['id']).to start_with('ogrp_')+ expect(body['seller_count']).to eq(2)+ expect(body['orders'].map { |child| child['seller_id'] }).to all(be_present)+ end+ end++ context 'when the order holds one seller' do+ let(:seller) { create(:seller, :approved, store: store) }+ let!(:order) do+ draft = create(:order_ready_to_ship, store: store, line_items_count: 2)+ draft.update_columns(status: 'draft', completed_at: nil, payment_status: nil)+ draft.line_items.reload.each do |line_item|+ line_item.variant.update!(seller: seller)+ line_item.update_columns(seller_id: seller.id)+ end+ draft.reload+ end++ it 'answers with the order, carrying its seller' do+ patch :complete, params: { id: order.prefixed_id, payment_pending: true }, as: :json++ expect(response).to have_http_status(:ok)+ body = JSON.parse(response.body)+ expect(body['id']).to eq(order.prefixed_id)+ expect(body['seller_id']).to eq(seller.prefixed_id)+ end+ endenddescribe 'PATCH #cancel' dodiff --git a/spree/api/spec/integration/spree/api/v3/admin/orders_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders_spec.rbindex f17fe1e70f..cd84a3be1d 100644--- a/spree/api/spec/integration/spree/api/v3/admin/orders_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/orders_spec.rb@@ -315,6 +315,10 @@ RSpec.describe 'Admin Orders API', type: :request, swagger_doc: 'api-reference/aCompletes an order in the `confirm` state, marking it as placed.Set `notify_customer: true` to send the order confirmation email.++ On a marketplace, an order holding several sellers' goods becomes one+ order per seller, and the response is the order group they belong to+ with those orders nested inside it.DESCadmin_scope :write, :ordersdiff --git a/spree/core/app/services/spree/carts/split_by_seller.rb b/spree/core/app/services/spree/carts/split_by_seller.rbindex 080a7bc8de..5c061fa1ef 100644--- a/spree/core/app/services/spree/carts/split_by_seller.rb+++ b/spree/core/app/services/spree/carts/split_by_seller.rb@@ -35,14 +35,15 @@ module Spreecustomer_note last_ip_address po_number].freeze- # @param cart [Spree::Cart]# @param order [Spree::Order] the paid draft order, adopted as the# group's first child rather than replaced — it is the record the# payment was taken against# @param partitions [Array<Spree::Carts::SellerPartition>] ordered, first# party first+ # @param cart [Spree::Cart, nil] nil for an order raised from the admin,+ # which never had one# @return [Spree::ServiceModule::Result] value is the Spree::OrderGroup- def call(cart:, order:, partitions:)+ def call(order:, partitions:, cart: nil)group = nil# Every apportionment here divides money in this one currency.@currency = order.currency@@ -76,20 +77,23 @@ module Spree# keeps the reference they saw at checkout, and the children number off# it: R1001-1, R1001-2. The cart_id moves up too — the group is what that# cart completed into, and it becomes the replay anchor.+ #+ # The facts come off the order rather than the cart because the order+ # carries every one of them and an admin-raised order has no cart; the+ # cart is only linked, as the replay anchor, when there is one.def build_group(cart, order)order.update_columns(cart_id: nil)- group = cart.store.order_groups.create!(+ order.store.order_groups.create!(cart: cart,- customer: cart.customer,+ customer: order.customer,number: order.number,- currency: cart.currency,- email: cart.email,- token: cart.token,- ship_address: cart.ship_address&.snapshot,- bill_address: cart.bill_address&.snapshot+ currency: order.currency,+ email: order.email,+ token: order.token,+ ship_address: order.ship_address&.snapshot,+ bill_address: order.bill_address&.snapshot)- groupend# Files the paid order under the group as its first child. Its owndiff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rbindex a0bfb7fce1..af8b499628 100644--- a/spree/core/app/workflows/spree/carts/complete.rb+++ b/spree/core/app/workflows/spree/carts/complete.rb@@ -407,82 +407,30 @@ module Spree# resumes like any other finalize failure.def finalize!(cart, order)@order = order- step :split_by_seller- step :allocate_payment_splitsstep :complete_ordersstep :complete_cartstep :mark_coupon_codes_usedexternal_step :commit_taxend- # Divides the paid draft order into one order per seller, under a group.- # A cart of one partition — all first-party, or all one seller — is left- # exactly as it is: no group, no splits, and the order it already built- # is the order the customer gets.+ # Places what the checkout produced, through the order-side workflow+ # that owns placement — including dividing the basket between sellers,+ # which an order raised from the admin needs just as much and which only+ # that workflow can give both of them.#- # The draft order built in PREPARE becomes the group's first child rather- # than being replaced. It is the record the payment was taken against and- # the row carrying the unique cart_id that makes completion replayable,- # so it is kept and narrowed to its own partition; the remaining- # partitions become new siblings beside it.- def split_by_seller- @order_group = cart.order_group- return if order_group.present?- return if order.placed?-- partitions = Spree::Carts::PartitionBySeller.call(purchase: order).value-- if partitions.one?- # Nothing to divide, but the sale still belongs to whoever made it:- # a basket entirely from one seller is that seller's order, and the- # column is what their own order list reads.- order.update_columns(seller_id: partitions.first.seller_id) if order.seller_id != partitions.first.seller_id- return- end-- return if partitions.empty?+ # It answers with the group when the basket divided, and the first of+ # its children is the order this checkout carries on with: that is the+ # one holding the confirmation email.+ def complete_orders+ result = Spree.order_complete_workflow.call(order: order, payment_pending: payment_pending)+ failure(cart, code: 'completion_failed', message: result.error) if result.failure?- result = Spree::Carts::SplitBySeller.call(cart: cart, order: order, partitions: partitions)- failure(cart, code: 'split_failed', message: result.error) if result.failure?+ return unless result.value.is_a?(Spree::OrderGroup)@order_group = result.value- # Ordered, because which child comes first decides which one carries- # the confirmation email — that must not depend on how the rows come- # back.@order = order_group.orders.order(:id).firstend- def allocate_payment_splits- return if order_group.nil?-- result = Spree::OrderGroups::AllocatePayments.call(group: order_group)- failure(cart, code: 'split_failed', message: result.error) if result.failure?- end-- # Places what the checkout produced — the children of a split, or the one- # order otherwise. Each child publishes its own order.placed, which is- # what gets every seller their own commission lines with no marketplace- # code in the commission engine.- #- # A split checkout's payments were already taken against the whole basket- # and moved onto the group, so the children place without processing them- # again. One purchase means one confirmation email: the first child- # carries the notification and its siblings place silently.- def complete_orders- split = order_group.present?-- placed_orders.each_with_index do |child, index|- result = Spree.order_complete_workflow.call(- order: child,- payment_pending: split,- notify_customer: split && !index.zero? ? false : nil- )- failure(cart, code: 'completion_failed', message: result.error) if result.failure?- end-- order_group&.publish_event('order_group.completed')- end-# Tells the tax engine the sale is final. A no-op for the built-in# provider, whose rows are already the record; external engines file the# document that a tax return is later built from. Outside thediff --git a/spree/core/app/workflows/spree/orders/complete.rb b/spree/core/app/workflows/spree/orders/complete.rbindex f73d79ed7e..4b0a5e8c4e 100644--- a/spree/core/app/workflows/spree/orders/complete.rb+++ b/spree/core/app/workflows/spree/orders/complete.rb@@ -7,6 +7,9 @@ module Spree# may still need to process payments). Idempotent: an already-placed# order halts successfully, so interrupted completions replay safely.class Complete < Spree::Workflow+ # Set only when the order divided between sellers.+ attr_reader :order_group+# @param order [Spree::Order]# @param payment_pending [Boolean] when true the order places without# processing payments (B2B / invoice-later). With no payment rows the@@ -15,17 +18,29 @@ module Spree# rollup work's call (docs/plans/6.0-b2b-wholesale-shipping.md phase 7)# @param notify_customer [Boolean, nil] admin drafts pass false to# complete silently; nil (checkout) leaves customer notification on+ # @return [Spree::ServiceModule::Result] value is the order, or the+ # Spree::OrderGroup when it divided between sellersdef perform(order:, payment_pending: false, notify_customer: nil)superorder.notify_customer = notify_customer unless notify_customer.nil?- halt!(order) if order.completed?+ # Replaying finishes what an interrupted division started — a sibling+ # left in draft is an order nobody will ever ship — and answers with+ # what the first run produced, rather than reporting one seller's order+ # where it first reported the whole purchase.+ if order.completed?+ @order_group = order.order_group+ step :complete_sibling_orders+ halt!(order_group || order)+ end+step :ensure_not_canceledorder.with_lock dounless order.reload.placed?step :process_payments unless payment_pending || !order.payment_required?+ step :split_by_sellerstep :finalize_fulfillmentsstep :place_orderstep :use_coupon_codes@@ -39,8 +54,9 @@ module Spreestep :release_stock_reservationsstep :update_statusesstep :publish_order_placed+ step :complete_sibling_orders- success(order)+ success(order_group || order)endprivate@@ -56,6 +72,52 @@ module Spreefailure(order, Spree.t(:payment_processing_failed)) unless payment_covered?end+ # Files the sale under whoever made it, dividing the order into one per+ # seller when it holds several sellers' goods.+ #+ # Here because this is the one home both entry points share. Commission+ # is charged from the line item's seller while the ledger credits the+ # order's, so an order that skipped this — as one raised from the admin+ # used to — is charged for and credited to nobody.+ #+ # Runs after payment so the money is settled once against the whole+ # basket, and before placement so each seller's order is placed in its+ # own right.+ def split_by_seller+ # A sibling arrives already divided.+ return if order.order_group_id.present?++ partitions = Spree::Carts::PartitionBySeller.call(purchase: order).value+ return if partitions.empty?+ return stamp_seller(partitions.first.seller_id) if partitions.one?++ # The cart travels with it: the group becomes what that cart completed+ # into, and the row carrying its id is the replay anchor.+ result = Spree::Carts::SplitBySeller.call(order: order, partitions: partitions, cart: order.cart)+ failure(order, result.error) if result.failure?++ # The division adopts this very order as the group's first child and+ # reloads it, so it stays the row this workflow locked and the object+ # carrying the caller's notify_customer, which a freshly loaded one+ # would not.+ @order_group = result.value+ step :allocate_payment_splits+ end++ # Nothing to divide, but the sale still belongs to whoever made it: an+ # order entirely from one seller is that seller's, and the column is what+ # their own order list reads.+ def stamp_seller(seller_id)+ return if order.seller_id == seller_id++ order.update_columns(seller_id: seller_id, updated_at: Time.current)+ end++ def allocate_payment_splits+ result = Spree::OrderGroups::AllocatePayments.call(group: order_group)+ failure(order, result.error) if result.failure?+ end+# Typed adjustment rows are frozen once completed — the totals# recalculation only re-sums them, never regenerates (see# Spree::Carts::RecalculateTotals) — so no per-row locking is needed.@@ -160,6 +222,34 @@ module Spreeorder.publish_event('order.completed', payload, { deprecated_alias_of: 'order.placed' })end+ # Places the orders the division produced beside this one.+ #+ # They place without processing payments, because the money was taken+ # against the whole basket before the division and the group now holds+ # it, and silently, because one purchase means one confirmation email.+ # Only the ones still in draft, so a replay finishes an interrupted+ # division instead of re-placing what already went out.+ def complete_sibling_orders+ return if order_group.nil?++ pending = order_group.orders.where.not(id: order.id).where(status: 'draft').order(:id)+ pending.each { |sibling| place_sibling(sibling) }++ # The division loaded these children before placing them, and the rows+ # just placed are not those objects — anything reading the group now+ # would see drafts that no longer exist.+ order_group.orders.reset++ return unless order_group.orders.all?(&:placed?)++ order_group.publish_event('order_group.completed')+ end++ def place_sibling(sibling)+ result = Spree.order_complete_workflow.call(order: sibling, payment_pending: true, notify_customer: false)+ failure(order, result.error) if result.failure?+ end+def payment_covered?order.payments.resetorder.payments.valid.where(status: %w[pending processing completed]).sum(:amount) >= order.amount_due_at_checkoutdiff --git a/spree/core/spec/workflows/spree/orders/complete_spec.rb b/spree/core/spec/workflows/spree/orders/complete_spec.rbindex 67314be470..14a4f2776c 100644--- a/spree/core/spec/workflows/spree/orders/complete_spec.rb+++ b/spree/core/spec/workflows/spree/orders/complete_spec.rb@@ -202,5 +202,170 @@ module Spreeexpect(order.completed_at).to be_presentendend++ # An order raised from the admin never passes through a cart, so this is+ # the only place its sale gets filed under whoever made it.+ describe 'filing the sale under its seller' do+ let(:seller) { create(:seller, :approved, store: store, name: 'Sparks Audio') }+ let(:other_seller) { create(:seller, :approved, store: store, name: 'Quill Books') }++ # A draft order raised in the back office, whose sellers the caller+ # decides. Nil is the operator's own goods.+ def draft_for(*sellers, paid: true)+ draft = create(:order_ready_to_ship, store: store, line_items_count: sellers.size)+ draft.update_columns(status: 'draft', completed_at: nil, payment_status: nil)+ draft.line_items.reload.each_with_index do |line_item, index|+ assigned = sellers[index]+ line_item.variant.update!(seller: assigned)+ line_item.update_columns(seller_id: assigned&.id)+ end+ draft.reload.recalculate_totals!+ draft.payments.destroy_all+ # Settled before the division, as the money always is: the operator+ # took one payment against the whole order.+ create(:payment, order: draft, status: 'completed', amount: draft.reload.total) if paid+ draft.reload+ end++ it 'stamps a single seller onto the order' do+ draft = draft_for(seller, seller)++ result = described_class.call(order: draft, payment_pending: true)++ expect(result).to be_success+ expect(result.value).to be_a(Spree::Order)+ expect(draft.reload.seller_id).to eq(seller.id)+ expect(Spree::OrderGroup.count).to eq(0)+ end++ it 'leaves the operator\'s own order without a seller' do+ draft = draft_for(nil, nil)++ described_class.call(order: draft, payment_pending: true)++ expect(draft.reload.seller_id).to be_nil+ expect(Spree::OrderGroup.count).to eq(0)+ end++ it 'divides an order holding two sellers goods into one order each' do+ draft = draft_for(seller, other_seller)++ result = described_class.call(order: draft, payment_pending: true)++ expect(result).to be_success+ group = result.value+ expect(group).to be_a(Spree::OrderGroup)+ expect(group.orders.reload.map(&:seller_id)).to match_array([seller.id, other_seller.id])+ expect(group.orders.map(&:status).uniq).to eq(['placed'])+ end++ # The customer authorised one amount, so the children's totals have to+ # add back up to it rather than each being re-derived.+ it 'keeps the children totalling what the order was worth' do+ draft = draft_for(seller, other_seller)+ expected_total = draft.total++ group = described_class.call(order: draft, payment_pending: true).value++ expect(group.orders.reload.sum(&:total)).to eq(expected_total)+ end++ it 'records each child\'s share of the payment' do+ draft = draft_for(seller, other_seller)+ expected_total = draft.total++ group = described_class.call(order: draft, payment_pending: true).value++ expect(group.payment_splits.sum(:authorized_amount)).to eq(expected_total)+ end++ # Invoice-later has no money to apportion, so there are no shares to+ # write — and every child must still place and roll up a status rather+ # than stalling on payment nobody made.+ it 'divides an unpaid invoice-later order with no shares to record' do+ draft = draft_for(seller, other_seller, paid: false)++ group = described_class.call(order: draft, payment_pending: true).value++ expect(group.orders.reload.count).to eq(2)+ expect(group.payment_splits).to be_empty+ expect(group.orders.map(&:status).uniq).to eq(['placed'])+ expect(group.orders.map(&:payment_status).uniq).to eq(['none'])+ end++ it 'commissions each seller on their own order', :events do+ create(:commission_rate, store: store, value: 15)+ draft = draft_for(seller, other_seller)++ group = described_class.call(order: draft, payment_pending: true).value++ expect(Spree::CommissionLine.pluck(:seller_id)).to match_array([seller.id, other_seller.id])+ expect(group.orders.reload.map { |child| child.reload.commission_total }).to all(be_positive)+ end++ # The division adopts this order, so the flag the caller set on it in+ # memory has to survive — a freshly loaded child would silently email a+ # customer the operator asked not to notify.+ it 'keeps a silent completion silent when the order divides', :events do+ draft = draft_for(seller, other_seller)+ notified = []+ allow_any_instance_of(Spree::Order).to receive(:publish_event).and_wrap_original do |original, *args|+ notified << original.receiver.notify_customer if args.first == 'order.placed'+ original.call(*args)+ end++ described_class.call(order: draft, payment_pending: true, notify_customer: false)++ expect(notified).to all(be(false))+ end++ # A division interrupted after the first child was placed leaves siblings+ # in draft; nothing else ever places them, so the replay must.+ it 'places a sibling left behind by an interrupted division' do+ draft = draft_for(seller, other_seller)+ group = described_class.call(order: draft, payment_pending: true).value+ stranded = group.orders.reload.order(:id).last+ stranded.update_columns(status: 'draft', completed_at: nil)++ described_class.call(order: draft.reload, payment_pending: true)++ expect(stranded.reload.status).to eq('placed')+ end++ # Nothing retries a webhook that was never published.+ it 'announces the group on a replay that had nothing left to place', :events do+ draft = draft_for(seller, other_seller)+ described_class.call(order: draft, payment_pending: true)++ announced = 0+ allow_any_instance_of(Spree::OrderGroup).to receive(:publish_event) do |_, name, *|+ announced += 1 if name == 'order_group.completed'+ end++ described_class.call(order: draft.reload, payment_pending: true)++ expect(announced).to eq(1)+ end++ it 'divides once when the completion is replayed' do+ draft = draft_for(seller, other_seller)+ described_class.call(order: draft, payment_pending: true)++ expect { described_class.call(order: draft.reload, payment_pending: true) }.+ not_to change(Spree::OrderGroup, :count)+ end++ # A retried completion must not report one seller's order where the+ # first run reported the whole purchase.+ it 'answers a replay with the group it made the first time' do+ draft = draft_for(seller, other_seller)+ group = described_class.call(order: draft, payment_pending: true).value++ replayed = described_class.call(order: draft.reload, payment_pending: true)++ expect(replayed).to be_success+ expect(replayed.value).to eq(group)+ end+ endendend