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
fix(core): keep split-order cart completion consistent across crashes (#1745)
Viktor Holik5485672481a0
diff --git a/apps/docs/platform/order-group/reference/workflows.mdx b/apps/docs/platform/order-group/reference/workflows.mdxindex b92998688..549826492 100644--- a/apps/docs/platform/order-group/reference/workflows.mdx+++ b/apps/docs/platform/order-group/reference/workflows.mdx@@ -38,12 +38,12 @@ The workflow stores its execution (`store: true`) and keeps it for 3 days. It ho### Steps-The workflow runs these steps in order. Steps 3 to 6 run only when no group exists for the cart:+The workflow runs these steps in order. Steps 3 to 6 run only when the cart has no `order_cart` link yet, so a cart counts as completed once its orders are linked to it:-1. `acquireLockStep` on the cart id, then a query for an existing group and the cart.-2. `validateCartPaymentsStep`, then the `validate` and `setOrderStatus` hooks.+1. `acquireLockStep` on the cart id, then queries for the cart's `order_cart` links, an existing group, and the cart.+2. `validateCartItemsStep`, `validateCartPaymentsStep` and `compensatePaymentIfNeededStep`, then the `validate` and `setOrderStatus` hooks.3. `validateSellerCartItemsStep` and `validateSellerCartShippingStep`.-4. `createOrderGroupStep` and `createOrdersStep`, in parallel.+4. `createOrderGroupStep`, then `createOrdersStep`.5. `createRemoteLinkStep`, `mirrorLineItemOfferLinksToOrderStep`, `updateCartsStep` to set `completed_at`, `reserveInventoryStep`, `registerUsageStep`, and two `emitEventStep` calls.6. `authorizePaymentSessionStep`, then `splitCapturedCartPaymentWorkflow` and `refreshOrderCommissionLinesWorkflow` as steps.7. `releaseLockStep` on the cart id.@@ -88,11 +88,11 @@ It returns `{ rows, metadata }`, where `metadata` holds `count`, `skip`, and `ta## createOrderGroupStep-Creates one `OrderGroup` record. Step id `create-order-group`.+Creates one `OrderGroup` record, or returns the cart's existing group when there is one. Step id `create-order-group`.| Input | Type | Description || --- | --- | --- || `cart_id` | `string` | The completed cart || `customer_id` | `string \| null`, optional | The customer on the cart |-It returns the created group. On rollback, it deletes the group with `deleteOrderGroups`. Use it in your own workflow only when you also create and link the child orders yourself.+It returns the group. On rollback, it deletes the group with `deleteOrderGroups` only if the step created it. Use it in your own workflow only when you also create and link the child orders yourself.diff --git a/integration-tests/http/order/store/split-order-completion-recovery.spec.ts b/integration-tests/http/order/store/split-order-completion-recovery.spec.tsnew file mode 100644index 000000000..b49cdcae8--- /dev/null+++ b/integration-tests/http/order/store/split-order-completion-recovery.spec.ts@@ -0,0 +1,246 @@+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import {+ IRegionModuleService,+ ISalesChannelModuleService,+ MedusaContainer,+} from "@medusajs/framework/types"+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"+import { MercurModules } from "@mercurjs/types"+import { createCustomerUser } from "../../../helpers/create-customer-user"+import {+ adminHeaders,+ createAdminUser,+ generatePublishableKey,+ generateStoreHeaders,+} from "../../../helpers/create-admin-user"+import { seedSellerOfferWithShipping } from "../../../helpers/split-order-checkout"++jest.setTimeout(180000)++medusaIntegrationTestRunner({+ testSuite: ({ getContainer, api, dbConnection }) => {+ describe("Store - split order completion recovery", () => {+ let appContainer: MedusaContainer+ let storeHeaders: { headers: Record<string, string> }+ let customerId: string+ let customerEmail: string+ let region: { id: string }+ let salesChannel: { id: string }+ let sellerA: Awaited<ReturnType<typeof seedSellerOfferWithShipping>>+ let sellerB: Awaited<ReturnType<typeof seedSellerOfferWithShipping>>++ beforeAll(async () => {+ appContainer = getContainer()+ })++ beforeEach(async () => {+ await createAdminUser(dbConnection, adminHeaders, appContainer)++ const customerResult = await createCustomerUser(appContainer, {+ email: "[email protected]",+ first_name: "Recovery",+ last_name: "Buyer",+ })+ customerId = customerResult.customer.id+ customerEmail = customerResult.customer.email!+ const apiKey = await generatePublishableKey(appContainer)+ const baseStoreHeaders = generateStoreHeaders({+ publishableKey: apiKey,+ })+ storeHeaders = {+ headers: {+ ...baseStoreHeaders.headers,+ ...customerResult.headers.headers,+ },+ }++ salesChannel = await appContainer+ .resolve<ISalesChannelModuleService>(Modules.SALES_CHANNEL)+ .createSalesChannels({ name: "Recovery Channel" })++ region = await appContainer+ .resolve<IRegionModuleService>(Modules.REGION)+ .createRegions({+ name: "Recovery Region",+ currency_code: "usd",+ countries: ["us"],+ })++ await appContainer.resolve(ContainerRegistrationKeys.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: "RecoveryA",+ stocked: 10,+ offerPrice: 1000,+ })+ sellerB = await seedSellerOfferWithShipping({+ container: appContainer,+ api,+ salesChannelId: salesChannel.id,+ email: "[email protected]",+ name: "RecoveryB",+ stocked: 10,+ offerPrice: 2000,+ })+ })++ const prepareCart = async (): Promise<string> => {+ const cart = (+ await api.post(+ `/store/carts`,+ {+ region_id: region.id,+ sales_channel_id: salesChannel.id,+ currency_code: "usd",+ },+ storeHeaders+ )+ ).data.cart++ for (const offerId of [sellerA.offer.id, sellerB.offer.id]) {+ await api.post(+ `/store/carts/${cart.id}/line-items`,+ { offer_id: offerId, quantity: 1 },+ storeHeaders+ )+ }++ const address = {+ first_name: "Buyer",+ last_name: "Test",+ address_1: "123 Main St",+ city: "New York",+ country_code: "us",+ postal_code: "10001",+ }+ await api.post(+ `/store/carts/${cart.id}`,+ {+ email: customerEmail,+ shipping_address: address,+ billing_address: address,+ },+ storeHeaders+ )++ const options = Object.values(+ (+ await api.get(+ `/store/shipping-options?cart_id=${cart.id}`,+ storeHeaders+ )+ ).data.shipping_options as Record<string, { id: string }[]>+ ).flat()+ for (const option of options) {+ await api.post(+ `/store/carts/${cart.id}/shipping-methods`,+ { option_id: option.id },+ storeHeaders+ )+ }++ const paymentCollection = (+ await api.post(+ `/store/payment-collections`,+ { cart_id: cart.id },+ storeHeaders+ )+ ).data.payment_collection+ await api.post(+ `/store/payment-collections/${paymentCollection.id}/payment-sessions`,+ { provider_id: "pp_system_default" },+ storeHeaders+ )++ return cart.id+ }++ const completeCart = async (cartId: string): Promise<string> =>+ (await api.post(`/store/carts/${cartId}/complete`, {}, storeHeaders))+ .data.order_group.id++ const getCartState = async (cartId: string) => {+ const query = appContainer.resolve(ContainerRegistrationKeys.QUERY)+ const [+ { data: orderGroups },+ { data: orderCarts },+ { data: orders },+ { data: carts },+ ] = await Promise.all([+ query.graph({+ entity: "order_group",+ fields: ["id", "orders.id"],+ filters: { cart_id: cartId },+ }),+ query.graph({+ entity: "order_cart",+ fields: ["order_id"],+ filters: { cart_id: cartId },+ }),+ query.graph({+ entity: "order",+ fields: ["id"],+ filters: { customer_id: customerId },+ }),+ query.graph({+ entity: "cart",+ fields: ["completed_at"],+ filters: { id: cartId },+ }),+ ])++ return {+ orderGroups: orderGroups as { id: string; orders: { id: string }[] }[],+ orderCartOrderIds: orderCarts.map((link) => link.order_id),+ customerOrderIds: orders.map((order) => order.id),+ completedAt: carts[0].completed_at,+ }+ }++ it("reuses the order group left by a completion that stopped before creating orders", async () => {+ const cartId = await prepareCart()++ const leftoverGroup = await appContainer+ .resolve(MercurModules.SELLER)+ .createOrderGroups({ cart_id: cartId, customer_id: customerId })++ const orderGroupId = await completeCart(cartId)++ expect(orderGroupId).toBe(leftoverGroup.id)++ const state = await getCartState(cartId)+ expect(state.orderGroups).toHaveLength(1)+ expect(state.orderGroups[0].orders).toHaveLength(2)+ expect(state.orderCartOrderIds).toHaveLength(2)+ expect(state.customerOrderIds.sort()).toEqual(+ state.orderGroups[0].orders.map((order) => order.id).sort()+ )+ expect(state.completedAt).toBeTruthy()+ })++ it("returns the same order group without creating orders when a completed cart is completed again", async () => {+ const cartId = await prepareCart()++ const firstOrderGroupId = await completeCart(cartId)+ const before = await getCartState(cartId)++ const secondOrderGroupId = await completeCart(cartId)+ const after = await getCartState(cartId)++ expect(secondOrderGroupId).toBe(firstOrderGroupId)+ expect(after.orderGroups).toHaveLength(1)+ expect(after.customerOrderIds.sort()).toEqual(+ before.customerOrderIds.sort()+ )+ expect(after.customerOrderIds).toHaveLength(2)+ })+ })+ },+})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 7b5c93845..cebe9ea5e 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@@ -32,6 +32,7 @@ import {reserveInventoryStep,updateCartsStep,useQueryGraphStep,+ validateCartItemsStep,validateCartPaymentsStep,} from "@medusajs/medusa/core-flows"import { CreateOrderGroupDTO, MercurModules, SellerDTO } from "@mercurjs/types"@@ -97,7 +98,14 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(executeOnSubWorkflow: true,})- const [orderGroup, cartData] = parallelize(+ const [orderCart, orderGroup, cartData] = parallelize(+ useQueryGraphStep({+ entity: "order_cart",+ fields: ["cart_id", "order_id"],+ filters: { cart_id: input.cart_id },+ }).config({+ name: "order-cart-query",+ }),useQueryGraphStep({entity: "order_group",fields: ["id", "cart_id"],@@ -105,6 +113,8 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(options: {isList: false,},+ }).config({+ name: "order-group-query",}),useQueryGraphStep({entity: "cart",@@ -118,9 +128,15 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(}))- const orderGroupId = transform({ orderGroup }, ({ orderGroup }) => {- return orderGroup?.data?.id- })+ const { isCompleted, existingOrderGroupId } = transform(+ { orderCart, orderGroup },+ ({ orderCart, orderGroup }) => ({+ isCompleted: orderCart.data.length > 0,+ existingOrderGroupId: orderGroup?.data?.id as string | undefined,+ })+ )++ validateCartItemsStep({ cart: cartData.data })const paymentSessions = validateCartPaymentsStep({ cart: cartData.data })compensatePaymentIfNeededStep({@@ -141,8 +157,10 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(cart: cartData.data,})- const createdOrderGroup = when("create-order-group", { orderGroupId }, ({ orderGroupId }) => {- return !orderGroupId+ // Orders are only linked to the cart once they exist, so the order_cart+ // link (not the order group) marks a completed cart, as in Medusa.+ const createdOrderGroup = when("create-order-group", { isCompleted }, ({ isCompleted }) => {+ return !isCompleted}).then(() => {const cartOptionIds = transform({ cart: cartData.data }, ({ cart }) => {return cart.shipping_methods?.map((sm) => sm.shipping_option_id)@@ -422,10 +440,11 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow()- const [createdOrderGroup, createdOrders] = parallelize(- createOrderGroupStep(orderGroupData),- createOrdersStep(ordersToCreate)- )+ // The group is persisted before the orders so a crash can't leave+ // an order without one.+ const createdOrderGroup = createOrderGroupStep(orderGroupData)++ const createdOrders = createOrdersStep(ordersToCreate)const orderLineOfferPairs = transform({ createdOrders, offerIdsByOrderId },@@ -676,9 +695,12 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(executeOnSubWorkflow: true,})- const result = transform({ createdOrderGroup, orderGroupId }, ({ createdOrderGroup, orderGroupId }) => {- return { order_group_id: createdOrderGroup?.id ?? orderGroupId }- })+ const result = transform(+ { createdOrderGroup, existingOrderGroupId },+ ({ createdOrderGroup, existingOrderGroupId }) => {+ return { order_group_id: createdOrderGroup?.id ?? existingOrderGroupId }+ }+ )return new WorkflowResponse(result, {hooks: [validate, setOrderStatus],diff --git a/packages/core/src/workflows/order-group/steps/create-order-group.ts b/packages/core/src/workflows/order-group/steps/create-order-group.tsindex 064250c9f..747bd254e 100644--- a/packages/core/src/workflows/order-group/steps/create-order-group.ts+++ b/packages/core/src/workflows/order-group/steps/create-order-group.ts@@ -1,20 +1,39 @@import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"-import { CreateOrderGroupDTO, MercurModules } from "@mercurjs/types"+import { CreateOrderGroupDTO, MercurModules, OrderGroupDTO } from "@mercurjs/types"import SellerModuleService from "../../../modules/seller/service"type CreateOrderGroupStepInput = CreateOrderGroupDTO+type CreateOrderGroupStepOutput = Pick<+ OrderGroupDTO,+ "id" | "display_id" | "cart_id" | "customer_id"+>+export const createOrderGroupStep = createStep("create-order-group",async (input: CreateOrderGroupStepInput, { container }) => {const service = container.resolve<SellerModuleService>(MercurModules.SELLER)+ // A completion interrupted before its orders were created leaves the group+ // behind; reuse it so a retry doesn't create a second one for the cart.+ const [existing] = await service.listOrderGroups({ cart_id: input.cart_id })++ if (existing) {+ return new StepResponse<CreateOrderGroupStepOutput, string | null>(+ existing,+ null+ )+ }+const orderGroup = await service.createOrderGroups(input)- return new StepResponse(orderGroup, orderGroup.id)+ return new StepResponse<CreateOrderGroupStepOutput, string | null>(+ orderGroup,+ orderGroup.id+ )},- async (id: string, { container }) => {+ async (id: string | null, { container }) => {if (!id) {return}