Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

feat(core): fulfillmentDelivered hook on markOrderFulfillmentAsDeliveredWorkflow (#1607)

Viktor Holik06557949d70e
diff --git a/integration-tests/http/order/vendor/order-fulfillment-delivered-hook.spec.ts b/integration-tests/http/order/vendor/order-fulfillment-delivered-hook.spec.ts
new file mode 100644
index 000000000..5bdfee9b2
--- /dev/null
+++ b/integration-tests/http/order/vendor/order-fulfillment-delivered-hook.spec.ts
@@ -0,0 +1,142 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import {
+ IRegionModuleService,
+ ISalesChannelModuleService,
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import { markOrderFulfillmentAsDeliveredWorkflow } from "@mercurjs/core/workflows"
+import { createCustomerUser } from "../../../helpers/create-customer-user"
+import {
+ generatePublishableKey,
+ generateStoreHeaders,
+} from "../../../helpers/create-admin-user"
+import {
+ completeSplitOrderCheckout,
+ seedSellerOfferWithShipping,
+} from "../../../helpers/split-order-checkout"
+
+jest.setTimeout(120000)
+
+// A workflow hook accepts a single handler, so it is registered once and each
+// test reads what it collected.
+const delivered: { order_id: string; fulfillment_id: string }[] = []
+
+markOrderFulfillmentAsDeliveredWorkflow.hooks.fulfillmentDelivered((input) => {
+ delivered.push(input)
+})
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api }) => {
+ describe("Vendor - fulfillmentDelivered hook", () => {
+ let appContainer: MedusaContainer
+ let sellerSeed: Awaited<ReturnType<typeof seedSellerOfferWithShipping>>
+ let storeHeaders: { headers: Record<string, string> }
+ let customerEmail: string
+ let region: { id: string }
+ let salesChannel: { id: string }
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ })
+
+ beforeEach(async () => {
+ delivered.length = 0
+
+ const customerResult = await createCustomerUser(appContainer, {
+ email: "[email protected]",
+ first_name: "Delivered",
+ last_name: "Buyer",
+ })
+ 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: "Delivered Hook Channel" })
+
+ region = await appContainer
+ .resolve<IRegionModuleService>(Modules.REGION)
+ .createRegions({
+ name: "Delivered Hook 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" },
+ })
+
+ sellerSeed = await seedSellerOfferWithShipping({
+ container: appContainer,
+ api,
+ salesChannelId: salesChannel.id,
+ email: "[email protected]",
+ name: "DeliveredHook",
+ stocked: 10,
+ offerPrice: 1000,
+ })
+ })
+
+ it("hands the order and fulfillment ids to the hook when a vendor marks a fulfillment delivered", async () => {
+ const order = await completeSplitOrderCheckout({
+ container: appContainer,
+ api,
+ storeHeaders,
+ regionId: region.id,
+ salesChannelId: salesChannel.id,
+ offerId: sellerSeed.offer.id,
+ email: customerEmail,
+ })
+
+ const items: { id: string; quantity: number }[] = (
+ await api.get(
+ `/vendor/orders/${order.id}?fields=*items`,
+ sellerSeed.headers
+ )
+ ).data.order.items
+ const [stockLocation] = (
+ await api.get(`/vendor/stock-locations`, sellerSeed.headers)
+ ).data.stock_locations
+
+ const fulfillment = (
+ await api.post(
+ `/vendor/orders/${order.id}/fulfillments`,
+ {
+ items: items.map((item) => ({
+ id: item.id,
+ quantity: item.quantity,
+ })),
+ requires_shipping: true,
+ location_id: stockLocation.id,
+ },
+ sellerSeed.headers
+ )
+ ).data.fulfillment
+
+ expect(delivered).toEqual([])
+
+ const response = await api.post(
+ `/vendor/orders/${order.id}/fulfillments/${fulfillment.id}/mark-as-delivered`,
+ {},
+ sellerSeed.headers
+ )
+
+ expect(response.status).toEqual(200)
+ expect(delivered).toEqual([
+ { order_id: order.id, fulfillment_id: fulfillment.id },
+ ])
+ })
+ })
+ },
+})
diff --git a/integration-tests/jest.config.js b/integration-tests/jest.config.js
index efe10946c..7d28f00d0 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 shipped core-flows cart and payment files. Jest never
+ // Mercur patches shipped core-flows cart, order 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$":
+ "node_modules[\\\\/].*core-flows[\\\\/]dist[\\\\/](cart|order|payment)[\\\\/].*\\.js$":
"@mercurjs/core/patches/jest-transformer",
"^.+\\.[jt]s$": [
"@swc/jest",
@@ -21,10 +21,10 @@ module.exports = {
],
},
testEnvironment: "node",
- // Everything in node_modules is left untransformed except the core-flows cart
- // and payment files the patches target.
+ // Everything in node_modules is left untransformed except the core-flows cart,
+ // order and payment files the patches target.
transformIgnorePatterns: [
- "/node_modules/(?!.*core-flows[\\\\/]dist[\\\\/](cart|payment)[\\\\/])",
+ "/node_modules/(?!.*core-flows[\\\\/]dist[\\\\/](cart|order|payment)[\\\\/])",
],
moduleFileExtensions: ["js", "ts", "json"],
modulePathIgnorePatterns: ["dist/"],
diff --git a/packages/core/src/patches/README.md b/packages/core/src/patches/README.md
index fc4b0a085..7d72eccd8 100644
--- a/packages/core/src/patches/README.md
+++ b/packages/core/src/patches/README.md
@@ -51,11 +51,11 @@ through `transformIgnorePatterns` (see `integration-tests/jest.config.js`):
```js
transform: {
- "node_modules[\\/].*core-flows[\\/]dist[\\/](cart|payment)[\\/].*\\.js$":
+ "node_modules[\\/].*core-flows[\\/]dist[\\/](cart|order|payment)[\\/].*\\.js$":
"@mercurjs/core/patches/jest-transformer",
"^.+\\.[jt]s$": ["@swc/jest", { /* ... */ }],
},
-transformIgnorePatterns: ["/node_modules/(?!.*core-flows[\\/]dist[\\/](cart|payment)[\\/])"],
+transformIgnorePatterns: ["/node_modules/(?!.*core-flows[\\/]dist[\\/](cart|order|payment)[\\/])"],
```
Both paths funnel through `patchSourceForPath`, so a patch means the same thing
@@ -76,7 +76,9 @@ package manager is detected and skipped rather than treated as a conflict.
- **out of range** — the copy this project resolves is outside the patch's
`compatible` range: boot fails with the installed version. Incidental copies in
a shared package-manager store are skipped rather than fatal.
-- **applied** — one log line per patch, with the number of copies touched.
+- **applied** — one log line per patch, with the number of copies touched, at
+ `debug` through Medusa's logger. The default `LOG_LEVEL` (`http`) hides it;
+ run with `LOG_LEVEL=debug` to see it in the console or in `LOG_FILE`.
The diff's own context is the real guard: if upstream moves the code, the hunk
stops matching and boot fails with the patch name and the bug it corrects. The
diff --git a/packages/core/src/patches/__tests__/fixtures/core-flows-first.ts b/packages/core/src/patches/__tests__/fixtures/core-flows-first.ts
index 0e9787a00..d2393217b 100644
--- a/packages/core/src/patches/__tests__/fixtures/core-flows-first.ts
+++ b/packages/core/src/patches/__tests__/fixtures/core-flows-first.ts
@@ -9,6 +9,6 @@ const hookTypes = () => {
}
const before = hookTypes()
-applyMercurPatches({ logger: { info: () => {}, warn: () => {} } })
+applyMercurPatches({ logger: { debug: () => {}, warn: () => {} } })
process.stdout.write(JSON.stringify({ before, after: hookTypes() }))
diff --git a/packages/core/src/patches/__tests__/fixtures/workflows-entry.ts b/packages/core/src/patches/__tests__/fixtures/workflows-entry.ts
new file mode 100644
index 000000000..21c2401cb
--- /dev/null
+++ b/packages/core/src/patches/__tests__/fixtures/workflows-entry.ts
@@ -0,0 +1,11 @@
+import { applyMercurPatches } from "../../index"
+
+applyMercurPatches({ logger: { debug: () => {}, warn: () => {} } })
+
+const { markOrderFulfillmentAsDeliveredWorkflow } = require("../../../workflows")
+
+process.stdout.write(
+ JSON.stringify(
+ typeof markOrderFulfillmentAsDeliveredWorkflow.hooks.fulfillmentDelivered
+ )
+)
diff --git a/packages/core/src/patches/__tests__/jest-transformer.unit.spec.ts b/packages/core/src/patches/__tests__/jest-transformer.unit.spec.ts
index ca307d08e..fb1acc5d2 100644
--- a/packages/core/src/patches/__tests__/jest-transformer.unit.spec.ts
+++ b/packages/core/src/patches/__tests__/jest-transformer.unit.spec.ts
@@ -52,7 +52,11 @@ describe("jest transformer", () => {
it.each([
["dist/payment/workflows/capture-payment.js", "paymentCaptured"],
["dist/payment/workflows/refund-payment.js", "paymentRefunded"],
- ])("exposes the payment hook in %s", (relativePath, hookName) => {
+ [
+ "dist/order/workflows/mark-order-fulfillment-as-delivered.js",
+ "fulfillmentDelivered",
+ ],
+ ])("exposes the hook in %s", (relativePath, hookName) => {
const sourcePath = join(copy().dir, relativePath)
const { code } = transform(readFileSync(sourcePath, "utf8"), sourcePath)
diff --git a/packages/core/src/patches/__tests__/load-order.unit.spec.ts b/packages/core/src/patches/__tests__/load-order.unit.spec.ts
index 3b5d7cda2..e917d6f5b 100644
--- a/packages/core/src/patches/__tests__/load-order.unit.spec.ts
+++ b/packages/core/src/patches/__tests__/load-order.unit.spec.ts
@@ -5,14 +5,21 @@ import { join } from "path"
// loader, which is where the patches live, so each case runs in a real process.
const CORE_ROOT = join(__dirname, "..", "..", "..")
-function run(fixture: string): unknown {
- const output = execFileSync(
+function execute(fixture: string, env: NodeJS.ProcessEnv = {}): string {
+ return execFileSync(
process.execPath,
[require.resolve("tsx/cli"), join(__dirname, "fixtures", fixture)],
- { cwd: CORE_ROOT, encoding: "utf8", env: { ...process.env, NODE_ENV: "test" } }
+ {
+ cwd: CORE_ROOT,
+ encoding: "utf8",
+ env: { ...process.env, NODE_ENV: "test", ...env },
+ }
)
- // Importing `@mercurjs/core` logs each applied patch to stdout ahead of the result.
- return JSON.parse(output.trim().split("\n").pop()!)
+}
+
+function run(fixture: string): unknown {
+ // With LOG_LEVEL=debug each applied patch is logged to stdout ahead of the result.
+ return JSON.parse(execute(fixture).trim().split("\n").pop()!)
}
describe("patch load order", () => {
@@ -26,4 +33,17 @@ describe("patch load order", () => {
after: ["function", "function"],
})
})
+
+ it("logs applied patches at debug, out of the default console output", () => {
+ expect(execute("core-imported-first.ts", { LOG_LEVEL: "http" })).not.toContain(
+ "Applied patch"
+ )
+ expect(execute("core-imported-first.ts", { LOG_LEVEL: "debug" })).toContain(
+ "Applied patch"
+ )
+ })
+
+ it("exposes fulfillmentDelivered on the workflow exported from @mercurjs/core/workflows", () => {
+ expect(run("workflows-entry.ts")).toEqual("function")
+ })
})
diff --git a/packages/core/src/patches/index.ts b/packages/core/src/patches/index.ts
index 798647942..dad88f5c4 100644
--- a/packages/core/src/patches/index.ts
+++ b/packages/core/src/patches/index.ts
@@ -1,6 +1,8 @@
import { existsSync, realpathSync } from "fs"
import { join } from "path"
+import { logger as medusaLogger } from "@medusajs/framework/logger"
+
import { isPatchApplied, readPatchedFiles } from "./apply-patch"
import {
isAlreadyLoaded,
@@ -31,7 +33,7 @@ const PATCH_DIR = join(__dirname, "patches")
export type ApplyPatchesOptions = {
/** Patch file names to skip, for adopters who need to opt out of one. */
disabled?: string[]
- logger?: Pick<Console, "info" | "warn">
+ logger?: Pick<typeof medusaLogger, "debug" | "warn">
}
function fail(entry: PatchEntry, copy: PackageCopy, detail: string): never {
@@ -105,7 +107,7 @@ function applyToCopy(
export function applyMercurPatches(options: ApplyPatchesOptions = {}): void {
const disabled = new Set(options.disabled ?? [])
- const logger = options.logger ?? console
+ const logger = options.logger ?? medusaLogger
const patchedPackages = new Set<string>()
for (const entry of PATCHES) {
@@ -140,7 +142,9 @@ export function applyMercurPatches(options: ApplyPatchesOptions = {}): void {
)
}
- logger.info(
+ // Medusa's own loaders report what they registered at debug, which the
+ // default LOG_LEVEL ("http") keeps out of the console.
+ logger.debug(
`[mercur] Applied patch "${entry.file}" to ${patchedCount} copy/copies of ` +
`${entry.package}`
)
diff --git a/packages/core/src/patches/jest-transformer.ts b/packages/core/src/patches/jest-transformer.ts
index a7f708337..9b1f2ca7c 100644
--- a/packages/core/src/patches/jest-transformer.ts
+++ b/packages/core/src/patches/jest-transformer.ts
@@ -15,11 +15,11 @@ import { PATCHES } from "./manifest"
// through `transformIgnorePatterns`:
//
// transform: {
-// "node_modules[\\\\/].*core-flows[\\\\/]dist[\\\\/](cart|payment)[\\\\/].*\\.js$":
+// "node_modules[\\\\/].*core-flows[\\\\/]dist[\\\\/](cart|order|payment)[\\\\/].*\\.js$":
// "@mercurjs/core/patches/jest-transformer",
// "^.+\\.[jt]s$": ["@swc/jest", { ... }],
// },
-// transformIgnorePatterns: ["/node_modules/(?!.*core-flows[\\\\/]dist[\\\\/](cart|payment)[\\\\/])"],
+// transformIgnorePatterns: ["/node_modules/(?!.*core-flows[\\\\/]dist[\\\\/](cart|order|payment)[\\\\/])"],
type TransformOutput = { code: string }
diff --git a/packages/core/src/patches/manifest.ts b/packages/core/src/patches/manifest.ts
index af96e7cf2..f42601189 100644
--- a/packages/core/src/patches/manifest.ts
+++ b/packages/core/src/patches/manifest.ts
@@ -38,4 +38,14 @@ export const PATCHES: PatchEntry[] = [
"record every capture and refund inside the movement's own transaction, with " +
"compensation, needs paymentCaptured and paymentRefunded.",
},
+ {
+ file: "@[email protected]",
+ package: "@medusajs/core-flows",
+ compatible: { from: "2.18.0", to: "2.22.0" },
+ reason:
+ "markOrderFulfillmentAsDeliveredWorkflow ends in an event and exposes no hook. " +
+ "Delivery is where a marketplace releases the seller's money from pending to " +
+ "payable, and that release must run in the delivery's own transaction, with " +
+ "compensation, so it needs fulfillmentDelivered.",
+ },
]
diff --git a/packages/core/src/patches/patches/@[email protected] b/packages/core/src/patches/patches/@[email protected]
new file mode 100644
index 000000000..3159d24e8
--- /dev/null
+++ b/packages/core/src/patches/patches/@[email protected]
@@ -0,0 +1,39 @@
+diff --git a/dist/order/workflows/mark-order-fulfillment-as-delivered.d.ts b/dist/order/workflows/mark-order-fulfillment-as-delivered.d.ts
+index ca18c8e..0017842 100644
+--- a/dist/order/workflows/mark-order-fulfillment-as-delivered.d.ts
++++ b/dist/order/workflows/mark-order-fulfillment-as-delivered.d.ts
+@@ -94,5 +94,10 @@ export declare const markOrderFulfillmentAsDeliveredWorkflowId = "mark-order-ful
+ *
+ * Mark a fulfillment in an order as delivered.
+ */
+-export declare const markOrderFulfillmentAsDeliveredWorkflow: import("@medusajs/framework/workflows-sdk").ReturnWorkflow<MarkOrderFulfillmentAsDeliveredWorkflowInput, undefined, []>;
++export declare const markOrderFulfillmentAsDeliveredWorkflow: import("@medusajs/framework/workflows-sdk").ReturnWorkflow<MarkOrderFulfillmentAsDeliveredWorkflowInput, undefined, [
++ import("@medusajs/framework/workflows-sdk").Hook<"fulfillmentDelivered", {
++ order_id: string;
++ fulfillment_id: string;
++ }, unknown>
++]>;
+ //# sourceMappingURL=mark-order-fulfillment-as-delivered.d.ts.map
+\ No newline at end of file
+diff --git a/dist/order/workflows/mark-order-fulfillment-as-delivered.js b/dist/order/workflows/mark-order-fulfillment-as-delivered.js
+index 1829603..ee0814f 100644
+--- a/dist/order/workflows/mark-order-fulfillment-as-delivered.js
++++ b/dist/order/workflows/mark-order-fulfillment-as-delivered.js
+@@ -160,6 +160,15 @@ exports.markOrderFulfillmentAsDeliveredWorkflow = (0, workflows_sdk_1.createWork
+ no_notification: input.no_notification,
+ },
+ });
+- return new workflows_sdk_1.WorkflowResponse(void 0);
++ // MERCUR: delivery is the point a marketplace releases the seller's money,
++ // and that release must sit in the delivery's own transaction, with
++ // compensation. The event above fires after commit and cannot be undone.
++ const fulfillmentDelivered = (0, workflows_sdk_1.createHook)("fulfillmentDelivered", {
++ order_id: orderId,
++ fulfillment_id: (0, workflows_sdk_1.transform)({ deliveredFulfillment }, ({ deliveredFulfillment }) => deliveredFulfillment.id),
++ });
++ return new workflows_sdk_1.WorkflowResponse(void 0, {
++ hooks: [fulfillmentDelivered],
++ });
+ });
+ //# sourceMappingURL=mark-order-fulfillment-as-delivered.js.map
+\ No newline at end of file
diff --git a/packages/core/src/workflows/order/workflows/fulfillment-hooks.ts b/packages/core/src/workflows/order/workflows/fulfillment-hooks.ts
new file mode 100644
index 000000000..a3fa7520a
--- /dev/null
+++ b/packages/core/src/workflows/order/workflows/fulfillment-hooks.ts
@@ -0,0 +1,26 @@
+import type { Hook, ReturnWorkflow } from "@medusajs/framework/workflows-sdk"
+import {
+ markOrderFulfillmentAsDeliveredWorkflow as medusaMarkOrderFulfillmentAsDeliveredWorkflow,
+ type MarkOrderFulfillmentAsDeliveredWorkflowInput,
+} from "@medusajs/medusa/core-flows"
+
+export type MarkOrderFulfillmentAsDeliveredWorkflowHooks = [
+ Hook<
+ "fulfillmentDelivered",
+ {
+ order_id: string
+ fulfillment_id: string
+ },
+ unknown
+ >,
+]
+
+// The hook comes from the core-flows delivery-hook 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@*-delivery-hook.patch.
+export const markOrderFulfillmentAsDeliveredWorkflow =
+ medusaMarkOrderFulfillmentAsDeliveredWorkflow as unknown as ReturnWorkflow<
+ MarkOrderFulfillmentAsDeliveredWorkflowInput,
+ undefined,
+ MarkOrderFulfillmentAsDeliveredWorkflowHooks
+ >
diff --git a/packages/core/src/workflows/order/workflows/index.ts b/packages/core/src/workflows/order/workflows/index.ts
index c7535a250..ccf98b181 100644
--- a/packages/core/src/workflows/order/workflows/index.ts
+++ b/packages/core/src/workflows/order/workflows/index.ts
@@ -4,3 +4,4 @@ export * from "./confirm-return-receive"
export * from "./confirm-exchange-request"
export * from "./confirm-claim-request"
export * from "./confirm-order-edit-request"
+export * from "./fulfillment-hooks"