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: make order-payout subscriber idempotent (#781)

Viktor Holik153799c22a41
diff --git a/bun.lock b/bun.lock
index 3fad6285d..1cd31bcb4 100644
--- a/bun.lock
+++ b/bun.lock
@@ -38,7 +38,7 @@
},
"packages/admin": {
"name": "@mercurjs/admin",
- "version": "2.0.0-canary.88",
+ "version": "2.0.0-canary.89",
"dependencies": {
"@ariakit/react": "^0.4.15",
"@babel/runtime": "^7.26.10",
@@ -98,7 +98,7 @@
},
"packages/cli": {
"name": "@mercurjs/cli",
- "version": "2.0.0-canary.88",
+ "version": "2.0.0-canary.89",
"bin": {
"mercurjs": "./dist/index.js",
},
@@ -109,7 +109,7 @@
"@medusajs/admin-vite-plugin": "2.13.3",
"@medusajs/dashboard": "2.13.3",
"@medusajs/framework": "2.13.3",
- "@mercurjs/dashboard-sdk": "2.0.0-canary.88",
+ "@mercurjs/dashboard-sdk": "2.0.0-canary.89",
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.19",
"commander": "^14.0.2",
@@ -153,7 +153,7 @@
},
"packages/client": {
"name": "@mercurjs/client",
- "version": "2.0.0-canary.88",
+ "version": "2.0.0-canary.89",
"dependencies": {
"@tanstack/react-query": "^5.64.2",
"qs": "^6.12.1",
@@ -170,7 +170,7 @@
},
"packages/core-plugin": {
"name": "@mercurjs/core-plugin",
- "version": "2.0.0-canary.88",
+ "version": "2.0.0-canary.89",
"devDependencies": {
"@medusajs/cli": "^2.13.3",
"@medusajs/core-flows": "^2.13.3",
@@ -211,7 +211,7 @@
},
"packages/dashboard-sdk": {
"name": "@mercurjs/dashboard-sdk",
- "version": "2.0.0-canary.88",
+ "version": "2.0.0-canary.89",
"dependencies": {
"@babel/parser": "7.25.6",
"@babel/traverse": "7.25.6",
@@ -228,7 +228,7 @@
},
"packages/dashboard-shared": {
"name": "@mercurjs/dashboard-shared",
- "version": "2.0.0-canary.88",
+ "version": "2.0.0-canary.89",
"dependencies": {
"@ariakit/react": "^0.4.15",
"@babel/runtime": "^7.26.10",
@@ -241,7 +241,7 @@
"@medusajs/dashboard": "^2.13.3",
"@medusajs/icons": "2.13.3",
"@medusajs/ui": "4.1.1",
- "@mercurjs/client": "2.0.0-canary.88",
+ "@mercurjs/client": "2.0.0-canary.89",
"@radix-ui/react-dialog": "1.1.4",
"@radix-ui/react-dismissable-layer": "1.1.4",
"@tanstack/react-query": "5.64.2",
@@ -280,6 +280,20 @@
"typescript": "5.9.3",
},
},
+ "packages/providers/payout-stripe-connect": {
+ "name": "@mercurjs/payout-stripe-connect",
+ "version": "2.0.0-canary.89",
+ "dependencies": {
+ "stripe": "^15.5.0",
+ },
+ "devDependencies": {
+ "@medusajs/framework": "2.13.4",
+ "@mercurjs/types": "2.0.0-canary.89",
+ },
+ "peerDependencies": {
+ "@medusajs/framework": "2.13.4",
+ },
+ },
"packages/registry": {
"name": "@mercurjs/registry",
"version": "0.0.0",
@@ -320,7 +334,7 @@
},
"packages/types": {
"name": "@mercurjs/types",
- "version": "2.0.0-canary.88",
+ "version": "2.0.0-canary.89",
"dependencies": {
"@medusajs/types": "2.13.3",
},
@@ -330,7 +344,7 @@
},
"packages/vendor": {
"name": "@mercurjs/vendor",
- "version": "2.0.0-canary.88",
+ "version": "2.0.0-canary.89",
"dependencies": {
"@ariakit/react": "^0.4.15",
"@babel/runtime": "^7.26.10",
@@ -343,8 +357,8 @@
"@medusajs/dashboard": "^2.13.3",
"@medusajs/icons": "2.13.3",
"@medusajs/ui": "4.1.1",
- "@mercurjs/client": "2.0.0-canary.88",
- "@mercurjs/dashboard-shared": "2.0.0-canary.88",
+ "@mercurjs/client": "2.0.0-canary.89",
+ "@mercurjs/dashboard-shared": "2.0.0-canary.89",
"@radix-ui/react-dialog": "1.1.4",
"@radix-ui/react-dismissable-layer": "1.1.4",
"@tanstack/react-query": "5.64.2",
@@ -994,6 +1008,8 @@
"@mercurjs/integration-tests": ["@mercurjs/integration-tests@workspace:integration-tests"],
+ "@mercurjs/payout-stripe-connect": ["@mercurjs/payout-stripe-connect@workspace:packages/providers/payout-stripe-connect"],
+
"@mercurjs/registry": ["@mercurjs/registry@workspace:packages/registry"],
"@mercurjs/types": ["@mercurjs/types@workspace:packages/types"],
@@ -3132,7 +3148,7 @@
"strip-json-comments": ["[email protected]", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="],
- "stripe": ["[email protected]", "", { "dependencies": { "qs": "^6.11.0" }, "peerDependencies": { "@types/node": ">=16" }, "optionalPeers": ["@types/node"] }, "sha512-FjgIiE98dMMTNssfdjMvFdD4eZyEzdWAOwPYqzhPRNZeg9ggFWlPXmX1iJKD5pPIwZBaPlC3SayQQkwsPo6/YQ=="],
+ "stripe": ["[email protected]", "", { "dependencies": { "@types/node": ">=8.1.0", "qs": "^6.11.0" } }, "sha512-slTbYS1WhRJXVB8YXU8fgHizkUrM9KJyrw4Dd8pLEwzKHYyQTIE46EePC2MVbSDZdE24o1GdNtzmJV4PrPpmJA=="],
"strnum": ["[email protected]", "", {}, "sha512-Y7Bj8XyJxnPAORMZj/xltsfo55uOiyHcU2tnAVzHUnSJR/KsEX+9RoDeXEnsXtl/CX4fAcrt64gZ13aGaWPeBg=="],
@@ -3506,12 +3522,22 @@
"@medusajs/dashboard/@medusajs/ui": ["@medusajs/[email protected]", "", { "dependencies": { "@dnd-kit/core": "^6.1.0", "@dnd-kit/sortable": "^8.0.0", "@dnd-kit/utilities": "^3.2.2", "@medusajs/icons": "2.13.3", "@radix-ui/react-dialog": "1.1.4", "@radix-ui/react-dismissable-layer": "1.1.4", "@tanstack/react-table": "8.20.5", "clsx": "^1.2.1", "copy-to-clipboard": "^3.3.3", "cva": "1.0.0-beta.1", "lodash.isequal": "^4.5.0", "prism-react-renderer": "^2.0.6", "prismjs": "^1.30.0", "radix-ui": "1.1.2", "react-aria": "^3.33.1", "react-currency-input-field": "^3.6.11", "react-stately": "^3.31.1", "sonner": "^1.5.0", "tailwind-merge": "^2.2.1" }, "peerDependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "sha512-mvjPFT6yN3I0YElmuSCnbiFnAZ1X4HpVWU46SXKW5PO9raM6Ny/kGDMB3GG2jPGX1Z18CoWAc5rDss8s0deh/g=="],
- "@medusajs/payment-stripe/stripe": ["[email protected]", "", { "dependencies": { "@types/node": ">=8.1.0", "qs": "^6.11.0" } }, "sha512-slTbYS1WhRJXVB8YXU8fgHizkUrM9KJyrw4Dd8pLEwzKHYyQTIE46EePC2MVbSDZdE24o1GdNtzmJV4PrPpmJA=="],
+ "@medusajs/payment/stripe": ["[email protected]", "", { "dependencies": { "qs": "^6.11.0" }, "peerDependencies": { "@types/node": ">=16" }, "optionalPeers": ["@types/node"] }, "sha512-FjgIiE98dMMTNssfdjMvFdD4eZyEzdWAOwPYqzhPRNZeg9ggFWlPXmX1iJKD5pPIwZBaPlC3SayQQkwsPo6/YQ=="],
"@medusajs/ui/@medusajs/icons": ["@medusajs/[email protected]", "", { "peerDependencies": { "react": "^18.3.1" } }, "sha512-A0j+C4jURXSWARbxjEOXh3get9N7dY7n3TNTdmpOeY0XPZeDfKaL1yVBD2EC90jVTWY045whrMBCJUuV7kjYPg=="],
+ "@mercurjs/client/@medusajs/framework": ["@medusajs/[email protected]", "", { "dependencies": { "@aws-sdk/client-dynamodb": "^3.218.0", "@jercle/yargonaut": "^1.1.5", "@medusajs/deps": "2.13.4", "@medusajs/modules-sdk": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/telemetry": "2.13.4", "@medusajs/types": "2.13.4", "@medusajs/utils": "2.13.4", "@medusajs/workflows-sdk": "2.13.4", "@types/express": "^4.17.21", "chokidar": "^4.0.3", "compression": "^1.8.1", "connect-dynamodb": "^3.0.5", "connect-redis": "5.2.0", "cookie-parser": "^1.4.6", "cors": "^2.8.5", "express": "^4.21.0", "express-session": "^1.17.3", "glob": "11.1.0", "jsonwebtoken": "^9.0.2", "lodash.memoize": "^4.1.2", "morgan": "^1.9.1", "path-to-regexp": "^8.2.0", "tsconfig-paths": "^4.2.0", "zod-validation-error": "3.5.1" }, "peerDependencies": { "@medusajs/cli": "2.13.4", "ioredis": "^5.4.1" }, "optionalPeers": ["ioredis"], "bin": { "medusa-mikro-orm": "dist/mikro-orm-cli/bin.js" } }, "sha512-OoamovYj/hkDyDSfj7zyaO48o4uyn+Us0+t789z5G90b5KYuUjx2Y2QX7OXy3pRLv6RbsgnyMfUfY5oi1iNFtQ=="],
+
+ "@mercurjs/core-plugin/@medusajs/framework": ["@medusajs/[email protected]", "", { "dependencies": { "@aws-sdk/client-dynamodb": "^3.218.0", "@jercle/yargonaut": "^1.1.5", "@medusajs/deps": "2.13.4", "@medusajs/modules-sdk": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/telemetry": "2.13.4", "@medusajs/types": "2.13.4", "@medusajs/utils": "2.13.4", "@medusajs/workflows-sdk": "2.13.4", "@types/express": "^4.17.21", "chokidar": "^4.0.3", "compression": "^1.8.1", "connect-dynamodb": "^3.0.5", "connect-redis": "5.2.0", "cookie-parser": "^1.4.6", "cors": "^2.8.5", "express": "^4.21.0", "express-session": "^1.17.3", "glob": "11.1.0", "jsonwebtoken": "^9.0.2", "lodash.memoize": "^4.1.2", "morgan": "^1.9.1", "path-to-regexp": "^8.2.0", "tsconfig-paths": "^4.2.0", "zod-validation-error": "3.5.1" }, "peerDependencies": { "@medusajs/cli": "2.13.4", "ioredis": "^5.4.1" }, "optionalPeers": ["ioredis"], "bin": { "medusa-mikro-orm": "dist/mikro-orm-cli/bin.js" } }, "sha512-OoamovYj/hkDyDSfj7zyaO48o4uyn+Us0+t789z5G90b5KYuUjx2Y2QX7OXy3pRLv6RbsgnyMfUfY5oi1iNFtQ=="],
+
"@mercurjs/dashboard-sdk/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg=="],
+ "@mercurjs/integration-tests/@medusajs/framework": ["@medusajs/[email protected]", "", { "dependencies": { "@aws-sdk/client-dynamodb": "^3.218.0", "@jercle/yargonaut": "^1.1.5", "@medusajs/deps": "2.13.4", "@medusajs/modules-sdk": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/telemetry": "2.13.4", "@medusajs/types": "2.13.4", "@medusajs/utils": "2.13.4", "@medusajs/workflows-sdk": "2.13.4", "@types/express": "^4.17.21", "chokidar": "^4.0.3", "compression": "^1.8.1", "connect-dynamodb": "^3.0.5", "connect-redis": "5.2.0", "cookie-parser": "^1.4.6", "cors": "^2.8.5", "express": "^4.21.0", "express-session": "^1.17.3", "glob": "11.1.0", "jsonwebtoken": "^9.0.2", "lodash.memoize": "^4.1.2", "morgan": "^1.9.1", "path-to-regexp": "^8.2.0", "tsconfig-paths": "^4.2.0", "zod-validation-error": "3.5.1" }, "peerDependencies": { "@medusajs/cli": "2.13.4", "ioredis": "^5.4.1" }, "optionalPeers": ["ioredis"], "bin": { "medusa-mikro-orm": "dist/mikro-orm-cli/bin.js" } }, "sha512-OoamovYj/hkDyDSfj7zyaO48o4uyn+Us0+t789z5G90b5KYuUjx2Y2QX7OXy3pRLv6RbsgnyMfUfY5oi1iNFtQ=="],
+
+ "@mercurjs/payout-stripe-connect/@medusajs/framework": ["@medusajs/[email protected]", "", { "dependencies": { "@aws-sdk/client-dynamodb": "^3.218.0", "@jercle/yargonaut": "^1.1.5", "@medusajs/deps": "2.13.4", "@medusajs/modules-sdk": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/telemetry": "2.13.4", "@medusajs/types": "2.13.4", "@medusajs/utils": "2.13.4", "@medusajs/workflows-sdk": "2.13.4", "@types/express": "^4.17.21", "chokidar": "^4.0.3", "compression": "^1.8.1", "connect-dynamodb": "^3.0.5", "connect-redis": "5.2.0", "cookie-parser": "^1.4.6", "cors": "^2.8.5", "express": "^4.21.0", "express-session": "^1.17.3", "glob": "11.1.0", "jsonwebtoken": "^9.0.2", "lodash.memoize": "^4.1.2", "morgan": "^1.9.1", "path-to-regexp": "^8.2.0", "tsconfig-paths": "^4.2.0", "zod-validation-error": "3.5.1" }, "peerDependencies": { "@medusajs/cli": "2.13.4", "ioredis": "^5.4.1" }, "optionalPeers": ["ioredis"], "bin": { "medusa-mikro-orm": "dist/mikro-orm-cli/bin.js" } }, "sha512-OoamovYj/hkDyDSfj7zyaO48o4uyn+Us0+t789z5G90b5KYuUjx2Y2QX7OXy3pRLv6RbsgnyMfUfY5oi1iNFtQ=="],
+
+ "@mercurjs/registry/@medusajs/framework": ["@medusajs/[email protected]", "", { "dependencies": { "@aws-sdk/client-dynamodb": "^3.218.0", "@jercle/yargonaut": "^1.1.5", "@medusajs/deps": "2.13.4", "@medusajs/modules-sdk": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/telemetry": "2.13.4", "@medusajs/types": "2.13.4", "@medusajs/utils": "2.13.4", "@medusajs/workflows-sdk": "2.13.4", "@types/express": "^4.17.21", "chokidar": "^4.0.3", "compression": "^1.8.1", "connect-dynamodb": "^3.0.5", "connect-redis": "5.2.0", "cookie-parser": "^1.4.6", "cors": "^2.8.5", "express": "^4.21.0", "express-session": "^1.17.3", "glob": "11.1.0", "jsonwebtoken": "^9.0.2", "lodash.memoize": "^4.1.2", "morgan": "^1.9.1", "path-to-regexp": "^8.2.0", "tsconfig-paths": "^4.2.0", "zod-validation-error": "3.5.1" }, "peerDependencies": { "@medusajs/cli": "2.13.4", "ioredis": "^5.4.1" }, "optionalPeers": ["ioredis"], "bin": { "medusa-mikro-orm": "dist/mikro-orm-cli/bin.js" } }, "sha512-OoamovYj/hkDyDSfj7zyaO48o4uyn+Us0+t789z5G90b5KYuUjx2Y2QX7OXy3pRLv6RbsgnyMfUfY5oi1iNFtQ=="],
+
"@mercurjs/registry/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg=="],
"@mercurjs/registry/jsonwebtoken": ["[email protected]", "", { "dependencies": { "jws": "^3.2.2", "lodash.includes": "^4.3.0", "lodash.isboolean": "^3.0.3", "lodash.isinteger": "^4.0.4", "lodash.isnumber": "^3.0.3", "lodash.isplainobject": "^4.0.6", "lodash.isstring": "^4.0.1", "lodash.once": "^4.0.0", "ms": "^2.1.1", "semver": "^7.5.4" } }, "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ=="],
@@ -3960,6 +3986,8 @@
"strip-ansi-cjs/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+ "stripe/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg=="],
+
"sucrase/commander": ["[email protected]", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="],
"supports-color/has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
@@ -4100,7 +4128,77 @@
"@medusajs/cli/ora/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
- "@medusajs/payment-stripe/stripe/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg=="],
+ "@mercurjs/client/@medusajs/framework/@medusajs/deps": ["@medusajs/[email protected]", "", { "dependencies": { "@mikro-orm/cli": "6.4.16", "@mikro-orm/core": "6.4.16", "@mikro-orm/knex": "6.4.16", "@mikro-orm/migrations": "6.4.16", "@mikro-orm/postgresql": "6.4.16", "@opentelemetry/api": "^1.9.0", "@opentelemetry/instrumentation-pg": "^0.52.0", "@opentelemetry/resources": "^2.0.0", "@opentelemetry/sdk-node": "^0.200.0", "@opentelemetry/sdk-trace-node": "^2.0.0", "awilix": "^8.0.1", "pg": "^8.16.3", "zod": "3.25.76" } }, "sha512-wUfNMFaDU3RjAJRg8mIcE/DC2kH7yMcouzIANVIO4SZj6ydF+4dPmbNl1Ysmletr1FQYlfLnFl+lNbjW2d6Fxg=="],
+
+ "@mercurjs/client/@medusajs/framework/@medusajs/modules-sdk": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/utils": "2.13.4" } }, "sha512-QHhlKW0UrYyvwuMaz3Pkgkkb6q02F/M+zS/7gPHiUXaop8EPYaQ+aaT7gun5CkU1VrSm9/Ua52HJdEH9Myz4yw=="],
+
+ "@mercurjs/client/@medusajs/framework/@medusajs/orchestration": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/utils": "2.13.4", "ulid": "^2.3.0" } }, "sha512-tSBBajULzKbrzU8Fcjxnf7e13n7kVGErZl8avGy1xL1S57nNLk6vrPmft8s/PQA9KpFdWAi8c3GdNwVtm6+7/g=="],
+
+ "@mercurjs/client/@medusajs/framework/@medusajs/telemetry": ["@medusajs/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.26.10", "axios": "^1.13.1", "axios-retry": "^3.1.9", "boxen": "^5.0.1", "ci-info": "^3.2.0", "configstore": "^5.0.1", "is-docker": "^2.2.1", "remove-trailing-slash": "^0.1.1", "uuid": "^9.0.0" } }, "sha512-EoRFSMt91MFbDfL3A765irZL6MWeixs/npfXHXRtY6CDXL9L6tDhC29JXqFdgSsgW5Qp+qNDVUmoXM1WzF5JaQ=="],
+
+ "@mercurjs/client/@medusajs/framework/@medusajs/types": ["@medusajs/[email protected]", "", { "dependencies": { "bignumber.js": "^9.1.2" }, "peerDependencies": { "ioredis": "^5.4.1", "vite": "^5.4.21" }, "optionalPeers": ["ioredis", "vite"] }, "sha512-tp9jXAwTWC8eN29QcYe9GK78iprJ+K9YnwAfneUdZgn++wHaqnn/gAkrJxRmEiFlB/xgwlDT+49xzbBEqPLTYw=="],
+
+ "@mercurjs/client/@medusajs/framework/@medusajs/utils": ["@medusajs/[email protected]", "", { "dependencies": { "@graphql-codegen/core": "^4.0.2", "@graphql-codegen/typescript": "^4.0.9", "@graphql-tools/merge": "^9.0.7", "@graphql-tools/schema": "^10.0.6", "@medusajs/deps": "2.13.4", "@types/pluralize": "^0.0.33", "bignumber.js": "^9.1.2", "dotenv": "^16.4.5", "dotenv-expand": "^11.0.6", "graphql": "^16.9.0", "jsonwebtoken": "^9.0.2", "pg-connection-string": "^2.7.0", "pluralize": "^8.0.0", "ulid": "^2.3.0" }, "peerDependencies": { "express": "^4.21.0" } }, "sha512-TxBOePQSVZcY/6KQf7TqXifDZqcxowEK+3g3swubxuXGZHRmVa5cpQOyV0sk8jJeQQVaVh18sl2FsBrB9TygyA=="],
+
+ "@mercurjs/client/@medusajs/framework/@medusajs/workflows-sdk": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/modules-sdk": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/utils": "2.13.4", "ulid": "^2.3.0" } }, "sha512-/rX7p6L0RefA3i3ZclrzuZQBWbEsC8VxUIE6LdirZMaImJQhI+/TDyIU5pWQPbcCbPl+chzaPw7KjtXkUpXGig=="],
+
+ "@mercurjs/core-plugin/@medusajs/framework/@medusajs/deps": ["@medusajs/[email protected]", "", { "dependencies": { "@mikro-orm/cli": "6.4.16", "@mikro-orm/core": "6.4.16", "@mikro-orm/knex": "6.4.16", "@mikro-orm/migrations": "6.4.16", "@mikro-orm/postgresql": "6.4.16", "@opentelemetry/api": "^1.9.0", "@opentelemetry/instrumentation-pg": "^0.52.0", "@opentelemetry/resources": "^2.0.0", "@opentelemetry/sdk-node": "^0.200.0", "@opentelemetry/sdk-trace-node": "^2.0.0", "awilix": "^8.0.1", "pg": "^8.16.3", "zod": "3.25.76" } }, "sha512-wUfNMFaDU3RjAJRg8mIcE/DC2kH7yMcouzIANVIO4SZj6ydF+4dPmbNl1Ysmletr1FQYlfLnFl+lNbjW2d6Fxg=="],
+
+ "@mercurjs/core-plugin/@medusajs/framework/@medusajs/modules-sdk": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/utils": "2.13.4" } }, "sha512-QHhlKW0UrYyvwuMaz3Pkgkkb6q02F/M+zS/7gPHiUXaop8EPYaQ+aaT7gun5CkU1VrSm9/Ua52HJdEH9Myz4yw=="],
+
+ "@mercurjs/core-plugin/@medusajs/framework/@medusajs/orchestration": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/utils": "2.13.4", "ulid": "^2.3.0" } }, "sha512-tSBBajULzKbrzU8Fcjxnf7e13n7kVGErZl8avGy1xL1S57nNLk6vrPmft8s/PQA9KpFdWAi8c3GdNwVtm6+7/g=="],
+
+ "@mercurjs/core-plugin/@medusajs/framework/@medusajs/telemetry": ["@medusajs/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.26.10", "axios": "^1.13.1", "axios-retry": "^3.1.9", "boxen": "^5.0.1", "ci-info": "^3.2.0", "configstore": "^5.0.1", "is-docker": "^2.2.1", "remove-trailing-slash": "^0.1.1", "uuid": "^9.0.0" } }, "sha512-EoRFSMt91MFbDfL3A765irZL6MWeixs/npfXHXRtY6CDXL9L6tDhC29JXqFdgSsgW5Qp+qNDVUmoXM1WzF5JaQ=="],
+
+ "@mercurjs/core-plugin/@medusajs/framework/@medusajs/types": ["@medusajs/[email protected]", "", { "dependencies": { "bignumber.js": "^9.1.2" }, "peerDependencies": { "ioredis": "^5.4.1", "vite": "^5.4.21" }, "optionalPeers": ["ioredis", "vite"] }, "sha512-tp9jXAwTWC8eN29QcYe9GK78iprJ+K9YnwAfneUdZgn++wHaqnn/gAkrJxRmEiFlB/xgwlDT+49xzbBEqPLTYw=="],
+
+ "@mercurjs/core-plugin/@medusajs/framework/@medusajs/utils": ["@medusajs/[email protected]", "", { "dependencies": { "@graphql-codegen/core": "^4.0.2", "@graphql-codegen/typescript": "^4.0.9", "@graphql-tools/merge": "^9.0.7", "@graphql-tools/schema": "^10.0.6", "@medusajs/deps": "2.13.4", "@types/pluralize": "^0.0.33", "bignumber.js": "^9.1.2", "dotenv": "^16.4.5", "dotenv-expand": "^11.0.6", "graphql": "^16.9.0", "jsonwebtoken": "^9.0.2", "pg-connection-string": "^2.7.0", "pluralize": "^8.0.0", "ulid": "^2.3.0" }, "peerDependencies": { "express": "^4.21.0" } }, "sha512-TxBOePQSVZcY/6KQf7TqXifDZqcxowEK+3g3swubxuXGZHRmVa5cpQOyV0sk8jJeQQVaVh18sl2FsBrB9TygyA=="],
+
+ "@mercurjs/core-plugin/@medusajs/framework/@medusajs/workflows-sdk": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/modules-sdk": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/utils": "2.13.4", "ulid": "^2.3.0" } }, "sha512-/rX7p6L0RefA3i3ZclrzuZQBWbEsC8VxUIE6LdirZMaImJQhI+/TDyIU5pWQPbcCbPl+chzaPw7KjtXkUpXGig=="],
+
+ "@mercurjs/integration-tests/@medusajs/framework/@medusajs/deps": ["@medusajs/[email protected]", "", { "dependencies": { "@mikro-orm/cli": "6.4.16", "@mikro-orm/core": "6.4.16", "@mikro-orm/knex": "6.4.16", "@mikro-orm/migrations": "6.4.16", "@mikro-orm/postgresql": "6.4.16", "@opentelemetry/api": "^1.9.0", "@opentelemetry/instrumentation-pg": "^0.52.0", "@opentelemetry/resources": "^2.0.0", "@opentelemetry/sdk-node": "^0.200.0", "@opentelemetry/sdk-trace-node": "^2.0.0", "awilix": "^8.0.1", "pg": "^8.16.3", "zod": "3.25.76" } }, "sha512-wUfNMFaDU3RjAJRg8mIcE/DC2kH7yMcouzIANVIO4SZj6ydF+4dPmbNl1Ysmletr1FQYlfLnFl+lNbjW2d6Fxg=="],
+
+ "@mercurjs/integration-tests/@medusajs/framework/@medusajs/modules-sdk": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/utils": "2.13.4" } }, "sha512-QHhlKW0UrYyvwuMaz3Pkgkkb6q02F/M+zS/7gPHiUXaop8EPYaQ+aaT7gun5CkU1VrSm9/Ua52HJdEH9Myz4yw=="],
+
+ "@mercurjs/integration-tests/@medusajs/framework/@medusajs/orchestration": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/utils": "2.13.4", "ulid": "^2.3.0" } }, "sha512-tSBBajULzKbrzU8Fcjxnf7e13n7kVGErZl8avGy1xL1S57nNLk6vrPmft8s/PQA9KpFdWAi8c3GdNwVtm6+7/g=="],
+
+ "@mercurjs/integration-tests/@medusajs/framework/@medusajs/telemetry": ["@medusajs/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.26.10", "axios": "^1.13.1", "axios-retry": "^3.1.9", "boxen": "^5.0.1", "ci-info": "^3.2.0", "configstore": "^5.0.1", "is-docker": "^2.2.1", "remove-trailing-slash": "^0.1.1", "uuid": "^9.0.0" } }, "sha512-EoRFSMt91MFbDfL3A765irZL6MWeixs/npfXHXRtY6CDXL9L6tDhC29JXqFdgSsgW5Qp+qNDVUmoXM1WzF5JaQ=="],
+
+ "@mercurjs/integration-tests/@medusajs/framework/@medusajs/types": ["@medusajs/[email protected]", "", { "dependencies": { "bignumber.js": "^9.1.2" }, "peerDependencies": { "ioredis": "^5.4.1", "vite": "^5.4.21" }, "optionalPeers": ["ioredis", "vite"] }, "sha512-tp9jXAwTWC8eN29QcYe9GK78iprJ+K9YnwAfneUdZgn++wHaqnn/gAkrJxRmEiFlB/xgwlDT+49xzbBEqPLTYw=="],
+
+ "@mercurjs/integration-tests/@medusajs/framework/@medusajs/utils": ["@medusajs/[email protected]", "", { "dependencies": { "@graphql-codegen/core": "^4.0.2", "@graphql-codegen/typescript": "^4.0.9", "@graphql-tools/merge": "^9.0.7", "@graphql-tools/schema": "^10.0.6", "@medusajs/deps": "2.13.4", "@types/pluralize": "^0.0.33", "bignumber.js": "^9.1.2", "dotenv": "^16.4.5", "dotenv-expand": "^11.0.6", "graphql": "^16.9.0", "jsonwebtoken": "^9.0.2", "pg-connection-string": "^2.7.0", "pluralize": "^8.0.0", "ulid": "^2.3.0" }, "peerDependencies": { "express": "^4.21.0" } }, "sha512-TxBOePQSVZcY/6KQf7TqXifDZqcxowEK+3g3swubxuXGZHRmVa5cpQOyV0sk8jJeQQVaVh18sl2FsBrB9TygyA=="],
+
+ "@mercurjs/integration-tests/@medusajs/framework/@medusajs/workflows-sdk": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/modules-sdk": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/utils": "2.13.4", "ulid": "^2.3.0" } }, "sha512-/rX7p6L0RefA3i3ZclrzuZQBWbEsC8VxUIE6LdirZMaImJQhI+/TDyIU5pWQPbcCbPl+chzaPw7KjtXkUpXGig=="],
+
+ "@mercurjs/payout-stripe-connect/@medusajs/framework/@medusajs/deps": ["@medusajs/[email protected]", "", { "dependencies": { "@mikro-orm/cli": "6.4.16", "@mikro-orm/core": "6.4.16", "@mikro-orm/knex": "6.4.16", "@mikro-orm/migrations": "6.4.16", "@mikro-orm/postgresql": "6.4.16", "@opentelemetry/api": "^1.9.0", "@opentelemetry/instrumentation-pg": "^0.52.0", "@opentelemetry/resources": "^2.0.0", "@opentelemetry/sdk-node": "^0.200.0", "@opentelemetry/sdk-trace-node": "^2.0.0", "awilix": "^8.0.1", "pg": "^8.16.3", "zod": "3.25.76" } }, "sha512-wUfNMFaDU3RjAJRg8mIcE/DC2kH7yMcouzIANVIO4SZj6ydF+4dPmbNl1Ysmletr1FQYlfLnFl+lNbjW2d6Fxg=="],
+
+ "@mercurjs/payout-stripe-connect/@medusajs/framework/@medusajs/modules-sdk": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/utils": "2.13.4" } }, "sha512-QHhlKW0UrYyvwuMaz3Pkgkkb6q02F/M+zS/7gPHiUXaop8EPYaQ+aaT7gun5CkU1VrSm9/Ua52HJdEH9Myz4yw=="],
+
+ "@mercurjs/payout-stripe-connect/@medusajs/framework/@medusajs/orchestration": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/utils": "2.13.4", "ulid": "^2.3.0" } }, "sha512-tSBBajULzKbrzU8Fcjxnf7e13n7kVGErZl8avGy1xL1S57nNLk6vrPmft8s/PQA9KpFdWAi8c3GdNwVtm6+7/g=="],
+
+ "@mercurjs/payout-stripe-connect/@medusajs/framework/@medusajs/telemetry": ["@medusajs/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.26.10", "axios": "^1.13.1", "axios-retry": "^3.1.9", "boxen": "^5.0.1", "ci-info": "^3.2.0", "configstore": "^5.0.1", "is-docker": "^2.2.1", "remove-trailing-slash": "^0.1.1", "uuid": "^9.0.0" } }, "sha512-EoRFSMt91MFbDfL3A765irZL6MWeixs/npfXHXRtY6CDXL9L6tDhC29JXqFdgSsgW5Qp+qNDVUmoXM1WzF5JaQ=="],
+
+ "@mercurjs/payout-stripe-connect/@medusajs/framework/@medusajs/types": ["@medusajs/[email protected]", "", { "dependencies": { "bignumber.js": "^9.1.2" }, "peerDependencies": { "ioredis": "^5.4.1", "vite": "^5.4.21" }, "optionalPeers": ["ioredis", "vite"] }, "sha512-tp9jXAwTWC8eN29QcYe9GK78iprJ+K9YnwAfneUdZgn++wHaqnn/gAkrJxRmEiFlB/xgwlDT+49xzbBEqPLTYw=="],
+
+ "@mercurjs/payout-stripe-connect/@medusajs/framework/@medusajs/utils": ["@medusajs/[email protected]", "", { "dependencies": { "@graphql-codegen/core": "^4.0.2", "@graphql-codegen/typescript": "^4.0.9", "@graphql-tools/merge": "^9.0.7", "@graphql-tools/schema": "^10.0.6", "@medusajs/deps": "2.13.4", "@types/pluralize": "^0.0.33", "bignumber.js": "^9.1.2", "dotenv": "^16.4.5", "dotenv-expand": "^11.0.6", "graphql": "^16.9.0", "jsonwebtoken": "^9.0.2", "pg-connection-string": "^2.7.0", "pluralize": "^8.0.0", "ulid": "^2.3.0" }, "peerDependencies": { "express": "^4.21.0" } }, "sha512-TxBOePQSVZcY/6KQf7TqXifDZqcxowEK+3g3swubxuXGZHRmVa5cpQOyV0sk8jJeQQVaVh18sl2FsBrB9TygyA=="],
+
+ "@mercurjs/payout-stripe-connect/@medusajs/framework/@medusajs/workflows-sdk": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/modules-sdk": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/utils": "2.13.4", "ulid": "^2.3.0" } }, "sha512-/rX7p6L0RefA3i3ZclrzuZQBWbEsC8VxUIE6LdirZMaImJQhI+/TDyIU5pWQPbcCbPl+chzaPw7KjtXkUpXGig=="],
+
+ "@mercurjs/registry/@medusajs/framework/@medusajs/deps": ["@medusajs/[email protected]", "", { "dependencies": { "@mikro-orm/cli": "6.4.16", "@mikro-orm/core": "6.4.16", "@mikro-orm/knex": "6.4.16", "@mikro-orm/migrations": "6.4.16", "@mikro-orm/postgresql": "6.4.16", "@opentelemetry/api": "^1.9.0", "@opentelemetry/instrumentation-pg": "^0.52.0", "@opentelemetry/resources": "^2.0.0", "@opentelemetry/sdk-node": "^0.200.0", "@opentelemetry/sdk-trace-node": "^2.0.0", "awilix": "^8.0.1", "pg": "^8.16.3", "zod": "3.25.76" } }, "sha512-wUfNMFaDU3RjAJRg8mIcE/DC2kH7yMcouzIANVIO4SZj6ydF+4dPmbNl1Ysmletr1FQYlfLnFl+lNbjW2d6Fxg=="],
+
+ "@mercurjs/registry/@medusajs/framework/@medusajs/modules-sdk": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/utils": "2.13.4" } }, "sha512-QHhlKW0UrYyvwuMaz3Pkgkkb6q02F/M+zS/7gPHiUXaop8EPYaQ+aaT7gun5CkU1VrSm9/Ua52HJdEH9Myz4yw=="],
+
+ "@mercurjs/registry/@medusajs/framework/@medusajs/orchestration": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/utils": "2.13.4", "ulid": "^2.3.0" } }, "sha512-tSBBajULzKbrzU8Fcjxnf7e13n7kVGErZl8avGy1xL1S57nNLk6vrPmft8s/PQA9KpFdWAi8c3GdNwVtm6+7/g=="],
+
+ "@mercurjs/registry/@medusajs/framework/@medusajs/telemetry": ["@medusajs/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.26.10", "axios": "^1.13.1", "axios-retry": "^3.1.9", "boxen": "^5.0.1", "ci-info": "^3.2.0", "configstore": "^5.0.1", "is-docker": "^2.2.1", "remove-trailing-slash": "^0.1.1", "uuid": "^9.0.0" } }, "sha512-EoRFSMt91MFbDfL3A765irZL6MWeixs/npfXHXRtY6CDXL9L6tDhC29JXqFdgSsgW5Qp+qNDVUmoXM1WzF5JaQ=="],
+
+ "@mercurjs/registry/@medusajs/framework/@medusajs/types": ["@medusajs/[email protected]", "", { "dependencies": { "bignumber.js": "^9.1.2" }, "peerDependencies": { "ioredis": "^5.4.1", "vite": "^5.4.21" }, "optionalPeers": ["ioredis", "vite"] }, "sha512-tp9jXAwTWC8eN29QcYe9GK78iprJ+K9YnwAfneUdZgn++wHaqnn/gAkrJxRmEiFlB/xgwlDT+49xzbBEqPLTYw=="],
+
+ "@mercurjs/registry/@medusajs/framework/@medusajs/utils": ["@medusajs/[email protected]", "", { "dependencies": { "@graphql-codegen/core": "^4.0.2", "@graphql-codegen/typescript": "^4.0.9", "@graphql-tools/merge": "^9.0.7", "@graphql-tools/schema": "^10.0.6", "@medusajs/deps": "2.13.4", "@types/pluralize": "^0.0.33", "bignumber.js": "^9.1.2", "dotenv": "^16.4.5", "dotenv-expand": "^11.0.6", "graphql": "^16.9.0", "jsonwebtoken": "^9.0.2", "pg-connection-string": "^2.7.0", "pluralize": "^8.0.0", "ulid": "^2.3.0" }, "peerDependencies": { "express": "^4.21.0" } }, "sha512-TxBOePQSVZcY/6KQf7TqXifDZqcxowEK+3g3swubxuXGZHRmVa5cpQOyV0sk8jJeQQVaVh18sl2FsBrB9TygyA=="],
+
+ "@mercurjs/registry/@medusajs/framework/@medusajs/workflows-sdk": ["@medusajs/[email protected]", "", { "dependencies": { "@medusajs/deps": "2.13.4", "@medusajs/modules-sdk": "2.13.4", "@medusajs/orchestration": "2.13.4", "@medusajs/utils": "2.13.4", "ulid": "^2.3.0" } }, "sha512-/rX7p6L0RefA3i3ZclrzuZQBWbEsC8VxUIE6LdirZMaImJQhI+/TDyIU5pWQPbcCbPl+chzaPw7KjtXkUpXGig=="],
+
+ "@mercurjs/registry/@medusajs/framework/jsonwebtoken": ["[email protected]", "", { "dependencies": { "jws": "^4.0.1", "lodash.includes": "^4.3.0", "lodash.isboolean": "^3.0.3", "lodash.isinteger": "^4.0.4", "lodash.isnumber": "^3.0.3", "lodash.isplainobject": "^4.0.6", "lodash.isstring": "^4.0.1", "lodash.once": "^4.0.0", "ms": "^2.1.1", "semver": "^7.5.4" } }, "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g=="],
"@mercurjs/registry/jsonwebtoken/jws": ["[email protected]", "", { "dependencies": { "jwa": "^1.4.2", "safe-buffer": "^5.0.1" } }, "sha512-byiJ0FLRdLdSVSReO/U4E7RoEyOCKnEnEPMjq3HxWtvzLsV08/i5RQKsFVNkCldrCaPr2vDNAOMsfs8T/Hze7g=="],
diff --git a/package.json b/package.json
index d3c074015..5e1a1bf51 100644
--- a/package.json
+++ b/package.json
@@ -5,6 +5,7 @@
"build": "turbo run build",
"dev": "turbo run dev",
"lint": "turbo run lint",
+ "test:integration:http": "turbo run test:integration:http --filter=@mercurjs/integration-tests",
"format": "prettier --write \"**/*.{ts,tsx,md}\"",
"check-types": "turbo run check-types"
},
@@ -24,6 +25,7 @@
"workspaces": [
"apps/*",
"packages/*",
+ "packages/providers/*",
"integration-tests"
]
-}
\ No newline at end of file
+}
diff --git a/packages/core-plugin/src/jobs/README.md b/packages/core-plugin/src/jobs/README.md
deleted file mode 100644
index eaf89d795..000000000
--- a/packages/core-plugin/src/jobs/README.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# Custom scheduled jobs
-
-A scheduled job is a function executed at a specified interval of time in the background of your Medusa application.
-
-A scheduled job is created in a TypeScript or JavaScript file under the `src/jobs` directory.
-
-For example, create the file `src/jobs/hello-world.ts` with the following content:
-
-```ts
-import {
- MedusaContainer
-} from "@medusajs/framework/types";
-
-export default async function myCustomJob(container: MedusaContainer) {
- const productService = container.resolve("product")
-
- const products = await productService.listAndCountProducts();
-
- // Do something with the products
-}
-
-export const config = {
- name: "daily-product-report",
- schedule: "0 0 * * *", // Every day at midnight
-};
-```
-
-A scheduled job file must export:
-
-- The function to be executed whenever it’s time to run the scheduled job.
-- A configuration object defining the job. It has three properties:
- - `name`: a unique name for the job.
- - `schedule`: a [cron expression](https://crontab.guru/).
- - `numberOfExecutions`: an optional integer, specifying how many times the job will execute before being removed
-
-The `handler` is a function that accepts one parameter, `container`, which is a `MedusaContainer` instance used to resolve services.
diff --git a/packages/core-plugin/src/jobs/capture-check.ts b/packages/core-plugin/src/jobs/capture-check.ts
new file mode 100644
index 000000000..55392563f
--- /dev/null
+++ b/packages/core-plugin/src/jobs/capture-check.ts
@@ -0,0 +1,215 @@
+import { getOrdersListWorkflow } from "@medusajs/core-flows"
+import type { MedusaContainer } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import type { FulfillmentStatus, IOrderModuleService } from "@medusajs/types"
+import {
+ MercurModules,
+ PaymentCollectionDTO,
+ PayoutAccountStatus,
+ PayoutEvents,
+} from "@mercurjs/types"
+
+import PayoutModuleService from "../modules/payout/services/payout-module-service"
+
+const FULFILLMENT_STATUS_ORDER: FulfillmentStatus[] = [
+ "not_fulfilled",
+ "partially_fulfilled",
+ "fulfilled",
+ "partially_shipped",
+ "shipped",
+ "partially_delivered",
+ "delivered",
+]
+
+function meetsRequiredFulfillmentStatus(
+ status: FulfillmentStatus,
+ required: FulfillmentStatus
+): boolean {
+ const statusIndex = FULFILLMENT_STATUS_ORDER.indexOf(status)
+ const requiredIndex = FULFILLMENT_STATUS_ORDER.indexOf(required)
+
+ return statusIndex !== -1 && statusIndex >= requiredIndex
+}
+
+const CAPTURE_CHECK_FIELDS = [
+ "id",
+ "display_id",
+ "status",
+ "email",
+ "currency_code",
+ "region_id",
+ "customer_id",
+ "sales_channel_id",
+ "created_at",
+ "updated_at",
+ "canceled_at",
+ "metadata",
+ "*items",
+ "*items.variant",
+ "*items.variant.product",
+ "*shipping_address",
+ "*billing_address",
+ "*shipping_methods",
+ "*payment_collections",
+ "*fulfillments",
+ "*summary",
+ "payouts.id",
+ "seller.payout_account.id",
+ "seller.payout_account.status",
+]
+
+export default async function captureCheckJob(container: MedusaContainer) {
+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
+ const eventBus = container.resolve(Modules.EVENT_BUS)
+ const orderModule = container.resolve<IOrderModuleService>(Modules.ORDER)
+ const service = container.resolve<PayoutModuleService>(MercurModules.PAYOUT)
+
+ const options = service.getOptions()
+
+ if (options.disabled) {
+ logger.warn("Capture check job skipped - payouts disabled")
+ return
+ }
+
+ const batchSize = 100
+ const authWindowMs = options.authorizationWindowMs
+ const safetyBufferMs = options.captureSafetyBufferMs
+ const requiredFulfillmentStatus = options.requiredFulfillmentStatus
+
+ logger.info("Capture check job started")
+ logger.debug(
+ `Capture check config - authWindowMs: ${authWindowMs}, safetyBufferMs: ${safetyBufferMs}, requiredFulfillmentStatus: ${requiredFulfillmentStatus}`
+ )
+
+ let offset = 0
+ let emittedCount = 0
+
+ const workflow = getOrdersListWorkflow(container)
+
+ while (true) {
+ const { result } = await workflow.run({
+ input: {
+ fields: CAPTURE_CHECK_FIELDS,
+ variables: {
+ filters: {
+ is_draft_order: false,
+ canceled_at: null,
+ metadata: {
+ $ne: { capture_requested: true },
+ }
+ },
+ take: batchSize,
+ skip: offset,
+ order: {
+ created_at: "ASC",
+ },
+ },
+ },
+ })
+
+ const { rows: orders } = result as {
+ rows: any[];
+ };
+
+ if (!orders.length) break
+
+ logger.debug(`Capture check - fetched ${orders.length} orders at offset ${offset}`)
+
+ const events: { name: string; data: Record<string, unknown> }[] = []
+ const orderIdsToUpdate: string[] = []
+
+ for (const order of orders) {
+ if (order.payouts?.length) {
+ logger.debug(`Order ${order.id} - skipped, has payouts`)
+ continue
+ }
+
+ if (order.seller?.payout_account?.status !== PayoutAccountStatus.ACTIVE) {
+ logger.debug(`Order ${order.id} - skipped, payout account not active`)
+ continue
+ }
+
+ if (!meetsRequiredFulfillmentStatus(order.fulfillment_status, requiredFulfillmentStatus)) {
+ logger.debug(`Order ${order.id} - skipped, fulfillment status ${order.fulfillment_status} below required ${requiredFulfillmentStatus}`)
+ continue
+ }
+
+ if (order.payment_status !== "authorized") {
+ logger.debug(`Order ${order.id} - skipped, payment status ${order.payment_status}`)
+ continue
+ }
+
+ const pc = (order.payment_collections ?? []).find(
+ (c: PaymentCollectionDTO) => c.status === "authorized"
+ )
+
+ if (!pc) {
+ logger.debug(`Order ${order.id} - skipped, no authorized payment collection`)
+ continue
+ }
+
+ const authorizedAt = new Date(pc.created_at).getTime()
+ const expiresAt = authorizedAt + authWindowMs
+ const captureDeadline = expiresAt - safetyBufferMs
+
+ const now = Date.now()
+
+ if (now >= expiresAt) {
+ logger.warn(`Order ${order.id} - authorization expired at ${new Date(expiresAt).toISOString()}`)
+
+ events.push({
+ name: PayoutEvents.OrderAuthorizationExpired,
+ data: {
+ order_id: order.id,
+ authorized_at: new Date(authorizedAt),
+ expires_at: new Date(expiresAt),
+ },
+ })
+
+ orderIdsToUpdate.push(order.id)
+ continue
+ }
+
+ if (now < captureDeadline) {
+ logger.debug(`Order ${order.id} - skipped, capture deadline not reached`)
+ continue
+ }
+
+ logger.info(`Emitting capture requested - order ${order.id}`)
+
+ events.push({
+ name: PayoutEvents.OrderCaptureRequested,
+ data: {
+ order_id: order.id,
+ authorized_at: new Date(authorizedAt),
+ expires_at: new Date(expiresAt),
+ },
+ })
+
+ orderIdsToUpdate.push(order.id)
+ }
+
+ if (events.length) {
+ await eventBus.emit(events, { attempts: 3 })
+
+ await orderModule.updateOrders(
+ orderIdsToUpdate.map((id) => ({
+ id,
+ metadata: { capture_requested: true },
+ }))
+ )
+
+ emittedCount += events.length
+ }
+
+ if (orders.length < batchSize) break
+ offset += batchSize
+ }
+
+ logger.info(`Capture check job completed - ${emittedCount} capture(s) requested`)
+}
+
+export const config = {
+ name: "capture-check",
+ schedule: "*/15 * * * *",
+}
diff --git a/packages/core-plugin/src/jobs/daily-payouts.ts b/packages/core-plugin/src/jobs/daily-payouts.ts
new file mode 100644
index 000000000..2b892b1a6
--- /dev/null
+++ b/packages/core-plugin/src/jobs/daily-payouts.ts
@@ -0,0 +1,113 @@
+import { getOrdersListWorkflow } from "@medusajs/core-flows"
+import type { MedusaContainer } from "@medusajs/framework/types"
+import {
+ ContainerRegistrationKeys,
+ Modules,
+} from "@medusajs/framework/utils"
+import { MercurModules, PayoutAccountStatus, PayoutEvents } from "@mercurjs/types"
+
+import PayoutModuleService from "../modules/payout/services/payout-module-service"
+
+const BATCH_SIZE = 100
+
+const DAILY_PAYOUTS_FIELDS = [
+ "id",
+ "metadata",
+ "currency_code",
+ "*payment_collections",
+ "*fulfillments",
+ "*summary",
+ "payouts.id",
+ "seller.payout_account.id",
+ "seller.payout_account.status",
+]
+
+export default async function dailyPayoutsJob(container: MedusaContainer) {
+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
+ const eventBus = container.resolve(Modules.EVENT_BUS)
+ const service = container.resolve<PayoutModuleService>(MercurModules.PAYOUT)
+
+ const options = service.getOptions()
+
+ if (options.disabled) {
+ logger.warn("Daily payouts job skipped - payouts disabled")
+ return
+ }
+
+ logger.info("Daily payouts job started")
+
+ let offset = 0
+ let emitted = 0
+
+ const listWorkflow = getOrdersListWorkflow(container)
+
+ while (true) {
+ const { result } = await listWorkflow.run({
+ input: {
+ fields: DAILY_PAYOUTS_FIELDS,
+ variables: {
+ filters: {
+ is_draft_order: false,
+ canceled_at: null,
+ $and: [
+ { metadata: { captured: true } },
+ { metadata: { $ne: { payout_transferred: true } } },
+ { metadata: { $ne: { payout_failed: true } } },
+ ],
+ },
+ take: BATCH_SIZE,
+ skip: offset,
+ order: {
+ created_at: "ASC",
+ },
+ },
+ },
+ })
+
+ const { rows: orders } = result as {
+ rows: any[];
+ }
+
+ if (!orders.length) break
+
+ logger.debug(`Daily payouts - fetched ${orders.length} orders at offset ${offset}`)
+
+ const events: { name: string; data: Record<string, unknown> }[] = []
+
+ for (const order of orders) {
+ if (order.payouts?.length) {
+ logger.debug(`Order ${order.id} - skipped, already has payouts`)
+ continue
+ }
+
+ if (order.seller?.payout_account?.status !== PayoutAccountStatus.ACTIVE) {
+ logger.debug(`Order ${order.id} - skipped, payout account not active (status: ${order.seller?.payout_account?.status})`)
+ continue
+ }
+
+ logger.info(`Emitting payout transfer requested - order ${order.id}`)
+
+ events.push({
+ name: PayoutEvents.PayoutRequested,
+ data: {
+ order_id: order.id,
+ },
+ })
+ }
+
+ if (events.length) {
+ await eventBus.emit(events, { attempts: 3 })
+ emitted += events.length
+ }
+
+ if (orders.length < BATCH_SIZE) break
+ offset += BATCH_SIZE
+ }
+
+ logger.info(`Daily payouts job completed - ${emitted} transfer(s) requested`)
+}
+
+export const config = {
+ name: "daily-payouts",
+ schedule: "0 1 * * *",
+}
diff --git a/packages/core-plugin/src/modules/payout/migrations/Migration20260130132816.ts b/packages/core-plugin/src/modules/payout/migrations/Migration20260130132816.ts
index aadaee873..f6bedc446 100644
--- a/packages/core-plugin/src/modules/payout/migrations/Migration20260130132816.ts
+++ b/packages/core-plugin/src/modules/payout/migrations/Migration20260130132816.ts
@@ -7,7 +7,7 @@ export class Migration20260130132816 extends Migration {
this.addSql(`create table if not exists "payout_account" ("id" text not null, "status" text check ("status" in ('pending', 'active', 'restricted', 'rejected')) not null default 'pending', "data" jsonb not null, "context" jsonb null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "payout_account_pkey" primary key ("id"));`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_payout_account_deleted_at" ON "payout_account" ("deleted_at") WHERE deleted_at IS NULL;`);
- this.addSql(`create table if not exists "payout" ("id" text not null, "currency_code" text not null, "amount" numeric not null, "data" jsonb null, "account_id" text not null, "status" text check ("status" in ('pending', 'processing', 'paid', 'failed', 'canceled')) not null default 'pending', "raw_amount" jsonb not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "payout_pkey" primary key ("id"));`);
+ this.addSql(`create table if not exists "payout" ("id" text not null, "currency_code" text not null, "amount" numeric not null, "data" jsonb null, "account_id" text not null, "status" text check ("status" in ('pending', 'paid', 'failed', 'canceled')) not null default 'pending', "raw_amount" jsonb not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "payout_pkey" primary key ("id"));`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_payout_account_id" ON "payout" ("account_id") WHERE deleted_at IS NULL;`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_payout_deleted_at" ON "payout" ("deleted_at") WHERE deleted_at IS NULL;`);
diff --git a/packages/core-plugin/src/modules/payout/migrations/Migration20260317000000.ts b/packages/core-plugin/src/modules/payout/migrations/Migration20260317000000.ts
new file mode 100644
index 000000000..9c695a55e
--- /dev/null
+++ b/packages/core-plugin/src/modules/payout/migrations/Migration20260317000000.ts
@@ -0,0 +1,28 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations";
+
+export class Migration20260317000000 extends Migration {
+
+ override async up(): Promise<void> {
+ this.addSql(`alter table if exists "payout_balance" drop constraint if exists "payout_balance_account_id_foreign";`);
+ this.addSql(`alter table if exists "payout_transaction" drop constraint if exists "payout_transaction_account_id_foreign";`);
+
+ this.addSql(`drop table if exists "payout_balance" cascade;`);
+ this.addSql(`drop table if exists "payout_transaction" cascade;`);
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(`create table if not exists "payout_balance" ("id" text not null, "currency_code" text not null, "totals" jsonb not null, "account_id" text not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "payout_balance_pkey" primary key ("id"));`);
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_payout_balance_account_id" ON "payout_balance" ("account_id") WHERE deleted_at IS NULL;`);
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_payout_balance_deleted_at" ON "payout_balance" ("deleted_at") WHERE deleted_at IS NULL;`);
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_payout_balance_account_currency" ON "payout_balance" ("account_id", "currency_code") WHERE deleted_at IS NULL;`);
+
+ this.addSql(`create table if not exists "payout_transaction" ("id" text not null, "amount" numeric not null, "currency_code" text not null, "reference" text null, "reference_id" text null, "account_id" text not null, "raw_amount" jsonb not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "payout_transaction_pkey" primary key ("id"));`);
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_payout_transaction_account_id" ON "payout_transaction" ("account_id") WHERE deleted_at IS NULL;`);
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_payout_transaction_deleted_at" ON "payout_transaction" ("deleted_at") WHERE deleted_at IS NULL;`);
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_payout_transaction_reference" ON "payout_transaction" ("reference", "reference_id") WHERE deleted_at IS NULL;`);
+
+ this.addSql(`alter table if exists "payout_balance" add constraint "payout_balance_account_id_foreign" foreign key ("account_id") references "payout_account" ("id") on update cascade;`);
+ this.addSql(`alter table if exists "payout_transaction" add constraint "payout_transaction_account_id_foreign" foreign key ("account_id") references "payout_account" ("id") on update cascade;`);
+ }
+
+}
diff --git a/packages/core-plugin/src/modules/payout/models/balance.ts b/packages/core-plugin/src/modules/payout/models/balance.ts
deleted file mode 100644
index 55d40a065..000000000
--- a/packages/core-plugin/src/modules/payout/models/balance.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { model } from "@medusajs/framework/utils";
-
-import { PayoutAccount } from "./payout-account";
-
-export const PayoutBalance = model
- .define("payout_balance", {
- id: model.id({ prefix: "pbal" }).primaryKey(),
- currency_code: model.text(),
- /**
- * PayoutBalance.totals JSON structure:
- * {
- * balance: BigNumberValue, // Current available balance (display)
- * raw_balance: BigNumberRawValue, // Raw balance for precise calculations
- * }
- *
- * Example:
- * {
- * balance: 15000, // $150.00 (in cents)
- * raw_balance: { value: "15000", precision: 20 }
- * }
- */
- totals: model.json(),
- account: model.belongsTo(() => PayoutAccount, {
- mappedBy: "balances",
- }),
- })
- .indexes([
- {
- name: "IDX_payout_balance_account_currency",
- on: ["account_id", "currency_code"],
- unique: true,
- },
- ]);
diff --git a/packages/core-plugin/src/modules/payout/models/index.ts b/packages/core-plugin/src/modules/payout/models/index.ts
index f32f22ea6..9d7b04c8c 100644
--- a/packages/core-plugin/src/modules/payout/models/index.ts
+++ b/packages/core-plugin/src/modules/payout/models/index.ts
@@ -1,5 +1,3 @@
export { Onboarding } from './onboarding'
export { Payout } from './payout'
export { PayoutAccount } from './payout-account'
-export { PayoutBalance } from './balance'
-export { PayoutTransaction } from './transaction'
diff --git a/packages/core-plugin/src/modules/payout/models/payout-account.ts b/packages/core-plugin/src/modules/payout/models/payout-account.ts
index fc90e0cfc..b683be5ce 100644
--- a/packages/core-plugin/src/modules/payout/models/payout-account.ts
+++ b/packages/core-plugin/src/modules/payout/models/payout-account.ts
@@ -3,8 +3,6 @@ import { model } from "@medusajs/framework/utils";
import { PayoutAccountStatus } from "@mercurjs/types";
import { Onboarding } from "./onboarding";
import { Payout } from "./payout";
-import { PayoutTransaction } from "./transaction";
-import { PayoutBalance } from "./balance";
export const PayoutAccount = model.define("payout_account", {
id: model.id({ prefix: "pacc" }).primaryKey(),
@@ -17,10 +15,4 @@ export const PayoutAccount = model.define("payout_account", {
payouts: model.hasMany(() => Payout, {
mappedBy: 'account'
}),
- transactions: model.hasMany(() => PayoutTransaction, {
- mappedBy: 'account'
- }),
- balances: model.hasMany(() => PayoutBalance, {
- mappedBy: 'account'
- }),
});
diff --git a/packages/core-plugin/src/modules/payout/models/transaction.ts b/packages/core-plugin/src/modules/payout/models/transaction.ts
deleted file mode 100644
index ebe149edd..000000000
--- a/packages/core-plugin/src/modules/payout/models/transaction.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { model } from '@medusajs/framework/utils'
-
-import { PayoutAccount } from './payout-account'
-
-export const PayoutTransaction = model.define('payout_transaction', {
- id: model.id({ prefix: 'ptxn' }).primaryKey(),
- amount: model.bigNumber(),
- currency_code: model.text(),
- reference: model.text().nullable(),
- reference_id: model.text().nullable(),
- account: model.belongsTo(() => PayoutAccount, {
- mappedBy: 'transactions'
- }),
-})
- .indexes([
- {
- name: "IDX_payout_transaction_account_id",
- on: ["account_id"],
- },
- {
- name: "IDX_payout_transaction_reference",
- on: ["reference", "reference_id"],
- },
- ])
diff --git a/packages/core-plugin/src/modules/payout/services/payout-module-service.ts b/packages/core-plugin/src/modules/payout/services/payout-module-service.ts
index e3ce99859..5f7574d41 100644
--- a/packages/core-plugin/src/modules/payout/services/payout-module-service.ts
+++ b/packages/core-plugin/src/modules/payout/services/payout-module-service.ts
@@ -1,37 +1,29 @@
import {
- BigNumber,
- createRawPropertiesFromBigNumber,
EmitEvents,
InjectManager,
InjectTransactionManager,
- MathBN,
MedusaContext,
MedusaError,
MedusaService,
- promiseAll,
} from "@medusajs/framework/utils"
import {
CreatePayoutAccountDTO,
CreatePayoutAccountResponse,
CreatePayoutDTO,
CreateOnboardingDTO,
- CreatePayoutTransactionDTO,
OnboardingDTO,
PayoutAccountDTO,
PayoutAccountStatus,
PayoutDTO,
- PayoutTransactionDTO,
PayoutWebhookActionInput,
PayoutWebhookResult,
- PayoutBalanceDTO,
- PayoutBalanceTotals,
+ PayoutModuleOptions,
+ PAYOUT_MODULE_OPTION_DEFAULTS,
} from "@mercurjs/types"
import PayoutProviderService from "./provider-service"
-import { Onboarding, Payout, PayoutAccount, PayoutBalance, PayoutTransaction } from "../models"
-import { BigNumberInput, Context, DAL, InferEntityType, ModulesSdkTypes } from "@medusajs/framework/types"
+import { Onboarding, Payout, PayoutAccount } from "../models"
+import { Context, DAL, InferEntityType, ModulesSdkTypes } from "@medusajs/framework/types"
import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
-import { IsolationLevel } from "@medusajs/framework/mikro-orm/core"
-import { calculatePayoutTransactions } from "../utils/calculate-payout-transactions"
type InjectedDependencies = {
payoutProviderService: PayoutProviderService
@@ -42,59 +34,26 @@ export default class PayoutModuleService extends MedusaService({
Onboarding,
Payout,
PayoutAccount,
- PayoutBalance,
- PayoutTransaction,
}) {
protected readonly payoutProviderService_: PayoutProviderService
protected readonly baseRepository_: DAL.RepositoryService
+ protected readonly options_: PayoutModuleOptions
- constructor({ payoutProviderService, baseRepository }: InjectedDependencies) {
+ constructor({ payoutProviderService, baseRepository }: InjectedDependencies, options: PayoutModuleOptions) {
// @ts-ignore
super(...arguments)
this.payoutProviderService_ = payoutProviderService
this.baseRepository_ = baseRepository
- }
-
- @InjectManager()
- private async validatePayoutAvailability_(
- account_id: string,
- amount: BigNumberInput,
- currency_code: string,
- @MedusaContext() sharedContext?: Context<EntityManager>
- ): Promise<void> {
- const account = await this.retrievePayoutAccount(
- account_id,
- { select: ['id', 'status'] },
- sharedContext
- )
-
- if (account.status !== PayoutAccountStatus.ACTIVE) {
- throw new MedusaError(
- MedusaError.Types.NOT_ALLOWED,
- `Account '${account_id}' is not active`
- )
+ this.options_ = {
+ ...PAYOUT_MODULE_OPTION_DEFAULTS,
+ ...(options ?? {}),
}
+ }
- const [balance] = await this.listPayoutBalances(
- { account_id, currency_code },
- { take: 1 },
- sharedContext
- )
-
- if (!balance) {
- throw new MedusaError(
- MedusaError.Types.NOT_ALLOWED,
- 'Insufficient funds'
- )
- }
-
- const currentBalance = (balance.totals as unknown as PayoutBalanceTotals)?.raw_balance?.value ?? "0"
-
- if (MathBN.lt(currentBalance, amount)) {
- throw new MedusaError(
- MedusaError.Types.NOT_ALLOWED,
- 'Insufficient funds'
- )
+ getOptions() {
+ return {
+ ...PAYOUT_MODULE_OPTION_DEFAULTS,
+ ...(this.options_ ?? {}),
}
}
@@ -193,17 +152,17 @@ export default class PayoutModuleService extends MedusaService({
input: CreatePayoutDTO,
@MedusaContext() sharedContext?: Context<EntityManager>
): Promise<PayoutDTO> {
- await this.validatePayoutAvailability_(
- input.account_id,
- input.amount,
- input.currency_code,
- sharedContext
- )
-
const payoutAccount = await this.retrievePayoutAccount(input.account_id, {
- select: ['id', 'data']
+ select: ['id', 'status', 'data']
}, sharedContext)
+ if (payoutAccount.status !== PayoutAccountStatus.ACTIVE) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_ALLOWED,
+ `Account '${input.account_id}' is not active`
+ )
+ }
+
const providerResponse = await this.payoutProviderService_.createPayout({
account_id: input.account_id,
amount: input.amount,
@@ -234,162 +193,4 @@ export default class PayoutModuleService extends MedusaService({
): Promise<PayoutWebhookResult> {
return await this.payoutProviderService_.getWebhookActionAndData(input)
}
-
- @InjectTransactionManager()
- private async addPayoutTransactions_(
- account_id: string,
- transactions: Omit<CreatePayoutTransactionDTO, 'account_id'>[],
- @MedusaContext() sharedContext?: Context<EntityManager>
- ): Promise<PayoutTransactionDTO[]> {
- return await this.baseRepository_.transaction<EntityManager>(
- async (transactionManager) => {
- // Group transactions by currency_code
- const groupedByCurrency = transactions.reduce((acc, txn) => {
- if (!acc[txn.currency_code]) {
- acc[txn.currency_code] = []
- }
- acc[txn.currency_code].push(txn)
- return acc
- }, {} as Record<string, Omit<CreatePayoutTransactionDTO, 'account_id'>[]>)
-
- // Update balances for each currency
- await promiseAll(
- Object.entries(groupedByCurrency).map(async ([currency_code, currencyTransactions]) => {
- const [existingBalance] = await this.listPayoutBalances(
- { account_id, currency_code },
- { take: 1 },
- { transactionManager }
- )
-
- const newTotals = calculatePayoutTransactions({
- currentBalance: existingBalance as unknown as PayoutBalanceDTO,
- transactions: currencyTransactions
- })
-
- if (!existingBalance) {
- await this.createPayoutBalances(
- { account_id, currency_code, totals: newTotals },
- { transactionManager }
- )
- } else {
- await this.updatePayoutBalances(
- { id: existingBalance.id, totals: newTotals },
- { transactionManager }
- )
- }
- })
- )
-
- const createdTransactions = await this.createPayoutTransactions(
- transactions.map((txn) => ({
- ...txn,
- account_id,
- amount: MathBN.convert(txn.amount).toNumber(),
- })),
- { transactionManager }
- )
-
- return await this.baseRepository_.serialize<PayoutTransactionDTO[]>(createdTransactions)
- },
- {
- transaction: sharedContext?.transactionManager,
- isolationLevel: IsolationLevel.SERIALIZABLE,
- }
- )
- }
-
- @InjectManager()
- @EmitEvents()
- async addPayoutTransactions(
- account_id: string,
- transactions: Omit<CreatePayoutTransactionDTO, 'account_id'>[],
- @MedusaContext() sharedContext?: Context<EntityManager>
- ): Promise<PayoutTransactionDTO[]> {
- return await this.addPayoutTransactions_(
- account_id,
- transactions,
- sharedContext
- )
- }
-
- @InjectTransactionManager()
- @EmitEvents()
- // @ts-ignore
- async deletePayoutTransactions(
- transactionIds: string | string[],
- @MedusaContext() sharedContext: Context<EntityManager> = {}
- ): Promise<void> {
- const ids = Array.isArray(transactionIds) ? transactionIds : [transactionIds]
-
- if (!ids.length) {
- return
- }
-
- const transactions = await super.listPayoutTransactions(
- { id: ids },
- undefined,
- sharedContext
- )
-
- if (!transactions.length) {
- return
- }
-
- await super.deletePayoutTransactions(ids, sharedContext)
-
- await this.updatePayoutBalanceAfterUpdate_(transactions, sharedContext)
- }
-
- @InjectTransactionManager()
- private async updatePayoutBalanceAfterUpdate_(
- transactions: PayoutTransactionDTO[],
- @MedusaContext() sharedContext: Context<EntityManager> = {}
- ): Promise<void> {
- // Group transactions by account_id and currency_code
- const grouped = transactions.reduce((acc, txn) => {
- const key = `${txn.account_id}-${txn.currency_code}`
- if (!acc[key]) {
- acc[key] = {
- account_id: txn.account_id,
- currency_code: txn.currency_code,
- totalAmount: MathBN.convert(0)
- }
- }
- acc[key].totalAmount = MathBN.add(acc[key].totalAmount, txn.amount)
- return acc
- }, {} as Record<string, { account_id: string; currency_code: string; totalAmount: BigNumberInput }>)
-
- await promiseAll(
- Object.values(grouped).map(async (group) => {
- const [balance] = await this.listPayoutBalances(
- { account_id: group.account_id, currency_code: group.currency_code },
- { take: 1 },
- sharedContext
- )
-
- if (!balance) {
- return
- }
-
- const currentRawBalance = (balance.totals as unknown as PayoutBalanceTotals)?.raw_balance?.value ?? "0"
-
- // Subtract the deleted transaction amounts from the balance
- const newBalance = MathBN.sub(
- MathBN.convert(currentRawBalance),
- group.totalAmount
- )
-
- const totals = {
- balance: new BigNumber(newBalance),
- }
-
- createRawPropertiesFromBigNumber(totals)
-
- await this.updatePayoutBalances(
- { id: balance.id, totals },
- sharedContext
- )
- })
- )
- }
}
diff --git a/packages/core-plugin/src/modules/payout/utils/calculate-payout-transactions.ts b/packages/core-plugin/src/modules/payout/utils/calculate-payout-transactions.ts
deleted file mode 100644
index 556ef2d7c..000000000
--- a/packages/core-plugin/src/modules/payout/utils/calculate-payout-transactions.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { BigNumberInput } from "@medusajs/framework/types"
-import { BigNumber, createRawPropertiesFromBigNumber, MathBN } from "@medusajs/framework/utils"
-import { PayoutBalanceDTO, PayoutBalanceTotals } from "@mercurjs/types"
-
-export function calculatePayoutTransactions({ transactions, currentBalance }: {
- currentBalance?: PayoutBalanceDTO,
- transactions: {
- amount: BigNumberInput
- reference?: string
- reference_id?: string
- }[]
-}
-): PayoutBalanceTotals {
- const currentRawBalance = currentBalance?.totals?.raw_balance?.value ?? "0"
- let newBalance = MathBN.convert(currentRawBalance)
-
- for (const transaction of transactions) {
- newBalance = MathBN.add(newBalance, transaction.amount)
- }
-
- const totals = {
- balance: new BigNumber(newBalance),
- }
-
- createRawPropertiesFromBigNumber(totals)
-
- return totals as unknown as PayoutBalanceTotals
-}
diff --git a/packages/core-plugin/src/modules/payout/utils/index.ts b/packages/core-plugin/src/modules/payout/utils/index.ts
deleted file mode 100644
index a1677e7a1..000000000
--- a/packages/core-plugin/src/modules/payout/utils/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './calculate-payout-transactions'
\ No newline at end of file
diff --git a/packages/core-plugin/src/subscribers/README.md b/packages/core-plugin/src/subscribers/README.md
deleted file mode 100644
index 0f5f58bf8..000000000
--- a/packages/core-plugin/src/subscribers/README.md
+++ /dev/null
@@ -1,59 +0,0 @@
-# Custom subscribers
-
-Subscribers handle events emitted in the Medusa application.
-
-The subscriber is created in a TypeScript or JavaScript file under the `src/subscribers` directory.
-
-For example, create the file `src/subscribers/product-created.ts` with the following content:
-
-```ts
-import {
- type SubscriberConfig,
-} from "@medusajs/framework"
-
-// subscriber function
-export default async function productCreateHandler() {
- console.log("A product was created")
-}
-
-// subscriber config
-export const config: SubscriberConfig = {
- event: "product.created",
-}
-```
-
-A subscriber file must export:
-
-- The subscriber function that is an asynchronous function executed whenever the associated event is triggered.
-- A configuration object defining the event this subscriber is listening to.
-
-## Subscriber Parameters
-
-A subscriber receives an object having the following properties:
-
-- `event`: An object holding the event's details. It has a `data` property, which is the event's data payload.
-- `container`: The Medusa container. Use it to resolve modules' main services and other registered resources.
-
-```ts
-import type {
- SubscriberArgs,
- SubscriberConfig,
-} from "@medusajs/framework"
-
-export default async function productCreateHandler({
- event: { data },
- container,
-}: SubscriberArgs<{ id: string }>) {
- const productId = data.id
-
- const productModuleService = container.resolve("product")
-
- const product = await productModuleService.retrieveProduct(productId)
-
- console.log(`The product ${product.title} was created`)
-}
-
-export const config: SubscriberConfig = {
- event: "product.created",
-}
-```
\ No newline at end of file
diff --git a/packages/core-plugin/src/subscribers/capture-order.ts b/packages/core-plugin/src/subscribers/capture-order.ts
new file mode 100644
index 000000000..1ebe090a4
--- /dev/null
+++ b/packages/core-plugin/src/subscribers/capture-order.ts
@@ -0,0 +1,99 @@
+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
+import { capturePaymentWorkflow } from "@medusajs/medusa/core-flows"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import type { IOrderModuleService, PaymentCollectionDTO } from "@medusajs/types"
+import { PayoutEvents } from "@mercurjs/types"
+
+export default async function captureOrderHandler({
+ event: { data },
+ container,
+}: SubscriberArgs<{
+ order_id: string
+ authorized_at: Date
+ expires_at: Date
+}>) {
+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+
+ logger.info(`Capture requested for order ${data.order_id}`)
+ logger.debug(
+ `Order ${data.order_id} - authorized_at: ${data.authorized_at}, expires_at: ${data.expires_at}`
+ )
+
+ const { data: orders } = await query.graph({
+ entity: "order",
+ fields: [
+ "id",
+ "payment_collections.payments.id",
+ "payment_collections.payments.captured_at",
+ ],
+ filters: {
+ id: data.order_id,
+ },
+ })
+
+ const order = orders[0]
+
+ if (!order) {
+ logger.error(`Order not found - ${data.order_id}`)
+ return
+ }
+
+ const payments = order.payment_collections?.flatMap(
+ (pc: PaymentCollectionDTO) => pc.payments ?? []
+ )
+
+ logger.debug(
+ `Order ${data.order_id} - found ${payments?.length ?? 0} payment(s)`
+ )
+
+ const payment = payments?.find((p: any) => !p.captured_at)
+
+ if (!payment) {
+ logger.warn(`No uncaptured payment found for order - ${data.order_id}`)
+ return
+ }
+
+ try {
+ await capturePaymentWorkflow(container).run({
+ input: {
+ payment_id: payment.id,
+ },
+ })
+
+ const orderModule = container.resolve<IOrderModuleService>(Modules.ORDER)
+
+ await orderModule.updateOrders(data.order_id, {
+ metadata: {
+ captured: true,
+ },
+ })
+
+ logger.info(
+ `Payment captured successfully - ${payment.id} - order ${data.order_id}`
+ )
+ } catch (error) {
+ logger.error(
+ `Failed to capture payment - ${payment.id} - order ${data.order_id} - ${error}`
+ )
+
+ const orderModule = container.resolve<IOrderModuleService>(Modules.ORDER)
+
+ await orderModule.updateOrders(data.order_id, {
+ metadata: {
+ capture_failed: true,
+ },
+ })
+
+ logger.debug(
+ `Marked capture_failed on order ${data.order_id}`
+ )
+ }
+}
+
+export const config: SubscriberConfig = {
+ event: PayoutEvents.OrderCaptureRequested,
+ context: {
+ subscriberId: "capture-order-handler",
+ },
+}
diff --git a/packages/core-plugin/src/subscribers/order-payout.ts b/packages/core-plugin/src/subscribers/order-payout.ts
new file mode 100644
index 000000000..ca10dd84c
--- /dev/null
+++ b/packages/core-plugin/src/subscribers/order-payout.ts
@@ -0,0 +1,74 @@
+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import type { IOrderModuleService } from "@medusajs/types"
+import { PayoutEvents } from "@mercurjs/types"
+
+import { createPayoutWorkflow } from "../workflows/payout"
+
+type PayoutRequestedData = {
+ order_id: string
+}
+
+export default async function orderPayoutHandler({
+ event: { data },
+ container,
+}: SubscriberArgs<PayoutRequestedData>) {
+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
+ const orderModule = container.resolve<IOrderModuleService>(Modules.ORDER)
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+
+ logger.info(`Payout requested for order ${data.order_id}`)
+
+ const { data: orders } = await query.graph({
+ entity: "order",
+ fields: ["id", "payouts.id"],
+ filters: { id: data.order_id },
+ })
+
+ const order = orders[0]
+
+ if (!order) {
+ logger.error(`Order not found - ${data.order_id}`)
+ return
+ }
+
+ if ((order as any).payouts?.length) {
+ logger.warn(`Order ${data.order_id} - skipped, payout already exists`)
+ return
+ }
+
+ try {
+ await createPayoutWorkflow(container).run({
+ input: {
+ order_id: data.order_id,
+ },
+ })
+
+ await orderModule.updateOrders(data.order_id, {
+ metadata: {
+ payout_transferred: true,
+ },
+ })
+
+ logger.info(`Payout successfully - order ${data.order_id}`)
+ } catch (error) {
+ logger.error(
+ `Failed to create payout - order ${data.order_id} - ${error}`
+ )
+
+ await orderModule.updateOrders(data.order_id, {
+ metadata: {
+ payout_failed: true,
+ },
+ })
+
+ logger.debug(`Marked payout_failed on order ${data.order_id}`)
+ }
+}
+
+export const config: SubscriberConfig = {
+ event: PayoutEvents.PayoutRequested,
+ context: {
+ subscriberId: "order-payout-handler",
+ },
+}
diff --git a/packages/core-plugin/src/subscribers/payout-webhook.ts b/packages/core-plugin/src/subscribers/payout-webhook.ts
index c892ff6a3..673c77c2d 100644
--- a/packages/core-plugin/src/subscribers/payout-webhook.ts
+++ b/packages/core-plugin/src/subscribers/payout-webhook.ts
@@ -4,7 +4,7 @@ import { Modules } from "@medusajs/framework/utils"
import PayoutModuleService from "../modules/payout/services/payout-module-service"
import { ProviderWebhookPayload } from "@medusajs/framework/types"
import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
-import { processPayoutWorkflowId } from "../workflows/payout"
+import { processPayoutForWebhookWorkflowId } from "../workflows/payout"
type SerializedBuffer = {
data: ArrayBuffer
@@ -36,7 +36,7 @@ export default async function payoutWebhookHandler({
}
const wfEngine = container.resolve(Modules.WORKFLOW_ENGINE)
- await wfEngine.run(processPayoutWorkflowId, { input: processedEvent })
+ await wfEngine.run(processPayoutForWebhookWorkflowId, { input: processedEvent })
}
export const config: SubscriberConfig = {
diff --git a/packages/core-plugin/src/workflows/payout/steps/add-payout-transactions.ts b/packages/core-plugin/src/workflows/payout/steps/add-payout-transactions.ts
deleted file mode 100644
index 671edae75..000000000
--- a/packages/core-plugin/src/workflows/payout/steps/add-payout-transactions.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
-import { CreatePayoutTransactionDTO, MercurModules } from "@mercurjs/types"
-
-import PayoutModuleService from "../../../modules/payout/services/payout-module-service"
-
-type AddPayoutTransactionsInput = {
- account_id: string
- transactions: Omit<CreatePayoutTransactionDTO, 'account_id'>[]
-}
-
-export const addPayoutTransactionsStepId = "add-payout-transactions-step"
-
-/**
- * This step creates payout transactions and updates the account balance.
- */
-export const addPayoutTransactionsStep = createStep(
- addPayoutTransactionsStepId,
- async (input: AddPayoutTransactionsInput, { container }) => {
- const payoutService = container.resolve<PayoutModuleService>(MercurModules.PAYOUT)
-
- if (!input.transactions.length) {
- return new StepResponse([], [])
- }
-
- const created = await payoutService.addPayoutTransactions(
- input.account_id,
- input.transactions
- )
-
- return new StepResponse(
- created,
- created.map((t) => t.id)
- )
- },
- async (transactionIds, { container }) => {
- if (!transactionIds?.length) {
- return
- }
-
- const payoutService = container.resolve<PayoutModuleService>(MercurModules.PAYOUT)
-
- await payoutService.deletePayoutTransactions(transactionIds)
- }
-)
diff --git a/packages/core-plugin/src/workflows/payout/steps/index.ts b/packages/core-plugin/src/workflows/payout/steps/index.ts
index 304886b96..a7345b450 100644
--- a/packages/core-plugin/src/workflows/payout/steps/index.ts
+++ b/packages/core-plugin/src/workflows/payout/steps/index.ts
@@ -1,4 +1,3 @@
-export * from "./add-payout-transactions"
export * from "./create-payout-account"
export * from "./create-onboarding"
export * from "./create-payout"
diff --git a/packages/core-plugin/src/workflows/payout/workflows/create-payout.ts b/packages/core-plugin/src/workflows/payout/workflows/create-payout.ts
index 5d7338644..191000aa9 100644
--- a/packages/core-plugin/src/workflows/payout/workflows/create-payout.ts
+++ b/packages/core-plugin/src/workflows/payout/workflows/create-payout.ts
@@ -1,45 +1,77 @@
-import { createRemoteLinkStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"
-import { WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
-import { MathBN } from "@medusajs/framework/utils"
-import { CreatePayoutDTO, MercurModules } from "@mercurjs/types"
+import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
+import { getOrderDetailWorkflow } from "@medusajs/medusa/core-flows"
+import { WorkflowData, WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
+import { MathBN, MedusaError } from "@medusajs/framework/utils"
+import { MercurModules } from "@mercurjs/types"
-import { addPayoutTransactionsStep, createPayoutStep } from "../steps"
+import { createPayoutStep } from "../steps"
+
+type CreatePayoutWorkflowInput = {
+ order_id: string
+}
export const createPayoutWorkflowId = "create-payout"
export const createPayoutWorkflow = createWorkflow(
createPayoutWorkflowId,
- function (input: CreatePayoutDTO) {
- const { data: payoutAccount } = useQueryGraphStep({
- entity: "payout_account",
- fields: ["id", "seller.id"],
- filters: { id: input.account_id },
- options: {
- isList: false,
+ function (input: WorkflowData<CreatePayoutWorkflowInput>) {
+ const order = getOrderDetailWorkflow.runAsStep({
+ input: {
+ order_id: input.order_id,
+ fields: [
+ 'id',
+ 'currency_code',
+ 'total',
+ 'seller.*',
+ 'seller.payout_account.*',
+ 'items.*',
+ 'items.commission_lines.*',
+ ],
}
})
- const payout = createPayoutStep({
- account_id: input.account_id,
- amount: input.amount,
- currency_code: input.currency_code,
- context: input.context,
- data: input.data,
- })
+ const payoutInput = transform({ order }, ({ order }) => {
+ const payoutAccountId = (order as any).seller?.payout_account?.id
+ const sellerId = (order as any).seller?.id
- const transactionInput = transform({ input, payout }, ({ input, payout }) => ({
- account_id: input.account_id,
- transactions: [
- {
- amount: MathBN.mult(input.amount, -1),
- currency_code: input.currency_code,
- reference: "payout",
- reference_id: payout.id,
+ if (!payoutAccountId) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_FOUND,
+ `Seller does not have a payout account`
+ )
+ }
+
+ const totalCommission = (order.items ?? []).reduce(
+ (acc: number, item: any) => {
+ const commissionAmount = item.commission_line?.amount ?? 0
+ return MathBN.add(acc, commissionAmount) as unknown as number
},
- ],
- }))
+ 0
+ )
+
+ const amount = MathBN.sub(order.total, totalCommission) as unknown as number
- addPayoutTransactionsStep(transactionInput)
+ return {
+ account_id: payoutAccountId,
+ seller_id: sellerId,
+ amount,
+ currency_code: order.currency_code,
+ data: {
+ order_id: order.id,
+ },
+ context: {
+ idempotency_key: order.id,
+ },
+ }
+ })
+
+ const payout = createPayoutStep({
+ account_id: payoutInput.account_id,
+ amount: payoutInput.amount,
+ currency_code: payoutInput.currency_code,
+ data: payoutInput.data,
+ context: payoutInput.context,
+ })
createRemoteLinkStep([
{
@@ -47,7 +79,7 @@ export const createPayoutWorkflow = createWorkflow(
payout_id: payout.id,
},
[MercurModules.SELLER]: {
- seller_id: payoutAccount.seller.id,
+ seller_id: payoutInput.seller_id,
},
},
])
diff --git a/packages/core-plugin/src/workflows/payout/workflows/credit-order-to-payout-account.ts b/packages/core-plugin/src/workflows/payout/workflows/credit-order-to-payout-account.ts
deleted file mode 100644
index 1c80efdd4..000000000
--- a/packages/core-plugin/src/workflows/payout/workflows/credit-order-to-payout-account.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { getOrderDetailWorkflow } from "@medusajs/medusa/core-flows"
-import {
- WorkflowData,
- WorkflowResponse,
- createWorkflow,
- transform,
-} from "@medusajs/framework/workflows-sdk"
-import { MathBN, MedusaError } from "@medusajs/framework/utils"
-
-import { addPayoutTransactionsStep } from "../steps"
-
-export type CreditOrderToPayoutWorkflowInput = {
- order_id: string
-}
-
-export const creditOrderToPayoutAccountWorkflowId = "credit-order-to-payout-account"
-
-/**
- * This workflow credits the seller's payout account balance with the order earnings.
- * It calculates the net amount by subtracting commissions from the order total.
- */
-export const creditOrderToPayoutAccountWorkflow = createWorkflow(
- creditOrderToPayoutAccountWorkflowId,
- function (input: WorkflowData<CreditOrderToPayoutWorkflowInput>) {
- const order = getOrderDetailWorkflow.runAsStep({
- input: {
- order_id: input.order_id,
- fields: ['id', 'currency_code', 'total', 'seller.*', 'seller.payout_account.*', 'items.*', 'items.commission_lines.*'],
- }
- })
-
- const transactionInput = transform({ order }, ({ order }) => {
- const payoutAccountId = (order as any).seller?.payout_account?.id
-
- if (!payoutAccountId) {
- throw new MedusaError(
- MedusaError.Types.NOT_FOUND,
- `Seller does not have a payout account`
- )
- }
-
- const totalCommission = (order.items ?? []).reduce(
- (acc: number, item: any) => {
- const commissionAmount = item.commission_line?.amount ?? 0
- return MathBN.add(acc, commissionAmount) as unknown as number
- },
- 0
- )
-
- const amount = MathBN.sub(order.total, totalCommission)
-
- return {
- account_id: payoutAccountId,
- transactions: [
- {
- amount: amount,
- currency_code: order.currency_code,
- reference: "order",
- reference_id: order.id,
- },
- ],
- }
- })
-
- const transactions = addPayoutTransactionsStep(transactionInput)
-
- return new WorkflowResponse(transactions)
- }
-)
diff --git a/packages/core-plugin/src/workflows/payout/workflows/index.ts b/packages/core-plugin/src/workflows/payout/workflows/index.ts
index 34744a4a3..914d7c8ce 100644
--- a/packages/core-plugin/src/workflows/payout/workflows/index.ts
+++ b/packages/core-plugin/src/workflows/payout/workflows/index.ts
@@ -1,5 +1,4 @@
export * from "./create-payout-account"
export * from "./create-onboarding"
export * from "./create-payout"
-export * from "./credit-order-to-payout-account"
-export * from "./process-payout"
+export * from "./process-payout-for-webhook"
diff --git a/packages/core-plugin/src/workflows/payout/workflows/process-payout.ts b/packages/core-plugin/src/workflows/payout/workflows/process-payout-for-webhook.ts
similarity index 87%
rename from packages/core-plugin/src/workflows/payout/workflows/process-payout.ts
rename to packages/core-plugin/src/workflows/payout/workflows/process-payout-for-webhook.ts
index 98a84e817..44546f3f9 100644
--- a/packages/core-plugin/src/workflows/payout/workflows/process-payout.ts
+++ b/packages/core-plugin/src/workflows/payout/workflows/process-payout-for-webhook.ts
@@ -8,13 +8,13 @@ import {
import { updatePayoutAccountStep } from "../steps/update-payout-account"
import { updatePayoutStep } from "../steps/update-payout"
-export interface ProcessPayoutWorkflowInput extends PayoutWebhookResult {}
+export interface ProcessPayoutForWebhookWorkflowInput extends PayoutWebhookResult { }
-export const processPayoutWorkflowId = "process-payout-workflow"
+export const processPayoutForWebhookWorkflowId = "process-payout-for-webhook"
-export const processPayoutWorkflow = createWorkflow(
- processPayoutWorkflowId,
- (input: ProcessPayoutWorkflowInput) => {
+export const processPayoutForWebhookWorkflow = createWorkflow(
+ processPayoutForWebhookWorkflowId,
+ (input: ProcessPayoutForWebhookWorkflowInput) => {
when({ input }, ({ input }) => {
return input.action === "account.activated" && !!input.data?.id
}).then(() => {
diff --git a/packages/providers/payout-stripe-connect/package.json b/packages/providers/payout-stripe-connect/package.json
new file mode 100644
index 000000000..c0e407737
--- /dev/null
+++ b/packages/providers/payout-stripe-connect/package.json
@@ -0,0 +1,31 @@
+{
+ "name": "@mercurjs/payout-stripe-connect",
+ "version": "2.0.0-canary.89",
+ "description": "Stripe Connect payment provider for Mercur",
+ "private": true,
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/mercurjs/mercur",
+ "directory": "packages/providers/payment-stripe-connect"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "author": "Medusa",
+ "license": "MIT",
+ "peerDependencies": {
+ "@medusajs/framework": "2.13.4"
+ },
+ "devDependencies": {
+ "@medusajs/framework": "2.13.4",
+ "@mercurjs/types": "2.0.0-canary.89"
+ },
+ "dependencies": {
+ "stripe": "^15.5.0"
+ },
+ "keywords": [
+ "medusa-plugin",
+ "medusa-plugin-payment",
+ "stripe-connect"
+ ]
+}
\ No newline at end of file
diff --git a/packages/providers/payout-stripe-connect/src/index.ts b/packages/providers/payout-stripe-connect/src/index.ts
new file mode 100644
index 000000000..a28da3049
--- /dev/null
+++ b/packages/providers/payout-stripe-connect/src/index.ts
@@ -0,0 +1,5 @@
+import { ModuleProvider, Modules } from "@medusajs/framework/utils"
+
+export default ModuleProvider(Modules.PAYMENT, {
+ services: [],
+})
\ No newline at end of file
diff --git a/packages/providers/payout-stripe-connect/src/services/stripe-connect.ts b/packages/providers/payout-stripe-connect/src/services/stripe-connect.ts
new file mode 100644
index 000000000..230f82d25
--- /dev/null
+++ b/packages/providers/payout-stripe-connect/src/services/stripe-connect.ts
@@ -0,0 +1,267 @@
+import { isPresent, MedusaError } from "@medusajs/framework/utils"
+import {
+ CreateOnboardingInput,
+ CreateOnboardingResponse,
+ CreatePayoutAccountInput,
+ CreatePayoutAccountResponse,
+ CreatePayoutInput,
+ CreatePayoutResponse,
+ IPayoutProvider,
+ PayoutAccountStatus,
+ PayoutStatus,
+ PayoutWebhookActionInput,
+ PayoutWebhookResult,
+} from "@mercurjs/types"
+import { StripeConnectOptions } from "@types"
+import { getSmallestUnit } from "@utils"
+import Stripe from "stripe"
+
+const DEFAULT_ACCOUNT_VALIDATION = {
+ detailsSubmitted: true,
+ chargesEnabled: true,
+ payoutsEnabled: true,
+ noOutstandingRequirements: true,
+ requiredCapabilities: [],
+}
+
+class StripeConnectProviderService implements IPayoutProvider {
+ static identifier = "stripe-connect"
+ protected stripe_: Stripe
+ protected config_: StripeConnectOptions
+
+ protected constructor(
+ options: StripeConnectOptions
+ ) {
+ this.config_ = options
+ this.stripe_ = new Stripe(options.apiKey)
+ }
+
+ protected normalizePayoutParameters(
+ extra: Record<string, unknown>
+ ): Partial<Stripe.TransferCreateParams> & { destination: string } {
+ const res = {
+ } as Partial<Stripe.TransferCreateParams>
+
+ res.destination = extra!.id as string
+ res.source_transaction = extra?.source_transaction as string | undefined
+ res.transfer_group = extra?.order_id as string | undefined
+ res.description = extra?.description as string | undefined
+ res.metadata = extra?.metadata as Stripe.MetadataParam | undefined
+
+
+ return res as Partial<Stripe.TransferCreateParams> & { destination: string }
+ }
+
+ private getWebhookResultFromAccount_(
+ account: Stripe.Account
+ ): PayoutWebhookResult {
+ const validation = {
+ ...DEFAULT_ACCOUNT_VALIDATION,
+ ...this.config_.accountValidation,
+ }
+ const requirements = account.requirements
+ const disabledReason = requirements?.disabled_reason
+ const hasOutstandingRequirements = Boolean(
+ requirements?.currently_due?.length ||
+ requirements?.past_due?.length ||
+ requirements?.pending_verification?.length
+ )
+ const requiredCapabilities = validation.requiredCapabilities ?? []
+ const hasInactiveCapabilities = requiredCapabilities.some((capability) => {
+ return account.capabilities?.[capability as keyof Stripe.Account.Capabilities] !== "active"
+ })
+
+ if (disabledReason?.startsWith("rejected.")) {
+ return {
+ action: "account.rejected",
+ data: {
+ id: account.id,
+ },
+ }
+ }
+
+ if (
+ (!validation.detailsSubmitted || account.details_submitted) &&
+ (!validation.chargesEnabled || account.charges_enabled) &&
+ (!validation.payoutsEnabled || account.payouts_enabled) &&
+ (!validation.noOutstandingRequirements || !hasOutstandingRequirements) &&
+ !hasInactiveCapabilities
+ ) {
+ return {
+ action: "account.activated",
+ data: {
+ id: account.id,
+ },
+ }
+ }
+
+ if (disabledReason) {
+ return {
+ action: "account.restricted",
+ data: {
+ id: account.id,
+ },
+ }
+ }
+
+ return {
+ action: "account.restricted",
+ data: {
+ id: account.id,
+ },
+ }
+ }
+
+ private getWebhookResultFromPayout_(
+ payout: Stripe.Payout
+ ): PayoutWebhookResult {
+ const payoutId = payout.metadata?.payout_id || payout.id
+
+ switch (payout.status) {
+ case "pending":
+ case "in_transit":
+ return {
+ action: "payout.processing",
+ data: {
+ id: payoutId,
+ },
+ }
+ case "paid":
+ return {
+ action: "payout.paid",
+ data: {
+ id: payoutId,
+ },
+ }
+ case "failed":
+ return {
+ action: "payout.failed",
+ data: {
+ id: payoutId,
+ },
+ }
+ case "canceled":
+ return {
+ action: "payout.canceled",
+ data: {
+ id: payoutId,
+ },
+ }
+ default:
+ return {
+ action: "not_supported",
+ }
+ }
+ }
+
+ async createPayoutAccount(
+ input: CreatePayoutAccountInput
+ ): Promise<CreatePayoutAccountResponse> {
+ const { data } = input;
+ const country = data?.country as string
+
+ if (!isPresent(country)) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `"country" is required`
+ );
+ }
+
+ const response = await this.stripe_.accounts.create({
+ type: 'express',
+ country,
+ }, {
+ idempotencyKey: input.context?.idempotency_key
+ })
+
+ return {
+ id: response.id,
+ status: PayoutAccountStatus.PENDING,
+ data: response as unknown as Record<string, unknown>
+ }
+ }
+
+ async createPayout(input: CreatePayoutInput): Promise<CreatePayoutResponse> {
+ const normalizedInput = this.normalizePayoutParameters(input.data!)
+ const transfer = await this.stripe_.transfers.create(
+ {
+ currency: input.currency_code,
+ amount: getSmallestUnit(input.amount, input.currency_code),
+ ...normalizedInput,
+ },
+ { idempotencyKey: input.context?.idempotency_key }
+ );
+
+
+ return {
+ data: transfer as unknown as Record<string, unknown>,
+ status: PayoutStatus.PENDING
+ }
+ }
+
+ async createOnboarding(
+ input: CreateOnboardingInput
+ ): Promise<CreateOnboardingResponse> {
+ const id = input?.data?.id as string
+ if (!isPresent(id)) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `'id' is required`
+ );
+ }
+
+ if (!isPresent(input.data?.refresh_url)) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `'refresh_url' is required`
+ );
+ }
+
+ if (!isPresent(input.data?.return_url)) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `'return_url' is required`
+ );
+ }
+
+ const accountLink = await this.stripe_.accountLinks.create({
+ account: id,
+ refresh_url: input.data?.refresh_url as string,
+ return_url: input.data?.return_url as string,
+ type: "account_onboarding",
+ }, {
+ idempotencyKey: input.context?.idempotency_key
+ });
+
+ return {
+ data: accountLink as unknown as Record<string, unknown>,
+ };
+ }
+
+ async getWebhookActionAndData(
+ payload: PayoutWebhookActionInput
+ ): Promise<PayoutWebhookResult> {
+ const signature = payload.headers["stripe-signature"] as string
+
+ const event = this.stripe_.webhooks.constructEvent(
+ payload.rawData as string | Buffer,
+ signature,
+ this.config_.webhookSecret
+ )
+
+ switch (event.type) {
+ case "account.updated":
+ return this.getWebhookResultFromAccount_(event.data.object as Stripe.Account)
+ case "payout.created":
+ case "payout.updated":
+ case "payout.paid":
+ case "payout.failed":
+ case "payout.canceled":
+ return this.getWebhookResultFromPayout_(event.data.object as Stripe.Payout)
+ default:
+ return { action: "not_supported" }
+ }
+ }
+}
+
+export default StripeConnectProviderService
diff --git a/packages/providers/payout-stripe-connect/src/types/index.ts b/packages/providers/payout-stripe-connect/src/types/index.ts
new file mode 100644
index 000000000..c0a129eab
--- /dev/null
+++ b/packages/providers/payout-stripe-connect/src/types/index.ts
@@ -0,0 +1,37 @@
+export interface StripeConnectAccountValidationOptions {
+ /**
+ * Require Stripe to mark onboarding details as submitted
+ */
+ detailsSubmitted?: boolean
+ /**
+ * Require the account to be enabled for charges
+ */
+ chargesEnabled?: boolean
+ /**
+ * Require the account to be enabled for payouts
+ */
+ payoutsEnabled?: boolean
+ /**
+ * Treat pending Stripe requirements as a restricted account
+ */
+ noOutstandingRequirements?: boolean
+ /**
+ * Require specific Stripe capabilities to be active
+ */
+ requiredCapabilities?: string[]
+}
+
+export interface StripeConnectOptions {
+ /**
+ * The API key for the Stripe Connect account
+ */
+ apiKey: string
+ /**
+ * The webhook secret used to verify webhooks
+ */
+ webhookSecret: string
+ /**
+ * Controls how connected accounts are validated from Stripe webhook data
+ */
+ accountValidation?: StripeConnectAccountValidationOptions
+}
diff --git a/packages/providers/payout-stripe-connect/src/utils/index.ts b/packages/providers/payout-stripe-connect/src/utils/index.ts
new file mode 100644
index 000000000..2b94cee59
--- /dev/null
+++ b/packages/providers/payout-stripe-connect/src/utils/index.ts
@@ -0,0 +1,79 @@
+import { BigNumberInput } from '@medusajs/framework/types'
+import { BigNumber, MathBN } from '@medusajs/framework/utils'
+
+function getCurrencyMultiplier(currency) {
+ const currencyMultipliers = {
+ 0: [
+ 'BIF',
+ 'CLP',
+ 'DJF',
+ 'GNF',
+ 'JPY',
+ 'KMF',
+ 'KRW',
+ 'MGA',
+ 'PYG',
+ 'RWF',
+ 'UGX',
+ 'VND',
+ 'VUV',
+ 'XAF',
+ 'XOF',
+ 'XPF'
+ ],
+ 3: ['BHD', 'IQD', 'JOD', 'KWD', 'OMR', 'TND']
+ }
+
+ currency = currency.toUpperCase()
+ let power = 2
+ for (const [key, value] of Object.entries(currencyMultipliers)) {
+ if (value.includes(currency)) {
+ power = parseInt(key, 10)
+ break
+ }
+ }
+ return Math.pow(10, power)
+}
+
+/**
+ * Converts an amount to the format required by Stripe based on currency.
+ * https://docs.stripe.com/currencies
+ * @param {BigNumberInput} amount - The amount to be converted.
+ * @param {string} currency - The currency code (e.g., 'USD', 'JOD').
+ * @returns {number} - The converted amount in the smallest currency unit.
+ */
+export function getSmallestUnit(
+ amount: BigNumberInput,
+ currency: string
+): number {
+ const multiplier = getCurrencyMultiplier(currency)
+
+ const amount_ =
+ Math.round(new BigNumber(MathBN.mult(amount, multiplier)).numeric) /
+ multiplier
+
+ const smallestAmount = new BigNumber(MathBN.mult(amount_, multiplier))
+
+ let numeric = smallestAmount.numeric
+ // Check if the currency requires rounding to the nearest ten
+ if (multiplier === 1e3) {
+ numeric = Math.ceil(numeric / 10) * 10
+ }
+
+ return parseInt(numeric.toString().split('.').shift()!, 10)
+}
+
+/**
+ * Converts an amount from the smallest currency unit to the standard unit based on currency.
+ * @param {BigNumberInput} amount - The amount in the smallest currency unit.
+ * @param {string} currency - The currency code (e.g., 'USD', 'JOD').
+ * @returns {number} - The converted amount in the standard currency unit.
+ */
+export function getAmountFromSmallestUnit(
+ amount: BigNumberInput,
+ currency: string
+): number {
+ const multiplier = getCurrencyMultiplier(currency)
+ const standardAmount = new BigNumber(MathBN.div(amount, multiplier))
+ return standardAmount.numeric
+}
\ No newline at end of file
diff --git a/packages/providers/payout-stripe-connect/tsconfig.json b/packages/providers/payout-stripe-connect/tsconfig.json
new file mode 100644
index 000000000..f8ad8ecb1
--- /dev/null
+++ b/packages/providers/payout-stripe-connect/tsconfig.json
@@ -0,0 +1,34 @@
+{
+ "compilerOptions": {
+ "lib": ["ES2021"],
+ "target": "ES2021",
+ "outDir": "./dist",
+ "esModuleInterop": true,
+ "declaration": true,
+ "declarationMap": true,
+ "noUnusedLocals": true,
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "emitDecoratorMetadata": true,
+ "experimentalDecorators": true,
+ "sourceMap": true,
+ "noImplicitReturns": true,
+ "resolveJsonModule": true,
+ "forceConsistentCasingInFileNames": true,
+ "strictNullChecks": true,
+ "strictFunctionTypes": true,
+ "noImplicitThis": true,
+ "allowJs": true,
+ "skipLibCheck": true,
+ "incremental": false,
+ "paths": {
+ "@models": ["./src/models"],
+ "@services": ["./src/services"],
+ "@repositories": ["./src/repositories"],
+ "@types": ["./src/types"],
+ "@utils": ["./src/utils"]
+ }
+ },
+ "include": ["./src"],
+ "exclude": ["./dist", "./node_modules"]
+}
diff --git a/packages/registry/src/requests/workflows/requests/steps/validate-request-status.ts b/packages/registry/src/requests/workflows/requests/steps/validate-request-status.ts
index afa6af710..504ad3998 100644
--- a/packages/registry/src/requests/workflows/requests/steps/validate-request-status.ts
+++ b/packages/registry/src/requests/workflows/requests/steps/validate-request-status.ts
@@ -2,6 +2,7 @@ import { createStep } from "@medusajs/framework/workflows-sdk"
import { ContainerRegistrationKeys, MedusaError } from "@medusajs/framework/utils"
import { RequestStatus } from "../../../types"
+import { Query } from "@mercurjs/types"
type ValidateRequestStatusStepInput = {
alias: string
@@ -12,7 +13,7 @@ type ValidateRequestStatusStepInput = {
export const validateRequestStatusStep = createStep(
"validate-request-status",
async (input: ValidateRequestStatusStepInput, { container }) => {
- const query = container.resolve(ContainerRegistrationKeys.QUERY)
+ const query = container.resolve<Query>(ContainerRegistrationKeys.QUERY)
const {
data: [entity],
diff --git a/packages/types/src/payout/common.ts b/packages/types/src/payout/common.ts
index 1c8d96120..215615ecc 100644
--- a/packages/types/src/payout/common.ts
+++ b/packages/types/src/payout/common.ts
@@ -1,4 +1,4 @@
-import { BigNumberInput, BigNumberRawValue, BigNumberValue } from "@medusajs/types"
+import { BigNumberInput, FulfillmentStatus } from "@medusajs/types"
export enum PayoutAccountStatus {
/**
@@ -30,6 +30,61 @@ export enum PayoutStatus {
CANCELED = "canceled",
}
+export enum PayoutEvents {
+ // TODO: Move to order-related domain events
+ OrderCaptureRequested = 'order.capture_requested',
+ OrderAuthorizationExpired = 'order.authorization_expired',
+ PayoutRequested = 'payout.requested',
+}
+
+
+export interface PayoutModuleOptions {
+ /**
+ * Disable automatic capture checks and daily payout jobs.
+ * When true, both the capture-check and daily-payouts scheduled jobs
+ * will exit immediately without processing any orders.
+ * Default: false.
+ */
+ disabled?: boolean
+
+ /**
+ * How long a payment authorization remains valid before capture is no longer possible.
+ * Default: 7 days.
+ */
+ authorizationWindowMs?: number
+
+ /**
+ * How long a seller has to complete required acceptance or fulfillment actions
+ * before the order should be rejected or canceled.
+ * Example: 72 hours.
+ */
+ sellerActionWindowMs?: number
+
+ /**
+ * Safety margin before authorization expiry. Capture should happen before:
+ * authorization expiry - capture safety buffer.
+ * Default: 24 hours.
+ */
+ captureSafetyBufferMs?: number
+
+ /**
+ * Minimum fulfillment status an order must have before it becomes eligible
+ * for capture and payout. The check uses an ordered scale:
+ * not_fulfilled < partially_fulfilled < fulfilled < partially_shipped < shipped < partially_delivered < delivered
+ * An order qualifies when its status is >= the configured requirement.
+ * Default: "fulfilled".
+ */
+ requiredFulfillmentStatus?: FulfillmentStatus
+}
+
+export const PAYOUT_MODULE_OPTION_DEFAULTS: Required<PayoutModuleOptions> = {
+ disabled: false,
+ authorizationWindowMs: 7 * 24 * 60 * 60 * 1000,
+ sellerActionWindowMs: 72 * 60 * 60 * 1000,
+ captureSafetyBufferMs: 24 * 60 * 60 * 1000,
+ requiredFulfillmentStatus: "fulfilled",
+}
+
export type PayoutWebhookAction =
| "not_supported"
@@ -72,30 +127,3 @@ export interface PayoutDTO {
updated_at: Date
}
-/**
- * The payout balance totals stored in JSON
- */
-export type PayoutBalanceTotals = {
- balance: BigNumberValue
- raw_balance: BigNumberRawValue
-}
-
-export interface PayoutBalanceDTO {
- id: string
- account_id: string
- currency_code: string
- totals: PayoutBalanceTotals
- created_at: Date
- updated_at: Date
-}
-
-export interface PayoutTransactionDTO {
- id: string
- account_id: string
- amount: BigNumberInput
- currency_code: string
- reference: string | null
- reference_id: string | null
- created_at: Date
- updated_at: Date
-}
diff --git a/packages/types/src/payout/mutations.ts b/packages/types/src/payout/mutations.ts
index bd0f8852f..6f4637178 100644
--- a/packages/types/src/payout/mutations.ts
+++ b/packages/types/src/payout/mutations.ts
@@ -1,6 +1,5 @@
import { PayoutAccountStatus, PayoutStatus } from "./common"
import { PayoutProviderInput } from "./provider"
-import { BigNumberInput } from "@medusajs/types"
export interface CreatePayoutAccountDTO extends PayoutProviderInput {
}
@@ -25,16 +24,3 @@ export interface UpdatePayoutDTO {
status: PayoutStatus
}
-export interface CreatePayoutTransactionDTO {
- account_id: string
- amount: BigNumberInput
- currency_code: string
- reference?: string
- reference_id?: string
-}
-
-export interface CreatePayoutBalanceDTO {
- account_id: string
- currency_code: string
- totals?: Record<string, unknown>
-}
diff --git a/turbo.json b/turbo.json
index 09c9f3dcc..23f8bbe7d 100644
--- a/turbo.json
+++ b/turbo.json
@@ -14,6 +14,9 @@
"check-types": {
"dependsOn": ["^check-types"]
},
+ "test:integration:http": {
+ "cache": false
+ },
"dev": {
"cache": false,
"persistent": true