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(cart): compensate marketplace writes when checkout is canceled after completion (#1729)
Viktor Holikd974ce4bc22a
diff --git a/packages/core/src/workflows/cart/steps/link-line-item-to-offer.ts b/packages/core/src/workflows/cart/steps/link-line-item-to-offer.tsindex 4e7311f39..b5c649019 100644--- a/packages/core/src/workflows/cart/steps/link-line-item-to-offer.ts+++ b/packages/core/src/workflows/cart/steps/link-line-item-to-offer.ts@@ -6,6 +6,8 @@ import {import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"import { MercurModules } from "@mercurjs/types"+import { dismissLinks } from "../../common/utils"+export type LinkLineItemToOfferInput = Array<{line_item_id: stringoffer_id: string@@ -44,6 +46,6 @@ export const linkLineItemToOfferStep = createStep(return}const link = container.resolve(ContainerRegistrationKeys.LINK)- await link.dismiss(createdLinks)+ await dismissLinks(link, createdLinks)},)diff --git a/packages/core/src/workflows/cart/steps/mirror-line-item-offer-links-to-order.ts b/packages/core/src/workflows/cart/steps/mirror-line-item-offer-links-to-order.tsindex ba9475b1f..f9dbc4518 100644--- a/packages/core/src/workflows/cart/steps/mirror-line-item-offer-links-to-order.ts+++ b/packages/core/src/workflows/cart/steps/mirror-line-item-offer-links-to-order.ts@@ -6,6 +6,8 @@ import {import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"import { MercurModules } from "@mercurjs/types"+import { dismissLinks } from "../../common/utils"+export type OrderLineItemOfferPair = {order_line_item_id: stringoffer_id: string@@ -49,6 +51,6 @@ export const mirrorLineItemOfferLinksToOrderStep = createStep(return}const link = container.resolve(ContainerRegistrationKeys.LINK)- await link.dismiss(createdLinks)+ await dismissLinks(link, createdLinks)},)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 d49d94297..b04dfc90e 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@@ -26,7 +26,6 @@ import {acquireLockStep,authorizePaymentSessionStep,createOrdersStep,- createRemoteLinkStep,emitEventStep,releaseLockStep,reserveInventoryStep,@@ -54,6 +53,7 @@ import {PromotionSellerIds,} from "../utils"import { registerUsageStep } from "../../promotion"+import { createLinksStep } from "../../common/steps"import { splitCapturedCartPaymentWorkflow } from "../../payment/workflows/split-order-payments"import { refreshOrderCommissionLinesWorkflow } from "../../commission/workflows/refresh-order-commission-lines"import {@@ -609,7 +609,7 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(})parallelize(- createRemoteLinkStep(linksToCreate),+ createLinksStep(linksToCreate),mirrorLineItemOfferLinksToOrderStep({pairs: orderLineOfferPairs,}),diff --git a/packages/core/src/workflows/commission/steps/upsert-commission-lines.ts b/packages/core/src/workflows/commission/steps/upsert-commission-lines.tsindex 6c837b106..c090201b7 100644--- a/packages/core/src/workflows/commission/steps/upsert-commission-lines.ts+++ b/packages/core/src/workflows/commission/steps/upsert-commission-lines.ts@@ -11,6 +11,29 @@ type UpsertCommissionLinesStepInput = {commission_lines: CreateCommissionLineDTO[]}+type UpsertCommissionLinesCompensation = {+ created_ids: string[]+ replaced: CommissionLineDTO[]+}++const anchorFilters = (lines: CreateCommissionLineDTO[]) => {+ const itemIds = lines+ .map((line) => line.item_id)+ .filter((id): id is string => !!id)+ const shippingMethodIds = lines+ .map((line) => line.shipping_method_id)+ .filter((id): id is string => !!id)++ const filters: Record<string, unknown>[] = []+ if (itemIds.length) {+ filters.push({ item_id: itemIds })+ }+ if (shippingMethodIds.length) {+ filters.push({ shipping_method_id: shippingMethodIds })+ }+ return filters+}+export const upsertCommissionLinesStepId = "upsert-commission-lines"export const upsertCommissionLinesStep = createStep(@@ -18,19 +41,59 @@ export const upsertCommissionLinesStep = createStep(async (input: UpsertCommissionLinesStepInput,{ container }- ): Promise<StepResponse<CommissionLineDTO[]>> => {+ ): Promise<+ StepResponse<CommissionLineDTO[], UpsertCommissionLinesCompensation>+ > => {if (!input.commission_lines.length) {- return new StepResponse([])+ return new StepResponse([], { created_ids: [], replaced: [] })}const service = container.resolve<CommissionModuleService>(MercurModules.COMMISSION)+ const filters = anchorFilters(input.commission_lines)+ const replaced = filters.length+ ? await service.listCommissionLines({ $or: filters })+ : []+const commissionLines = await service.upsertCommissionLines(input.commission_lines)- return new StepResponse(commissionLines)+ return new StepResponse(commissionLines, {+ created_ids: commissionLines.map((line) => line.id),+ replaced,+ })+ },+ async (compensation, { container }) => {+ if (!compensation?.created_ids.length) {+ return+ }++ const service = container.resolve<CommissionModuleService>(+ MercurModules.COMMISSION+ )++ // Restore each anchor to its pre-step state: remove the lines the step+ // wrote, then put back the ones it replaced.+ await service.deleteCommissionLines(compensation.created_ids)++ const replacedLines = compensation.replaced.map((line) => ({+ id: line.id,+ item_id: line.item_id,+ shipping_method_id: line.shipping_method_id,+ commission_rate_id: line.commission_rate_id,+ provider_id: line.provider_id,+ code: line.code,+ rate: line.rate,+ amount: line.amount,+ description: line.description,+ data: line.data,+ }))++ if (replacedLines.length) {+ await service.createCommissionLines(replacedLines)+ }})diff --git a/packages/core/src/workflows/commission/workflows/refresh-order-commission-lines.ts b/packages/core/src/workflows/commission/workflows/refresh-order-commission-lines.tsindex 056f9e4c7..bcb7cd409 100644--- a/packages/core/src/workflows/commission/workflows/refresh-order-commission-lines.ts+++ b/packages/core/src/workflows/commission/workflows/refresh-order-commission-lines.ts@@ -46,6 +46,10 @@ export type RefreshOrderCommissionLinesWorkflowInput = {export const refreshOrderCommissionLinesWorkflowId = "refresh-order-commission-lines"+// Checkout runs this as a step of a stored workflow; compensating it there needs+// a stored execution of its own, kept as long as checkout keeps its own.+const THREE_DAYS = 3 * 24 * 60 * 60+/*** `setCommissionContext` receives the contexts built from the orders. A* handler returns `new StepResponse(contexts)` with `additional_context`@@ -72,7 +76,11 @@ export const refreshOrderCommissionLinesWorkflow: ReturnWorkflow<CommissionLineDTO[],RefreshOrderCommissionLinesWorkflowHooks> = createWorkflow(- refreshOrderCommissionLinesWorkflowId,+ {+ name: refreshOrderCommissionLinesWorkflowId,+ store: true,+ retentionTime: THREE_DAYS,+ },function (input: WorkflowData<RefreshOrderCommissionLinesWorkflowInput>) {diff --git a/packages/core/src/workflows/common/index.ts b/packages/core/src/workflows/common/index.tsnew file mode 100644index 000000000..2f4890486--- /dev/null+++ b/packages/core/src/workflows/common/index.ts@@ -0,0 +1,2 @@+export * from "./steps"+export * from "./utils"diff --git a/packages/core/src/workflows/common/steps/create-links.ts b/packages/core/src/workflows/common/steps/create-links.tsnew file mode 100644index 000000000..a12377e6c--- /dev/null+++ b/packages/core/src/workflows/common/steps/create-links.ts@@ -0,0 +1,39 @@+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"+import { LinkDefinition } from "@medusajs/framework/types"+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"++import { dismissLinks } from "../utils"++export const createLinksStepId = "create-links"+/**+ * This step creates links between records, like Medusa's+ * `createRemoteLinkStep`. Its compensation dismisses the links no matter in+ * which order their modules come back from the stored workflow state.+ *+ * @example+ * createLinksStep([{+ * [Modules.ORDER]: { order_id: "order_123" },+ * [MercurModules.SELLER]: { seller_id: "sel_123" }+ * }])+ */+export const createLinksStep = createStep(+ createLinksStepId,+ async (input: LinkDefinition[], { container }) => {+ if (!input?.length) {+ return new StepResponse([], [])+ }++ const link = container.resolve(ContainerRegistrationKeys.LINK)+ const links = await link.create(input)++ return new StepResponse(links, input)+ },+ async (createdLinks, { container }) => {+ if (!createdLinks?.length) {+ return+ }++ const link = container.resolve(ContainerRegistrationKeys.LINK)+ await dismissLinks(link, createdLinks)+ }+)diff --git a/packages/core/src/workflows/common/steps/index.ts b/packages/core/src/workflows/common/steps/index.tsnew file mode 100644index 000000000..a55824e3e--- /dev/null+++ b/packages/core/src/workflows/common/steps/index.ts@@ -0,0 +1 @@+export * from "./create-links"diff --git a/packages/core/src/workflows/common/utils/__tests__/link-order.unit.spec.ts b/packages/core/src/workflows/common/utils/__tests__/link-order.unit.spec.tsnew file mode 100644index 000000000..782fb2f79--- /dev/null+++ b/packages/core/src/workflows/common/utils/__tests__/link-order.unit.spec.ts@@ -0,0 +1,40 @@+import { orderLinkModules } from "../link-order"++const registered = new Set(["order-order_id-offer-offer_id"])+const lookup = (a: string, aKey: string, b: string, bKey: string) =>+ registered.has([a, aKey, b, bKey].join("-")) || undefined++describe("orderLinkModules", () => {+ it("keeps a link whose modules are already in the registered order", () => {+ const link = {+ order: { order_id: "order_1" },+ offer: { offer_id: "offer_1" },+ }++ expect(orderLinkModules(link, lookup)).toBe(link)+ })++ it("restores the registered order after jsonb sorted the keys", () => {+ const link = {+ offer: { offer_id: "offer_1" },+ order: { order_id: "order_1" },+ data: { note: "kept" },+ }++ expect(Object.keys(orderLinkModules(link, lookup))).toEqual([+ "order",+ "offer",+ "data",+ ])+ expect(orderLinkModules(link, lookup).data).toEqual({ note: "kept" })+ })++ it("leaves a link alone when neither direction is registered", () => {+ const link = {+ cart: { cart_id: "cart_1" },+ order: { order_id: "order_1" },+ }++ expect(orderLinkModules(link, lookup)).toBe(link)+ })+})diff --git a/packages/core/src/workflows/common/utils/dismiss-links.ts b/packages/core/src/workflows/common/utils/dismiss-links.tsnew file mode 100644index 000000000..9f0b59ee0--- /dev/null+++ b/packages/core/src/workflows/common/utils/dismiss-links.ts@@ -0,0 +1,15 @@+import { Link } from "@medusajs/framework/modules-sdk"+import { LinkDefinition } from "@medusajs/framework/types"++import { orderLinkModules } from "./link-order"++export const dismissLinks = async (link: Link, links: LinkDefinition[]) => {+ if (!links.length) {+ return+ }++ const lookup = (a: string, aKey: string, b: string, bKey: string) =>+ link.getLinkModule(a, aKey, b, bKey)++ await link.dismiss(links.map((entry) => orderLinkModules(entry, lookup)))+}diff --git a/packages/core/src/workflows/common/utils/index.ts b/packages/core/src/workflows/common/utils/index.tsnew file mode 100644index 000000000..71a5b5ec0--- /dev/null+++ b/packages/core/src/workflows/common/utils/index.ts@@ -0,0 +1,2 @@+export * from "./dismiss-links"+export * from "./link-order"diff --git a/packages/core/src/workflows/common/utils/link-order.ts b/packages/core/src/workflows/common/utils/link-order.tsnew file mode 100644index 000000000..4078e541d--- /dev/null+++ b/packages/core/src/workflows/common/utils/link-order.ts@@ -0,0 +1,46 @@+import { LinkDefinition } from "@medusajs/framework/types"++export type LinkDirectionLookup = (+ moduleA: string,+ moduleAKey: string,+ moduleB: string,+ moduleBKey: string+) => unknown++/**+ * Link definitions are plain objects whose module order decides which link+ * module `Link.dismiss` resolves. Workflow state persisted in a `jsonb`+ * column comes back with its keys sorted, so a compensation that replays the+ * stored links can end up asking for a `cart-order` link that only exists+ * as `order-cart`. Swap the two modules back when only the reverse pair is+ * registered.+ */+export const orderLinkModules = (+ link: LinkDefinition,+ hasLinkModule: LinkDirectionLookup+): LinkDefinition => {+ const modules = Object.keys(link).filter((key) => key !== "data")+ if (modules.length !== 2) {+ return link+ }++ const [moduleA, moduleB] = modules+ const keyA = Object.keys(link[moduleA]).join(",")+ const keyB = Object.keys(link[moduleB]).join(",")++ if (+ hasLinkModule(moduleA, keyA, moduleB, keyB) ||+ !hasLinkModule(moduleB, keyB, moduleA, keyA)+ ) {+ return link+ }++ const reordered: LinkDefinition = {+ [moduleB]: link[moduleB],+ [moduleA]: link[moduleA],+ }+ if ("data" in link) {+ reordered.data = link.data+ }+ return reordered+}diff --git a/packages/core/src/workflows/index.ts b/packages/core/src/workflows/index.tsindex 94e8d2724..fff7152e5 100644--- a/packages/core/src/workflows/index.ts+++ b/packages/core/src/workflows/index.ts@@ -1,5 +1,6 @@import "../patches/register"+export * from "./common"export * from "./campaign"export * from "./customer-group"export * from "./commission"diff --git a/packages/core/src/workflows/payment/steps/record-payment-captures.ts b/packages/core/src/workflows/payment/steps/record-payment-captures.tsindex 569f69101..eaa63ee33 100644--- a/packages/core/src/workflows/payment/steps/record-payment-captures.ts+++ b/packages/core/src/workflows/payment/steps/record-payment-captures.ts@@ -16,13 +16,30 @@ export type RecordPaymentCapturesStepInput = {amount: BigNumberInput}[]+type RecordPaymentCapturesCompensation = {+ capture_ids: string[]+ /**+ * Payments the step marked as captured.+ */+ captured_payment_ids: string[]+}++// Captures are rows of the payment module, written by the methods the module+// service generates for its models; they are not on `IPaymentModuleService`.+type CaptureRowService = {+ deleteCaptures(ids: string[]): Promise<void>+ updatePayments(+ data: { id: string; captured_at: Date | null }[]+ ): Promise<unknown>+}+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.+ * Its compensation removes the capture records again; the provider is not+ * contacted, since the money was captured before the step ran.** @example* const payments = recordPaymentCapturesStep([{@@ -35,13 +52,55 @@ export const recordPaymentCapturesStep = createStep(async (input: RecordPaymentCapturesStepInput, { container }) => {const paymentModule = container.resolve(Modules.PAYMENT)const payments: PaymentDTO[] = []+ const compensation: RecordPaymentCapturesCompensation = {+ capture_ids: [],+ captured_payment_ids: [],+ }for (const capture of input ?? []) {- payments.push(- await paymentModule.capturePayment({ ...capture, is_captured: true })+ const before = await paymentModule.retrievePayment(capture.payment_id, {+ relations: ["captures"],+ })+ const knownCaptureIds = new Set(+ (before.captures ?? []).map((existing) => existing.id)+ )++ const payment = await paymentModule.capturePayment({+ ...capture,+ is_captured: true,+ })+ payments.push(payment)++ compensation.capture_ids.push(+ ...(payment.captures ?? [])+ .map((created) => created.id)+ .filter((id) => !knownCaptureIds.has(id)))+ if (!before.captured_at && payment.captured_at) {+ compensation.captured_payment_ids.push(payment.id)+ }+ }++ return new StepResponse(payments, compensation)+ },+ async (compensation, { container }) => {+ if (!compensation?.capture_ids.length) {+ return}- return new StepResponse(payments)+ const service = container.resolve(+ Modules.PAYMENT+ ) as unknown as CaptureRowService++ await service.deleteCaptures(compensation.capture_ids)++ if (compensation.captured_payment_ids.length) {+ await service.updatePayments(+ compensation.captured_payment_ids.map((id) => ({+ id,+ captured_at: null,+ }))+ )+ }})diff --git a/packages/core/src/workflows/payment/workflows/split-order-payments.ts b/packages/core/src/workflows/payment/workflows/split-order-payments.tsindex fe98da0a1..018c42af0 100644--- a/packages/core/src/workflows/payment/workflows/split-order-payments.ts+++ b/packages/core/src/workflows/payment/workflows/split-order-payments.ts@@ -11,7 +11,6 @@ import {addOrderTransactionStep,cancelPaymentStep,createPaymentCollectionsStep,- createRemoteLinkStep,emitEventStep,refundPaymentsStep,releaseLockStep,@@ -19,6 +18,7 @@ import {useQueryGraphStep,} from "@medusajs/medusa/core-flows"+import { createLinksStep } from "../../common/steps"import { createOrderPaymentsStep } from "../steps/create-order-payments"import { recordPaymentCapturesStep } from "../steps/record-payment-captures"import {@@ -42,6 +42,9 @@ export type SplitCapturedCartPaymentWorkflowInput = {}const LOCK_TIMEOUT_SECONDS = 30+// Checkout runs this as a step of a stored workflow; compensating it there needs+// a stored execution of its own, kept as long as checkout keeps its own.+const THREE_DAYS = 3 * 24 * 60 * 60const LOCK_TTL_SECONDS = 120type CartPaymentCollectionLink = {@@ -78,7 +81,11 @@ export const splitCapturedCartPaymentWorkflowId = "split-captured-cart-payment"* Split a captured cart payment into a payment per order.*/export const splitCapturedCartPaymentWorkflow = createWorkflow(- splitCapturedCartPaymentWorkflowId,+ {+ name: splitCapturedCartPaymentWorkflowId,+ store: true,+ retentionTime: THREE_DAYS,+ },(input: SplitCapturedCartPaymentWorkflowInput) => {// Not the cart id itself: checkout holds that lock while it runs this// workflow as a step.@@ -125,7 +132,7 @@ export const splitCapturedCartPaymentWorkflow = createWorkflow(buildOrderPaymentCollectionLinks(plan, collections))- createRemoteLinkStep(links).config({+ createLinksStep(links).config({name: "link-order-payment-collections",})