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): add payment, return and commission workflow hooks (#1558)
Viktor Holik00595c5afc54
diff --git a/integration-tests/jest.config.js b/integration-tests/jest.config.jsindex 952ff7db5..efe10946c 100644--- a/integration-tests/jest.config.js+++ b/integration-tests/jest.config.js@@ -5,10 +5,10 @@ loadEnv("test", process.cwd())module.exports = {transform: {- // Mercur patches two shipped core-flows files. Jest never consults Node's- // module hooks, so without this the patches are inert under test and the- // suite silently exercises unpatched code.- "node_modules[\\\\/].*core-flows[\\\\/]dist[\\\\/]cart[\\\\/].*\\.js$":+ // Mercur patches shipped core-flows cart and payment files. Jest never+ // consults Node's module hooks, so without this the patches are inert under+ // test and the suite silently exercises unpatched code.+ "node_modules[\\\\/].*core-flows[\\\\/]dist[\\\\/](cart|payment)[\\\\/].*\\.js$":"@mercurjs/core/patches/jest-transformer","^.+\\.[jt]s$": ["@swc/jest",@@ -22,9 +22,9 @@ module.exports = {},testEnvironment: "node",// Everything in node_modules is left untransformed except the core-flows cart- // files the patches target.+ // and payment files the patches target.transformIgnorePatterns: [- "/node_modules/(?!.*core-flows[\\\\/]dist[\\\\/]cart[\\\\/])",+ "/node_modules/(?!.*core-flows[\\\\/]dist[\\\\/](cart|payment)[\\\\/])",],moduleFileExtensions: ["js", "ts", "json"],modulePathIgnorePatterns: ["dist/"],diff --git a/packages/core/src/patches/README.md b/packages/core/src/patches/README.mdindex 2cb4d7034..d5afa38b0 100644--- a/packages/core/src/patches/README.md+++ b/packages/core/src/patches/README.md@@ -41,11 +41,11 @@ through `transformIgnorePatterns` (see `integration-tests/jest.config.js`):```jstransform: {- "node_modules[\\/].*core-flows[\\/]dist[\\/]cart[\\/].*\\.js$":+ "node_modules[\\/].*core-flows[\\/]dist[\\/](cart|payment)[\\/].*\\.js$":"@mercurjs/core/patches/jest-transformer","^.+\\.[jt]s$": ["@swc/jest", { /* ... */ }],},-transformIgnorePatterns: ["/node_modules/(?!.*core-flows[\\/]dist[\\/]cart[\\/])"],+transformIgnorePatterns: ["/node_modules/(?!.*core-flows[\\/]dist[\\/](cart|payment)[\\/])"],```Both paths funnel through `patchSourceForPath`, so a patch means the same thingdiff --git a/packages/core/src/patches/__tests__/jest-transformer.unit.spec.ts b/packages/core/src/patches/__tests__/jest-transformer.unit.spec.tsindex b32fb9528..ca307d08e 100644--- a/packages/core/src/patches/__tests__/jest-transformer.unit.spec.ts+++ b/packages/core/src/patches/__tests__/jest-transformer.unit.spec.ts@@ -49,6 +49,17 @@ describe("jest transformer", () => {expect(code).toContain("const shouldCleanupOrphanProfiles = false")})+ it.each([+ ["dist/payment/workflows/capture-payment.js", "paymentCaptured"],+ ["dist/payment/workflows/refund-payment.js", "paymentRefunded"],+ ])("exposes the payment hook in %s", (relativePath, hookName) => {+ const sourcePath = join(copy().dir, relativePath)+ const { code } = transform(readFileSync(sourcePath, "utf8"), sourcePath)++ expect(code).toContain(`createHook)("${hookName}"`)+ expect(code).toContain(`hooks: [${hookName}]`)+ })+it("leaves files it does not target untouched", () => {const source = "module.exports = 1\n"expect(transform(source, "/tmp/somewhere/else.js").code).toEqual(source)diff --git a/packages/core/src/patches/__tests__/patches.unit.spec.ts b/packages/core/src/patches/__tests__/patches.unit.spec.tsindex 484afc9a3..841b35262 100644--- a/packages/core/src/patches/__tests__/patches.unit.spec.ts+++ b/packages/core/src/patches/__tests__/patches.unit.spec.ts@@ -66,7 +66,11 @@ describe("patches", () => {for (const file of files) {const source = readFileSync(join(copy.dir, file.path), "utf8")- const contextLine = file.hunks[0].before.find((line) => line.trim())!+ // Doc-comment lines like " */" repeat throughout a .d.ts, so drift a+ // line that only occurs once or the replace lands outside the hunk.+ const contextLine = file.hunks[0].before.find(+ (line) => line.trim() && source.split(line).length === 2+ )!const drifted = source.replace(contextLine,`${contextLine} /* upstream moved */`diff --git a/packages/core/src/patches/index.ts b/packages/core/src/patches/index.tsindex 2220fcc45..001228296 100644--- a/packages/core/src/patches/index.ts+++ b/packages/core/src/patches/index.ts@@ -108,6 +108,7 @@ function applyToCopy(export function applyMercurPatches(options: ApplyPatchesOptions = {}): void {const disabled = new Set(options.disabled ?? [])const logger = options.logger ?? console+ const patchedPackages = new Set<string>()for (const entry of PATCHES) {if (disabled.has(entry.file)) {@@ -146,10 +147,17 @@ export function applyMercurPatches(options: ApplyPatchesOptions = {}): void {`${entry.package}`)- // Load the patched package now rather than leaving it to Medusa: the- // override only bites on first require, so failing here keeps the failure- // next to the patch that caused it.- require(entry.package)+ patchedPackages.add(entry.package)+ }++ // Load the patched packages now rather than leaving it to Medusa: the+ // override only bites on first require, so failing here keeps the failure+ // next to the patches that caused it. Deferred until every patch is+ // registered, because requiring a package after its first patch loads the+ // files a later patch targets unpatched, and the package index keeps+ // re-exporting those stale modules even after they are reloaded.+ for (const packageName of patchedPackages) {+ require(packageName)}}diff --git a/packages/core/src/patches/jest-transformer.ts b/packages/core/src/patches/jest-transformer.tsindex 80bef310c..a7f708337 100644--- a/packages/core/src/patches/jest-transformer.ts+++ b/packages/core/src/patches/jest-transformer.ts@@ -11,15 +11,15 @@ import { PATCHES } from "./manifest"// silently inert in every test suite — production and tests would disagree// about what the code does, which is worse than not patching at all.//-// Register it ahead of the project's own transform, and let the two patched-// files through `transformIgnorePatterns`:+// Register it ahead of the project's own transform, and let the patched files+// through `transformIgnorePatterns`://// transform: {-// "node_modules[\\\\/].*core-flows[\\\\/]dist[\\\\/]cart[\\\\/].*\\.js$":+// "node_modules[\\\\/].*core-flows[\\\\/]dist[\\\\/](cart|payment)[\\\\/].*\\.js$":// "@mercurjs/core/patches/jest-transformer",// "^.+\\.[jt]s$": ["@swc/jest", { ... }],// },-// transformIgnorePatterns: ["/node_modules/(?!.*core-flows[\\\\/]dist[\\\\/]cart[\\\\/])"],+// transformIgnorePatterns: ["/node_modules/(?!.*core-flows[\\\\/]dist[\\\\/](cart|payment)[\\\\/])"],type TransformOutput = { code: string }diff --git a/packages/core/src/patches/manifest.ts b/packages/core/src/patches/manifest.tsindex 86c037c50..af96e7cf2 100644--- a/packages/core/src/patches/manifest.ts+++ b/packages/core/src/patches/manifest.ts@@ -27,4 +27,15 @@ export const PATCHES: PatchEntry[] = ["is judged orphaned and checkout fails. The patch disables that cleanup. " +"See mercurjs/mercur#1442.",},+ {+ file: "@[email protected]",+ package: "@medusajs/core-flows",+ // Both targeted workflows are unchanged from 2.18.0 through 2.21.0.+ compatible: { from: "2.18.0", to: "2.22.0" },+ reason:+ "capturePaymentWorkflow and refundPaymentWorkflow end in an event and expose no " ++ "hook, unlike createOrderWorkflow and cancelOrderWorkflow. A ledger that must " ++ "record every capture and refund inside the movement's own transaction, with " ++ "compensation, needs paymentCaptured and paymentRefunded.",+ },]diff --git a/packages/core/src/patches/patches/@[email protected] b/packages/core/src/patches/patches/@[email protected]new file mode 100644index 000000000..4f187c84e--- /dev/null+++ b/packages/core/src/patches/patches/@[email protected]@@ -0,0 +1,89 @@+diff --git a/dist/payment/workflows/capture-payment.d.ts b/dist/payment/workflows/capture-payment.d.ts+index 1b495fa..1e2fe8c 100644+--- a/dist/payment/workflows/capture-payment.d.ts++++ b/dist/payment/workflows/capture-payment.d.ts+@@ -36,5 +36,11 @@ export declare const capturePaymentWorkflowId = "capture-payment-workflow";+ *+ * Capture a payment.+ */+-export declare const capturePaymentWorkflow: import("@medusajs/framework/workflows-sdk").ReturnWorkflow<CapturePaymentWorkflowInput, PaymentDTO, []>;++export declare const capturePaymentWorkflow: import("@medusajs/framework/workflows-sdk").ReturnWorkflow<CapturePaymentWorkflowInput, PaymentDTO, [++ import("@medusajs/framework/workflows-sdk").Hook<"paymentCaptured", {++ payment: PaymentDTO;++ order_id: string | null;++ amount: BigNumberInput | null;++ }, unknown>++]>;+ //# sourceMappingURL=capture-payment.d.ts.map+\ No newline at end of file+diff --git a/dist/payment/workflows/capture-payment.js b/dist/payment/workflows/capture-payment.js+index 404cfaf..e069e4d 100644+--- a/dist/payment/workflows/capture-payment.js++++ b/dist/payment/workflows/capture-payment.js+@@ -54,6 +54,16 @@ exports.capturePaymentWorkflow = (0, workflows_sdk_1.createWorkflow)(exports.cap+ eventName: utils_1.PaymentEvents.CAPTURED,+ data: { id: payment.id },+ });+- return new workflows_sdk_1.WorkflowResponse(payment);++ // MERCUR: payment has no hook where order has orderCreated / orderCanceled.++ // A ledger that must record every capture in the capture's own transaction++ // needs one; an event fires after commit and cannot be compensated.++ const paymentCaptured = (0, workflows_sdk_1.createHook)("paymentCaptured", {++ payment,++ order_id: (0, workflows_sdk_1.transform)({ orderPayment }, ({ orderPayment }) => orderPayment?.order?.id ?? null),++ amount: (0, workflows_sdk_1.transform)({ input }, ({ input }) => input.amount ?? null),++ });++ return new workflows_sdk_1.WorkflowResponse(payment, {++ hooks: [paymentCaptured],++ });+ });+ //# sourceMappingURL=capture-payment.js.map+\ No newline at end of file+diff --git a/dist/payment/workflows/refund-payment.d.ts b/dist/payment/workflows/refund-payment.d.ts+index 3848939..7ff118d 100644+--- a/dist/payment/workflows/refund-payment.d.ts++++ b/dist/payment/workflows/refund-payment.d.ts+@@ -58,5 +58,17 @@ export declare const refundPaymentWorkflowId = "refund-payment-workflow";+ *+ * Refund a payment.+ */+-export declare const refundPaymentWorkflow: import("@medusajs/framework/workflows-sdk").ReturnWorkflow<RefundPaymentWorkflowInput, any, []>;++export declare const refundPaymentWorkflow: import("@medusajs/framework/workflows-sdk").ReturnWorkflow<RefundPaymentWorkflowInput, any, [++ import("@medusajs/framework/workflows-sdk").Hook<"paymentRefunded", {++ payment: PaymentDTO;++ order_id: string | null;++ amount: BigNumberInput | null;++ credit_line_amount: BigNumberInput;++ refund_reason: {++ id: string;++ label: string;++ code: string | null;++ } | null;++ }, unknown>++]>;+ //# sourceMappingURL=refund-payment.d.ts.map+\ No newline at end of file+diff --git a/dist/payment/workflows/refund-payment.js b/dist/payment/workflows/refund-payment.js+index 5d19f53..dcd8b37 100644+--- a/dist/payment/workflows/refund-payment.js++++ b/dist/payment/workflows/refund-payment.js+@@ -145,6 +145,17 @@ exports.refundPaymentWorkflow = (0, workflows_sdk_1.createWorkflow)(exports.refu+ eventName: utils_1.PaymentEvents.REFUNDED,+ data: { id: payment.id },+ });+- return new workflows_sdk_1.WorkflowResponse(payment);++ // MERCUR: see capture-payment.js. A refund is the correction side of a++ // capture and needs the same in-transaction seam.++ const paymentRefunded = (0, workflows_sdk_1.createHook)("paymentRefunded", {++ payment: refundPayment,++ order_id: (0, workflows_sdk_1.transform)({ order }, ({ order }) => order?.id ?? null),++ amount: (0, workflows_sdk_1.transform)({ input }, ({ input }) => input.amount ?? null),++ credit_line_amount: creditLineAmount,++ refund_reason: (0, workflows_sdk_1.transform)({ refundReason }, ({ refundReason }) => refundReason ?? null),++ });++ return new workflows_sdk_1.WorkflowResponse(payment, {++ hooks: [paymentRefunded],++ });+ });+ //# sourceMappingURL=refund-payment.js.map+\ No newline at end of filediff --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 b0ea76ebf..7a023279a 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@@ -60,6 +60,9 @@ export const refreshOrderCommissionLinesWorkflowId = "refresh-order-commission-l* `setCommissionContext` receives the contexts built from the orders. A* handler returns `new StepResponse(contexts)` with `additional_context`* filled in, or nothing to leave the contexts as they are.+ *+ * `commissionLinesUpserted` runs after the lines are written, inside the same+ * transaction, so a consumer's failure rolls the refresh back.*/export type RefreshOrderCommissionLinesWorkflowHooks = [Hook<@@ -67,6 +70,11 @@ export type RefreshOrderCommissionLinesWorkflowHooks = [{ contexts: CommissionCalculationContext[] },CommissionCalculationContext[] | void>,+ Hook<+ "commissionLinesUpserted",+ { order_ids: string[]; commission_lines: CommissionLineDTO[] },+ unknown+ >,]export const refreshOrderCommissionLinesWorkflow: ReturnWorkflow<@@ -137,8 +145,13 @@ export const refreshOrderCommissionLinesWorkflow: ReturnWorkflow<commission_lines: commissionLines,})+ const commissionLinesUpserted = createHook("commissionLinesUpserted", {+ order_ids: input.order_ids,+ commission_lines: upsertedCommissionLines,+ })+return new WorkflowResponse(upsertedCommissionLines, {- hooks: [setCommissionContext],+ hooks: [setCommissionContext, commissionLinesUpserted],})})diff --git a/packages/core/src/workflows/order/workflows/confirm-return-receive.ts b/packages/core/src/workflows/order/workflows/confirm-return-receive.tsindex 69a9d881e..d8507ada5 100644--- a/packages/core/src/workflows/order/workflows/confirm-return-receive.ts+++ b/packages/core/src/workflows/order/workflows/confirm-return-receive.ts@@ -17,8 +17,10 @@ import {ReturnStatus,} from "@medusajs/framework/utils"import {+ createHook,createWorkflow,createStep,+ Hook,parallelize,StepResponse,transform,@@ -185,11 +187,28 @@ export type ConfirmReceiveReturnRequestWorkflowInput = {export const confirmReturnReceiveWorkflowId = "mercur-confirm-return-receive"+export type ConfirmReturnReceiveWorkflowHooks = [+ Hook<+ "returnReceived",+ {+ order_id: string+ return_id: string+ seller_id: string | null+ items: {+ id: string+ received_quantity: BigNumberInput+ damaged_quantity: BigNumberInput+ }[]+ },+ unknown+ >,+]+export const confirmReturnReceiveWorkflow = createWorkflow(confirmReturnReceiveWorkflowId,function (input: ConfirmReceiveReturnRequestWorkflowInput,- ): WorkflowResponse<OrderPreviewDTO> {+ ): WorkflowResponse<OrderPreviewDTO, ConfirmReturnReceiveWorkflowHooks> {const orderReturn = useRemoteQueryStep({entry_point: "return",fields: [@@ -213,7 +232,7 @@ export const confirmReturnReceiveWorkflow = createWorkflow(const order: OrderDTO = useRemoteQueryStep({entry_point: "orders",- fields: ["id", "version", "canceled_at"],+ fields: ["id", "version", "canceled_at", "seller.id"],variables: { id: orderReturn.order_id },list: false,throw_if_key_not_found: true,@@ -377,6 +396,19 @@ export const confirmReturnReceiveWorkflow = createWorkflow(}),)- return new WorkflowResponse(previewOrderChangeStep(order.id))+ const sellerId = transform({ order }, ({ order }) => {+ return (order as OrderDTO & { seller?: { id: string } | null }).seller?.id ?? null+ })++ const returnReceived = createHook("returnReceived", {+ order_id: order.id,+ return_id: orderReturn.id,+ seller_id: sellerId,+ items: updateReturnItem,+ })++ return new WorkflowResponse(previewOrderChangeStep(order.id), {+ hooks: [returnReceived],+ })},)diff --git a/packages/core/src/workflows/payment/workflows/index.ts b/packages/core/src/workflows/payment/workflows/index.tsindex a6475e214..c53f91a7e 100644--- a/packages/core/src/workflows/payment/workflows/index.ts+++ b/packages/core/src/workflows/payment/workflows/index.ts@@ -1 +1,2 @@export * from "./process-payment"+export * from "./payment-hooks"diff --git a/packages/core/src/workflows/payment/workflows/payment-hooks.ts b/packages/core/src/workflows/payment/workflows/payment-hooks.tsnew file mode 100644index 000000000..be2ef1574--- /dev/null+++ b/packages/core/src/workflows/payment/workflows/payment-hooks.ts@@ -0,0 +1,51 @@+import type { BigNumberInput, PaymentDTO } from "@medusajs/framework/types"+import type { Hook, ReturnWorkflow } from "@medusajs/framework/workflows-sdk"+import {+ capturePaymentWorkflow as medusaCapturePaymentWorkflow,+ refundPaymentWorkflow as medusaRefundPaymentWorkflow,+ type CapturePaymentWorkflowInput,+ type RefundPaymentWorkflowInput,+} from "@medusajs/medusa/core-flows"++export type CapturePaymentWorkflowHooks = [+ Hook<+ "paymentCaptured",+ {+ payment: PaymentDTO+ order_id: string | null+ amount: BigNumberInput | null+ },+ unknown+ >,+]++export type RefundPaymentWorkflowHooks = [+ Hook<+ "paymentRefunded",+ {+ payment: PaymentDTO+ order_id: string | null+ amount: BigNumberInput | null+ credit_line_amount: BigNumberInput+ refund_reason: { id: string; label: string; code: string | null } | null+ },+ unknown+ >,+]++// The hooks come from the core-flows payment-hooks patch, which is applied in+// memory and cannot reach Medusa's shipped typings, so the patched shape is+// asserted here. Keep in sync with patches/@medusajs+core-flows@*-payment-hooks.patch.+export const capturePaymentWorkflow =+ medusaCapturePaymentWorkflow as unknown as ReturnWorkflow<+ CapturePaymentWorkflowInput,+ PaymentDTO,+ CapturePaymentWorkflowHooks+ >++export const refundPaymentWorkflow =+ medusaRefundPaymentWorkflow as unknown as ReturnWorkflow<+ RefundPaymentWorkflowInput,+ PaymentDTO,+ RefundPaymentWorkflowHooks+ >