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: type carts.complete as Order | OrderGroup in @spree/sdk (#14695)

Damian Legawiecdf8a0eafe4f2
diff --git a/.changeset/sdk-cart-complete-order-group.md b/.changeset/sdk-cart-complete-order-group.md
new file mode 100644
index 0000000000..20c680c2a0
--- /dev/null
+++ b/.changeset/sdk-cart-complete-order-group.md
@@ -0,0 +1,5 @@
+---
+"@spree/sdk": minor
+---
+
+`carts.complete` is now typed as `Order | OrderGroup`: in a marketplace, a cart holding several sellers' goods completes into an order group rather than a single order. Added the `OrderGroup` type export and an `isOrderGroup` type guard so storefronts can tell the two apart.
diff --git a/docs/developer/core-concepts/carts.mdx b/docs/developer/core-concepts/carts.mdx
index 667e51483e..25ecd99c01 100644
--- a/docs/developer/core-concepts/carts.mdx
+++ b/docs/developer/core-concepts/carts.mdx
@@ -259,7 +259,7 @@ To add your own step or requirement, see
const order = await client.carts.complete(cartId)
```
- You get back an [Order](/developer/core-concepts/orders).
+ You get back an [Order](/developer/core-concepts/orders) — or, in a marketplace where the cart held several sellers' goods, an [order group](/developer/core-concepts/sellers#one-checkout-several-sellers) holding one order per seller. Tell them apart with `isOrderGroup` from `@spree/sdk`.
</Step>
</Steps>
diff --git a/docs/developer/core-concepts/sellers.mdx b/docs/developer/core-concepts/sellers.mdx
index 47e2d06cd5..dc8cb7e4b5 100644
--- a/docs/developer/core-concepts/sellers.mdx
+++ b/docs/developer/core-concepts/sellers.mdx
@@ -261,6 +261,15 @@ A back office must handle it too: an order raised from the admin divides the sam
<CodeGroup>
+```typescript Store SDK
+import { isOrderGroup } from '@spree/sdk'
+
+const result = await client.carts.complete(cartId, { spreeToken: cart.token })
+
+// One order per seller when the cart held several sellers' goods.
+const orders = isOrderGroup(result) ? result.orders : [result]
+```
+
```typescript Admin SDK
import { isOrderGroup } from '@spree/admin-sdk'
diff --git a/docs/developer/sdk/store/cart-checkout.mdx b/docs/developer/sdk/store/cart-checkout.mdx
index 06d122ff9a..bf6308faf7 100644
--- a/docs/developer/sdk/store/cart-checkout.mdx
+++ b/docs/developer/sdk/store/cart-checkout.mdx
@@ -122,9 +122,26 @@ await client.carts.update(cartId, {
### Complete Checkout
```typescript
-await client.carts.complete(cartId, { spreeToken: cart.token });
+import { isOrderGroup } from '@spree/sdk';
+
+const result = await client.carts.complete(cartId, { spreeToken: cart.token });
+```
+
+Completing a cart usually returns one order. In a [marketplace](/developer/core-concepts/sellers#one-checkout-several-sellers), a cart holding several sellers' goods divides into one order per seller, and the response is the **order group** that ties them together: one purchase, one payment, combined totals, and the per-seller orders in `orders`. Use `isOrderGroup` to tell the two apart:
+
+```typescript
+if (isOrderGroup(result)) {
+ // One purchase, shown to the customer under the group's number and total.
+ console.log(result.number, result.display_total);
+ // How it will arrive: one order per seller, each with its own items and delivery.
+ result.orders.forEach((order) => console.log(order.number, order.items));
+} else {
+ console.log(result.number, result.display_total);
+}
```
+A storefront that never sells through more than one seller always gets an order back, but checking costs nothing and keeps the confirmation page working if sellers are added later.
+
### Fulfillments
Fulfillments are included in the cart response — there is no separate list endpoint.
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
index 85e8129807..b8a9815499 100644
--- a/packages/sdk/src/index.ts
+++ b/packages/sdk/src/index.ts
@@ -5,6 +5,7 @@ export type { RequestFn, RequestOptions, RetryConfig } from '@spree/sdk-core'
export { SpreeError } from '@spree/sdk-core'
export type { Client, ClientConfig } from './client'
export { createClient } from './client'
+export { isOrderGroup } from './order-group'
// Store client class (for advanced use / subclassing)
export { StoreClient } from './store-client'
diff --git a/packages/sdk/src/order-group.ts b/packages/sdk/src/order-group.ts
new file mode 100644
index 0000000000..2d49be654f
--- /dev/null
+++ b/packages/sdk/src/order-group.ts
@@ -0,0 +1,12 @@
+import type { Order, OrderGroup } from './types'
+
+/**
+ * Whether a checkout completion answered with the group a multi-seller cart
+ * divided into, rather than with one order.
+ *
+ * Keyed on `orders`, which only the group carries — the payload has no type
+ * discriminator of its own.
+ */
+export function isOrderGroup(result: Order | OrderGroup): result is OrderGroup {
+ return Array.isArray((result as OrderGroup).orders)
+}
diff --git a/packages/sdk/src/store-client.ts b/packages/sdk/src/store-client.ts
index f266f42d8d..845136eebf 100644
--- a/packages/sdk/src/store-client.ts
+++ b/packages/sdk/src/store-client.ts
@@ -40,6 +40,7 @@ import type {
Market,
NewsletterSubscriber,
Order,
+ OrderGroup,
OrderListParams,
Payment,
PaymentSession,
@@ -503,11 +504,13 @@ export class StoreClient {
/**
* Complete the cart and finalize the purchase.
- * Returns an Order (not Cart).
+ * Returns an Order (not Cart). In a marketplace, a cart holding several
+ * sellers' goods divides into one order per seller, and the group it
+ * produced is what comes back — narrow the result with `isOrderGroup`.
* @param cartId - Cart prefixed ID
*/
- complete: (cartId: string, options?: RequestOptions): Promise<Order> =>
- this.request<Order>('POST', `/carts/${cartId}/complete`, options),
+ complete: (cartId: string, options?: RequestOptions): Promise<Order | OrderGroup> =>
+ this.request<Order | OrderGroup>('POST', `/carts/${cartId}/complete`, options),
/**
* Nested resource: Line items
diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.ts
index 096adb8ae0..549e114e6f 100644
--- a/packages/sdk/src/types/index.ts
+++ b/packages/sdk/src/types/index.ts
@@ -38,6 +38,7 @@ export type {
OptionType,
OptionValue,
Order,
+ OrderGroup,
Payment,
PaymentMethod,
PaymentSession,
diff --git a/packages/sdk/tests/cart.test.ts b/packages/sdk/tests/cart.test.ts
index 896c73b5c5..7d2ab93af3 100644
--- a/packages/sdk/tests/cart.test.ts
+++ b/packages/sdk/tests/cart.test.ts
@@ -1,6 +1,12 @@
+import { HttpResponse, http } from 'msw'
import { beforeAll, describe, expect, it } from 'vitest'
import type { Client } from '../src'
-import { createTestClient } from './helpers'
+import { isOrderGroup } from '../src'
+import { createTestClient, TEST_BASE_URL } from './helpers'
+import { fixtures } from './mocks/handlers'
+import { server } from './mocks/server'
+
+const API_PREFIX = `${TEST_BASE_URL}/api/v3/store`
describe('carts', () => {
let client: Client
@@ -64,12 +70,37 @@ describe('carts', () => {
})
})
+ // A cart holding several sellers' goods divides on completion, and the
+ // group it produced is what comes back.
describe('complete', () => {
- it('completes the cart and returns an order', async () => {
+ it('answers with the order when the cart holds one seller', async () => {
const result = await client.carts.complete('cart_1', opts)
+ expect(isOrderGroup(result)).toBe(false)
expect(result.id).toBe('or_1')
expect(result.completed_at).toBeDefined()
})
+
+ it('answers with the group when the cart divided', async () => {
+ server.use(
+ http.post(`${API_PREFIX}/carts/cart_1/complete`, () =>
+ HttpResponse.json({
+ ...fixtures.order,
+ id: 'ogrp_1',
+ orders: [
+ { ...fixtures.order, id: 'or_1', number: 'R123456-1' },
+ { ...fixtures.order, id: 'or_2', number: 'R123456-2' },
+ ],
+ }),
+ ),
+ )
+
+ const result = await client.carts.complete('cart_1', opts)
+
+ expect(isOrderGroup(result)).toBe(true)
+ if (!isOrderGroup(result)) throw new Error('expected a group')
+ expect(result.id).toBe('ogrp_1')
+ expect(result.orders.map((order) => order.id)).toEqual(['or_1', 'or_2'])
+ })
})
describe('items', () => {