The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
feat(core): split the cart payment into per-order payments at capture (#1627)
Viktor Holikaa52c8b7252f
diff --git a/apps/docs/learn/migration-to-2-0.mdx b/apps/docs/learn/migration-to-2-0.mdxindex a853aaf2c..6f45e8845 100644--- a/apps/docs/learn/migration-to-2-0.mdx+++ b/apps/docs/learn/migration-to-2-0.mdx@@ -116,7 +116,7 @@ The 1.x `OrderSet` entity is renamed to `OrderGroup` in 2.x. This is a breakingTwo fields were removed from the group:-- **`payment_collection_id`**: payment collections are now linked at the individual order level. Query the linked orders to get the payment collection.+- **`payment_collection_id`**: orders share the cart's payment collection until the payment is captured, then each gets its own. Read `payment_collections` on the orders (see [Order Groups](/learn/order-groups)).- **`sales_channel_id`**: the sales channel is stored on each individual order.Two fields are now computed at query time rather than stored: **`seller_count`** (distinct sellers across linked orders) and **`total`** (sum of order totals).diff --git a/apps/docs/learn/order-groups.mdx b/apps/docs/learn/order-groups.mdxindex f5e45094c..ab449cae2 100644--- a/apps/docs/learn/order-groups.mdx+++ b/apps/docs/learn/order-groups.mdx@@ -54,16 +54,39 @@ Order groups are created automatically during checkout by the `completeCartWithS- Each seller and the customer (if new relationship)6. **Finalize** — Inventory is reserved, payment is authorized, and the `order_group.created` event is emitted-<Info>- A single payment collection is shared across all of a cart's split orders and stays on the **cart**, not on each order. Split orders are **not** linked directly to the payment collection (Medusa's `order ↔ payment_collection` link is one-to-one on the payment-collection side). Read the payment collection through the cart:+## Payments++The customer pays for the cart once: one payment collection on the cart, one payment at the payment provider. Medusa links a payment collection to a single order, so the orders of a cart share that payment through the cart until it is captured:++```text+order → cart → payment_collection → payment+```++When the cart payment is captured, it is split. Every order gets a payment collection of its own, linked to the order, with a captured payment for the order's share. That payment is on the same provider as the cart payment and points at the same charge. Shares are proportional to the order totals, rounded to the currency precision, and sum exactly to the captured amount.- ```text- order → cart → payment_collection- ```+```text+order → payment_collections → payment+```- Order-group and vendor order reads normalize `cart.payment_collection` back onto `payment_collections` and recompute `payment_status` from it, so consumers keep the familiar shape. When requesting fields on vendor order routes, make sure the request does not replace route defaults that already include `cart.payment_collection.*` (a `fields=` list containing bare fields replaces defaults in Medusa; use `+`-prefixed fields to merge, or include the `cart.payment_collection.*` paths explicitly).+From then on Medusa's order and payment workflows and the stock admin and vendor routes work on the order unchanged.++| Moment | What happens |+|--------|--------------|+| Cancel an order before capture | No payment is touched: the authorization is still needed by the cart's other orders. Once every order of the cart is canceled, the authorization is voided. |+| Capture | The cart payment is captured as a whole, by the provider webhook or from the dashboard, and split between the orders. What was charged for orders canceled earlier is refunded. |+| Refund an order's payment | The amount is refunded at the provider against the customer's charge and recorded on that order. It cannot exceed the order's share. |+| Cancel an order after capture | The order's share is refunded. |++Order reads expose whichever applies under `payment_collections`: the cart's collection before the capture, the order's own afterwards.++<Info>+ The split, and voiding the authorization after the last cancel, run in subscribers to `payment.captured` and `order.canceled`, shortly after the request returns. A provider that captures on authorization is split during checkout.</Info>+<Note>+ Orders whose payment was captured before this model was introduced are not split retroactively and keep the cart's shared collection.+</Note>+## Events| Event | Payload | When |diff --git a/integration-tests/helpers/split-order-checkout.ts b/integration-tests/helpers/split-order-checkout.tsindex 389b0cb6f..bc29726ef 100644--- a/integration-tests/helpers/split-order-checkout.ts+++ b/integration-tests/helpers/split-order-checkout.ts@@ -141,13 +141,12 @@ export const seedSellerOfferWithShipping = async (opts: {return { sellerId: result.seller.id, headers, offer }}-export const completeSplitOrderCheckout = async (opts: {+type SplitOrderCheckoutOptions = {container: MedusaContainerapi: anystoreHeaders: anyregionId: stringsalesChannelId: string- offerId: string/*** Must be the authenticated customer's own email. Medusa's* findOrCreateCustomerStep treats a customer without `has_account` as a@@ -155,7 +154,23 @@ export const completeSplitOrderCheckout = async (opts: {* guest customer — and the resulting orders stop belonging to the buyer.*/email: string-}) => {+}++export const completeSplitOrderCheckout = async (+ opts: SplitOrderCheckoutOptions & { offerId: string }+) => {+ const [order] = await completeSplitOrderGroupCheckout({+ ...opts,+ offerIds: [opts.offerId],+ })++ return order+}++/** Checks out one cart holding every given offer; resolves to its split orders. */+export const completeSplitOrderGroupCheckout = async (+ opts: SplitOrderCheckoutOptions & { offerIds: string[] }+): Promise<{ id: string }[]> => {const { container, api, storeHeaders } = optsconst cart = (@@ -170,11 +185,13 @@ export const completeSplitOrderCheckout = async (opts: {)).data.cart- await api.post(- `/store/carts/${cart.id}/line-items`,- { offer_id: opts.offerId, quantity: 1 },- storeHeaders- )+ for (const offerId of opts.offerIds) {+ await api.post(+ `/store/carts/${cart.id}/line-items`,+ { offer_id: offerId, quantity: 1 },+ storeHeaders+ )+ }const address = {first_name: "Buyer",@@ -236,5 +253,5 @@ export const completeSplitOrderCheckout = async (opts: {fields: ["id", "orders.id"],})- return (orderGroup[0] as any).orders[0]+ return (orderGroup[0] as any).orders}diff --git a/integration-tests/http/order/vendor/order-cancel.spec.ts b/integration-tests/http/order/vendor/order-cancel.spec.tsindex 61fa3ccf7..e23162db5 100644--- a/integration-tests/http/order/vendor/order-cancel.spec.ts+++ b/integration-tests/http/order/vendor/order-cancel.spec.ts@@ -20,18 +20,10 @@ jest.setTimeout(120000)/*** SPEC-008 §B — Cancel Order MVP rule. The kebab-level "cannot cancel* when items have been fulfilled" gate is enforced by the vendor UI- * (`OrderGeneralSection`, session hh). The backend route at- * `packages/core/src/api/vendor/orders/[id]/cancel/route.ts` calls- * Medusa's `cancelOrderWorkflow` directly, which handles the cascade- * (status flip → captured-payment refund → authorized-payment void →- * customer notification). These tests lock in:- * - The happy path (no fulfillments, captured payment) refunds.- * - Cross-seller scope is enforced on the cancel route.- *- * The fulfilled-items gate is intentionally **not** asserted at the- * backend layer — Medusa's workflow cancels fulfillments alongside- * the order, so the "no fulfilled items" rule lives only in the UI- * (per `docs/vendor-orders-design-diff.md` §MVP).+ * (`OrderGeneralSection`). The backend route runs Medusa's+ * `cancelOrderWorkflow`, which reaches the order's payment through its own+ * payment collection; the payment side is covered in+ * `http/payment/split-order-payments.spec.ts`.*/const approveSeller = async (@@ -344,14 +336,7 @@ medusaIntegrationTestRunner({})describe("POST /vendor/orders/:id/cancel", () => {- // The Mercur cancel route surfaces a pre-existing MikroORM- // 'strategy' error in `getJoinedFilters` (mikro-orm 6.4.16 +- // Medusa 2.13.4 + Mercur order extensions). The same error- // appears in the legacy `order.spec.ts` cancel cases — not- // introduced by SPEC-008 work. Skipping until the upstream- // MikroORM populate path is fixed; the route itself does call- // `cancelOrderWorkflow` correctly per UI verification.- it.skip("cancels a seller-owned order and flips status to canceled", async () => {+ it("cancels a seller-owned order and flips status to canceled", async () => {const order = await completeCartCheckout(seller1Seed.offer.id)const response = await api.post(@@ -373,12 +358,6 @@ medusaIntegrationTestRunner({it("rejects cross-seller cancel — seller B cannot cancel seller A's order", async () => {const orderA = await completeCartCheckout(seller1Seed.offer.id)- // `validateSellerOrder` runs at the top of the route- // handler and throws NOT_FOUND before either the- // `cancelOrderWorkflow` or the post-cancel `query.graph`- // is invoked — so the cross-seller path is unaffected- // by the MikroORM populate regression that gates the- // happy-path test above.const response = await api.post(`/vendor/orders/${orderA.id}/cancel`,diff --git a/integration-tests/http/payment/split-order-payments.spec.ts b/integration-tests/http/payment/split-order-payments.spec.tsnew file mode 100644index 000000000..380ea8200--- /dev/null+++ b/integration-tests/http/payment/split-order-payments.spec.ts@@ -0,0 +1,465 @@+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import {+ IRegionModuleService,+ ISalesChannelModuleService,+ MedusaContainer,+} from "@medusajs/framework/types"+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"+import { createCustomerUser } from "../../helpers/create-customer-user"+import {+ adminHeaders,+ createAdminUser,+ generatePublishableKey,+ generateStoreHeaders,+} from "../../helpers/create-admin-user"+import {+ completeSplitOrderGroupCheckout,+ seedSellerOfferWithShipping,+} from "../../helpers/split-order-checkout"++jest.setTimeout(180000)++const SELLER_A_TOTAL = 3000+const SELLER_B_TOTAL = 4500++/**+ * Issue #1596 — the orders of a cart share its payment until that payment is+ * captured. The capture splits it: every order gets a payment collection of+ * its own, linked to the order, so Medusa's stock refund and cancel routes+ * work on it.+ */+medusaIntegrationTestRunner({+ testSuite: ({ getContainer, api, dbConnection }) => {+ describe("Split order payments (split at capture)", () => {+ let appContainer: MedusaContainer+ let sellerA: any+ let sellerB: any+ let storeHeaders: any+ let customerEmail: string+ let region: any+ let salesChannel: any++ beforeAll(async () => {+ appContainer = getContainer()+ })++ beforeEach(async () => {+ await createAdminUser(dbConnection, adminHeaders, appContainer)++ const customerResult = await createCustomerUser(appContainer, {+ email: "[email protected]",+ first_name: "Split",+ last_name: "Buyer",+ })+ customerEmail = customerResult.customer.email!+ const apiKey = await generatePublishableKey(appContainer)+ const baseStoreHeaders = generateStoreHeaders({+ publishableKey: apiKey,+ })+ storeHeaders = {+ headers: {+ ...baseStoreHeaders.headers,+ ...customerResult.headers.headers,+ },+ }++ const salesChannelModule =+ appContainer.resolve<ISalesChannelModuleService>(+ Modules.SALES_CHANNEL+ )+ salesChannel = await salesChannelModule.createSalesChannels({+ name: "Split Payment Channel",+ })++ const regionModule = appContainer.resolve<IRegionModuleService>(+ Modules.REGION+ )+ region = await regionModule.createRegions({+ name: "Split Payment Region",+ currency_code: "usd",+ countries: ["us"],+ })++ const link = appContainer.resolve(ContainerRegistrationKeys.LINK)+ await link.create({+ [Modules.REGION]: { region_id: region.id },+ [Modules.PAYMENT]: {+ payment_provider_id: "pp_system_default",+ },+ })++ sellerA = await seedSellerOfferWithShipping({+ container: appContainer,+ api,+ salesChannelId: salesChannel.id,+ email: "[email protected]",+ name: "SplitPayA",+ stocked: 20,+ offerPrice: 2500,+ })+ sellerB = await seedSellerOfferWithShipping({+ container: appContainer,+ api,+ salesChannelId: salesChannel.id,+ email: "[email protected]",+ name: "SplitPayB",+ stocked: 20,+ offerPrice: 4000,+ })+ })++ const query = () =>+ appContainer.resolve(ContainerRegistrationKeys.QUERY)++ const getOrder = async (orderId: string) => {+ const {+ data: [order],+ } = await query().graph({+ entity: "order",+ filters: { id: orderId },+ fields: [+ "id",+ "status",+ "total",+ "summary",+ "transactions.reference",+ "transactions.amount",+ "payment_collections.id",+ "payment_collections.amount",+ "payment_collections.status",+ "payment_collections.payments.id",+ "payment_collections.payments.provider_id",+ "payment_collections.payments.amount",+ "payment_collections.payments.canceled_at",+ "payment_collections.payments.captured_at",+ "payment_collections.payments.captures.amount",+ "payment_collections.payments.refunds.amount",+ "cart.payment_collection.status",+ "cart.payment_collection.payments.id",+ "cart.payment_collection.payments.canceled_at",+ "cart.payment_collection.payments.captured_at",+ "cart.payment_collection.payments.captures.amount",+ "cart.payment_collection.payments.refunds.amount",+ ],+ })+ return order as any+ }++ const orderPayment = async (orderId: string) =>+ (await getOrder(orderId)).payment_collections[0]?.payments[0]++ const cartPayment = async (orderId: string) =>+ (await getOrder(orderId)).cart.payment_collection.payments[0]++ const amounts = (movements: any[]) =>+ (movements ?? []).map((m) => Number(m.amount))++ const transactionsOf = (order: any, reference: string) =>+ order.transactions+ .filter((t: any) => t.reference === reference)+ .map((t: any) => Number(t.amount))++ // The split and the void run from an event subscriber, after the+ // request returns.+ const eventually = async (assertion: () => Promise<void>) => {+ const deadline = Date.now() + 15000+ for (;;) {+ try {+ return await assertion()+ } catch (error) {+ if (Date.now() > deadline) {+ throw error+ }+ await new Promise((r) => setTimeout(r, 250))+ }+ }+ }++ const checkout = async (offerIds: string[]) => {+ const orders = await completeSplitOrderGroupCheckout({+ container: appContainer,+ api,+ storeHeaders,+ regionId: region.id,+ salesChannelId: salesChannel.id,+ offerIds,+ email: customerEmail,+ })++ const { data: links } = await query().graph({+ entity: "order_seller",+ filters: { order_id: orders.map((o) => o.id) },+ fields: ["order_id", "seller_id"],+ })+ const orderIdOf = (sellerId: string) =>+ links.find((l: any) => l.seller_id === sellerId)+ ?.order_id as string++ return {+ orderA: orderIdOf(sellerA.sellerId),+ orderB: orderIdOf(sellerB.sellerId),+ }+ }++ const checkoutBothSellers = () =>+ checkout([sellerA.offer.id, sellerB.offer.id])++ const capture = (paymentId: string) =>+ api.post(+ `/admin/payments/${paymentId}/capture`,+ {},+ adminHeaders+ )++ const captureEverything = async (orderA: string, orderB: string) => {+ await capture((await cartPayment(orderA)).id)+ await eventually(async () => {+ expect(+ (await orderPayment(orderA))?.captured_at+ ).toBeTruthy()+ expect(+ (await orderPayment(orderB))?.captured_at+ ).toBeTruthy()+ })+ }++ describe("before capture", () => {+ it("keeps the orders on the cart's shared payment collection", async () => {+ const { orderA, orderB } = await checkoutBothSellers()++ expect((await getOrder(orderA)).payment_collections).toEqual(+ []+ )+ expect((await getOrder(orderB)).payment_collections).toEqual(+ []+ )++ const { data } = await api.get(+ `/admin/orders/${orderA}`,+ adminHeaders+ )++ expect(data.order.payment_collections).toHaveLength(1)+ expect(+ Number(data.order.payment_collections[0].amount)+ ).toEqual(SELLER_A_TOTAL + SELLER_B_TOTAL)+ expect(data.order.payment_status).toEqual("authorized")+ })+ })++ describe("capture", () => {+ it("gives every order its own captured payment collection", async () => {+ const { orderA, orderB } = await checkoutBothSellers()++ await captureEverything(orderA, orderB)++ const a = await getOrder(orderA)+ const b = await getOrder(orderB)++ expect(a.payment_collections).toHaveLength(1)+ expect(b.payment_collections).toHaveLength(1)+ expect(a.payment_collections[0].id).not.toEqual(+ b.payment_collections[0].id+ )+ expect(Number(a.payment_collections[0].amount)).toEqual(+ SELLER_A_TOTAL+ )+ expect(Number(b.payment_collections[0].amount)).toEqual(+ SELLER_B_TOTAL+ )+ expect(+ a.payment_collections[0].payments[0].provider_id+ ).toEqual("pp_system_default")++ expect(transactionsOf(a, "capture")).toEqual([+ SELLER_A_TOTAL,+ ])+ expect(transactionsOf(b, "capture")).toEqual([+ SELLER_B_TOTAL,+ ])+ expect(Number(a.summary.pending_difference)).toEqual(0)+ expect(Number(b.summary.pending_difference)).toEqual(0)+ })++ it("exposes the order's own payment collection on the admin order", async () => {+ const { orderA, orderB } = await checkoutBothSellers()+ await captureEverything(orderA, orderB)++ const { data } = await api.get(+ `/admin/orders/${orderA}`,+ adminHeaders+ )++ expect(data.order.payment_collections).toHaveLength(1)+ expect(+ Number(data.order.payment_collections[0].amount)+ ).toEqual(SELLER_A_TOTAL)+ expect(data.order.payment_status).toEqual("captured")+ })++ it("does not split the same capture twice", async () => {+ const { orderA, orderB } = await checkoutBothSellers()+ await captureEverything(orderA, orderB)++ await capture((await cartPayment(orderA)).id).catch(+ (e) => e.response+ )+ await new Promise((r) => setTimeout(r, 1500))++ const a = await getOrder(orderA)+ expect(a.payment_collections).toHaveLength(1)+ expect(transactionsOf(a, "capture")).toEqual([+ SELLER_A_TOTAL,+ ])+ expect(amounts((await cartPayment(orderA)).refunds)).toEqual(+ []+ )+ })+ })++ describe("refund", () => {+ it("refunds an order's payment through the stock admin route", async () => {+ const { orderA, orderB } = await checkoutBothSellers()+ await captureEverything(orderA, orderB)++ const response = await api.post(+ `/admin/payments/${(await orderPayment(orderA)).id}/refund`,+ { amount: 1000 },+ adminHeaders+ )+ expect(response.status).toEqual(200)++ const a = await getOrder(orderA)+ const b = await getOrder(orderB)++ expect(transactionsOf(a, "refund")).toEqual([-1000])+ expect(transactionsOf(b, "refund")).toEqual([])+ expect(Number(a.summary.pending_difference)).toEqual(0)+ })++ it("cannot refund more than the order's share", async () => {+ const { orderA, orderB } = await checkoutBothSellers()+ await captureEverything(orderA, orderB)++ const response = await api+ .post(+ `/admin/payments/${(await orderPayment(orderA)).id}/refund`,+ { amount: SELLER_A_TOTAL + 500 },+ adminHeaders+ )+ .catch((e) => e.response)++ expect(response.status).toEqual(400)+ expect((await orderPayment(orderA)).refunds).toHaveLength(0)+ })++ it("lets a seller refund only their own order's payment", async () => {+ const { orderA, orderB } = await checkoutBothSellers()+ await captureEverything(orderA, orderB)++ const own = await api.post(+ `/vendor/payments/${(await orderPayment(orderA)).id}/refund`,+ { amount: 500 },+ sellerA.headers+ )+ expect(own.status).toEqual(200)+ expect(+ transactionsOf(await getOrder(orderA), "refund")+ ).toEqual([-500])++ const foreign = await api+ .post(+ `/vendor/payments/${(await orderPayment(orderB)).id}/refund`,+ { amount: 500 },+ sellerA.headers+ )+ .catch((e) => e.response)+ expect(foreign.status).toEqual(404)+ })+ })++ describe("cancel", () => {+ it("refunds only the canceled order after capture", async () => {+ const { orderA, orderB } = await checkoutBothSellers()+ await captureEverything(orderA, orderB)++ const response = await api.post(+ `/vendor/orders/${orderA}/cancel`,+ {},+ sellerA.headers+ )+ expect(response.status).toEqual(200)++ const a = await getOrder(orderA)++ expect(a.status).toEqual("canceled")+ expect(transactionsOf(a, "refund")).toEqual([+ -SELLER_A_TOTAL,+ ])+ expect(+ amounts((await orderPayment(orderA)).refunds)+ ).toEqual([SELLER_A_TOTAL])+ expect(+ amounts((await orderPayment(orderB)).refunds)+ ).toEqual([])+ })++ it("keeps the authorization for the remaining order, then refunds the canceled share on capture", async () => {+ const { orderA, orderB } = await checkoutBothSellers()++ await api.post(+ `/admin/orders/${orderA}/cancel`,+ {},+ adminHeaders+ )++ expect((await cartPayment(orderA)).canceled_at).toBeNull()++ await capture((await cartPayment(orderA)).id)++ await eventually(async () => {+ expect(+ (await orderPayment(orderB))?.captured_at+ ).toBeTruthy()+ expect(+ amounts((await cartPayment(orderA)).refunds)+ ).toEqual([SELLER_A_TOTAL])+ })++ const a = await getOrder(orderA)+ expect(a.payment_collections).toEqual([])+ expect(transactionsOf(a, "capture")).toEqual([])+ expect(+ transactionsOf(await getOrder(orderB), "capture")+ ).toEqual([SELLER_B_TOTAL])+ })++ it("voids the cart payment once every order is canceled", async () => {+ const { orderA, orderB } = await checkoutBothSellers()++ await api.post(+ `/admin/orders/${orderA}/cancel`,+ {},+ adminHeaders+ )+ await api.post(+ `/admin/orders/${orderB}/cancel`,+ {},+ adminHeaders+ )++ await eventually(async () => {+ const order = await getOrder(orderA)+ expect(+ order.cart.payment_collection.payments[0]+ .canceled_at+ ).toBeTruthy()+ expect(order.cart.payment_collection.status).toEqual(+ "canceled"+ )+ })+ })+ })+ })+ },+})diff --git a/packages/core/src/api/utils/split-order-payment-status.ts b/packages/core/src/api/utils/split-order-payment-status.tsindex 702625c38..f06931ed1 100644--- a/packages/core/src/api/utils/split-order-payment-status.ts+++ b/packages/core/src/api/utils/split-order-payment-status.ts@@ -3,48 +3,53 @@ import { deduplicate } from "@medusajs/framework/utils"import { getLastPaymentStatus } from "../../workflows/order-group/utils/aggregate-status"+import { resolveOrderPaymentCollections } from "../../workflows/payment/utils/split-order-payment-group"+type OrderWithCartPaymentCollection = {- cart?: { payment_collection?: unknown } | null+ cart?: { payment_collection?: { metadata?: Record<string, unknown> | null } | null } | nullpayment_collections?: unknown[]payment_status?: string}-// The shared cart payment collection is reached through the cart, not linked-// to the order. These fields must always be loaded so the routes can normalize-// them back onto `payment_collections` and recompute `payment_status` — even-// when the client sends an absolute `fields=` list that would otherwise replace-// the route defaults.-const CART_PAYMENT_COLLECTION_FIELDS = [- "cart.payment_collection.*",- "cart.payment_collection.payments.*",- "cart.payment_collection.payments.refunds.*",- "cart.payment_collection.payments.refunds.refund_reason.*",- "cart.payment_collection.payment_sessions.*",+// An order is paid through the cart's shared payment collection until that+// payment is captured, and through its own linked collection afterwards. Both+// are always loaded so the routes can pick the right one and recompute+// `payment_status`, even when the client sends an absolute `fields=` list that+// would otherwise replace the route defaults.+const PAYMENT_COLLECTION_FIELDS = [+ "*",+ "payments.*",+ "payments.refunds.*",+ "payments.refunds.refund_reason.*",+ "payment_sessions.*",]export const withCartPaymentCollectionFields = (fields: string[]): string[] => {- return deduplicate([...fields, ...CART_PAYMENT_COLLECTION_FIELDS])+ return deduplicate([+ ...fields,+ ...PAYMENT_COLLECTION_FIELDS.map((f) => `payment_collections.${f}`),+ ...PAYMENT_COLLECTION_FIELDS.map((f) => `cart.payment_collection.${f}`),+ ])}-// The shared cart payment collection is fetched via `cart.payment_collection`-// (it is not linked directly to an order). Expose it back on the order under-// `payment_collections` so consumers keep the familiar shape, and recompute-// `payment_status` from it — Medusa's aggregation reads the linked payment-// collections, which are always empty for split orders under the cart-path model.+// Exposes the order's payment collections under `payment_collections` whichever+// way they are attached, and recomputes `payment_status` from them: Medusa's+// aggregation only reads the linked ones.export const normalizeOrderPaymentCollections = <T extends OrderWithCartPaymentCollection>(order: T): T => {- const paymentCollection = order.cart?.payment_collection+ const hadCart = !!order.cart+ const paymentCollections = resolveOrderPaymentCollections(order)delete order.cart- if (!paymentCollection) {+ if (!hadCart && !order.payment_collections) {return order}- order.payment_collections = [paymentCollection]+ order.payment_collections = paymentCollectionsorder.payment_status = getLastPaymentStatus(order as unknown as OrderDetailDTO)diff --git a/packages/core/src/api/vendor/payments/helpers.ts b/packages/core/src/api/vendor/payments/helpers.tsindex 899f53bc8..824d7bb05 100644--- a/packages/core/src/api/vendor/payments/helpers.ts+++ b/packages/core/src/api/vendor/payments/helpers.ts@@ -29,39 +29,46 @@ export const validateSellerPayment = async () => {const query = scope.resolve(ContainerRegistrationKeys.QUERY)- // The payment collection is shared across all split orders of a cart, so it- // is not linked directly to any single order. Resolve the owning cart and- // check the seller owns one of that cart's orders.+ // A payment is either an order's own, or the cart payment its orders share+ // until it is captured, which is reachable only through the cart.const {data: [payment],} = await query.graph({entity: "payment",filters: { id: paymentId },- fields: ["id", "payment_collection.cart.id"],+ fields: [+ "id",+ "payment_collection.order.id",+ "payment_collection.cart.id",+ ],})- const cartId = (+ const paymentCollection = (payment as- | { payment_collection?: { cart?: { id?: string } | null } | null }+ | {+ payment_collection?: {+ order?: { id?: string } | null+ cart?: { id?: string } | null+ } | null+ }| undefined- )?.payment_collection?.cart?.id+ )?.payment_collection- if (!cartId) {- throw new MedusaError(- MedusaError.Types.NOT_FOUND,- `Payment with id: ${paymentId} was not found`- )- }+ let orderIds: string[] = []- const { data: orderCartLinks } = await query.graph({- entity: "order_cart",- filters: { cart_id: cartId },- fields: ["order_id"],- })+ if (paymentCollection?.order?.id) {+ orderIds = [paymentCollection.order.id]+ } else if (paymentCollection?.cart?.id) {+ const { data: orderCartLinks } = await query.graph({+ entity: "order_cart",+ filters: { cart_id: paymentCollection.cart.id },+ fields: ["order_id"],+ })- const orderIds = orderCartLinks- .map((link) => (link as { order_id?: string }).order_id)- .filter((id): id is string => Boolean(id))+ orderIds = orderCartLinks+ .map((link) => (link as { order_id?: string }).order_id)+ .filter((id): id is string => Boolean(id))+ }if (!orderIds.length) {throw new MedusaError(diff --git a/packages/core/src/subscribers/split-order-canceled.ts b/packages/core/src/subscribers/split-order-canceled.tsnew file mode 100644index 000000000..24236acd7--- /dev/null+++ b/packages/core/src/subscribers/split-order-canceled.ts@@ -0,0 +1,31 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"+import { OrderWorkflowEvents } from "@medusajs/framework/utils"++import {+ resolveSplitOrderCartId,+ voidCanceledCartPaymentWorkflow,+} from "../workflows/payment"++export default async function splitOrderCanceledHandler({+ event,+ container,+}: SubscriberArgs<{ id: string }>) {+ const cartId = await resolveSplitOrderCartId(container, {+ order_id: event.data.id,+ })++ if (!cartId) {+ return+ }++ await voidCanceledCartPaymentWorkflow(container).run({+ input: { cart_id: cartId },+ })+}++export const config: SubscriberConfig = {+ event: OrderWorkflowEvents.CANCELED,+ context: {+ subscriberId: "mercur-split-order-canceled",+ },+}diff --git a/packages/core/src/subscribers/split-order-payment-captured.ts b/packages/core/src/subscribers/split-order-payment-captured.tsnew file mode 100644index 000000000..19abd09fb--- /dev/null+++ b/packages/core/src/subscribers/split-order-payment-captured.ts@@ -0,0 +1,31 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"+import { PaymentEvents } from "@medusajs/framework/utils"++import {+ resolveSplitOrderCartId,+ splitCapturedCartPaymentWorkflow,+} from "../workflows/payment"++export default async function splitOrderPaymentCapturedHandler({+ event,+ container,+}: SubscriberArgs<{ id: string }>) {+ const cartId = await resolveSplitOrderCartId(container, {+ payment_id: event.data.id,+ })++ if (!cartId) {+ return+ }++ await splitCapturedCartPaymentWorkflow(container).run({+ input: { cart_id: cartId },+ })+}++export const config: SubscriberConfig = {+ event: PaymentEvents.CAPTURED,+ context: {+ subscriberId: "mercur-split-order-payment-captured",+ },+}diff --git a/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts b/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.tsindex cf9588f97..ada951ef9 100644--- a/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts+++ b/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts@@ -8,7 +8,6 @@ import {} from "@medusajs/framework/types"import {generateEntityId,- MathBN,Modules,OrderStatus,OrderWorkflowEvents,@@ -23,7 +22,6 @@ import {} from "@medusajs/framework/workflows-sdk"import {acquireLockStep,- addOrderTransactionStep,authorizePaymentSessionStep,createOrdersStep,createRemoteLinkStep,@@ -50,6 +48,7 @@ import {prepareTaxLinesData,} from "../utils"import { registerUsageStep } from "../../promotion"+import { splitCapturedCartPaymentWorkflow } from "../../payment/workflows/split-order-payments"import { refreshOrderCommissionLinesWorkflow } from "../../commission/workflows/refresh-order-commission-lines"import {prepareOfferInventoryInput,@@ -523,13 +522,10 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(})}- // The cart's payment collection is shared across every- // split order, but Medusa's order↔payment_collection link is- // one-to-one on the payment-collection side, so it cannot be- // linked to more than one order. Each order already links to- // the cart, and the cart links to the payment collection, so- // the shared collection stays reachable per order via- // `order.cart.payment_collection`.+ // Orders are not linked to the cart's payment collection:+ // Medusa allows a payment collection only one order. They+ // share it through the cart until the payment is captured,+ // when each order gets a payment collection of its own.links.push(...Object.entries(sellerOrdersMap).map(([sellerId, orderId]) => ({[Modules.ORDER]: { order_id: orderId },@@ -593,46 +589,27 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(id: paymentSessions![0].id,})- const orderTransactions = transform(- { payment, createdOrders },- ({ payment, createdOrders }) => {- if (!payment?.captures?.length) {- return []- }-- const transactions = createdOrders.flatMap((order) => {- const proportion = MathBN.div(order.total, payment.amount)+ const orderIds = transform({ createdOrders }, ({ createdOrders }) => {+ return createdOrders.map((order) => order.id)+ })- return (payment.captures ?? []).map((capture) => {- const captureAmount = capture.raw_amount ?? capture.amount- const proportionalAmount = MathBN.mult(captureAmount, proportion)+ // A provider that captures on authorization leaves the payment+ // captured here; one captured later is split from the+ // `payment.captured` subscriber.+ const splitPaymentInput = transform({ payment, cart: cartData.data }, ({ cart }) => {+ return { cart_id: cart.id }+ })- return {- order_id: order.id,- amount: proportionalAmount,- currency_code: payment.currency_code,- reference: "capture",- reference_id: capture.id,- }- })- })+ splitCapturedCartPaymentWorkflow.runAsStep({+ input: splitPaymentInput,+ })- return transactions+ refreshOrderCommissionLinesWorkflow.runAsStep({+ input: {+ order_ids: orderIds}- )-- const orderIds = transform({ createdOrders }, ({ createdOrders }) => {- return createdOrders.map((order) => order.id)})- parallelize(- addOrderTransactionStep(orderTransactions),- refreshOrderCommissionLinesWorkflow.runAsStep({- input: {- order_ids: orderIds- }- }))-createHook("orderGroupCreated", {order_group_id: createdOrderGroup.id,cart_id: cartData.data.id,diff --git a/packages/core/src/workflows/order-group/workflows/get-order-group-detail.ts b/packages/core/src/workflows/order-group/workflows/get-order-group-detail.tsindex 627b33600..8cae672da 100644--- a/packages/core/src/workflows/order-group/workflows/get-order-group-detail.ts+++ b/packages/core/src/workflows/order-group/workflows/get-order-group-detail.ts@@ -8,6 +8,8 @@ import {} from "@medusajs/framework/workflows-sdk"import { useQueryGraphStep } from "@medusajs/medusa/core-flows"+import { resolveOrderPaymentCollections } from "../../payment/utils/split-order-payment-group"+import {getLastFulfillmentStatus,getLastPaymentStatus,@@ -36,6 +38,11 @@ export const getOrderGroupDetailWorkflow = createWorkflow("orders.cart.payment_collection.amount","orders.cart.payment_collection.captured_amount","orders.cart.payment_collection.refunded_amount",+ "orders.cart.payment_collection.metadata",+ "orders.payment_collections.status",+ "orders.payment_collections.amount",+ "orders.payment_collections.captured_amount",+ "orders.payment_collections.refunded_amount","orders.fulfillments.packed_at","orders.fulfillments.shipped_at","orders.fulfillments.delivered_at",@@ -68,16 +75,16 @@ export const getOrderGroupDetailWorkflow = createWorkflow(if (orderGroup.orders) {for (const order of orderGroup.orders) {const order_ = order as OrderDetailDTO & {- cart?: { payment_collection?: unknown }+ cart?: {+ payment_collection?: {+ metadata?: Record<string, unknown> | null+ } | null+ }}- // The shared cart payment collection is fetched via- // `cart.payment_collection`; expose it under `payment_collections`- // so the status helper and API response keep the same shape.- const cartPaymentCollection = order_.cart?.payment_collection- order_.payment_collections = cartPaymentCollection- ? [cartPaymentCollection as OrderDetailDTO["payment_collections"][number]]- : []+ order_.payment_collections = resolveOrderPaymentCollections(+ order_+ ) as OrderDetailDTO["payment_collections"]order_.payment_status = getLastPaymentStatus(order_diff --git a/packages/core/src/workflows/order-group/workflows/get-order-groups-list.ts b/packages/core/src/workflows/order-group/workflows/get-order-groups-list.tsindex bba2685ff..d2aa30973 100644--- a/packages/core/src/workflows/order-group/workflows/get-order-groups-list.ts+++ b/packages/core/src/workflows/order-group/workflows/get-order-groups-list.ts@@ -8,6 +8,8 @@ import {} from "@medusajs/framework/workflows-sdk"import { useQueryGraphStep } from "@medusajs/medusa/core-flows"+import { resolveOrderPaymentCollections } from "../../payment/utils/split-order-payment-group"+import {getLastFulfillmentStatus,getLastPaymentStatus,@@ -45,6 +47,11 @@ export const getOrderGroupsListWorkflow = createWorkflow("orders.cart.payment_collection.amount","orders.cart.payment_collection.captured_amount","orders.cart.payment_collection.refunded_amount",+ "orders.cart.payment_collection.metadata",+ "orders.payment_collections.status",+ "orders.payment_collections.amount",+ "orders.payment_collections.captured_amount",+ "orders.payment_collections.refunded_amount","orders.fulfillments.packed_at","orders.fulfillments.shipped_at","orders.fulfillments.delivered_at",@@ -93,16 +100,16 @@ export const getOrderGroupsListWorkflow = createWorkflow(for (const order of group.orders) {const order_ = order as OrderDetailDTO & {- cart?: { payment_collection?: unknown }+ cart?: {+ payment_collection?: {+ metadata?: Record<string, unknown> | null+ } | null+ }}- // The shared cart payment collection is fetched via- // `cart.payment_collection`; expose it under `payment_collections`- // so the status helper and API response keep the same shape.- const cartPaymentCollection = order_.cart?.payment_collection- order_.payment_collections = cartPaymentCollection- ? [cartPaymentCollection as OrderDetailDTO["payment_collections"][number]]- : []+ order_.payment_collections = resolveOrderPaymentCollections(+ order_+ ) as OrderDetailDTO["payment_collections"]order_.payment_status = getLastPaymentStatus(order_diff --git a/packages/core/src/workflows/payment/index.ts b/packages/core/src/workflows/payment/index.tsindex e399489e8..ba99b3a8e 100644--- a/packages/core/src/workflows/payment/index.ts+++ b/packages/core/src/workflows/payment/index.ts@@ -1 +1,3 @@+export * from "./steps"+export * from "./utils"export * from "./workflows"diff --git a/packages/core/src/workflows/payment/steps/create-order-payments.ts b/packages/core/src/workflows/payment/steps/create-order-payments.tsnew file mode 100644index 000000000..8f285c451--- /dev/null+++ b/packages/core/src/workflows/payment/steps/create-order-payments.ts@@ -0,0 +1,113 @@+import { BigNumberInput } from "@medusajs/framework/types"+import { Modules, PaymentSessionStatus } from "@medusajs/framework/utils"+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"++/**+ * The payments to create.+ */+export type CreateOrderPaymentsStepInput = {+ /**+ * The ID of the payment collection the payment belongs to.+ */+ payment_collection_id: string+ /**+ * The ID of the provider holding the charge.+ */+ provider_id: string+ /**+ * The payment's currency code.+ */+ currency_code: string+ /**+ * The amount the payment is authorized for.+ */+ amount: BigNumberInput+ /**+ * The provider data of the charge the payment points at.+ */+ data: Record<string, unknown>+}[]++type SessionRow = CreateOrderPaymentsStepInput[number] & {+ status: PaymentSessionStatus+ authorized_at: Date+}++type PaymentRow = CreateOrderPaymentsStepInput[number] & {+ payment_session: string+}++// `createPaymentSession` always opens a new session at the provider, which+// would charge the customer a second time. These payments point at a charge+// that already exists, so their rows are written with the methods the module+// service generates for its models. They are on the service, not on+// `IPaymentModuleService`.+type PaymentRowService = {+ createPaymentSessions(data: SessionRow[]): Promise<{ id: string }[]>+ createPayments(+ data: PaymentRow[]+ ): Promise<{ id: string; payment_collection_id: string }[]>+ deletePayments(ids: string[]): Promise<void>+ deletePaymentSessions(ids: string[]): Promise<void>+}++export const createOrderPaymentsStepId = "create-order-payments"+/**+ * This step creates authorized payments for a charge that already exists at+ * the payment provider, without contacting the provider.+ *+ * @example+ * const payments = createOrderPaymentsStep([{+ * payment_collection_id: "pay_col_123",+ * provider_id: "pp_stripe_stripe",+ * currency_code: "usd",+ * amount: 40,+ * data: { id: "pi_123" }+ * }])+ */+export const createOrderPaymentsStep = createStep(+ createOrderPaymentsStepId,+ async (input: CreateOrderPaymentsStepInput, { container }) => {+ if (!input?.length) {+ return new StepResponse([], { payment_ids: [], session_ids: [] })+ }++ const service = container.resolve(+ Modules.PAYMENT+ ) as unknown as PaymentRowService++ const authorizedAt = new Date()+ const sessions = await service.createPaymentSessions(+ input.map((payment) => ({+ ...payment,+ status: PaymentSessionStatus.AUTHORIZED,+ authorized_at: authorizedAt,+ }))+ )+ const sessionIds = sessions.map((session) => session.id)++ const payments = await service.createPayments(+ input.map((payment, index) => ({+ ...payment,+ payment_session: sessionIds[index],+ }))+ )++ return new StepResponse(payments, {+ payment_ids: payments.map((payment) => payment.id),+ session_ids: sessionIds,+ })+ },+ async (created, { container }) => {+ if (!created?.session_ids.length) {+ return+ }++ const service = container.resolve(+ Modules.PAYMENT+ ) as unknown as PaymentRowService++ await service.deletePayments(created.payment_ids)+ await service.deletePaymentSessions(created.session_ids)+ }+)diff --git a/packages/core/src/workflows/payment/steps/index.ts b/packages/core/src/workflows/payment/steps/index.tsnew file mode 100644index 000000000..105ea8a78--- /dev/null+++ b/packages/core/src/workflows/payment/steps/index.ts@@ -0,0 +1,2 @@+export * from "./create-order-payments"+export * from "./record-payment-captures"diff --git a/packages/core/src/workflows/payment/steps/record-payment-captures.ts b/packages/core/src/workflows/payment/steps/record-payment-captures.tsnew file mode 100644index 000000000..569f69101--- /dev/null+++ b/packages/core/src/workflows/payment/steps/record-payment-captures.ts@@ -0,0 +1,47 @@+import { BigNumberInput, PaymentDTO } from "@medusajs/framework/types"+import { Modules } from "@medusajs/framework/utils"+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"++/**+ * The captures to record.+ */+export type RecordPaymentCapturesStepInput = {+ /**+ * The ID of the payment the capture belongs to.+ */+ payment_id: string+ /**+ * The captured amount.+ */+ amount: BigNumberInput+}[]++export const recordPaymentCapturesStepId = "record-payment-captures"+/**+ * This step records captures the payment provider has already made, without+ * capturing at the provider again.+ *+ * It is not compensated, like Medusa's `capturePaymentStep`: the money was+ * captured before the step ran.+ *+ * @example+ * const payments = recordPaymentCapturesStep([{+ * payment_id: "pay_123",+ * amount: 40+ * }])+ */+export const recordPaymentCapturesStep = createStep(+ recordPaymentCapturesStepId,+ async (input: RecordPaymentCapturesStepInput, { container }) => {+ const paymentModule = container.resolve(Modules.PAYMENT)+ const payments: PaymentDTO[] = []++ for (const capture of input ?? []) {+ payments.push(+ await paymentModule.capturePayment({ ...capture, is_captured: true })+ )+ }++ return new StepResponse(payments)+ }+)diff --git a/packages/core/src/workflows/payment/utils/__tests__/split-order-payment.unit.spec.ts b/packages/core/src/workflows/payment/utils/__tests__/split-order-payment.unit.spec.tsnew file mode 100644index 000000000..bc34cdd32--- /dev/null+++ b/packages/core/src/workflows/payment/utils/__tests__/split-order-payment.unit.spec.ts@@ -0,0 +1,303 @@+import { MathBN } from "@medusajs/framework/utils"++import { allocateProportionally } from "../split-order-payment"+import {+ planCartPaymentSplit,+ planCartPaymentVoid,+ resolveOrderPaymentCollections,+ SplitOrderGroupCollection,+ SplitOrderGroupOrder,+} from "../split-order-payment-group"++const toNumbers = (values: { toNumber(): number }[]) =>+ values.map((value) => value.toNumber())++describe("allocateProportionally", () => {+ it("splits by weight", () => {+ const shares = allocateProportionally({+ amount: 200,+ weights: [98, 102],+ decimalDigits: 2,+ })++ expect(toNumbers(shares)).toEqual([98, 102])+ })++ it("rounds to the currency precision and still sums to the amount", () => {+ const shares = allocateProportionally({+ amount: 100,+ weights: [1, 1, 1],+ decimalDigits: 2,+ })++ expect(toNumbers(shares)).toEqual([33.34, 33.33, 33.33])+ expect(MathBN.sum(...shares).toNumber()).toEqual(100)+ })++ it("gives the leftover units to the largest fractions", () => {+ const shares = allocateProportionally({+ amount: 10,+ weights: [1, 5, 1],+ decimalDigits: 0,+ })++ expect(toNumbers(shares)).toEqual([2, 7, 1])+ })++ it("never allocates more than the amount when it is below the weights", () => {+ const shares = allocateProportionally({+ amount: 150,+ weights: [98, 102],+ decimalDigits: 2,+ })++ expect(toNumbers(shares)).toEqual([73.5, 76.5])+ })++ it("splits evenly when every weight is zero", () => {+ const shares = allocateProportionally({+ amount: 10,+ weights: [0, 0],+ decimalDigits: 2,+ })++ expect(toNumbers(shares)).toEqual([5, 5])+ })+})++describe("resolveOrderPaymentCollections", () => {+ const own = { id: "pay_col_order" }++ it("uses the order's own collections once the cart payment is split", () => {+ const collections = resolveOrderPaymentCollections({+ payment_collections: [own],+ cart: {+ payment_collection: { metadata: { split_order_collections: true } },+ },+ })++ expect(collections).toEqual([own])+ })++ it("keeps the cart collection for an order that never got its own", () => {+ const shared = {+ id: "pay_col_cart",+ metadata: { split_order_collections: true },+ }++ expect(+ resolveOrderPaymentCollections({+ payment_collections: [],+ cart: { payment_collection: shared },+ })+ ).toEqual([shared])+ })++ it("uses the cart collection until the cart payment is split", () => {+ const shared = { id: "pay_col_cart", metadata: null }++ expect(+ resolveOrderPaymentCollections({+ payment_collections: [],+ cart: { payment_collection: shared },+ })+ ).toEqual([shared])+ })++ it("uses the linked collections when the cart is not loaded", () => {+ expect(+ resolveOrderPaymentCollections({ payment_collections: [own] })+ ).toEqual([own])+ })+})++const cartCollection = (+ captures: number[],+ overrides: Partial<SplitOrderGroupCollection> = {}+): SplitOrderGroupCollection => ({+ id: "pay_col_cart",+ currency_code: "usd",+ metadata: null,+ payments: [+ {+ id: "pay_cart",+ provider_id: "pp_stripe_stripe",+ currency_code: "usd",+ amount: 200,+ data: { id: "pi_123" },+ captures: captures.map((amount, index) => ({+ id: `capt_cart_${index}`,+ amount,+ })),+ refunds: [],+ },+ ],+ ...overrides,+})++const order = (+ id: string,+ total: number,+ overrides: Partial<SplitOrderGroupOrder> = {}+): SplitOrderGroupOrder => ({+ id,+ status: "pending",+ canceled_at: null,+ total,+ payment_collections: [],+ ...overrides,+})++const splitOrder = (id: string, total: number, captured: number) =>+ order(id, total, {+ payment_collections: [+ {+ id: `pay_col_${id}`,+ currency_code: "usd",+ metadata: { cart_payment_collection_id: "pay_col_cart" },+ payments: [+ {+ id: `pay_${id}`,+ provider_id: "pp_stripe_stripe",+ currency_code: "usd",+ amount: total,+ captures: [{ id: `capt_${id}`, amount: captured }],+ refunds: [],+ },+ ],+ },+ ],+ })++const amountsOf = (rows: { amount: unknown }[]) =>+ rows.map((row) => MathBN.convert(row.amount as number).toNumber())++describe("planCartPaymentSplit", () => {+ it("plans nothing before the cart payment is captured", () => {+ const plan = planCartPaymentSplit(cartCollection([]), [+ order("order_a", 98),+ order("order_b", 102),+ ])++ expect(plan.collections).toEqual([])+ expect(plan.captures).toEqual([])+ })++ it("gives every order a collection, a payment and a capture for its share", () => {+ const plan = planCartPaymentSplit(cartCollection([200]), [+ order("order_a", 98),+ order("order_b", 102),+ ])++ expect(amountsOf(plan.collections)).toEqual([98, 102])+ expect(plan.payments.map((p) => p.provider_id)).toEqual([+ "pp_stripe_stripe",+ "pp_stripe_stripe",+ ])+ expect(plan.payments[0].data).toEqual({ id: "pi_123" })+ expect(amountsOf(plan.captures)).toEqual([98, 102])+ expect(plan.refunds).toEqual([])+ expect(plan.cart_payment_collection?.metadata).toEqual({+ split_order_collections: true,+ })+ })++ it("plans nothing new for a cart that is already split", () => {+ const plan = planCartPaymentSplit(+ cartCollection([200], { metadata: { split_order_collections: true } }),+ [splitOrder("order_a", 98, 98), splitOrder("order_b", 102, 102)]+ )++ expect(plan.collections).toEqual([])+ expect(plan.payments).toEqual([])+ expect(plan.captures).toEqual([])+ expect(plan.refunds).toEqual([])+ expect(plan.cart_payment_collection).toBeUndefined()+ expect(plan.recorded.map((c) => c.capture_id)).toEqual([+ "capt_order_a",+ "capt_order_b",+ ])+ })++ it("refunds the share of an order canceled before the capture", () => {+ const plan = planCartPaymentSplit(cartCollection([200]), [+ order("order_a", 98, { status: "canceled" }),+ order("order_b", 102),+ ])++ expect(plan.collections.map((c) => c.order_id)).toEqual(["order_b"])+ expect(amountsOf(plan.captures)).toEqual([102])+ expect(plan.refunds.map((r) => r.payment_id)).toEqual(["pay_cart"])+ expect(amountsOf(plan.refunds)).toEqual([98])+ })++ it("reuses a collection left without a payment", () => {+ const plan = planCartPaymentSplit(cartCollection([200]), [+ order("order_a", 98, {+ payment_collections: [+ {+ id: "pay_col_order_a",+ currency_code: "usd",+ metadata: { cart_payment_collection_id: "pay_col_cart" },+ payments: [],+ },+ ],+ }),+ order("order_b", 102),+ ])++ expect(plan.collections.map((c) => c.order_id)).toEqual(["order_b"])+ expect(plan.payments.map((p) => p.payment_collection_id)).toEqual([+ "pay_col_order_a",+ undefined,+ ])+ })++ it("adds only what a later partial capture brings", () => {+ const plan = planCartPaymentSplit(+ cartCollection([100, 100], {+ metadata: { split_order_collections: true },+ }),+ [splitOrder("order_a", 98, 49), splitOrder("order_b", 102, 51)]+ )++ expect(plan.payments).toEqual([])+ expect(plan.captures.map((c) => c.payment_id)).toEqual([+ "pay_order_a",+ "pay_order_b",+ ])+ expect(amountsOf(plan.captures)).toEqual([49, 51])+ })+})++describe("planCartPaymentVoid", () => {+ it("voids once every order is canceled", () => {+ expect(+ planCartPaymentVoid(cartCollection([]), [+ order("order_a", 98, { status: "canceled" }),+ order("order_b", 102, { status: "canceled" }),+ ])+ ).toEqual({+ payment_ids: ["pay_cart"],+ payment_collection_ids: ["pay_col_cart"],+ })+ })++ it("keeps the authorization while an order is open", () => {+ expect(+ planCartPaymentVoid(cartCollection([]), [+ order("order_a", 98, { status: "canceled" }),+ order("order_b", 102),+ ]).payment_ids+ ).toEqual([])+ })++ it("does not void a captured payment", () => {+ expect(+ planCartPaymentVoid(cartCollection([200]), [+ order("order_a", 98, { status: "canceled" }),+ order("order_b", 102, { status: "canceled" }),+ ]).payment_ids+ ).toEqual([])+ })+})diff --git a/packages/core/src/workflows/payment/utils/index.ts b/packages/core/src/workflows/payment/utils/index.tsnew file mode 100644index 000000000..09690d40f--- /dev/null+++ b/packages/core/src/workflows/payment/utils/index.ts@@ -0,0 +1,2 @@+export * from "./split-order-payment"+export * from "./split-order-payment-group"diff --git a/packages/core/src/workflows/payment/utils/split-order-payment-group.ts b/packages/core/src/workflows/payment/utils/split-order-payment-group.tsnew file mode 100644index 000000000..a872921b6--- /dev/null+++ b/packages/core/src/workflows/payment/utils/split-order-payment-group.ts@@ -0,0 +1,423 @@+import {+ BigNumberInput,+ LinkDefinition,+ MedusaContainer,+} from "@medusajs/framework/types"+import {+ ContainerRegistrationKeys,+ MathBN,+ Modules,+ OrderStatus,+} from "@medusajs/framework/utils"++import {+ allocateProportionally,+ getCurrencyDecimalDigits,+} from "./split-order-payment"++/** Set on a cart's payment collection once it is split into its orders'. */+export const SPLIT_ORDER_COLLECTIONS_FLAG = "split_order_collections"++/** Set on an order's payment collection, pointing at the cart's. */+export const CART_PAYMENT_COLLECTION_KEY = "cart_payment_collection_id"++type PaymentMovement = {+ id: string+ amount: BigNumberInput+ raw_amount?: BigNumberInput | null+}++export type SplitOrderGroupPayment = {+ id: string+ provider_id: string+ currency_code: string+ amount: BigNumberInput+ raw_amount?: BigNumberInput | null+ data?: Record<string, unknown> | null+ captured_at?: Date | string | null+ canceled_at?: Date | string | null+ captures?: PaymentMovement[] | null+ refunds?: PaymentMovement[] | null+}++export type SplitOrderGroupCollection = {+ id: string+ currency_code: string+ metadata?: Record<string, unknown> | null+ payments?: SplitOrderGroupPayment[] | null+}++export type SplitOrderGroupOrder = {+ id: string+ status: string+ canceled_at?: Date | string | null+ total: BigNumberInput+ payment_collections?: SplitOrderGroupCollection[] | null+}++const PAYMENT_FIELDS = [+ "id",+ "provider_id",+ "currency_code",+ "amount",+ "raw_amount",+ "data",+ "captured_at",+ "canceled_at",+ "captures.id",+ "captures.amount",+ "captures.raw_amount",+ "refunds.id",+ "refunds.amount",+ "refunds.raw_amount",+]++const COLLECTION_FIELDS = [+ "id",+ "currency_code",+ "metadata",+ ...PAYMENT_FIELDS.map((field) => `payments.${field}`),+]++/** Fields to query on `cart_payment_collection` to plan a split or a void. */+export const cartPaymentCollectionFields = COLLECTION_FIELDS.map(+ (field) => `payment_collection.${field}`+)++/** Fields to query on `order_cart` to plan a split or a void. */+export const cartOrderFields = [+ "order.id",+ "order.status",+ "order.canceled_at",+ "order.total",+ ...COLLECTION_FIELDS.map((field) => `order.payment_collections.${field}`),+]++const amountOf = (movement: {+ amount: BigNumberInput+ raw_amount?: BigNumberInput | null+}) => movement.raw_amount ?? movement.amount++const sum = (movements: PaymentMovement[] | null | undefined) =>+ (movements ?? []).reduce(+ (acc, movement) => MathBN.add(acc, amountOf(movement)),+ MathBN.convert(0)+ )++export const isPaymentCaptured = (payment: SplitOrderGroupPayment) =>+ !!payment.captured_at || (payment.captures ?? []).length > 0++export const isOrderCanceled = (order: {+ status: string+ canceled_at?: Date | string | null+}) => order.status === OrderStatus.CANCELED || !!order.canceled_at++export const hasSplitOrderCollections = (+ paymentCollection?: { metadata?: Record<string, unknown> | null } | null+) => paymentCollection?.metadata?.[SPLIT_ORDER_COLLECTIONS_FLAG] === true++/**+ * The payment collections that pay for an order. Until the cart payment is+ * captured that is the cart's shared collection; afterwards the order has its+ * own. An order canceled before the capture never gets one and keeps showing+ * the cart's.+ */+export const resolveOrderPaymentCollections = (order: {+ cart?: {+ payment_collection?: { metadata?: Record<string, unknown> | null } | null+ } | null+ payment_collections?: unknown[]+}): unknown[] => {+ const own = order.payment_collections ?? []+ const cartPaymentCollection = order.cart?.payment_collection++ if (!cartPaymentCollection) {+ return own+ }++ return hasSplitOrderCollections(cartPaymentCollection) && own.length+ ? own+ : [cartPaymentCollection]+}++/**+ * Resolves the cart a payment or an order belongs to. A payment can be the+ * cart's own or one created for an order when the cart payment was split.+ */+export const resolveSplitOrderCartId = async (+ container: MedusaContainer,+ input: { order_id: string } | { payment_id: string }+): Promise<string | undefined> => {+ const query = container.resolve(ContainerRegistrationKeys.QUERY)++ if ("order_id" in input) {+ const {+ data: [orderCart],+ } = await query.graph({+ entity: "order_cart",+ fields: ["cart_id"],+ filters: { order_id: input.order_id },+ })+ return orderCart?.cart_id+ }++ const {+ data: [payment],+ } = await query.graph({+ entity: "payment",+ fields: ["id", "payment_collection.id", "payment_collection.metadata"],+ filters: { id: input.payment_id },+ })++ const collection = payment?.payment_collection as+ | { id: string; metadata?: Record<string, unknown> | null }+ | undefined++ if (!collection) {+ return undefined+ }++ const {+ data: [cartLink],+ } = await query.graph({+ entity: "cart_payment_collection",+ fields: ["cart_id"],+ filters: {+ payment_collection_id:+ (collection.metadata?.[CART_PAYMENT_COLLECTION_KEY] as+ | string+ | undefined) ?? collection.id,+ },+ })++ return cartLink?.cart_id+}++const getCartPayment = (collection?: SplitOrderGroupCollection | null) =>+ (collection?.payments ?? []).find((payment) => !payment.canceled_at)++const getOrderCollection = (+ order: SplitOrderGroupOrder,+ cartCollectionId: string+) =>+ (order.payment_collections ?? []).find(+ (collection) =>+ collection.metadata?.[CART_PAYMENT_COLLECTION_KEY] === cartCollectionId+ )++export type CartPaymentSplitPlan = {+ /** Payment collections to create, one per order that has none yet. */+ collections: {+ order_id: string+ currency_code: string+ amount: BigNumberInput+ metadata: Record<string, unknown>+ }[]+ /**+ * Payments to create. `payment_collection_id` is unset for an order whose+ * collection is created in the same run.+ */+ payments: {+ order_id: string+ payment_collection_id?: string+ provider_id: string+ currency_code: string+ amount: BigNumberInput+ data: Record<string, unknown>+ }[]+ /**+ * Captures to record. `payment_id` is unset for an order whose payment is+ * created in the same run.+ */+ captures: {+ order_id: string+ payment_id?: string+ amount: BigNumberInput+ }[]+ /**+ * Captures the orders' payments already hold. Their order transactions are+ * written again on every run, which is a no-op unless an earlier run stopped+ * between recording a capture and writing its transaction.+ */+ recorded: {+ order_id: string+ currency_code: string+ capture_id: string+ amount: BigNumberInput+ }[]+ /** What was charged for orders canceled before the capture. */+ refunds: { payment_id: string; amount: BigNumberInput; note: string }[]+ /** Set when the cart collection still has to be flagged as split. */+ cart_payment_collection?: {+ id: string+ metadata: Record<string, unknown>+ }+}++const EMPTY_PLAN: CartPaymentSplitPlan = {+ collections: [],+ payments: [],+ captures: [],+ recorded: [],+ refunds: [],+}++/**+ * Works out what is missing for every order of a cart to hold its share of+ * what the cart payment has captured. Only ever plans the difference, so a+ * cart that is already split yields an empty plan.+ */+export const planCartPaymentSplit = (+ cartCollection: SplitOrderGroupCollection | null | undefined,+ orders: SplitOrderGroupOrder[]+): CartPaymentSplitPlan => {+ const cartPayment = getCartPayment(cartCollection)++ if (!cartCollection || !cartPayment || !orders.length) {+ return EMPTY_PLAN+ }++ const captured = sum(cartPayment.captures)++ if (!MathBN.gt(captured, 0)) {+ return EMPTY_PLAN+ }++ const decimalDigits = getCurrencyDecimalDigits(cartPayment.currency_code)+ const weights = orders.map((order) => order.total)++ // What each order is entitled to of the authorization, and of the part of+ // it captured so far.+ const shares = allocateProportionally({+ amount: amountOf(cartPayment),+ weights,+ decimalDigits,+ })+ const targets = allocateProportionally({+ amount: captured,+ weights,+ decimalDigits,+ })++ const plan: CartPaymentSplitPlan = {+ collections: [],+ payments: [],+ captures: [],+ recorded: [],+ refunds: [],+ }+ let attributed = MathBN.convert(0)++ orders.forEach((order, index) => {+ const collection = getOrderCollection(order, cartCollection.id)+ const payment = collection?.payments?.[0]+ const recorded = sum(payment?.captures)+ const missing = MathBN.sub(targets[index], recorded)++ attributed = MathBN.add(attributed, recorded)++ for (const capture of payment?.captures ?? []) {+ plan.recorded.push({+ order_id: order.id,+ currency_code: cartPayment.currency_code,+ capture_id: capture.id,+ amount: amountOf(capture),+ })+ }++ // An order canceled before the capture is not paid: its part of the+ // charge stays unattributed and is refunded.+ if (isOrderCanceled(order) || !MathBN.gt(missing, 0)) {+ return+ }++ if (!collection) {+ plan.collections.push({+ order_id: order.id,+ currency_code: cartPayment.currency_code,+ amount: shares[index],+ metadata: { [CART_PAYMENT_COLLECTION_KEY]: cartCollection.id },+ })+ }++ if (!payment) {+ plan.payments.push({+ order_id: order.id,+ payment_collection_id: collection?.id,+ provider_id: cartPayment.provider_id,+ currency_code: cartPayment.currency_code,+ amount: shares[index],+ data: cartPayment.data ?? {},+ })+ }++ plan.captures.push({+ order_id: order.id,+ payment_id: payment?.id,+ amount: missing,+ })+ attributed = MathBN.add(attributed, missing)+ })++ const unattributed = MathBN.sub(+ captured,+ attributed,+ sum(cartPayment.refunds)+ )++ if (MathBN.gt(unattributed, 0)) {+ plan.refunds.push({+ payment_id: cartPayment.id,+ amount: unattributed,+ note: "Share of orders canceled before the payment was captured",+ })+ }++ if (!hasSplitOrderCollections(cartCollection)) {+ plan.cart_payment_collection = {+ id: cartCollection.id,+ metadata: {+ ...cartCollection.metadata,+ [SPLIT_ORDER_COLLECTIONS_FLAG]: true,+ },+ }+ }++ return plan+}++/** The links between the orders and the payment collections created for them. */+export const buildOrderPaymentCollectionLinks = (+ plan: CartPaymentSplitPlan,+ createdCollections: { id: string }[]+): LinkDefinition[] =>+ plan.collections.map((collection, index) => ({+ [Modules.ORDER]: { order_id: collection.order_id },+ [Modules.PAYMENT]: { payment_collection_id: createdCollections[index].id },+ }))++/**+ * The cart payment to void: set once every order of the cart is canceled and+ * nothing of the payment was captured.+ */+export const planCartPaymentVoid = (+ cartCollection: SplitOrderGroupCollection | null | undefined,+ orders: SplitOrderGroupOrder[]+): { payment_ids: string[]; payment_collection_ids: string[] } => {+ const cartPayment = getCartPayment(cartCollection)++ if (+ !cartCollection ||+ !cartPayment ||+ !orders.length ||+ isPaymentCaptured(cartPayment) ||+ !orders.every(isOrderCanceled)+ ) {+ return { payment_ids: [], payment_collection_ids: [] }+ }++ return {+ payment_ids: [cartPayment.id],+ payment_collection_ids: [cartCollection.id],+ }+}diff --git a/packages/core/src/workflows/payment/utils/split-order-payment.ts b/packages/core/src/workflows/payment/utils/split-order-payment.tsnew file mode 100644index 000000000..2cb3d5267--- /dev/null+++ b/packages/core/src/workflows/payment/utils/split-order-payment.ts@@ -0,0 +1,93 @@+import { BigNumberInput } from "@medusajs/framework/types"+import { defaultCurrencies, MathBN } from "@medusajs/framework/utils"++type BigNumberValue = ReturnType<typeof MathBN.convert>++const DEFAULT_DECIMAL_DIGITS = 2++export const getCurrencyDecimalDigits = (currencyCode?: string | null) => {+ const currency = defaultCurrencies[(currencyCode ?? "").toUpperCase()]+ return currency?.decimal_digits ?? DEFAULT_DECIMAL_DIGITS+}++const floorTo = (value: BigNumberValue, decimalDigits: number) => {+ const rounded = MathBN.convert(value, decimalDigits)+ if (MathBN.lte(rounded, value)) {+ return rounded+ }+ return MathBN.sub(rounded, MathBN.div(1, MathBN.convert(10).pow(decimalDigits)))+}++/**+ * Splits `amount` across `weights` proportionally. Shares are rounded down to+ * the currency precision and the remainder is handed out one minor unit at a+ * time to the largest fractions, so the shares always sum exactly to `amount`.+ */+export const allocateProportionally = ({+ amount,+ weights,+ decimalDigits,+}: {+ amount: BigNumberInput+ weights: BigNumberInput[]+ decimalDigits: number+}): BigNumberValue[] => {+ if (!weights.length) {+ return []+ }++ const total = MathBN.convert(amount)+ const positiveWeights = weights.map((weight) =>+ MathBN.max(MathBN.convert(weight), 0)+ )+ const weightSum = positiveWeights.reduce(+ (acc, weight) => MathBN.add(acc, weight),+ MathBN.convert(0)+ )+ const effectiveWeights = MathBN.gt(weightSum, 0)+ ? positiveWeights+ : positiveWeights.map(() => MathBN.convert(1))+ const effectiveSum = MathBN.gt(weightSum, 0)+ ? weightSum+ : MathBN.convert(effectiveWeights.length)++ const unit = MathBN.div(1, MathBN.convert(10).pow(decimalDigits))+ const exact = effectiveWeights.map((weight) =>+ MathBN.div(MathBN.mult(total, weight), effectiveSum)+ )+ const shares = exact.map((share) => floorTo(share, decimalDigits))++ let leftover = MathBN.sub(+ total,+ shares.reduce((acc, share) => MathBN.add(acc, share), MathBN.convert(0))+ )++ const byLargestFraction = exact+ .map((share, index) => ({+ index,+ fraction: MathBN.sub(share, shares[index]),+ }))+ .sort((a, b) =>+ MathBN.eq(a.fraction, b.fraction)+ ? a.index - b.index+ : MathBN.gt(a.fraction, b.fraction)+ ? -1+ : 1+ )++ for (const { index } of byLargestFraction) {+ if (MathBN.lt(leftover, unit)) {+ break+ }+ shares[index] = MathBN.add(shares[index], unit)+ leftover = MathBN.sub(leftover, unit)+ }++ // Only reachable when `amount` itself is finer than the currency precision.+ if (MathBN.gt(leftover, 0)) {+ const { index } = byLargestFraction[0]+ shares[index] = MathBN.add(shares[index], leftover)+ }++ return shares+}diff --git a/packages/core/src/workflows/payment/workflows/index.ts b/packages/core/src/workflows/payment/workflows/index.tsindex c53f91a7e..6ee4a443d 100644--- a/packages/core/src/workflows/payment/workflows/index.ts+++ b/packages/core/src/workflows/payment/workflows/index.ts@@ -1,2 +1,3 @@export * from "./process-payment"export * from "./payment-hooks"+export * from "./split-order-payments"diff --git a/packages/core/src/workflows/payment/workflows/split-order-payments.ts b/packages/core/src/workflows/payment/workflows/split-order-payments.tsnew file mode 100644index 000000000..6c655abdf--- /dev/null+++ b/packages/core/src/workflows/payment/workflows/split-order-payments.ts@@ -0,0 +1,288 @@+import { PaymentCollectionStatus, PaymentEvents } from "@medusajs/framework/utils"+import {+ createWorkflow,+ transform,+ when,+ WorkflowResponse,+} from "@medusajs/framework/workflows-sdk"+import {+ acquireLockStep,+ addOrderTransactionStep,+ cancelPaymentStep,+ createPaymentCollectionsStep,+ createRemoteLinkStep,+ emitEventStep,+ refundPaymentsStep,+ releaseLockStep,+ updatePaymentCollectionStep,+ useQueryGraphStep,+} from "@medusajs/medusa/core-flows"++import { createOrderPaymentsStep } from "../steps/create-order-payments"+import { recordPaymentCapturesStep } from "../steps/record-payment-captures"+import {+ buildOrderPaymentCollectionLinks,+ cartOrderFields,+ cartPaymentCollectionFields,+ planCartPaymentSplit,+ planCartPaymentVoid,+ SplitOrderGroupCollection,+ SplitOrderGroupOrder,+} from "../utils"++/**+ * The cart whose payment to split.+ */+export type SplitCapturedCartPaymentWorkflowInput = {+ /**+ * The ID of the cart.+ */+ cart_id: string+}++const LOCK_TIMEOUT_SECONDS = 30+const LOCK_TTL_SECONDS = 120++type CartPaymentCollectionLink = {+ payment_collection?: SplitOrderGroupCollection | null+}++type CartOrderLink = { order?: SplitOrderGroupOrder | null }++const toOrders = (links: CartOrderLink[]) =>+ links.flatMap((link) => link.order ?? [])++export const splitCapturedCartPaymentWorkflowId = "split-captured-cart-payment"+/**+ * This workflow splits a captured cart payment between the orders of the+ * cart. Every order gets a payment collection of its own, linked to the order,+ * with a captured payment for the order's share on the cart payment's provider+ * and pointing at the same charge, so Medusa's refund and cancel workflows+ * apply to the order. What was charged for orders canceled before the capture+ * is refunded against the cart payment.+ *+ * The workflow only adds what is missing: it does nothing until the cart+ * payment has a capture, and nothing when run again for the same capture.+ *+ * @example+ * const { result } = await splitCapturedCartPaymentWorkflow(container)+ * .run({+ * input: {+ * cart_id: "cart_123",+ * }+ * })+ *+ * @summary+ *+ * Split a captured cart payment into a payment per order.+ */+export const splitCapturedCartPaymentWorkflow = createWorkflow(+ splitCapturedCartPaymentWorkflowId,+ (input: SplitCapturedCartPaymentWorkflowInput) => {+ // Not the cart id itself: checkout holds that lock while it runs this+ // workflow as a step.+ const lockKey = transform(+ { input },+ ({ input }) => `split-order-payment:${input.cart_id}`+ )++ acquireLockStep({+ key: lockKey,+ timeout: LOCK_TIMEOUT_SECONDS,+ ttl: LOCK_TTL_SECONDS,+ })++ const cartPaymentQuery = useQueryGraphStep({+ entity: "cart_payment_collection",+ fields: cartPaymentCollectionFields,+ filters: { cart_id: input.cart_id },+ }).config({ name: "get-cart-payment-collection" })++ const cartOrdersQuery = useQueryGraphStep({+ entity: "order_cart",+ fields: cartOrderFields,+ filters: { cart_id: input.cart_id },+ }).config({ name: "get-cart-orders" })++ const plan = transform(+ { cartPaymentQuery, cartOrdersQuery },+ ({ cartPaymentQuery, cartOrdersQuery }) =>+ planCartPaymentSplit(+ (cartPaymentQuery.data[0] as CartPaymentCollectionLink | undefined)+ ?.payment_collection,+ toOrders(cartOrdersQuery.data as CartOrderLink[])+ )+ )++ const collections = createPaymentCollectionsStep(plan.collections)++ const links = transform({ plan, collections }, ({ plan, collections }) =>+ buildOrderPaymentCollectionLinks(plan, collections)+ )++ createRemoteLinkStep(links).config({+ name: "link-order-payment-collections",+ })++ const paymentsToCreate = transform(+ { plan, collections },+ ({ plan, collections }) => {+ const createdByOrder = new Map(+ plan.collections.map((collection, index) => [+ collection.order_id,+ collections[index].id,+ ])+ )++ return plan.payments.map(({ order_id, ...payment }) => ({+ ...payment,+ payment_collection_id:+ payment.payment_collection_id ??+ (createdByOrder.get(order_id) as string),+ }))+ }+ )++ const payments = createOrderPaymentsStep(paymentsToCreate)++ const capturesToRecord = transform(+ { plan, payments },+ ({ plan, payments }) => {+ const createdByOrder = new Map(+ plan.payments.map((payment, index) => [+ payment.order_id,+ payments[index].id,+ ])+ )++ return plan.captures.map((capture) => ({+ payment_id:+ capture.payment_id ??+ (createdByOrder.get(capture.order_id) as string),+ amount: capture.amount,+ }))+ }+ )++ const capturedPayments = recordPaymentCapturesStep(capturesToRecord)++ const orderTransactions = transform(+ { plan, capturedPayments },+ ({ plan, capturedPayments }) => [+ ...plan.recorded.map((capture) => ({+ order_id: capture.order_id,+ amount: capture.amount,+ currency_code: capture.currency_code,+ reference: "capture",+ reference_id: capture.capture_id,+ })),+ ...capturedPayments.flatMap((payment, index) =>+ (payment.captures ?? []).map((capture) => ({+ order_id: plan.captures[index].order_id,+ amount: capture.raw_amount ?? capture.amount,+ currency_code: payment.currency_code,+ reference: "capture",+ reference_id: capture.id,+ }))+ ),+ ]+ )++ addOrderTransactionStep(orderTransactions)++ when("flag-cart-payment-collection", { plan }, ({ plan }) => {+ return !!plan.cart_payment_collection+ }).then(() => {+ updatePaymentCollectionStep({+ selector: { id: plan.cart_payment_collection!.id },+ update: { metadata: plan.cart_payment_collection!.metadata },+ })+ })++ refundPaymentsStep(plan.refunds)++ const capturedEvents = transform(+ { capturedPayments },+ ({ capturedPayments }) =>+ capturedPayments.map((payment) => ({ id: payment.id }))+ )++ emitEventStep({+ eventName: PaymentEvents.CAPTURED,+ data: capturedEvents,+ })++ releaseLockStep({ key: lockKey })++ return new WorkflowResponse(capturedPayments)+ }+)++/**+ * The cart whose payment to void.+ */+export type VoidCanceledCartPaymentWorkflowInput = {+ /**+ * The ID of the cart.+ */+ cart_id: string+}++export const voidCanceledCartPaymentWorkflowId = "void-canceled-cart-payment"+/**+ * This workflow voids a cart's payment once every order of the cart is+ * canceled. Until it is captured, the authorization is shared by the cart's+ * orders, so canceling a single order leaves it in place. The workflow does+ * nothing while an order is still open or once the payment is captured.+ *+ * @example+ * const { result } = await voidCanceledCartPaymentWorkflow(container)+ * .run({+ * input: {+ * cart_id: "cart_123",+ * }+ * })+ *+ * @summary+ *+ * Void a cart's payment when all of its orders are canceled.+ */+export const voidCanceledCartPaymentWorkflow = createWorkflow(+ voidCanceledCartPaymentWorkflowId,+ (input: VoidCanceledCartPaymentWorkflowInput) => {+ const cartPaymentQuery = useQueryGraphStep({+ entity: "cart_payment_collection",+ fields: cartPaymentCollectionFields,+ filters: { cart_id: input.cart_id },+ }).config({ name: "get-cart-payment-collection" })++ const cartOrdersQuery = useQueryGraphStep({+ entity: "order_cart",+ fields: cartOrderFields,+ filters: { cart_id: input.cart_id },+ }).config({ name: "get-cart-orders" })++ const plan = transform(+ { cartPaymentQuery, cartOrdersQuery },+ ({ cartPaymentQuery, cartOrdersQuery }) =>+ planCartPaymentVoid(+ (cartPaymentQuery.data[0] as CartPaymentCollectionLink | undefined)+ ?.payment_collection,+ toOrders(cartOrdersQuery.data as CartOrderLink[])+ )+ )++ cancelPaymentStep({ paymentIds: plan.payment_ids })++ when("cancel-cart-payment-collection", { plan }, ({ plan }) => {+ return plan.payment_collection_ids.length > 0+ }).then(() => {+ updatePaymentCollectionStep({+ selector: { id: plan.payment_collection_ids },+ update: { status: PaymentCollectionStatus.CANCELED },+ })+ })++ return new WorkflowResponse(plan)+ }+)