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(payout)!: thin single-provider payout module and Stripe connector plugin (#1693)

Viktor Holikad4636e76b26
diff --git a/.claude/skills/mercur-review/SKILL.md b/.claude/skills/mercur-review/SKILL.md
new file mode 100644
index 000000000..e5de78891
--- /dev/null
+++ b/.claude/skills/mercur-review/SKILL.md
@@ -0,0 +1,85 @@
+---
+name: mercur-review
+description: Review a Mercur change (current diff, branch or PR) with a swarm of independent reviewer agents, triage their findings into actionable / nit / ambiguous, fix the actionable ones and loop until clean. Use when the user asks to review, QA, check or "make this match Medusa" before a PR, or says the code looks AI-generated or off-pattern.
+argument-hint: "[PR number | branch | path] [--no-fix]"
+---
+
+# mercur-review — QA swarm, triage, loop
+
+A swarm of independent reviewers, a triage pass and an outer loop. The goal: the user should not have to point out Medusa patterns, naming or slop by hand. The reviewers do it, the fixes land, and only judgment calls reach the user.
+
+Three rules hold throughout:
+
+1. **The author does not review its own work.** Every reviewer is a fresh subagent that sees the diff and the reference files, never your reasoning or the conversation that produced the code.
+2. **Different lenses, not more of the same.** Each reviewer has one narrow brief (below). Overlap is wasted tokens.
+3. **Verify by observation, not reasoning.** A finding is fixed when a command shows it fixed (typecheck, spec, request), not when an explanation says so.
+
+## 1. Scope the change
+
+- No argument: `git diff main...HEAD` plus the working tree. A PR number: `gh pr diff <n>`. A path: that path's diff against `main`.
+- Write the changed file list and the diff to the scratchpad. Reviewers read from there.
+- Note which surfaces the diff touches (`packages/core` api / workflows / modules, `packages/admin`, `packages/vendor`, `packages/dashboard-shared`, plugins, docs). Skip reviewers whose surface isn't touched.
+
+## 2. Swarm: spawn the reviewers in parallel
+
+Launch these in **one message** as `general-purpose` agents. Give each the scratchpad diff path, its brief from `references/reviewers.md`, and the reference file it checks against. Each returns findings only. No fixes.
+
+| Reviewer | Lens | Checks against |
+| --- | --- | --- |
+| `medusa-patterns` | Does it look like Medusa wrote it: routes, workflows, steps, module service, links, query config | `references/medusa-backend.md` + `~/Desktop/medusa` |
+| `dashboard-patterns` | Does the UI look like the surrounding admin/vendor pages | `references/dashboard-ui.md` + `docs/UI-ARCHITECTURE.md` |
+| `qa-technical` | Correctness, data integrity, DB / query cost, transactions, races, empty-input edge cases | the diff + touched callers |
+| `security` | Authz/seller scoping, injection, secrets, webhook trust, unvalidated input | the diff |
+| `taste` | Naming, AI-slop comments and copy, dead code, over-abstraction, file size, `any` | `CLAUDE.md` Writing Code + `references/reviewers.md` |
+
+Only spawn `dashboard-patterns` for UI diffs and `medusa-patterns` for backend diffs. Keep the swarm at five agents or fewer.
+
+Every finding uses this shape:
+
+```
+- file:line — what is wrong (one sentence)
+ evidence: the Medusa/Mercur file that does it right, or the concrete failure
+ fix: the smallest change that resolves it
+ class: actionable | nit | ambiguous
+```
+
+A finding with no evidence is dropped. "Medusa does X" needs a path in `~/Desktop/medusa` or an existing Mercur file.
+
+## 3. Triage
+
+Merge the findings and dedupe them by file and line. Then sort:
+
+- **Actionable**: a clear defect or pattern break with one obvious fix (thin a route, move a step into its own file, add compensation, use `Form.Field`, drop an AI comment). Fix it.
+- **Nit**: style with no behavior impact and no established convention behind it. List it once and don't fix it unless it's trivial and in a line already being edited.
+- **Ambiguous**: the fix changes behavior, an API contract, a migration, or product copy, or two reviewers disagree. Don't fix it; collect it for the user with a recommendation.
+
+Be honest: a finding that would change a public route's response, a workflow's input/output, or an event payload is **ambiguous**, not actionable.
+
+## 4. Fix and verify
+
+Apply the actionable fixes yourself, then verify by observation:
+
+- `bunx tsc --noEmit -p <package>/tsconfig.json` for each touched package (filter to touched files; some packages have pre-existing errors)
+- `bunx oxlint --quiet <touched paths>`
+- Backend: `bun run test:integration:http -- <spec for the touched endpoints>` (never the whole suite); unit specs with `bun test <path>`
+- Plugin or dashboard changes: that package's build (`bun run build` in the plugin, `bunx tsup` in `packages/admin` / `packages/vendor`)
+- Never start the Playwright/e2e harness or drive the browser unless the user asks. For UI, report what the user should look at.
+
+A fix that fails verification is reverted and reclassified as ambiguous.
+
+## 5. Loop
+
+Re-run the swarm on the **new** diff (only the reviewers whose surface changed), triage again, and fix again. Stop after **3 rounds**, or as soon as a round produces no new actionable findings. Don't re-raise findings already classified as nit or ambiguous.
+
+`--no-fix`: run one round, skip step 4, and report.
+
+## Output
+
+Report to the user, in this order:
+
+1. **Fixed**: one line per actionable fix, `file:line`, with the verification command that proved it.
+2. **Needs your call**: the ambiguous items, each with the tradeoff and a recommended option.
+3. **Nits** (collapsed, optional to act on).
+4. Rounds run and what was verified (typecheck / lint / specs / builds), plus anything that couldn't be run.
+
+Do not commit or push unless the user asks.
diff --git a/.claude/skills/mercur-review/references/dashboard-ui.md b/.claude/skills/mercur-review/references/dashboard-ui.md
new file mode 100644
index 000000000..d16daa7c1
--- /dev/null
+++ b/.claude/skills/mercur-review/references/dashboard-ui.md
@@ -0,0 +1,44 @@
+# Dashboard UI patterns (admin, vendor, plugin panels)
+
+`docs/UI-ARCHITECTURE.md` is the contract. This file lists what reviews keep catching. Medusa's own dashboard lives at `~/Desktop/medusa/packages/admin/dashboard/src`; Mercur's canonical pages are `category-list`, `category-detail`, `product-create`, `category-edit`, `payouts/payout-detail` and `payout-accounts/payout-account-detail`.
+
+## Page structure
+
+- **One entity per route.**
+ - A list is `SingleColumnPage` + `Container className="divide-y p-0"` + a header row (`flex items-center justify-between px-6 py-4`, `<Heading>` + short subtitle + actions) + `_DataTable` with `filters`, `pagination`, `navigateTo` and `noRecords`.
+ - A detail is `TwoColumnPage` with `Main` / `Sidebar`, `showJSON`, `WidgetZone`s, a status `Alert` at the top when there is a reason, and a general section whose header holds the title, a `StatusBadge` and an `ActionMenu`.
+- **No page-level tabs, KPI/count strips or "job cards"** repeated across tabs. Related entities become nested sidebar items (`defineRouteConfig({ nested: "/parent" })`), like Medusa's Products → Collections / Categories.
+- **Don't duplicate core pages.** If core already shows an entity (payouts, payout accounts), a plugin adds a widget to that page's zone (`payouts.detail.side`, `payout_accounts.detail.side`, ...) instead of its own table.
+- **Side information goes in the sidebar column,** main content in the main column.
+
+## Linking to another entity
+
+Use the shared pattern, not a hand-made card:
+- `SidebarLink` (`packages/admin/src/components/common/sidebar-link/sidebar-link.tsx`): icon + label + description + arrow, as in the payout References section.
+- A section row whose value is a link (`text-ui-fg-subtle hover:text-ui-fg-base`), as in Medusa's order customer section.
+
+## Forms and modals
+
+- **Create** is a `RouteFocusModal` + `TabbedForm`. **Edit/small create** is a `RouteDrawer` + `RouteDrawer.Form` + `KeyboundForm`, routed as a child of the list page. In a plugin, use a parallel route folder (`routes/x/@create/page.tsx`) so it opens over the list (`SingleColumnPage hasOutlet`).
+- Use react-hook-form + `zodResolver`, and every field as `Form.Field` → `Form.Item` → `Form.Label` / `Form.Control` / `Form.Hint` / `Form.ErrorMessage`. No `useState` forms and no raw `Drawer`.
+- Entity pickers are a `Combobox` with search over the API, never a free-text id input.
+- Destructive or irreversible actions go through `usePrompt()` and then a toast. Actions live in an `ActionMenu` with a `permission`, `disabled` and `disabledTooltip`. Edit actions come first; destructive ones go last, in their own group.
+
+## Data
+
+- Use hooks in `hooks/api/<domain>.tsx` with `queryKeysFactory`. Queries return `{ ...data, ...rest }`, and mutations accept options and forward `onSuccess` after invalidating.
+- Never spread `q: undefined` (or any undefined param) into a client query; spread it conditionally.
+- Vendor product lists use `useProductTableQuery`'s curated fields. Adding `+field` to `GET /vendor/products` returns a 500.
+
+## What users see
+
+- **Labels, not raw values.** Map status enums and provider codes (`requirements.past_due`, `rejected.fraud`) to sentences, and show names instead of ids.
+- **Short copy.** Subtitles are one short clause. Empty states say what will appear, not how the system works. No "AI-ish" explanatory paragraphs.
+- **Strings go through i18n** in core panels: `en.json` + `$schema.json` together. Plugin panels without i18n keep the copy short and consistent.
+- **Brand icons follow the Medusa extension-icon shape:** a full 15×15 square (no own radius), a brand fill, a white→transparent 20% gradient overlay and a 9×9 glyph area (see the loyalty plugin's `gift-card-icon.tsx`). Nav items for plugin routes are `type: "extension"` so the sidebar draws the bordered tile.
+
+## Tokens
+
+- Only Medusa UI tokens (`text-ui-fg-*`, `bg-ui-bg-*`, `border-ui-border-*`, `shadow-elevation-*`) and only `@medusajs/icons`. Brand marks are the one exception, with a one-line comment saying so.
+- Use `Text` / `Heading` for typography, never raw `<p>` / `<h*>` with color classes.
+- `data-testid` goes on headings, inputs, buttons and menu triggers (kebab-case, scoped to the page).
diff --git a/.claude/skills/mercur-review/references/medusa-backend.md b/.claude/skills/mercur-review/references/medusa-backend.md
new file mode 100644
index 000000000..2bc1535fb
--- /dev/null
+++ b/.claude/skills/mercur-review/references/medusa-backend.md
@@ -0,0 +1,78 @@
+# Medusa backend patterns (what Mercur code must match)
+
+Paths below are relative to `~/Desktop/medusa/packages`. When unsure, open the Medusa file and copy its shape. These are the corrections the user has had to make by hand before.
+
+## API routes: thin
+
+Canonical files: `medusa/src/api/admin/payments/[id]/capture/route.ts` and `medusa/src/api/store/payment-collections/helpers.ts`.
+
+A route does exactly this:
+
+```ts
+export const POST = async (req: AuthenticatedMedusaRequest<Body>, res: MedusaResponse<Response>) => {
+ await xWorkflow(req.scope).run({ input: { id: req.params.id, ...req.validatedBody } })
+ const entity = await refetchX(req.params.id, req.scope, req.queryConfig.fields)
+ res.json({ entity })
+}
+```
+
+- The refetch helper lives in the resource's `helpers.ts`: `refetchEntity({ entity, idOrFilter, scope, fields })` from `@medusajs/framework/http`.
+- `GET` list/detail routes may call `query.graph` directly with `req.queryConfig.fields`, `req.filterableFields` and `req.queryConfig.pagination`.
+- Validation comes from `middlewares.ts`: `validateAndTransformBody` with a zod `.strict()` schema and `validateAndTransformQuery` with `query-config.ts` defaults. Fields lists go in `query-config.ts`, never inline in the route.
+- **Not allowed in a route:** `createStep`/`createWorkflow`, `service.*` calls, lookups to resolve ids, branching on entity state, running two workflows, `throwOnError: false` to paper over a failure, or reading module options.
+- Webhook hook routes only emit an event (`medusa/src/api/hooks/payment/[provider]/route.ts`). The subscriber parses and runs the workflow by id (`medusa/src/subscribers/payment-webhook.ts`).
+
+## Workflows
+
+Canonical files: `core/core-flows/src/payment/workflows/refund-payment.ts` and `process-payment.ts`.
+
+- **Exports:** `export const xWorkflowId = "kebab-id"`, `export type XWorkflowInput`, `export const xWorkflow = createWorkflow(xWorkflowId, function (input) { ... })`, with a short JSDoc on what it does.
+- **Input:** takes ids and minimal values. The workflow loads what it needs. Don't pass data in only to forward it to an event; query it.
+- **Loading:** use `useQueryGraphStep({ entity, fields, filters, options: { isList: false, throwIfKeyNotFound: true } }).config({ name: "unique-name" })`. Every repeated query step gets a unique `.config({ name })`.
+- **Branching and data:** branch with `when("named-condition", { deps }, fn).then(() => ...)`, and do calculations only in `transform`.
+ - **No nested `when`:** a `when` inside another `when`'s `.then` breaks the outer one at load. Use sibling `when` blocks that return values, and `transform` over the possibly-undefined result.
+ - **Guard empty filters:** wrap a query in `when` if its `id: [...]` or `$or: [...]` filter could be empty.
+- **Validation:** `validate-*` steps throw `MedusaError` with the right type (`NOT_FOUND`, `NOT_ALLOWED`, `INVALID_DATA`, `CONFLICT`) and return `new StepResponse(void 0)`.
+- **Composition:** reuse Medusa steps (`createRemoteLinkStep`, `emitEventStep`, `useQueryGraphStep`) and Mercur steps, nest other workflows with `xWorkflow.runAsStep({ input })`, and expose extension points with `createHook`. Check `~/Desktop/medusa/packages/core/core-flows` for an existing step before writing one.
+- **Helpers:** pure helpers (no container, no IO) go in `workflows/<domain>/utils/` (like `core-flows/src/payment-collection/utils`). A helper that queries or writes is a step, not a util. A ~400-line util doing query + compute + write inside one step is the anti-pattern to flag.
+
+## Steps
+
+Canonical files: `core/core-flows/src/payment/steps/capture-payment.ts` and `payment-collection/steps/create-payment-account-holder.ts`.
+
+- One step per file in `steps/`, and the `steps/index.ts` barrel re-exports every file.
+- Export `xStepId` + `xStep = createStep(xStepId, invoke, compensate)`.
+- One module call per step. Compensation restores exactly what the step changed: delete created rows, write back the previous values captured before the update.
+- No compensation only when the effect can't be undone (money sent to a provider, a link a user already got). Say so in one comment, as Medusa does in `capture-payment.ts`.
+- Batch steps take arrays and tolerate `[]`.
+
+## Module services
+
+Canonical files: `modules/payment/src/services/payment-module.ts` and `payment-provider.ts`.
+
+- `class XModuleService extends MedusaService({ ...models })` gives generated CRUD (`createXs`, `updateXs`, `listXs`, ...). Custom methods use domain verbs that don't collide with the generated ones (`capturePayment`, `refundPayment`, `createAccountHolder`).
+- **Decorators:**
+ - Public methods that write: `@InjectManager() @EmitEvents()` with `@MedusaContext() sharedContext?: Context`.
+ - Internal transactional writers: `protected async x_()` with `@InjectTransactionManager()`.
+ - Provider calls: `protected async xFromProvider_()`, outside the transaction, so a row lock (`knex(table).where("id", id).forUpdate()` after `SET LOCAL lock_timeout`) is never held across a network call.
+- **No free functions or module-scope helpers** in the service file. Helpers become `protected` methods, and constants become `static readonly`. Status derivation lives in the service (like `maybeUpdatePaymentCollection_`), not in `utils/`.
+- Provider access goes through a provider service (`retrieveProvider` from the container). Optional provider methods are guarded.
+- Modules never import other modules. Cross-module data goes through links (`defineLink`) and workflows. Module migrations never touch other modules' tables.
+
+## Links, query, events
+
+- Links are created in workflows via `createRemoteLinkStep`, not with `link.create` inside a util.
+- `query.graph` can't filter by a cross-module link relation in every case. Check the existing Mercur usage first.
+- A link alias that matches a relation name on the same module silently breaks resolution (e.g. `images` on ProductCategory).
+- `fields` params: unprefixed fields replace route defaults; prefix with `+`/`-` to merge.
+- Events: `emitEventStep({ eventName, data })` in the workflow, with names from `@mercurjs/types` constants.
+
+## Overrides of Medusa routes
+
+Overriding a core Medusa route's validation needs the route file **and** the middleware listed in `disableMedusaMiddlewares`. A handler override alone still returns 400 for unrecognized fields.
+
+## Tests
+
+- Bug fixes ship with a failing test first.
+- Integration specs use `medusaIntegrationTestRunner` and the `integration-tests/helpers`, split by `admin` / `vendor` / `store`. Use the `createVendorProduct` helper for products.
+- Run only the touched specs: `bun run test:integration:http -- <pattern>`.
diff --git a/.claude/skills/mercur-review/references/reviewers.md b/.claude/skills/mercur-review/references/reviewers.md
new file mode 100644
index 000000000..a0c50c1fd
--- /dev/null
+++ b/.claude/skills/mercur-review/references/reviewers.md
@@ -0,0 +1,63 @@
+# Reviewer briefs
+
+Paste the matching brief into each reviewer agent's prompt, together with the diff path and the files listed. A reviewer reports findings only, in the finding shape from `SKILL.md`, ranked most severe first, at most 15. It reads the code, not the author's explanation.
+
+## medusa-patterns
+
+You review Mercur backend code (`packages/core`, `packages/plugins/*/src` outside `admin`/`vendor`) for one thing: would a Medusa core maintainer recognise this as Medusa-style code? Mercur is a Medusa plugin and must follow its conventions.
+
+Read `references/medusa-backend.md` first. For every claim, open the Medusa equivalent in `~/Desktop/medusa/packages` (`medusa/src/api`, `core/core-flows/src`, `modules/*/src/services`) and cite it. Flag:
+- routes doing business logic, service calls, lookups or more than one workflow run
+- steps or workflows defined inside route files; several steps in one file; steps without ids or compensation where a rollback is possible
+- workflows that query inside steps instead of `useQueryGraphStep`, take whole objects instead of ids, or pass data only to forward it into an event
+- module services with free functions, `utils/` helpers that belong inside the service as protected methods, custom names that diverge from the payment/order module vocabulary
+- cross-module references instead of links
+Do not flag naming taste or UI.
+
+## dashboard-patterns
+
+You review `packages/admin`, `packages/vendor`, `packages/dashboard-shared` and plugin `src/admin` / `src/vendor` code. Would it look at home next to the existing pages? Read `references/dashboard-ui.md` and `docs/UI-ARCHITECTURE.md`, and compare against the canonical pages they name (`category-list`, `category-detail`, `product-create`, `category-edit`, and the core `payouts` / `payout-accounts` pages). Cite the existing file that does it right. Flag:
+- a hand-rolled layout, card, strip or tile where a shared primitive exists (`SidebarLink`, `SectionRow`, `Container` sections, `ActionMenu`, `StatusBadge`, `_DataTable`)
+- `useState` forms, raw `Drawer`/`FocusModal` instead of `RouteDrawer`/`RouteFocusModal` + react-hook-form + zod
+- page-level tabs, KPI strips and dashboards the surrounding pages don't have
+- raw values shown to users (status codes, provider reason codes, ids where a name exists) instead of labels
+- duplicated pages for data core already shows (prefer a widget in the core page's zone)
+- colors, icons and typography outside the Medusa UI tokens; missing `data-testid`
+Do not flag backend code.
+
+## qa-technical
+
+You hunt correctness bugs in the diff and its direct callers. Assume the author is wrong until the code proves otherwise. Look for:
+- empty-input paths: `filters: { id: [] }`, `$or: []`, an empty `order_ids`. Medusa's query behavior on empty arrays is not guaranteed, so guard with `when`
+- nested `when(...)` inside a `.then()`: it breaks the outer condition at module load
+- `q: undefined` and other `undefined` query params sent through `@mercurjs/client` (serialized literally)
+- unprefixed `fields` replacing route defaults (use `+`/`-`)
+- money math outside `MathBN`, rounding, sign of reversals and debits
+- transactions held across provider or network calls, missing row locks, double processing on retry, idempotency keys reused after a refused attempt
+- compensation that doesn't restore what the step changed
+- N+1 queries and unbounded `take: null` lists on hot paths
+- callers (plugins, specs, docs) left on a renamed API
+Each finding needs a concrete input that breaks it.
+
+## security
+
+You review the diff for exploitable issues only:
+- vendor routes not scoped to `req.seller_context`, and admin/vendor routes missing `requirePermission`
+- ids from the request used without checking they belong to the actor
+- webhook handlers trusting payloads without the provider's signature check
+- secrets in options responses, logs or the client
+- raw SQL / `raw()` with interpolated input, and prompt injection into any LLM call
+- unvalidated bodies (no zod `.strict()` validator) on new POST routes
+State the attacker, the request and the impact for each one, or drop it.
+
+## taste
+
+You are the reviewer who hates slop. Mercur code must read as written by a careful human. Flag:
+- comments that narrate what the code does, restate names, reference specs/tickets, or say "Mercur-specific"/"for robustness". Only external gotchas earn a comment.
+- `any`, `as never`, `as unknown as` where a real type exists
+- names that don't match the Medusa vocabulary (`dispatch*`, `evaluate*`, `ensure*` where Medusa says `create`/`process`/`update`/`refetch`)
+- user-facing copy that is long, explanatory or marketing-ish (subtitles explaining the obvious, empty states with essays), raw enum values in copy
+- dead code, unused exports, compatibility shims nobody needs, abstractions with one caller
+- files over ~300 lines that mix concerns
+- any mention of AI tools, Mirakl, "port of" or "the connector" in code, comments or docs
+Rank by how much it makes the code look generated.
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 798b0ff77..9606402f2 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -55,7 +55,7 @@ jobs:
- name: Publish to npm
run: |
- for dir in packages/*/ packages/providers/*/ packages/plugins/*/; do
+ for dir in packages/*/ packages/plugins/*/; do
if [ -f "$dir/package.json" ] && ! grep -q '"private": true' "$dir/package.json"; then
echo "Publishing $dir with --tag ${{ steps.npm-tag.outputs.tag }}..."
cd "$dir"
diff --git a/.gitignore b/.gitignore
index 0862e23d1..12a59c7b5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -44,3 +44,9 @@ packages/modules/*
# Local spec tracker (not versioned)
docs/specs/
+
+# scripts/stripe-listen.sh logs and .env backup
+.stripe/
+.env.bak
+
+.playwright-mcp/
diff --git a/CLAUDE.md b/CLAUDE.md
index 19b47fd2c..541914708 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -9,6 +9,7 @@
## Skills
- **Design → code (Figma)**: when the task is turning a Figma design into dashboard UI code — the user shares a `figma.com` URL, selects a Figma node, or asks to "convert / implement / build this design / screen / mockup" in `packages/admin` or `packages/vendor` — load the `figma-ui` skill at `.claude/skills/figma-ui/SKILL.md` first. It reads the design from the Figma MCP (`get_screenshot` as the source of truth, `get_metadata` for structure) and maps it onto the design-system conventions in its `references/` (`components.md`, `spacing.md`, `patterns.md`) before writing JSX. Gate: `bun run lint` + `bun run build` stay green.
+- **Review (`/mercur-review`)**: before opening a PR, or when asked to review / QA a change or make it "match Medusa", load `.claude/skills/mercur-review/SKILL.md`. It runs independent reviewer agents (Medusa patterns, dashboard patterns, technical QA, security, taste) against `references/`, triages findings into actionable / nit / ambiguous, fixes the actionable ones, verifies them by running checks, and loops up to 3 rounds.
## Project Overview
@@ -35,7 +36,7 @@ bun run test:integration:tests # Run integration tests
- `packages/admin` - Admin panel UI package
- `packages/vendor` - Vendor panel UI package
- `packages/registry` - Private workspace for the Mercur blocks registry
-- `packages/providers/payout-stripe-connect` - Stripe Connect payout provider
+- `packages/plugins/stripe-connector` - Stripe connector plugin: Stripe payment provider, Stripe Connect payout provider, admin and vendor Stripe screens
- `apps/api` - Starter Medusa server wired to `@mercurjs/core`
- `apps/admin-test` - Starter admin Vite app (port 7000)
- `apps/vendor` - Starter vendor Vite app (port 7001)
diff --git a/RELEASING.md b/RELEASING.md
index 93c69692a..0f4933382 100644
--- a/RELEASING.md
+++ b/RELEASING.md
@@ -20,8 +20,7 @@ resolves to it.
- `@mercurjs/core`
- `@mercurjs/admin`
- `@mercurjs/vendor`
-- `@mercurjs/payout-stripe-connect`
-- `@mercurjs/magento2-connector-plugin`
+- `@mercurjs/stripe-connector-plugin`
`@mercurjs/registry` is private and not published.
@@ -61,7 +60,7 @@ and hoists it to the repo root, where `@mercurjs/core` resolves it and
```
Also bump every internal cross-dependency (`@mercurjs/*` and `create-mercur-app`)
- in `packages/*`, `packages/providers/*` and `packages/plugins/*` to the same `2.X.Y` (see [Internal Dependencies](#internal-dependencies)).
+ in `packages/*` and `packages/plugins/*` to the same `2.X.Y` (see [Internal Dependencies](#internal-dependencies)).
2. Bump every `@mercurjs/*` dependency version inside the `templates/basic` template so newly scaffolded projects pin to the matching release:
@@ -105,7 +104,7 @@ git push origin main --tags
Where `Z` is the next incremental number (0, 1, 2, ...).
Also bump every internal cross-dependency (`@mercurjs/*` and `create-mercur-app`)
- in `packages/*`, `packages/providers/*` and `packages/plugins/*` to the same `2.X.Y-canary.Z` (see [Internal Dependencies](#internal-dependencies)).
+ in `packages/*` and `packages/plugins/*` to the same `2.X.Y-canary.Z` (see [Internal Dependencies](#internal-dependencies)).
2. Bump every `@mercurjs/*` dependency version inside the `templates/basic` template to the same `2.X.Y-canary.Z` value:
@@ -151,7 +150,7 @@ shippable and is published so it can be tested before being promoted to
Where `Z` is the next incremental number (0, 1, 2, ...).
Also bump every internal cross-dependency (`@mercurjs/*` and `create-mercur-app`)
- in `packages/*`, `packages/providers/*` and `packages/plugins/*` to the same `2.X.Y-rc.Z` (see [Internal Dependencies](#internal-dependencies)).
+ in `packages/*` and `packages/plugins/*` to the same `2.X.Y-rc.Z` (see [Internal Dependencies](#internal-dependencies)).
2. Bump every `@mercurjs/*` dependency version inside the `templates/basic` template to the same `2.X.Y-rc.Z` value:
diff --git a/apps/api/medusa-config.ts b/apps/api/medusa-config.ts
index 52f74a7aa..b4bde3978 100644
--- a/apps/api/medusa-config.ts
+++ b/apps/api/medusa-config.ts
@@ -4,6 +4,7 @@ import { withMercur } from '@mercurjs/core'
loadEnv(process.env.NODE_ENV || 'development', process.cwd())
const REDIS_URL = process.env.REDIS_URL || 'redis://localhost:6379'
+const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY
module.exports = withMercur({
projectConfig: {
@@ -21,20 +22,76 @@ module.exports = withMercur({
featureFlags: {
seller_registration: true
},
+ plugins: [
+ {
+ resolve: '@mercurjs/stripe-connector-plugin',
+ options: {
+ apiKey: STRIPE_SECRET_KEY,
+ webhookSecret: process.env.STRIPE_SELLERS_WEBHOOK_SECRET,
+ alerting: {
+ technicalEmail: process.env.PAYOUT_ALERT_EMAIL,
+ from: process.env.PAYOUT_ALERT_FROM,
+ },
+ notifications: {
+ url: process.env.STRIPE_NOTIFICATIONS_URL,
+ secret: process.env.STRIPE_NOTIFICATIONS_SECRET,
+ },
+ },
+ },
+ ],
modules: [
+ ...(STRIPE_SECRET_KEY
+ ? [
+ {
+ resolve: '@medusajs/medusa/payment',
+ options: {
+ providers: [
+ {
+ resolve: '@mercurjs/stripe-connector-plugin/providers/payment-stripe',
+ id: 'stripe',
+ options: {
+ apiKey: STRIPE_SECRET_KEY,
+ webhookSecret: process.env.STRIPE_OPERATOR_WEBHOOK_SECRET,
+ },
+ },
+ ],
+ },
+ },
+ {
+ resolve: '@mercurjs/core/modules/payout',
+ options: {
+ providers: [
+ {
+ resolve: '@mercurjs/stripe-connector-plugin/providers/payout-stripe-connect',
+ id: 'stripe',
+ options: {
+ apiKey: STRIPE_SECRET_KEY,
+ webhookSecret: process.env.STRIPE_SELLERS_WEBHOOK_SECRET,
+ manualPayouts: true,
+ },
+ },
+ ],
+ onboarding: {
+ returnUrl: `${process.env.VENDOR_URL || 'http://localhost:7001'}/stripe`,
+ refreshBaseUrl: process.env.BACKEND_URL || 'http://localhost:9000',
+ },
+ },
+ },
+ ]
+ : []),
{
resolve: '@mercurjs/core/modules/admin-ui',
options: {
- appDir: '',
- path: '/dashboard',
+ appDir: '../admin-test',
+ path: '/',
disable: true
}
},
{
resolve: '@mercurjs/core/modules/vendor-ui',
options: {
- appDir: '',
- path: '/seller',
+ appDir: '../vendor',
+ path: '/',
disable: true
}
},
diff --git a/apps/api/package.json b/apps/api/package.json
index e28466469..a99e8a390 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -19,6 +19,10 @@
],
"scripts": {
"seed": "medusa exec ./src/scripts/seed.ts",
+ "stripe:simulate": "medusa exec ./src/scripts/simulate-stripe-payouts.ts",
+ "stripe:check-webhooks": "medusa exec ./src/scripts/check-stripe-webhooks.ts",
+ "stripe:onboarding": "medusa exec ./src/scripts/stripe-onboarding.ts",
+ "stripe:scenarios": "medusa exec ./src/scripts/stripe-scenarios.ts",
"start": "medusa start",
"dev": "medusa develop",
"test:integration:http": "TEST_TYPE=integration:http NODE_OPTIONS=--experimental-vm-modules jest --silent=false --runInBand --forceExit",
@@ -34,6 +38,7 @@
"@medusajs/medusa": "2.22.0",
"@medusajs/draft-order": "2.22.0",
"@mercurjs/core": "*",
+ "@mercurjs/stripe-connector-plugin": "*",
"@mercurjs/types": "*",
"http-proxy-middleware": "^3.0.3",
"@mercurjs/cli": "*"
diff --git a/apps/api/src/scripts/check-stripe-webhooks.ts b/apps/api/src/scripts/check-stripe-webhooks.ts
new file mode 100644
index 000000000..9b330225e
--- /dev/null
+++ b/apps/api/src/scripts/check-stripe-webhooks.ts
@@ -0,0 +1,159 @@
+import { ExecArgs } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { MercurModules, PayoutStatus } from "@mercurjs/types"
+import { getStripeClient } from "@mercurjs/stripe-connector-plugin/lib/stripe-client"
+import { STRIPE_CONNECTOR_MODULE } from "@mercurjs/stripe-connector-plugin/types"
+
+import { requireStripeTestKey } from "./utils/stripe-test-key"
+
+/**
+ * Proves the webhooks forwarded by scripts/stripe-listen.sh are verified and
+ * processed, not just answered: the hook routes reply 200 before the
+ * signature is checked, so each check triggers a real Stripe event and waits
+ * for its effect in the database.
+ *
+ * 1. account.updated (Connect) -> payout account re-synced
+ * 2. transfer.created (platform) -> payout moved to paid
+ * 3. payout.* (Connect) -> settlement bank payout status
+ *
+ * Run with the API and the listener up, after simulate-stripe-payouts:
+ * bun --cwd apps/api run stripe:check-webhooks
+ */
+const SELLER_NAME = process.env.SELLER_NAME ?? "Sole Society"
+const TIMEOUT_MS = Number(process.env.WEBHOOK_TIMEOUT_MS ?? 45000)
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
+
+const waitFor = async (check: () => Promise<boolean>, timeout = TIMEOUT_MS) => {
+ const deadline = Date.now() + timeout
+ while (Date.now() < deadline) {
+ if (await check()) return true
+ await sleep(1500)
+ }
+ return false
+}
+
+export default async function checkStripeWebhooks({ container }: ExecArgs) {
+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+ const payoutService = container.resolve(MercurModules.PAYOUT)
+ const connector = container.resolve(STRIPE_CONNECTOR_MODULE)
+
+ const stripe = getStripeClient(requireStripeTestKey())
+
+ const {
+ data: [seller],
+ } = await query.graph({
+ entity: "seller",
+ fields: ["id", "payout_account.id", "payout_account.external_id"],
+ filters: { name: SELLER_NAME },
+ })
+ const account = seller?.payout_account
+ if (!account?.external_id) throw new Error(`${SELLER_NAME} has no Stripe account`)
+
+ const results: { check: string; ok: boolean | null; detail: string }[] = []
+
+ // 1. account.updated
+ const nonce = `check_${Date.now()}`
+ await stripe.accounts.update(account.external_id, { metadata: { webhook_check: nonce } })
+ const synced = await waitFor(async () => {
+ const fresh = await payoutService.retrievePayoutAccount(account.id)
+ const metadata = (fresh.data as { metadata?: Record<string, string> } | null)?.metadata
+ return metadata?.webhook_check === nonce
+ })
+ results.push({
+ check: "account.updated -> /hooks/payout",
+ ok: synced,
+ detail: synced ? `${account.external_id} re-synced` : "account not re-synced; check the API log for a signature error",
+ })
+
+ // 2. transfer.created: a 1-unit transfer tagged with a paid payout, which is
+ // put back to processing so the webhook has something to move.
+ const [paid] = await payoutService.listPayouts(
+ { account_id: account.id, status: PayoutStatus.PAID },
+ { order: { created_at: "DESC" }, take: 1 }
+ )
+ if (!paid) {
+ results.push({ check: "transfer.created -> /hooks/payout", ok: null, detail: "no paid payout yet; run stripe:simulate first" })
+ } else {
+ // The sandbox platform balance is usually all pending, so the transfer is
+ // funded by a charge of its own.
+ const funding = await stripe.paymentIntents.create({
+ amount: 100,
+ currency: paid.currency_code,
+ payment_method: "pm_card_bypassPending",
+ payment_method_types: ["card"],
+ confirm: true,
+ metadata: { webhook_check: nonce },
+ })
+ // A transfer funded by a charge is in the currency the charge settled in.
+ const settledIn = (await stripe.accounts.retrieve()).default_currency ?? paid.currency_code
+ await payoutService.updatePayouts({ id: paid.id, status: PayoutStatus.PROCESSING })
+ let transferId: string | null = null
+ try {
+ const transfer = await stripe.transfers.create({
+ amount: 1,
+ currency: settledIn,
+ destination: account.external_id,
+ source_transaction: funding.latest_charge as string,
+ metadata: { payout_id: paid.id, webhook_check: nonce },
+ })
+ transferId = transfer.id
+ const moved = await waitFor(async () => (await payoutService.retrievePayout(paid.id)).status === PayoutStatus.PAID)
+ results.push({
+ check: "transfer.created -> /hooks/payout",
+ ok: moved,
+ detail: moved ? `payout ${paid.id} paid via ${transfer.id}` : `payout ${paid.id} still processing`,
+ })
+ } finally {
+ if (transferId) await stripe.transfers.createReversal(transferId).catch(() => null)
+ const current = await payoutService.retrievePayout(paid.id)
+ if (current.status !== PayoutStatus.PAID) {
+ await payoutService.updatePayouts({ id: paid.id, status: PayoutStatus.PAID })
+ }
+ }
+ }
+
+ // 3. bank payout of the latest settlement
+ const [settlement] = await connector.listSettlements(
+ { account_id: account.id },
+ { order: { period_end: "DESC" }, take: 1 }
+ )
+ if (!settlement?.provider_payout_id) {
+ results.push({ check: "payout.* -> settlement", ok: null, detail: "no settlement paid out yet; run stripe:simulate first" })
+ } else {
+ const original = { status: settlement.status, payout_status: settlement.payout_status }
+ await connector.updateSettlements({ id: settlement.id, payout_status: null })
+ let applied = false
+ try {
+ // Touching the payout emits payout.updated, so the check does not depend
+ // on Stripe moving the sandbox payout along in time.
+ const bankPayout = await stripe.payouts.update(
+ settlement.provider_payout_id,
+ { metadata: { webhook_check: nonce } },
+ { stripeAccount: account.external_id }
+ )
+ applied = await waitFor(async () => {
+ const [fresh] = await connector.listSettlements({ id: settlement.id })
+ return !!fresh?.payout_status
+ })
+ results.push({
+ check: "payout.* -> settlement",
+ ok: applied,
+ detail: `settlement ${settlement.id}, bank payout ${bankPayout.id} is ${bankPayout.status}`,
+ })
+ } finally {
+ if (!applied) {
+ await connector.updateSettlements({ id: settlement.id, ...original })
+ }
+ }
+ }
+
+ for (const result of results) {
+ const mark = result.ok === null ? "SKIP" : result.ok ? "PASS" : "FAIL"
+ logger.info(`${mark} ${result.check} ${result.detail}`)
+ }
+ if (results.some((result) => result.ok === false)) {
+ process.exitCode = 1
+ }
+}
diff --git a/apps/api/src/scripts/seed.ts b/apps/api/src/scripts/seed.ts
index ca0ad8fc7..160ba37e5 100644
--- a/apps/api/src/scripts/seed.ts
+++ b/apps/api/src/scripts/seed.ts
@@ -177,15 +177,6 @@ export default async function seedDemoData({ container }: ExecArgs) {
}
logger.info("Finished seeding regions.");
- if (!store.default_region_id) {
- await updateStoresWorkflow(container).run({
- input: {
- selector: { id: store.id },
- update: { default_region_id: region.id },
- },
- });
- }
-
logger.info("Seeding tax regions...");
const taxModuleService = container.resolve(Modules.TAX);
const existingTaxRegions = await taxModuleService.listTaxRegions();
diff --git a/apps/api/src/scripts/simulate-stripe-payouts.ts b/apps/api/src/scripts/simulate-stripe-payouts.ts
new file mode 100644
index 000000000..a01328918
--- /dev/null
+++ b/apps/api/src/scripts/simulate-stripe-payouts.ts
@@ -0,0 +1,328 @@
+import { ExecArgs } from "@medusajs/framework/types"
+import {
+ ContainerRegistrationKeys,
+ MathBN,
+ Modules,
+} from "@medusajs/framework/utils"
+import {
+ addToCartWorkflow,
+ createCartWorkflow,
+ createOrderFulfillmentWorkflow,
+ createPaymentCollectionForCartWorkflow,
+ createPaymentSessionsWorkflow,
+ refundPaymentWorkflow,
+} from "@medusajs/medusa/core-flows"
+import {
+ addSellerShippingMethodToCartWorkflow,
+ completeCartWithSplitOrdersWorkflow,
+ splitCapturedCartPaymentWorkflow,
+} from "@mercurjs/core/workflows"
+import { MercurModules } from "@mercurjs/types"
+import { getStripeClient } from "@mercurjs/stripe-connector-plugin/lib/stripe-client"
+import { AdjustmentType, JobTrigger, STRIPE_CONNECTOR_MODULE } from "@mercurjs/stripe-connector-plugin/types"
+import { runJob } from "@mercurjs/stripe-connector-plugin/utils/run-job"
+import { jobWorkflow } from "@mercurjs/stripe-connector-plugin/workflows/jobs"
+
+import { requireStripeTestKey } from "./utils/stripe-test-key"
+
+/**
+ * Walks one Sole Society order through the whole Stripe pipeline against the
+ * sandbox: Stripe-authorized checkout, fulfilment, capture, transfer, a
+ * partial refund with its reversal, and a settlement that pays the seller
+ * out. The connected account must already be active.
+ *
+ * Run with the API on the same database and Redis, and scripts/stripe-listen.sh
+ * forwarding webhooks (the cart is completed by the payment webhook):
+ * bun --cwd apps/api run stripe:simulate
+ */
+const SELLER_NAME = process.env.SELLER_NAME ?? "Sole Society"
+const SHIPPING_OPTION_NAME = "Standard Shipping"
+const PAYMENT_PROVIDER_ID = "pp_stripe-connector_stripe"
+// Test card whose funds skip the pending balance, so the payout has money to move.
+const TEST_PAYMENT_METHOD = "pm_card_bypassPending"
+const REFUND_SHARE = 0.25
+// Set to an existing order id to skip checkout and fulfilment and re-run the pipeline on it.
+const RESUME_ORDER_ID = process.env.RESUME_ORDER_ID
+const SKIP_REFUND = process.env.SKIP_REFUND === "1"
+const DIRECT_CHECKOUT = process.env.DIRECT_CHECKOUT === "1"
+const SKIP_ADJUSTMENTS = process.env.SKIP_ADJUSTMENTS === "1"
+const CURRENCY = process.env.CURRENCY?.toLowerCase()
+
+const providerIdOf = (data: unknown) => (data as { provider?: { id?: string } } | null)?.provider?.id
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
+
+export default async function simulateStripePayouts({ container }: ExecArgs) {
+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+ const link = container.resolve(ContainerRegistrationKeys.LINK)
+ const regionModule = container.resolve(Modules.REGION)
+ const salesChannelModule = container.resolve(Modules.SALES_CHANNEL)
+ const fulfillmentModule = container.resolve(Modules.FULFILLMENT)
+ const payoutService = container.resolve(MercurModules.PAYOUT)
+
+ const stripe = getStripeClient(requireStripeTestKey())
+
+ // 1. seller, account, shipping option
+ const {
+ data: [seller],
+ } = await query.graph({
+ entity: "seller",
+ fields: ["id", "name", "payout_account.id", "payout_account.status", "payout_account.external_id"],
+ filters: { name: SELLER_NAME },
+ })
+ if (!seller) throw new Error(`Seller ${SELLER_NAME} not found`)
+ if (seller.payout_account?.status !== "active") {
+ throw new Error(`${SELLER_NAME}'s payout account is ${seller.payout_account?.status ?? "missing"}; finish onboarding first`)
+ }
+ logger.info(`Seller ${seller.name} (${seller.id}) on ${seller.payout_account.external_id}`)
+
+ const { data: shippingOptions } = await query.graph({
+ entity: "shipping_option",
+ fields: ["id", "name", "seller.id", "service_zone.id", "service_zone.fulfillment_set_id"],
+ filters: { name: SHIPPING_OPTION_NAME },
+ })
+ const shippingOption = shippingOptions.find((so) => so.seller?.id === seller.id)
+ if (!shippingOption?.service_zone?.id) throw new Error(`${SELLER_NAME} has no "${SHIPPING_OPTION_NAME}" option`)
+
+ const geoZones = await fulfillmentModule.listGeoZones(
+ { type: "country", service_zone_id: shippingOption.service_zone.id },
+ { take: null }
+ )
+ const optionCountries = new Set(geoZones.map((g) => g.country_code?.toLowerCase()).filter(Boolean) as string[])
+
+ // 2. region covering one of those countries, with the Stripe provider enabled
+ const regions = await regionModule.listRegions({}, { relations: ["countries", "payment_providers"] })
+ let region = regions.find(
+ (r) => (!CURRENCY || r.currency_code === CURRENCY) && r.countries?.some((c) => c.iso_2 && optionCountries.has(c.iso_2.toLowerCase()))
+ )
+ if (!region) throw new Error("No region covers the shipping option's countries")
+ const country = region.countries!.find((c) => c.iso_2 && optionCountries.has(c.iso_2.toLowerCase()))!.iso_2!.toLowerCase()
+
+ if (!region.payment_providers?.some((p) => p.id === PAYMENT_PROVIDER_ID)) {
+ await link.create({
+ [Modules.REGION]: { region_id: region.id },
+ [Modules.PAYMENT]: { payment_provider_id: PAYMENT_PROVIDER_ID },
+ })
+ logger.info(`Enabled ${PAYMENT_PROVIDER_ID} on region ${region.name}`)
+ }
+
+ const [salesChannel] = await salesChannelModule.listSalesChannels({ name: "Default Sales Channel" }, { take: 1 })
+ if (!salesChannel) throw new Error("Default sales channel not found")
+
+ const fulfillmentSetId = shippingOption.service_zone.fulfillment_set_id
+ const { data: stockLocations } = await query.graph({
+ entity: "stock_locations",
+ fields: ["id", "fulfillment_sets.id"],
+ })
+ const locationId = stockLocations.find((sl) => (sl.fulfillment_sets ?? []).some((fs) => fs?.id === fulfillmentSetId))?.id
+ if (!locationId) throw new Error("Seller stock location not found")
+ await link
+ .create({
+ [Modules.SALES_CHANNEL]: { sales_channel_id: salesChannel.id },
+ [Modules.STOCK_LOCATION]: { stock_location_id: locationId },
+ })
+ .catch(() => null)
+
+ // 3. one published offer with stock
+ const { data: offers } = await query.graph({
+ entity: "offer",
+ fields: ["id", "sku", "variant_id"],
+ filters: { seller_id: seller.id },
+ })
+ const productModule = container.resolve(Modules.PRODUCT)
+ const variants = await productModule.listProductVariants(
+ { id: offers.map((o) => o.variant_id).filter(Boolean) as string[] },
+ { relations: ["product"], take: null }
+ )
+ const published = new Set(variants.filter((v) => v.product?.status === "published").map((v) => v.id))
+ const offer = offers.find((o) => o.variant_id && published.has(o.variant_id))
+ if (!offer) throw new Error(`${SELLER_NAME} has no offer on a published product`)
+
+ const run = async (job: Parameters<typeof runJob>[1], scope: Parameters<typeof jobWorkflow>[2] = {}) => {
+ const result = await runJob(container, job, JobTrigger.MANUAL, jobWorkflow(job, container, scope))
+ logger.info(`${job}: ${result?.status} ${JSON.stringify(result?.stats ?? {})}${result?.error ? ` error=${result.error}` : ""}`)
+ return result
+ }
+
+ let order: { id: string; display_id: number; total: unknown; items?: { id: string; quantity: number }[] | null }
+ let groupId: string
+
+ if (RESUME_ORDER_ID) {
+ const {
+ data: [existing],
+ } = await query.graph({
+ entity: "order",
+ fields: ["id", "display_id", "total", "items.id", "items.quantity"],
+ filters: { id: RESUME_ORDER_ID },
+ })
+ if (!existing) throw new Error(`Order ${RESUME_ORDER_ID} not found`)
+ order = existing as never
+ const { data: links } = await query.graph({ entity: "order_group_order", fields: ["order_group_id"], filters: { order_id: order.id } })
+ groupId = links[0]?.order_group_id
+ logger.info(`Resuming on order #${order.display_id} (${order.id})`)
+ } else {
+ // 4. cart → Stripe session → confirm with the test card → complete
+ const address = {
+ first_name: "Stripe",
+ last_name: "Tester",
+ address_1: "1 Test Street",
+ city: "Testville",
+ country_code: country,
+ postal_code: "10000",
+ }
+ const { result: cart } = await createCartWorkflow(container).run({
+ input: {
+ email: "[email protected]",
+ region_id: region.id,
+ sales_channel_id: salesChannel.id,
+ currency_code: region.currency_code,
+ shipping_address: address,
+ billing_address: address,
+ },
+ })
+ await addToCartWorkflow(container).run({
+ input: {
+ cart_id: cart.id,
+ items: [{ variant_id: offer.variant_id, quantity: 2, offer_id: offer.id, metadata: { offer_id: offer.id } } as never],
+ },
+ })
+ await addSellerShippingMethodToCartWorkflow(container).run({
+ input: { cart_id: cart.id, options: [{ id: shippingOption.id }] },
+ })
+ const { result: paymentCollection } = await createPaymentCollectionForCartWorkflow(container).run({
+ input: { cart_id: cart.id },
+ })
+ const { result: sessions } = await createPaymentSessionsWorkflow(container).run({
+ input: { payment_collection_id: paymentCollection.id, provider_id: PAYMENT_PROVIDER_ID },
+ })
+ const session = Array.isArray(sessions) ? sessions[0] : sessions
+ const intentId = (session.data as { id?: string })?.id
+ if (!intentId) throw new Error("Stripe session has no PaymentIntent id")
+
+ await stripe.paymentIntents.confirm(intentId, {
+ payment_method: TEST_PAYMENT_METHOD,
+ return_url: "http://localhost:9000",
+ })
+ logger.info(`Confirmed ${intentId} with ${TEST_PAYMENT_METHOD} (authorized, not captured)`)
+
+ let orderGroupId: string | undefined
+ if (DIRECT_CHECKOUT) {
+ const { result: completion, errors } = await completeCartWithSplitOrdersWorkflow(container).run({
+ input: { cart_id: cart.id },
+ throwOnError: false,
+ })
+ if (errors?.length) throw errors[0].error
+ orderGroupId = completion?.order_group_id
+ } else {
+ // A storefront that drops the customer mid-redirect relies on
+ // payment_intent.amount_capturable_updated to complete the cart.
+ // The order group is written midway through completion; completed_at
+ // marks the end, after which capturing cannot race checkout's own split.
+ for (let attempt = 0; attempt < 30 && !orderGroupId; attempt++) {
+ await sleep(2000)
+ const {
+ data: [completed],
+ } = await query.graph({ entity: "cart", fields: ["completed_at"], filters: { id: cart.id } })
+ if (!completed?.completed_at) continue
+ const { data: groups } = await query.graph({ entity: "order_group", fields: ["id"], filters: { cart_id: cart.id } })
+ orderGroupId = groups[0]?.id
+ }
+ if (!orderGroupId) {
+ throw new Error("The payment webhook did not complete the cart; is scripts/stripe-listen.sh running? (DIRECT_CHECKOUT=1 skips it)")
+ }
+ logger.info(`Cart ${cart.id} completed by the payment webhook`)
+ }
+ const {
+ data: [group],
+ } = await query.graph({
+ entity: "order_group",
+ fields: ["id", "display_id", "orders.id", "orders.display_id", "orders.total", "orders.items.id", "orders.items.quantity"],
+ filters: { id: orderGroupId },
+ })
+ order = group.orders![0] as never
+ groupId = group.id
+ logger.info(`Order group #${group.display_id}: order #${order.display_id} (${order.id}) total ${order.total} ${region.currency_code}`)
+
+ // 5. fulfil → the group is decided
+ await createOrderFulfillmentWorkflow(container).run({
+ input: {
+ order_id: order.id,
+ location_id: locationId,
+ items: (order.items ?? []).map((item) => ({ id: item.id, quantity: item.quantity })),
+ no_notification: true,
+ },
+ })
+ logger.info(`Fulfilled order #${order.display_id}`)
+ }
+
+ // 6. capture
+ await run("payout-validate-captures", { order_group_id: groupId })
+
+ // The captured cart payment is split into per-order payments by a subscriber.
+ const capturedOrderPayment = async () => {
+ const {
+ data: [fresh],
+ } = await query.graph({
+ entity: "order",
+ fields: ["id", "payment_collections.payments.id", "payment_collections.payments.captured_at"],
+ filters: { id: order.id },
+ })
+ return (fresh?.payment_collections ?? []).flatMap((c) => c?.payments ?? []).find((p) => p?.captured_at)?.id ?? null
+ }
+ let orderPaymentId: string | null = null
+ for (let attempt = 0; attempt < 20 && !orderPaymentId; attempt++) {
+ await sleep(1500)
+ orderPaymentId = await capturedOrderPayment()
+ }
+ if (!orderPaymentId) {
+ const { data: carts } = await query.graph({ entity: "order_cart", fields: ["cart_id"], filters: { order_id: order.id } })
+ logger.warn(`The payment.captured subscriber did not split cart ${carts[0]?.cart_id}'s payment; splitting it here`)
+ await splitCapturedCartPaymentWorkflow(container).run({ input: { cart_id: carts[0].cart_id } })
+ orderPaymentId = await capturedOrderPayment()
+ }
+ if (!orderPaymentId) throw new Error("Order payment was not captured and split")
+ logger.info(`Order payment ${orderPaymentId} captured`)
+
+ // 7. transfer
+ await run("payout-process-transfers", { order_id: order.id })
+
+ // 8. partial refund → reversal
+ if (!SKIP_REFUND) {
+ const refundAmount = Number(MathBN.convert(MathBN.mult(order.total as never, REFUND_SHARE)).toFixed(2))
+ await refundPaymentWorkflow(container).run({
+ input: { payment_id: orderPaymentId, amount: refundAmount, note: "Simulated partial refund" },
+ })
+ logger.info(`Refunded ${refundAmount} ${region.currency_code} on ${orderPaymentId}`)
+ }
+ await run("payout-process-reversals", { order_id: order.id })
+
+ // 9. operator adjustments, netted by the settlement
+ const connector = container.resolve(STRIPE_CONNECTOR_MODULE)
+ if (!SKIP_ADJUSTMENTS) {
+ await connector.createAdjustments([
+ { account_id: seller.payout_account.id, type: AdjustmentType.EXTRA_CREDIT, amount: 15, currency_code: region.currency_code, reason: "Simulated goodwill credit" },
+ { account_id: seller.payout_account.id, type: AdjustmentType.EXTRA_INVOICE, amount: 5, currency_code: region.currency_code, reason: "Simulated listing fee" },
+ ])
+ logger.info(`Added a 15 ${region.currency_code} credit and a 5 ${region.currency_code} invoice`)
+ }
+
+ // 10. settlement + payout
+ await run("payout-process-settlements", { seller_id: seller.id })
+
+ // 11. summary
+ const payouts = await payoutService.listPayouts({ order_id: order.id }, { relations: ["reversals"] })
+ for (const payout of payouts) {
+ logger.info(`payout ${payout.id} ${payout.amount} ${payout.currency_code} → ${payout.status}${providerIdOf(payout.data) ? ` ${providerIdOf(payout.data)}` : ""}${payout.status_reason ? ` (${payout.status_reason})` : ""}`)
+ for (const reversal of payout.reversals ?? []) {
+ logger.info(` reversal ${reversal.id} ${reversal.amount} → ${reversal.status}${providerIdOf(reversal.data) ? ` ${providerIdOf(reversal.data)}` : ""}${reversal.status_reason ? ` (${reversal.status_reason})` : ""}`)
+ }
+ }
+ for (const adjustment of await connector.listAdjustments({ account_id: seller.payout_account.id }, { order: { created_at: "DESC" }, take: 2 })) {
+ logger.info(`adjustment ${adjustment.id} ${adjustment.type} ${adjustment.amount} → ${adjustment.status}${adjustment.provider_transfer_id ? ` ${adjustment.provider_transfer_id}` : ""}${adjustment.status_reason ? ` (${adjustment.status_reason})` : ""}`)
+ }
+ const [settlement] = await connector.listSettlements({ account_id: seller.payout_account.id }, { order: { period_end: "DESC" }, take: 1 })
+ if (settlement) {
+ logger.info(`settlement ${settlement.id}: payouts ${settlement.payouts_total} − reversals ${settlement.reversals_total} + adjustments ${settlement.adjustments_total} = ${settlement.amount} ${settlement.currency_code} → ${settlement.status}${settlement.provider_payout_id ? ` ${settlement.provider_payout_id}` : ""}${settlement.status_reason ? ` (${settlement.status_reason})` : ""}`)
+ }
+}
diff --git a/apps/api/src/scripts/stripe-onboarding.ts b/apps/api/src/scripts/stripe-onboarding.ts
new file mode 100644
index 000000000..1a08b6b92
--- /dev/null
+++ b/apps/api/src/scripts/stripe-onboarding.ts
@@ -0,0 +1,89 @@
+import { ExecArgs } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { createOnboardingWorkflow, createPayoutAccountWorkflow } from "@mercurjs/core/workflows"
+import { MercurModules } from "@mercurjs/types"
+
+import { requireStripeTestKey } from "./utils/stripe-test-key"
+
+/**
+ * Prints a fresh Stripe onboarding link for a seller (creating the Express
+ * account if the seller has none) and then follows the payout account while
+ * you complete onboarding in the browser. Nothing else syncs the account, so
+ * every change printed was applied by an account.updated webhook.
+ *
+ * Run with the API and scripts/stripe-listen.sh up:
+ * SELLER_NAME="Kickz Corner" bun --cwd apps/api run stripe:onboarding
+ */
+const SELLER_NAME = process.env.SELLER_NAME ?? "Kickz Corner"
+const WATCH_MINUTES = Number(process.env.WATCH_MINUTES ?? 20)
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
+
+type Requirements = { currently_due?: string[]; past_due?: string[]; pending_verification?: string[] } | null
+
+export default async function stripeOnboarding({ container }: ExecArgs) {
+ requireStripeTestKey()
+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+ const payoutService = container.resolve(MercurModules.PAYOUT)
+
+ const {
+ data: [seller],
+ } = await query.graph({
+ entity: "seller",
+ fields: ["id", "name", "email", "payout_account.id"],
+ filters: { name: SELLER_NAME },
+ })
+ if (!seller) throw new Error(`Seller ${SELLER_NAME} not found`)
+
+ let accountId = seller.payout_account?.id
+ if (!accountId) {
+ const { result } = await createPayoutAccountWorkflow(container).run({ input: { seller_id: seller.id } })
+ accountId = result.id
+ logger.info(`Created a Stripe account for ${seller.name}`)
+ }
+
+ const onboarding = await createOnboardingWorkflow(container).run({ input: { account_id: accountId } })
+ const link = (onboarding.result.data ?? {}) as { url?: string; kind?: string; expires_at?: string | null }
+
+ const account = await payoutService.retrievePayoutAccount(accountId)
+ logger.info(`${seller.name} (${seller.email}) → ${account.external_id}, status ${account.status}`)
+ logger.info(`${link.kind === "login" ? "Express dashboard" : "Onboarding"} link${link.expires_at ? ` (expires ${link.expires_at})` : ""}:`)
+ console.log(`\n ${link.url}\n`)
+ logger.info(`Watching for ${WATCH_MINUTES} min; Ctrl+C to stop`)
+
+ const snapshot = (a: typeof account) => {
+ const requirements = (a.data as { requirements?: Requirements } | null)?.requirements ?? null
+ return [
+ `status=${a.status}`,
+ `kyc=${a.kyc_status}`,
+ `details_submitted=${a.details_submitted}`,
+ `charges=${a.charges_enabled}`,
+ `payouts=${a.payouts_enabled}`,
+ `due=${requirements?.currently_due?.length ?? 0}`,
+ `pending_verification=${requirements?.pending_verification?.length ?? 0}`,
+ a.disabled_reason ? `disabled=${a.disabled_reason}` : null,
+ ]
+ .filter(Boolean)
+ .join(" ")
+ }
+
+ let last = snapshot(account)
+ let lastSyncedAt = account.last_synced_at ? new Date(account.last_synced_at).getTime() : 0
+ logger.info(last)
+
+ const deadline = Date.now() + WATCH_MINUTES * 60_000
+ while (Date.now() < deadline) {
+ await sleep(2000)
+ const fresh = await payoutService.retrievePayoutAccount(accountId)
+ const syncedAt = fresh.last_synced_at ? new Date(fresh.last_synced_at).getTime() : 0
+ const current = snapshot(fresh)
+ if (syncedAt !== lastSyncedAt || current !== last) {
+ logger.info(`webhook sync: ${current}`)
+ const due = (fresh.data as { requirements?: Requirements } | null)?.requirements?.currently_due ?? []
+ if (due.length) logger.info(` currently due: ${due.join(", ")}`)
+ last = current
+ lastSyncedAt = syncedAt
+ }
+ }
+}
diff --git a/apps/api/src/scripts/stripe-scenarios.ts b/apps/api/src/scripts/stripe-scenarios.ts
new file mode 100644
index 000000000..8113663c7
--- /dev/null
+++ b/apps/api/src/scripts/stripe-scenarios.ts
@@ -0,0 +1,860 @@
+import { ExecArgs } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys, MathBN, Modules } from "@medusajs/framework/utils"
+import {
+ addToCartWorkflow,
+ cancelOrderWorkflow,
+ createCartWorkflow,
+ createOrderFulfillmentWorkflow,
+ createPaymentCollectionForCartWorkflow,
+ createPaymentSessionsWorkflow,
+ refundPaymentWorkflow,
+} from "@medusajs/medusa/core-flows"
+import {
+ addSellerShippingMethodToCartWorkflow,
+ completeCartWithSplitOrdersWorkflow,
+ createCommissionRatesWorkflow,
+ createOrderPayoutsWorkflow,
+ deleteCommissionRatesWorkflow,
+ processPayoutWorkflow,
+} from "@mercurjs/core/workflows"
+import { PayoutStatus } from "@mercurjs/types"
+import { getStripeClient } from "@mercurjs/stripe-connector-plugin/lib/stripe-client"
+import { JobTrigger, PAYOUT_JOBS, PayoutJobName } from "@mercurjs/stripe-connector-plugin/types"
+import { resolveConnector, resolvePayoutModule } from "@mercurjs/stripe-connector-plugin/utils/payout-module"
+import { runJob } from "@mercurjs/stripe-connector-plugin/utils/run-job"
+import { jobWorkflow } from "@mercurjs/stripe-connector-plugin/workflows/jobs"
+
+import { requireStripeTestKey } from "./utils/stripe-test-key"
+
+/**
+ * Runs the payout scenarios against the Stripe sandbox in USD and prints a
+ * PASS/FAIL line per check. Needs the API up (for HTTP checks and webhooks)
+ * and scripts/stripe-listen.sh forwarding.
+ *
+ * bun --cwd apps/api run stripe:scenarios
+ * ONLY=two-sellers,hold runs a subset; NOTIFICATIONS_LOG=<file> enables the notification checks
+ */
+const API = process.env.BACKEND_URL ?? "http://localhost:9000"
+const ADMIN = { email: process.env.ADMIN_EMAIL ?? "[email protected]", password: process.env.ADMIN_PASSWORD ?? "supersecret" }
+const SELLER_PASSWORD = "supersecret"
+const CURRENCY = "usd"
+const PAYMENT_PROVIDER_ID = "pp_stripe-connector_stripe"
+const ONLY = process.env.ONLY?.split(",").map((s) => s.trim())
+
+const transferIdOf = (data: unknown) => {
+ const d = data as { id?: string; provider?: { id?: string } } | null | undefined
+ return d?.provider?.id ?? d?.id ?? null
+}
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
+const num = (value: unknown) => Number(MathBN.convert(value as never).toFixed(2))
+
+type Check = { scenario: string; name: string; ok: boolean; detail: string }
+const results: Check[] = []
+
+type SellerCtx = {
+ id: string
+ name: string
+ email: string
+ accountId: string | null
+ externalId: string | null
+ accountStatus: string | null
+ shippingOptionId: string
+ locationId: string
+ offers: { id: string; variant_id: string }[]
+}
+
+type PlacedOrder = { id: string; display_id: number; total: number; seller_id: string; items: { id: string; quantity: number }[] }
+
+export default async function stripeScenarios({ container }: ExecArgs) {
+ const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+ const link = container.resolve(ContainerRegistrationKeys.LINK)
+ const payoutService = resolvePayoutModule(container)
+ const connector = resolveConnector(container)
+ const fulfillmentModule = container.resolve(Modules.FULFILLMENT)
+ const regionModule = container.resolve(Modules.REGION)
+ const productModule = container.resolve(Modules.PRODUCT)
+ const stripe = getStripeClient(requireStripeTestKey())
+
+ const check = (scenario: string, name: string, ok: boolean, detail = "") => {
+ results.push({ scenario, name, ok, detail })
+ logger.info(`${ok ? "PASS" : "FAIL"} [${scenario}] ${name}${detail ? ` ${detail}` : ""}`)
+ }
+
+ const waitFor = async <T>(fn: () => Promise<T | null | undefined | false>, timeout = 30000, every = 1500) => {
+ const deadline = Date.now() + timeout
+ while (Date.now() < deadline) {
+ const value = await fn()
+ if (value) return value
+ await sleep(every)
+ }
+ return null
+ }
+
+ const job = async (name: PayoutJobName, scope: Parameters<typeof jobWorkflow>[2] = {}) =>
+ runJob(container, name, JobTrigger.MANUAL, jobWorkflow(name, container, scope))
+
+ // --- environment -------------------------------------------------------
+
+ const regions = await regionModule.listRegions({ currency_code: CURRENCY }, { relations: ["countries", "payment_providers"] })
+ const region = regions.find((r) => r.countries?.some((c) => c.iso_2 === "us"))
+ if (!region) throw new Error("No USD region covering us")
+ if (!region.payment_providers?.some((p) => p.id === PAYMENT_PROVIDER_ID)) {
+ await link.create({ [Modules.REGION]: { region_id: region.id }, [Modules.PAYMENT]: { payment_provider_id: PAYMENT_PROVIDER_ID } })
+ }
+ const salesChannelModule = container.resolve(Modules.SALES_CHANNEL)
+ const [salesChannel] = await salesChannelModule.listSalesChannels({ name: "Default Sales Channel" }, { take: 1 })
+
+ const sellerCtx = async (name: string): Promise<SellerCtx> => {
+ const {
+ data: [seller],
+ } = await query.graph({
+ entity: "seller",
+ fields: ["id", "name", "email", "payout_account.id", "payout_account.status", "payout_account.external_id"],
+ filters: { name },
+ })
+ if (!seller) throw new Error(`Seller ${name} not found`)
+
+ const { data: options } = await query.graph({
+ entity: "shipping_option",
+ fields: ["id", "seller.id", "service_zone.id", "service_zone.fulfillment_set_id"],
+ filters: { name: "Standard Shipping" },
+ })
+ const option = options.find((o) => o.seller?.id === seller.id)
+ if (!option?.service_zone?.id) throw new Error(`${name} has no Standard Shipping`)
+ const zones = await fulfillmentModule.listGeoZones({ service_zone_id: option.service_zone.id } as never, { take: null })
+ if (!zones.some((z) => z.country_code === "us")) {
+ await fulfillmentModule.createGeoZones({ service_zone_id: option.service_zone.id, type: "country", country_code: "us" })
+ }
+
+ const { data: locations } = await query.graph({ entity: "stock_locations", fields: ["id", "fulfillment_sets.id"] })
+ const locationId = locations.find((l) => (l.fulfillment_sets ?? []).some((fs) => fs?.id === option.service_zone!.fulfillment_set_id))?.id
+ if (!locationId) throw new Error(`${name} has no stock location`)
+ await link
+ .create({ [Modules.SALES_CHANNEL]: { sales_channel_id: salesChannel.id }, [Modules.STOCK_LOCATION]: { stock_location_id: locationId } })
+ .catch(() => null)
+
+ const { data: offers } = await query.graph({ entity: "offer", fields: ["id", "variant_id"], filters: { seller_id: seller.id } })
+ const variants = await productModule.listProductVariants(
+ { id: offers.map((o) => o.variant_id).filter(Boolean) as string[] },
+ { relations: ["product"], take: null }
+ )
+ const published = new Set(variants.filter((v) => v.product?.status === "published").map((v) => v.id))
+
+ return {
+ id: seller.id,
+ name: seller.name,
+ email: seller.email,
+ accountId: seller.payout_account?.id ?? null,
+ externalId: seller.payout_account?.external_id ?? null,
+ accountStatus: seller.payout_account?.status ?? null,
+ shippingOptionId: option.id,
+ locationId,
+ offers: offers.filter((o) => o.variant_id && published.has(o.variant_id)) as { id: string; variant_id: string }[],
+ }
+ }
+
+ const address = {
+ first_name: "Scenario",
+ last_name: "Tester",
+ address_1: "1 Market St",
+ city: "San Francisco",
+ province: "ca",
+ country_code: "us",
+ postal_code: "94105",
+ }
+
+ /** Places one order group with an order per seller; the payment is authorized, not captured. */
+ const checkout = async (lines: { seller: SellerCtx; quantity?: number }[]) => {
+ const { result: cart } = await createCartWorkflow(container).run({
+ input: {
+ email: "[email protected]",
+ region_id: region.id,
+ sales_channel_id: salesChannel.id,
+ currency_code: CURRENCY,
+ shipping_address: address,
+ billing_address: address,
+ },
+ })
+ for (const { seller, quantity = 1 } of lines) {
+ let added = false
+ for (const offer of seller.offers.slice(0, 10)) {
+ const { errors } = await addToCartWorkflow(container).run({
+ input: { cart_id: cart.id, items: [{ variant_id: offer.variant_id, quantity, offer_id: offer.id, metadata: { offer_id: offer.id } } as never] },
+ throwOnError: false,
+ })
+ if (!errors?.length) {
+ added = true
+ break
+ }
+ }
+ if (!added) throw new Error(`No ${seller.name} offer could be added to a USD cart`)
+ }
+ await addSellerShippingMethodToCartWorkflow(container).run({
+ input: { cart_id: cart.id, options: lines.map(({ seller }) => ({ id: seller.shippingOptionId })) },
+ })
+ const { result: collection } = await createPaymentCollectionForCartWorkflow(container).run({ input: { cart_id: cart.id } })
+ const { result: sessions } = await createPaymentSessionsWorkflow(container).run({
+ input: { payment_collection_id: collection.id, provider_id: PAYMENT_PROVIDER_ID },
+ })
+ const session = Array.isArray(sessions) ? sessions[0] : sessions
+ const intentId = (session.data as { id: string }).id
+ await stripe.paymentIntents.confirm(intentId, { payment_method: "pm_card_bypassPending", return_url: API })
+
+ const { result: completion, errors } = await completeCartWithSplitOrdersWorkflow(container).run({
+ input: { cart_id: cart.id },
+ throwOnError: false,
+ })
+ if (errors?.length) throw errors[0].error
+ const {
+ data: [group],
+ } = await query.graph({
+ entity: "order_group",
+ fields: ["id", "display_id", "orders.id", "orders.display_id", "orders.total", "orders.seller.id", "orders.items.id", "orders.items.quantity"],
+ filters: { id: completion!.order_group_id },
+ })
+ const orders: PlacedOrder[] = (group.orders ?? []).map((o) => ({
+ id: o!.id,
+ display_id: Number(o!.display_id),
+ total: num(o!.total),
+ seller_id: (o as { seller?: { id: string } }).seller?.id as string,
+ items: (o!.items ?? []).map((i) => ({ id: i!.id, quantity: i!.quantity as number })),
+ }))
+ return { cartId: cart.id, groupId: group.id as string, groupDisplayId: group.display_id, intentId, cartTotal: num(collection.amount), orders }
+ }
+
+ const fulfill = async (order: PlacedOrder, seller: SellerCtx) =>
+ createOrderFulfillmentWorkflow(container).run({
+ input: { order_id: order.id, location_id: seller.locationId, items: order.items, no_notification: true },
+ })
+
+ const orderPayment = async (orderId: string) => {
+ const {
+ data: [order],
+ } = await query.graph({
+ entity: "order",
+ fields: ["payment_collections.payments.id", "payment_collections.payments.amount", "payment_collections.payments.captured_at"],
+ filters: { id: orderId },
+ })
+ return (order?.payment_collections ?? []).flatMap((c) => c?.payments ?? []).find((p) => p?.captured_at) ?? null
+ }
+
+ const waitOrderPayment = async (orderId: string) => (await waitFor(() => orderPayment(orderId))) as { id: string; amount: unknown } | null
+
+ const payoutOf = async (orderId: string) => {
+ const [payout] = await payoutService.listPayouts({ order_id: orderId }, { relations: ["reversals"] })
+ return payout ?? null
+ }
+
+ const commissionOf = async (order: PlacedOrder) => {
+ const { data: lines } = await query.graph({
+ entity: "commission_line",
+ fields: ["amount", "item_id", "commission_rate_id"],
+ filters: { item_id: order.items.map((i) => i.id) },
+ })
+ return { total: lines.reduce((sum, l) => sum + num(l.amount), 0), lines }
+ }
+
+ const transfersFor = async (payoutId: string, destination: string) => {
+ const page = await stripe.transfers.list({ destination, limit: 100 })
+ return page.data.filter((t) => t.metadata?.payout_id === payoutId)
+ }
+
+ const http = async (method: string, path: string, token: string, body?: unknown, headers: Record<string, string> = {}) => {
+ const res = await fetch(`${API}${path}`, {
+ method,
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}`, ...headers },
+ body: body ? JSON.stringify(body) : undefined,
+ })
+ const text = await res.text()
+ let json: Record<string, unknown> = {}
+ try {
+ json = JSON.parse(text)
+ } catch {
+ json = { raw: text }
+ }
+ return { status: res.status, json }
+ }
+
+ const login = async (actor: "user" | "member", email: string, password: string) => {
+ const res = await fetch(`${API}/auth/${actor}/emailpass`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ email, password }),
+ })
+ return ((await res.json()) as { token: string }).token
+ }
+
+ const scenario = async (name: string, fn: () => Promise<void>) => {
+ if (ONLY && !ONLY.includes(name)) return
+ logger.info(`--- ${name}`)
+ try {
+ await fn()
+ } catch (error) {
+ check(name, "scenario ran", false, (error as Error).message)
+ }
+ }
+
+ const sole = await sellerCtx("Sole Society")
+ const kickz = await sellerCtx("Kickz Corner")
+ const peak = await sellerCtx("Peak & Pace")
+
+ const expectPaidPayout = async (s: string, order: PlacedOrder, seller: SellerCtx) => {
+ const { total: commission } = await commissionOf(order)
+ const payout = await waitFor(async () => {
+ const p = await payoutOf(order.id)
+ return p && p.status === PayoutStatus.PAID ? p : null
+ })
+ const expected = num(order.total - commission)
+ check(s, `#${order.display_id} ${seller.name} payout paid`, !!payout, payout ? `${num(payout.amount)} ${CURRENCY}` : `status ${(await payoutOf(order.id))?.status ?? "none"}`)
+ if (payout) check(s, `#${order.display_id} payout = total − commission`, num(payout.amount) === expected, `${order.total} − ${commission} = ${expected}, got ${num(payout.amount)}`)
+ return payout
+ }
+
+ // --- 1. two sellers in one cart -----------------------------------------
+ await scenario("two-sellers", async () => {
+ const s = "two-sellers"
+ const placed = await checkout([{ seller: sole }, { seller: kickz }])
+ check(s, "one order per seller", placed.orders.length === 2 && new Set(placed.orders.map((o) => o.seller_id)).size === 2, `group #${placed.groupDisplayId}`)
+ const sum = num(placed.orders.reduce((acc, o) => acc + o.total, 0))
+ check(s, "order totals add up to the cart payment", sum === placed.cartTotal, `${sum} vs ${placed.cartTotal}`)
+
+ for (const order of placed.orders) await fulfill(order, order.seller_id === sole.id ? sole : kickz)
+ await job("payout-validate-captures", { order_group_id: placed.groupId })
+ const intent = await stripe.paymentIntents.retrieve(placed.intentId)
+ check(s, "cart payment captured once in full", intent.status === "succeeded" && intent.amount_received === Math.round(placed.cartTotal * 100), `${intent.amount_received / 100}`)
+
+ const shares: number[] = []
+ for (const order of placed.orders) {
+ const payment = await waitOrderPayment(order.id)
+ check(s, `#${order.display_id} has its own captured payment`, !!payment, payment ? `${num(payment.amount)}` : "missing")
+ if (payment) shares.push(num(payment.amount))
+ }
+ check(s, "payment shares add up to the cart total", num(shares.reduce((a, b) => a + b, 0)) === placed.cartTotal, shares.join(" + "))
+
+ const soleOrder = placed.orders.find((o) => o.seller_id === sole.id)!
+ const kickzOrder = placed.orders.find((o) => o.seller_id === kickz.id)!
+ const solePayout = await expectPaidPayout(s, soleOrder, sole)
+ const kickzPayout = await expectPaidPayout(s, kickzOrder, kickz)
+
+ const kickzPayment = await orderPayment(kickzOrder.id)
+ const refund = num(kickzOrder.total * 0.5)
+ await refundPaymentWorkflow(container).run({ input: { payment_id: kickzPayment!.id, amount: refund } })
+ await job("payout-process-reversals", { order_id: kickzOrder.id })
+ const kickzAfter = await waitFor(async () => {
+ const p = await payoutOf(kickzOrder.id)
+ return p?.reversals?.some((r) => r.status === PayoutStatus.PAID) ? p : null
+ })
+ const { total: kickzCommission } = await commissionOf(kickzOrder)
+ const expectedReversal = num(refund - (refund * kickzCommission) / kickzOrder.total)
+ const reversal = kickzAfter?.reversals?.[0]
+ check(s, "refund on one order reverses only that seller", !!reversal && num(reversal.amount) === expectedReversal, reversal ? `${num(reversal.amount)} (expected ${expectedReversal})` : "no reversal")
+ const soleAfter = await payoutOf(soleOrder.id)
+ check(s, "other seller's payout untouched", (soleAfter?.reversals ?? []).length === 0 && num(soleAfter!.amount) === num(solePayout?.amount))
+ if (kickzPayout) check(s, "one transfer per payout", (await transfersFor(kickzPayout.id, kickz.externalId!)).length === 1)
+ })
+
+ // --- 2. payout held until fulfilment ---------------------------------------
+ await scenario("hold", async () => {
+ const s = "hold"
+ const placed = await checkout([{ seller: sole }])
+ const order = placed.orders[0]
+ await createOrderPayoutsWorkflow(container).run({ input: { order_ids: [order.id] } })
+ const held = await payoutOf(order.id)
+ check(s, "unfulfilled order → payout on hold", held?.status === PayoutStatus.ON_HOLD && held.status_reason === "order_not_ready", `${held?.status} ${held?.status_reason}`)
+
+ await job("payout-validate-captures", { order_group_id: placed.groupId })
+ const intent = await stripe.paymentIntents.retrieve(placed.intentId)
+ check(s, "capture waits for fulfilment", intent.status === "requires_capture", intent.status)
+
+ await fulfill(order, sole)
+ await job("payout-validate-captures", { order_group_id: placed.groupId })
+ await waitOrderPayment(order.id)
+ await job("payout-process-transfers", { order_id: order.id })
+ await expectPaidPayout(s, order, sole)
+ })
+
+ // --- 3. seller whose account is not active -------------------------------
+ await scenario("account-not-ready", async () => {
+ const s = "account-not-ready"
+ if (peak.accountStatus === "active") {
+ check(s, "seller has an inactive account", false, `${peak.name} is active; pick another seller`)
+ return
+ }
+ const placed = await checkout([{ seller: peak }])
+ const order = placed.orders[0]
+ await fulfill(order, peak)
+ await job("payout-validate-captures", { order_group_id: placed.groupId })
+ await waitOrderPayment(order.id)
+ await job("payout-process-transfers", { order_id: order.id })
+ const payout = await payoutOf(order.id)
+ check(s, `${peak.name} (${peak.accountStatus}) → payout on hold`, payout?.status === PayoutStatus.ON_HOLD && !!payout.status_reason?.startsWith("account_"), `${payout?.status} ${payout?.status_reason}`)
+ })
+
+ // --- 4. cancellations -------------------------------------------------------
+ await scenario("cancel", async () => {
+ const s = "cancel"
+ const placed = await checkout([{ seller: sole }, { seller: kickz }])
+ const soleOrder = placed.orders.find((o) => o.seller_id === sole.id)!
+ const kickzOrder = placed.orders.find((o) => o.seller_id === kickz.id)!
+ await cancelOrderWorkflow(container).run({ input: { order_id: kickzOrder.id } })
+ await fulfill(soleOrder, sole)
+ await job("payout-validate-captures", { order_group_id: placed.groupId })
+ const intent = await stripe.paymentIntents.retrieve(placed.intentId)
+ check(s, "one of two orders canceled → only the rest is captured", intent.amount_received === Math.round(soleOrder.total * 100), `${intent.amount_received / 100} of ${placed.cartTotal}`)
+ const solePayment = await waitOrderPayment(soleOrder.id)
+ check(s, "open order gets its full total of the capture", !!solePayment && num(solePayment.amount) === soleOrder.total, `${num(solePayment?.amount)} of ${soleOrder.total}`)
+ // Stripe confirms the capture with payment_intent.succeeded; its handler must not record it again.
+ await sleep(15000)
+ const {
+ data: [cartLink],
+ } = await query.graph({
+ entity: "cart_payment_collection",
+ fields: ["payment_collection.payments.captures.id"],
+ filters: { cart_id: placed.cartId },
+ })
+ const recorded = cartLink.payment_collection?.payments?.[0]?.captures?.length ?? 0
+ check(s, "the capture is recorded once", recorded === 1, `${recorded} captures`)
+ const charge = await stripe.charges.retrieve(intent.latest_charge as string)
+ check(s, "nothing refunded to the customer", charge.amount_refunded === 0, `${charge.amount_refunded / 100} refunded`)
+ await job("payout-process-transfers", { order_id: soleOrder.id })
+ await createOrderPayoutsWorkflow(container).run({ input: { order_ids: [kickzOrder.id] } })
+ const aborted = await payoutOf(kickzOrder.id)
+ check(s, "canceled order → payout aborted", aborted?.status === PayoutStatus.ABORTED, `${aborted?.status} ${aborted?.status_reason}`)
+ await expectPaidPayout(s, soleOrder, sole)
+
+ const all = await checkout([{ seller: sole }, { seller: kickz }])
+ for (const order of all.orders) await cancelOrderWorkflow(container).run({ input: { order_id: order.id } })
+ await job("payout-validate-captures", { order_group_id: all.groupId })
+ const voided = await waitFor(async () => {
+ const pi = await stripe.paymentIntents.retrieve(all.intentId)
+ return pi.status === "canceled" ? pi : null
+ }, 20000)
+ check(s, "every order canceled → authorization released", !!voided, voided ? "canceled" : (await stripe.paymentIntents.retrieve(all.intentId)).status)
+ })
+
+ // --- 5+6. provider failure, refund before payout, retry -------------------
+ await scenario("failure-retry", async () => {
+ const s = "failure-retry"
+ const placed = await checkout([{ seller: kickz }])
+ const order = placed.orders[0]
+ await fulfill(order, kickz)
+ const pg = container.resolve(ContainerRegistrationKeys.PG_CONNECTION)
+ const setExternalId = (value: string) => pg.raw("update payout_account set external_id = ? where id = ?", [value, kickz.accountId])
+ await setExternalId("acct_doesnotexist000")
+ let failed: Awaited<ReturnType<typeof payoutOf>> | null = null
+ try {
+ await job("payout-validate-captures", { order_group_id: placed.groupId })
+ await waitOrderPayment(order.id)
+ await job("payout-process-transfers", { order_id: order.id })
+ failed = await waitFor(async () => {
+ const p = await payoutOf(order.id)
+ return p?.status === PayoutStatus.FAILED ? p : null
+ }, 20000)
+ } finally {
+ await setExternalId(kickz.externalId!)
+ }
+ check(s, "provider error → payout failed with a reason", !!failed && failed.status_reason === "provider_error", `${failed?.status ?? (await payoutOf(order.id))?.status} ${failed?.status_reason ?? ""}`)
+ if (!failed) return
+
+ const payment = await orderPayment(order.id)
+ const refund = num(order.total * 0.25)
+ await refundPaymentWorkflow(container).run({ input: { payment_id: payment!.id, amount: refund } })
+
+ const admin = await login("user", ADMIN.email, ADMIN.password)
+ const retry = await http("POST", `/admin/payouts/${failed.id}/retry`, admin)
+ check(s, "admin retry accepted", retry.status === 200, `HTTP ${retry.status}`)
+ const paid = await waitFor(async () => {
+ const p = await payoutOf(order.id)
+ return p?.status === PayoutStatus.PAID ? p : null
+ })
+ const { total: commission } = await commissionOf(order)
+ const expected = num(order.total - commission - (refund - (refund * commission) / order.total))
+ check(s, "retried payout paid, net of the earlier refund", !!paid && num(paid.amount) === expected, `${num(paid?.amount)} (expected ${expected})`)
+ await job("payout-process-reversals", { order_id: order.id })
+ const settled = await waitFor(async () => {
+ const p = await payoutOf(order.id)
+ return (p?.reversals ?? []).every((r) => r.status === PayoutStatus.ABORTED) ? p : null
+ }, 20000)
+ const reversals = settled?.reversals ?? (await payoutOf(order.id))?.reversals ?? []
+ check(s, "refund before the payout is absorbed, not reversed", !!settled && reversals.every((r) => r.status_reason === "refund_absorbed"), reversals.map((r) => `${r.status}/${r.status_reason}`).join(",") || "none")
+ const transfers = paid ? await transfersFor(paid.id, kickz.externalId!) : []
+ check(s, "exactly one transfer reached Stripe", transfers.length === 1, `${transfers.length}`)
+
+ await processPayoutWorkflow(container).run({ input: { payout_ids: [paid!.id] } })
+ await job("payout-process-transfers", { order_id: order.id })
+ check(s, "re-processing a paid payout sends nothing", (await transfersFor(paid!.id, kickz.externalId!)).length === 1)
+ })
+
+ // --- 7. full refund after payout -------------------------------------------
+ await scenario("full-refund", async () => {
+ const s = "full-refund"
+ const placed = await checkout([{ seller: sole }])
+ const order = placed.orders[0]
+ await fulfill(order, sole)
+ await job("payout-validate-captures", { order_group_id: placed.groupId })
+ const payment = await waitOrderPayment(order.id)
+ await job("payout-process-transfers", { order_id: order.id })
+ const payout = await expectPaidPayout(s, order, sole)
+ await refundPaymentWorkflow(container).run({ input: { payment_id: payment!.id, amount: order.total } })
+ await job("payout-process-reversals", { order_id: order.id })
+ const after = await waitFor(async () => {
+ const p = await payoutOf(order.id)
+ return p?.reversals?.some((r) => r.status === PayoutStatus.PAID) ? p : null
+ })
+ const reversed = num((after?.reversals ?? []).reduce((sum, r) => sum + num(r.amount), 0))
+ check(s, "full refund reverses the whole payout", !!after && reversed === num(payout?.amount), `${reversed} of ${num(payout?.amount)}`)
+ })
+
+ // --- 8. authorization about to expire -------------------------------------
+ await scenario("expiry", async () => {
+ const s = "expiry"
+ const placed = await checkout([{ seller: sole }, { seller: kickz }])
+ const soleOrder = placed.orders.find((o) => o.seller_id === sole.id)!
+ await fulfill(soleOrder, sole)
+ await job("payout-validate-captures", { order_group_id: placed.groupId })
+ check(s, "half-fulfilled group waits", (await stripe.paymentIntents.retrieve(placed.intentId)).status === "requires_capture")
+
+ const {
+ data: [cartLink],
+ } = await query.graph({ entity: "cart_payment_collection", fields: ["payment_collection.payments.id"], filters: { cart_id: placed.cartId } })
+ const paymentId = cartLink.payment_collection!.payments![0]!.id
+ const pg = container.resolve(ContainerRegistrationKeys.PG_CONNECTION)
+ const backdated = new Date(Date.now() - 6.5 * 24 * 60 * 60 * 1000)
+ await pg.raw("update payment set created_at = ? where id = ?", [backdated, paymentId])
+ await job("payout-validate-captures", { order_group_id: placed.groupId })
+ const intent = await stripe.paymentIntents.retrieve(placed.intentId)
+ check(s, "inside the safety buffer → captured before expiry", intent.status === "succeeded", `${intent.status}, ${intent.amount_received / 100} of ${placed.cartTotal}`)
+ })
+
+ // --- 9. commission rules -----------------------------------------------------
+ await scenario("commission-rules", async () => {
+ const s = "commission-rules"
+ const code = `scenario-kickz-fixed-${Date.now()}`
+ const { result: rates } = await createCommissionRatesWorkflow(container).run({
+ input: [
+ {
+ name: "Scenario Kickz fixed",
+ code,
+ type: "fixed",
+ value: 4,
+ values: [{ currency_code: CURRENCY, amount: 4 }],
+ rules: [{ reference: "seller", reference_id: kickz.id }],
+ } as never,
+ ],
+ })
+ try {
+ const placed = await checkout([{ seller: kickz, quantity: 2 }, { seller: sole }])
+ const kickzOrder = placed.orders.find((o) => o.seller_id === kickz.id)!
+ const soleOrder = placed.orders.find((o) => o.seller_id === sole.id)!
+ const kickzCommission = await commissionOf(kickzOrder)
+ check(s, "seller rule wins over the default rate", kickzCommission.lines.every((l) => l.commission_rate_id === rates[0].id), kickzCommission.lines.map((l) => l.commission_rate_id).join(","))
+ check(s, "fixed rate charges its amount per line", kickzCommission.total === 4 * kickzOrder.items.length, `${kickzCommission.total} for ${kickzOrder.items.length} line(s)`)
+ const soleCommission = await commissionOf(soleOrder)
+ check(s, "other seller stays on the default rate", soleCommission.lines.every((l) => l.commission_rate_id !== rates[0].id) && soleCommission.total > 0, `${soleCommission.total}`)
+ } finally {
+ await deleteCommissionRatesWorkflow(container).run({ input: { ids: rates.map((r) => r.id) } })
+ }
+ })
+
+ // --- 10. jobs ---------------------------------------------------------------------
+ await scenario("jobs", async () => {
+ const s = "jobs"
+ const admin = await login("user", ADMIN.email, ADMIN.password)
+ for (const name of PAYOUT_JOBS) {
+ let res = await http("POST", `/admin/stripe/jobs/${name}/run`, admin)
+ for (let attempt = 0; res.status === 409 && attempt < 20; attempt++) {
+ await sleep(3000)
+ res = await http("POST", `/admin/stripe/jobs/${name}/run`, admin)
+ }
+ const runs = await waitFor(async () => {
+ const list = await http("GET", `/admin/stripe/jobs/${name}/runs?limit=1`, admin)
+ const run = (list.json.runs as { status: string; trigger: string; error?: string | null }[] | undefined)?.[0]
+ return run && run.status !== "running" ? run : null
+ }, 60000, 2000)
+ check(s, `${name} runs from admin`, res.status < 300 && runs?.status === "succeeded", `HTTP ${res.status}, run ${runs?.status ?? "none"}${runs?.error ? ` (${runs.error})` : ""}`)
+ }
+ await sleep(5000)
+ const [a, b] = await Promise.all([job("payout-process-reversals"), job("payout-process-reversals")])
+ check(s, "the same job never runs twice at once", (a === null) !== (b === null), `${a ? a.status : "skipped"} / ${b ? b.status : "skipped"}`)
+ })
+
+ // --- 11. alerts ---------------------------------------------------------------------
+ await scenario("alerts", async () => {
+ const s = "alerts"
+ const admin = await login("user", ADMIN.email, ADMIN.password)
+ const before = await http("GET", "/admin/stripe/notifications?limit=1&order=-created_at", admin)
+ const lastBefore = (before.json.notifications as { id: string }[] | undefined)?.[0]?.id
+ const run = await job("payout-alert-failed-operations")
+ check(s, "alert job runs with failed operations present", run?.status === "succeeded", JSON.stringify(run?.stats ?? {}))
+ const after = await http("GET", "/admin/stripe/notifications?limit=1&order=-created_at", admin)
+ const latest = (after.json.notifications as { id: string; type?: string; status?: string }[] | undefined)?.[0]
+ const mailed = Number(run?.stats?.sent ?? 0)
+ if (mailed > 0) {
+ check(s, "the digest is logged", !!latest && latest.id !== lastBefore, latest ? `${latest.type ?? ""} ${latest.status ?? ""}` : `HTTP ${after.status}`)
+ } else {
+ check(s, "without an email provider the digest is skipped, not failed", run?.status === "succeeded", `sent ${mailed}`)
+ }
+ const kyc = await job("payout-monitor-kyc")
+ check(s, "KYC monitor runs (opt-in)", kyc?.status === "succeeded", JSON.stringify(kyc?.stats ?? {}))
+ })
+
+ // --- 12. admin actions --------------------------------------------------------------
+ await scenario("admin", async () => {
+ const s = "admin"
+ const admin = await login("user", ADMIN.email, ADMIN.password)
+ const status = await http("GET", "/admin/stripe/status", admin)
+ check(s, "status endpoint", status.status === 200, `last webhook ${String((status.json as { last_webhook_at?: string }).last_webhook_at ?? "n/a")}`)
+
+ const adjustment = await http("POST", "/admin/stripe/adjustments", admin, {
+ seller_id: sole.id,
+ type: "extra_credit",
+ amount: 2,
+ currency_code: CURRENCY,
+ reason: "Scenario admin credit",
+ })
+ check(s, "create adjustment", adjustment.status === 201, `HTTP ${adjustment.status}`)
+ await job("payout-process-settlements", { seller_id: sole.id })
+ const adjId = (adjustment.json.adjustment as { id: string } | undefined)?.id
+ const adj = adjId ? await connector.retrieveAdjustment(adjId) : null
+ check(s, "admin credit dispatched by the settlements run", adj?.status === PayoutStatus.PAID, `${adj?.status} ${adj?.provider_transfer_id ?? adj?.status_reason ?? ""}`)
+
+ const [stuck] = await connector.listSettlements({ status: "failed" }, { take: 1 })
+ if (stuck) {
+ const retry = await http("POST", `/admin/stripe/settlements/${stuck.id}/retry`, admin)
+ check(s, "settlement retry endpoint answers", retry.status < 500, `HTTP ${retry.status} ${String((retry.json as { message?: string }).message ?? "")}`)
+ }
+
+ const captures = await http("GET", "/admin/stripe/captures?limit=5", admin)
+ check(s, "captures list", captures.status === 200, `${(captures.json.captures as unknown[] | undefined)?.length ?? 0} rows`)
+
+ const placed = await checkout([{ seller: sole }])
+ const manual = await http("POST", `/admin/stripe/captures/${placed.groupId}/cancel`, admin)
+ const canceled = await waitFor(async () => {
+ const pi = await stripe.paymentIntents.retrieve(placed.intentId)
+ return pi.status === "canceled" ? pi : null
+ }, 15000)
+ check(s, "operator cancels an uncaptured group", manual.status < 300 && !!canceled, `HTTP ${manual.status}`)
+
+ const placed2 = await checkout([{ seller: sole }])
+ const capture = await http("POST", `/admin/stripe/captures/${placed2.groupId}/capture`, admin)
+ const captured = await waitFor(async () => {
+ const pi = await stripe.paymentIntents.retrieve(placed2.intentId)
+ return pi.status === "succeeded" ? pi : null
+ }, 15000)
+ check(s, "operator captures ahead of fulfilment", capture.status < 300 && !!captured, `HTTP ${capture.status}`)
+
+ const remap = await http("POST", "/admin/payout-accounts", admin, { seller_id: sole.id, external_id: sole.externalId })
+ check(s, "mapping an account onto a seller that has one is refused", remap.status >= 400 && remap.status < 500, `HTTP ${remap.status}`)
+
+ const sync = await http("POST", `/admin/payout-accounts/${kickz.accountId}/sync`, admin)
+ check(s, "account sync", sync.status === 200, `HTTP ${sync.status}`)
+
+ const ignore = await http("POST", `/admin/stripe/accounts/${peak.accountId}/ignore`, admin, { ignored: true })
+ check(s, "ignore seller", ignore.status < 300, `HTTP ${ignore.status} ${ignore.status >= 300 ? JSON.stringify(ignore.json).slice(0, 120) : ""}`)
+ if (ignore.status < 300) await http("POST", `/admin/stripe/accounts/${peak.accountId}/ignore`, admin, { ignored: false })
+ })
+
+ // --- 13. vendor isolation --------------------------------------------------------------
+ await scenario("vendor-isolation", async () => {
+ const s = "vendor-isolation"
+ const token = await login("member", kickz.email, SELLER_PASSWORD)
+ const as = { "x-seller-id": kickz.id }
+ const payouts = await http("GET", "/vendor/payouts?limit=100", token, undefined, as)
+ const rows = (payouts.json.payouts as { id: string; order_id: string | null }[] | undefined) ?? []
+ const own = await payoutService.listPayouts({ account_id: kickz.accountId! }, { take: null })
+ const ownIds = new Set(own.map((p) => p.id))
+ check(s, "vendor lists only its own payouts", payouts.status === 200 && rows.length > 0 && rows.every((r) => ownIds.has(r.id)), `${rows.length} rows`)
+
+ const [foreign] = await payoutService.listPayouts({ account_id: sole.accountId! }, { take: 1 })
+ const peek = await http("GET", `/vendor/payouts/${foreign.id}`, token, undefined, as)
+ check(s, "another seller's payout is not visible", peek.status === 404 || peek.status === 403, `HTTP ${peek.status}`)
+
+ const settlements = await http("GET", "/vendor/stripe/settlements?limit=100", token, undefined, as)
+ const srows = (settlements.json.settlements as { id: string }[] | undefined) ?? []
+ const ownSettlements = new Set((await connector.listSettlements({ account_id: kickz.accountId! }, { take: null })).map((x) => x.id))
+ check(s, "vendor lists only its own settlements", settlements.status === 200 && srows.every((r) => ownSettlements.has(r.id)), `${srows.length} rows`)
+
+ const spoof = await http("GET", "/vendor/payouts?limit=1", token, undefined, { "x-seller-id": sole.id })
+ check(s, "member cannot act as another seller (403)", spoof.status === 403 && !("payouts" in spoof.json), `HTTP ${spoof.status} ${String(spoof.json.message ?? "")}`)
+ })
+
+ // --- 14. webhook replay and signatures ---------------------------------------------------
+ await scenario("webhooks", async () => {
+ const s = "webhooks"
+ const secret = process.env.STRIPE_SELLERS_WEBHOOK_SECRET!
+ const send = async (event: Record<string, unknown>, signed = true) => {
+ const payload = JSON.stringify(event)
+ const header = signed
+ ? stripe.webhooks.generateTestHeaderString({ payload, secret })
+ : stripe.webhooks.generateTestHeaderString({ payload, secret: "whsec_wrong" })
+ const res = await fetch(`${API}/hooks/payout`, { method: "POST", headers: { "content-type": "application/json", "stripe-signature": header }, body: payload })
+ return res.status
+ }
+ const accountEvent = (id: string) => ({ id: `evt_scenario_${Date.now()}`, object: "event", type: "account.updated", account: id, created: Math.floor(Date.now() / 1000), data: { object: { id, object: "account" } } })
+
+ const synced = async () => (await payoutService.retrievePayoutAccount(kickz.accountId!)).last_synced_at
+ const t0 = await synced()
+ await send(accountEvent(kickz.externalId!), false)
+ await sleep(9000)
+ check(s, "bad signature is ignored", String(await synced()) === String(t0))
+
+ const event = accountEvent(kickz.externalId!)
+ await send(event)
+ const t1 = await waitFor(async () => {
+ const t = await synced()
+ return String(t) !== String(t0) ? t : null
+ })
+ check(s, "signed event is applied", !!t1)
+ await send(event)
+ const t2 = await waitFor(async () => {
+ const t = await synced()
+ return String(t) !== String(t1) ? t : null
+ })
+ const account = await payoutService.retrievePayoutAccount(kickz.accountId!)
+ check(s, "replayed event is harmless", account.status === "active", `re-synced: ${!!t2}, status ${account.status}`)
+
+ const [paid] = await payoutService.listPayouts({ account_id: kickz.accountId!, status: PayoutStatus.PAID }, { order: { created_at: "DESC" }, take: 1 })
+ const transferId = transferIdOf(paid?.data)
+ if (paid && transferId) {
+ const transfer = await stripe.transfers.retrieve(transferId)
+ await send({ id: `evt_scenario_tr_${Date.now()}`, object: "event", type: "transfer.created", created: Math.floor(Date.now() / 1000), data: { object: transfer } })
+ await sleep(9000)
+ const again = await payoutService.retrievePayout(paid.id)
+ check(s, "replayed transfer.created keeps the payout paid, no new transfer", again.status === PayoutStatus.PAID && (await transfersFor(paid.id, kickz.externalId!)).length === 1)
+ }
+ })
+
+ // --- 15. operator notifications -------------------------------------------------------------
+ await scenario("notifications", async () => {
+ const s = "notifications"
+ const logFile = process.env.NOTIFICATIONS_LOG
+ if (!logFile) {
+ check(s, "NOTIFICATIONS_LOG is set", false)
+ return
+ }
+ const fs = await import("node:fs")
+ type Received = { signature_ok: boolean; body: { type?: string; payload?: { id?: string } } & Record<string, unknown> }
+ const received = (): Received[] =>
+ fs.existsSync(logFile) ? fs.readFileSync(logFile, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l) as Received) : []
+ const about = (type: string, id: string) => received().filter((r) => r.body.type === type && r.body.payload?.id === id)
+ const pg = container.resolve(ContainerRegistrationKeys.PG_CONNECTION)
+
+ // payout.failed, notified once across retries
+ const placed = await checkout([{ seller: kickz }])
+ const order = placed.orders[0]
+ await fulfill(order, kickz)
+ const setExternalId = (value: string) => pg.raw("update payout_account set external_id = ? where id = ?", [value, kickz.accountId])
+ await setExternalId("acct_doesnotexist000")
+ let failedId: string | null = null
+ try {
+ await job("payout-validate-captures", { order_group_id: placed.groupId })
+ await waitOrderPayment(order.id)
+ await job("payout-process-transfers", { order_id: order.id })
+ const failed = await waitFor(async () => {
+ const p = await payoutOf(order.id)
+ return p?.status === PayoutStatus.FAILED ? p : null
+ }, 20000)
+ failedId = failed?.id ?? null
+ if (failedId) {
+ const first = await waitFor(async () => (about("payout.failed", failedId!).length ? about("payout.failed", failedId!) : null), 20000)
+ check(s, "payout.failed delivered", !!first, first ? `signature ${first[0].signature_ok ? "valid" : "INVALID"}` : "nothing received")
+ if (first) {
+ check(s, "payout.failed is signed", first[0].signature_ok)
+ const keys = Object.keys(first[0].body.payload ?? {})
+ check(s, "payout.failed carries order, account, seller, amount, reason", ["order_id", "account_id", "seller_id", "amount", "currency_code", "status_reason"].every((k) => keys.includes(k)), keys.join(","))
+ }
+ await processPayoutWorkflow(container).run({ input: { payout_ids: [failedId] } }).catch(() => null)
+ await job("payout-process-transfers", { order_id: order.id })
+ await sleep(8000)
+ check(s, "a payout that keeps failing notifies once", about("payout.failed", failedId).length === 1, `${about("payout.failed", failedId).length} notifications`)
+ } else {
+ check(s, "payout failed for the notification test", false, `${(await payoutOf(order.id))?.status}`)
+ }
+ } finally {
+ await setExternalId(kickz.externalId!)
+ }
+ if (failedId) {
+ const admin = await login("user", ADMIN.email, ADMIN.password)
+ await http("POST", `/admin/payouts/${failedId}/retry`, admin)
+ }
+
+ // payout_reversal.failed: the transfer is already fully reversed in Stripe
+ const placed2 = await checkout([{ seller: sole }])
+ const order2 = placed2.orders[0]
+ await fulfill(order2, sole)
+ await job("payout-validate-captures", { order_group_id: placed2.groupId })
+ const payment2 = await waitOrderPayment(order2.id)
+ await job("payout-process-transfers", { order_id: order2.id })
+ const paid2 = await waitFor(async () => {
+ const p = await payoutOf(order2.id)
+ return p?.status === PayoutStatus.PAID ? p : null
+ })
+ const transferId = transferIdOf(paid2?.data)
+ if (paid2 && transferId) {
+ // Point the payout at a transfer Stripe does not know, so the reversal is refused.
+ const setTransfer = (id: string) =>
+ pg.raw("update payout set data = jsonb_set(data, '{provider,id}', to_jsonb(?::text)) where id = ?", [id, paid2.id])
+ await setTransfer("tr_doesnotexist000")
+ let reversal: { id: string; status_reason: string | null } | null = null
+ try {
+ await refundPaymentWorkflow(container).run({ input: { payment_id: payment2!.id, amount: num(order2.total * 0.5) } })
+ await job("payout-process-reversals", { order_id: order2.id })
+ reversal = await waitFor(async () => {
+ const p = await payoutOf(order2.id)
+ return p?.reversals?.find((r) => r.status === PayoutStatus.FAILED) ?? null
+ }, 20000)
+ } finally {
+ await setTransfer(transferId)
+ }
+ check(s, "reversal refused by Stripe → failed", !!reversal, reversal ? `${reversal.status_reason}` : (await payoutOf(order2.id))?.reversals?.map((r) => `${r.status}/${r.status_reason}`).join(",") ?? "none")
+ if (reversal) {
+ const got = await waitFor(async () => (about("payout_reversal.failed", reversal!.id).length ? about("payout_reversal.failed", reversal!.id) : null), 20000)
+ check(s, "payout_reversal.failed delivered", !!got, got ? `signature ${got[0].signature_ok ? "valid" : "INVALID"}` : "nothing received")
+ await job("payout-process-reversals", { order_id: order2.id })
+ const done = await waitFor(async () => {
+ const p = await payoutOf(order2.id)
+ return p?.reversals?.find((r) => r.id === reversal!.id && r.status === PayoutStatus.PAID) ?? null
+ }, 20000)
+ check(s, "failed reversal is retried once the transfer is reachable", !!done, done ? "paid" : (await payoutOf(order2.id))?.reversals?.map((r) => r.status).join(",") ?? "")
+ }
+ }
+
+ // settlement.payout_failed through the payout.failed webhook
+ const [paidOut] = await connector.listSettlements({ status: "paid_out" }, { order: { created_at: "DESC" }, take: 1 })
+ if (paidOut?.provider_payout_id) {
+ const account = await payoutService.retrievePayoutAccount(paidOut.account_id)
+ const payload = JSON.stringify({
+ id: `evt_scenario_po_${Date.now()}`,
+ object: "event",
+ type: "payout.failed",
+ account: account.external_id,
+ created: Math.floor(Date.now() / 1000),
+ data: { object: { id: paidOut.provider_payout_id, object: "payout", status: "failed", failure_code: "account_closed", failure_message: "The bank account has been closed" } },
+ })
+ const header = stripe.webhooks.generateTestHeaderString({ payload, secret: process.env.STRIPE_SELLERS_WEBHOOK_SECRET! })
+ await fetch(`${API}/hooks/payout`, { method: "POST", headers: { "content-type": "application/json", "stripe-signature": header }, body: payload })
+ const failedSettlement = await waitFor(async () => {
+ const [fresh] = await connector.listSettlements({ id: paidOut.id })
+ return fresh?.payout_status === PayoutStatus.FAILED ? fresh : null
+ }, 20000)
+ check(s, "payout.failed webhook fails the settlement", !!failedSettlement, failedSettlement ? `${failedSettlement.status} ${failedSettlement.status_reason}` : "unchanged")
+ const got = await waitFor(async () => (about("settlement.payout_failed", paidOut.id).length ? about("settlement.payout_failed", paidOut.id) : null), 20000)
+ check(s, "settlement.payout_failed delivered", !!got, got ? `reason ${String((got[0].body.payload as Record<string, unknown>).status_reason)}` : "nothing received")
+ }
+
+ const [shortBalance] = await connector.listSettlements({ status: "failed", payout_status: PayoutStatus.ON_HOLD }, { take: 1 })
+ if (shortBalance) {
+ const admin = await login("user", ADMIN.email, ADMIN.password)
+ await http("POST", `/admin/stripe/settlements/${shortBalance.id}/retry`, admin)
+ await sleep(8000)
+ check(s, "settlement held on a short balance notifies", about("settlement.payout_failed", shortBalance.id).length > 0, `${shortBalance.id} ${shortBalance.status_reason}`)
+ }
+ })
+
+ const failed = results.filter((r) => !r.ok)
+ logger.info(`=== ${results.length - failed.length}/${results.length} checks passed`)
+ for (const f of failed) logger.info(`FAIL [${f.scenario}] ${f.name} ${f.detail}`)
+ if (failed.length) process.exitCode = 1
+}
+
diff --git a/apps/api/src/scripts/utils/stripe-test-key.ts b/apps/api/src/scripts/utils/stripe-test-key.ts
new file mode 100644
index 000000000..2ee51ddb5
--- /dev/null
+++ b/apps/api/src/scripts/utils/stripe-test-key.ts
@@ -0,0 +1,11 @@
+/** These scripts move real money on whatever account the key belongs to. */
+export function requireStripeTestKey(): string {
+ const key = process.env.STRIPE_SECRET_KEY
+ if (!key) {
+ throw new Error("STRIPE_SECRET_KEY is not set")
+ }
+ if (!/^(sk|rk)_test_/.test(key)) {
+ throw new Error("Refusing to run against a live Stripe key")
+ }
+ return key
+}
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index 727d8cf07..75f12f8ee 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -425,7 +425,20 @@
"icon": "plug",
"pages": [
"resources/integrations/overview",
- "resources/integrations/stripe-connect",
+ {
+ "group": "Stripe Connect",
+ "pages": [
+ "resources/integrations/stripe-connect/overview",
+ "resources/integrations/stripe-connect/quickstart",
+ "resources/integrations/stripe-connect/architecture",
+ "resources/integrations/stripe-connect/configuration",
+ "resources/integrations/stripe-connect/seller-onboarding",
+ "resources/integrations/stripe-connect/payments-and-capture",
+ "resources/integrations/stripe-connect/payouts-and-settlements",
+ "resources/integrations/stripe-connect/operations",
+ "resources/integrations/stripe-connect/reference"
+ ]
+ },
{
"group": "Magento 2",
"pages": [
@@ -865,6 +878,10 @@
]
},
"redirects": [
+ {
+ "source": "/resources/integrations/stripe-connect",
+ "destination": "/resources/integrations/stripe-connect/overview"
+ },
{
"source": "/resources/integrations/magento2",
"destination": "/resources/integrations/magento2/overview"
@@ -1135,15 +1152,15 @@
},
{
"source": "/how-to-guides/stripe-connect-integration",
- "destination": "/resources/integrations/stripe-connect"
+ "destination": "/resources/integrations/stripe-connect/overview"
},
{
"source": "/rc/how-to-guides/stripe-connect-integration",
- "destination": "/resources/integrations/stripe-connect"
+ "destination": "/resources/integrations/stripe-connect/overview"
},
{
"source": "/v2/how-to-guides/stripe-connect-integration",
- "destination": "/resources/integrations/stripe-connect"
+ "destination": "/resources/integrations/stripe-connect/overview"
},
{
"source": "/how-to-guides/medusa-cloud",
@@ -1359,7 +1376,7 @@
},
{
"source": "/integrations/stripe",
- "destination": "/resources/integrations/stripe-connect"
+ "destination": "/resources/integrations/stripe-connect/overview"
},
{
"source": "/integrations/:slug*",
@@ -1479,7 +1496,7 @@
},
{
"source": "/resources/tutorials/seller-payouts-stripe",
- "destination": "/resources/integrations/stripe-connect"
+ "destination": "/resources/integrations/stripe-connect/overview"
},
{
"source": "/resources/tutorials/store-setup-checklist",
diff --git a/apps/docs/figures/extension-zones.mjs b/apps/docs/figures/extension-zones.mjs
index f5432fa2d..848df5ec2 100644
--- a/apps/docs/figures/extension-zones.mjs
+++ b/apps/docs/figures/extension-zones.mjs
@@ -61,7 +61,7 @@ export default {
["orderGroupCreated", "completeCartWithSplitOrdersWorkflow"],
["offersCreated", "createOffersWorkflow"],
["productChangeConfirmed", "confirmProductChangeWorkflow"],
- ["payoutCreated", "createPayoutWorkflow"],
+ ["payoutsCreated", "createOrderPayoutsWorkflow"],
],
})
},
diff --git a/apps/docs/images/figures/extension-zones-dark.svg b/apps/docs/images/figures/extension-zones-dark.svg
index a6f8049a8..c1eaf1928 100644
--- a/apps/docs/images/figures/extension-zones-dark.svg
+++ b/apps/docs/images/figures/extension-zones-dark.svg
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1040" height="870" viewBox="0 0 1040 870" font-family="JetBrains Mono, SF Mono, SFMono-Regular, Menlo, Consolas, Liberation Mono, monospace" role="img" aria-label="Stacked panels for Blocks, Panels, and Backend, with an Extensions table in front listing one file per zone: a workflow hook, an API route, a module, a custom field, a page, and a widget, each with its typed target.">
<title>Stacked panels for Blocks, Panels, and Backend, with an Extensions table in front listing one file per zone: a workflow hook, an API route, a module, a custom field, a page, and a widget, each with its typed target.</title>
<defs><filter id="sh" x="-30%" y="-30%" width="160%" height="170%"><feDropShadow dx="0" dy="18" stdDeviation="22" flood-color="#000000" flood-opacity="0.55"/></filter><filter id="gr" x="0" y="0" width="100%" height="100%"><feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" seed="7" stitchTiles="stitch"/><feColorMatrix type="saturate" values="0"/><feComponentTransfer><feFuncA type="table" tableValues="0 1"/></feComponentTransfer><feComposite in2="SourceGraphic" operator="in"/></filter><pattern id="dt" width="11" height="11" patternUnits="userSpaceOnUse"><rect x="4.5" y="4.5" width="1.6" height="1.6" fill="#2c2737"/></pattern><clipPath id="c1"><rect x="0" y="0" width="826" height="514"/></clipPath><clipPath id="c2"><rect x="0" y="0" width="826" height="514"/></clipPath><clipPath id="c3"><rect x="0" y="0" width="826" height="514"/></clipPath><clipPath id="c4"><rect x="0" y="0" width="826" height="514"/></clipPath></defs>
-<rect x="-87.5" y="-87.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="88.5" y="-87.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="176" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="440" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="528.5" y="-87.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="968" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="0" y="0" width="88" height="88" fill="#1d1926"/><rect x="0" y="0" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="88.5" y="0.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="264" y="0" width="88" height="88" fill="url(#dt)"/><rect x="-87.5" y="88.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="616.5" y="88.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="792" y="88" width="88" height="88" fill="url(#dt)"/><rect x="1056" y="88" width="88" height="88" fill="url(#dt)"/><rect x="264.5" y="176.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="352" y="176" width="88" height="88" fill="url(#dt)"/><rect x="440" y="176" width="88" height="88" fill="url(#dt)"/><rect x="704.5" y="176.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="968.5" y="176.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="176.5" y="264.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="968" y="264" width="88" height="88" fill="url(#dt)"/><rect x="-88" y="352" width="88" height="88" fill="#1d1926"/><rect x="-88" y="352" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="528" y="352" width="88" height="88" fill="url(#dt)"/><rect x="-88" y="440" width="88" height="88" fill="url(#dt)"/><rect x="0" y="440" width="88" height="88" fill="#1d1926"/><rect x="0" y="440" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="176.5" y="440.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="528.5" y="440.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="616" y="440" width="88" height="88" fill="#1d1926"/><rect x="616" y="440" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="1056.5" y="440.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="0" y="528" width="88" height="88" fill="url(#dt)"/><rect x="352.5" y="528.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="792" y="528" width="88" height="88" fill="#1d1926"/><rect x="792" y="528" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="968" y="528" width="88" height="88" fill="url(#dt)"/><rect x="-87.5" y="616.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="264.5" y="616.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="352" y="616" width="88" height="88" fill="#1d1926"/><rect x="352" y="616" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="792" y="616" width="88" height="88" fill="url(#dt)"/><rect x="-88" y="704" width="88" height="88" fill="url(#dt)"/><rect x="0" y="704" width="88" height="88" fill="url(#dt)"/><rect x="704.5" y="704.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="1056.5" y="704.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="0.5" y="792.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="88" y="792" width="88" height="88" fill="url(#dt)"/><rect x="176" y="792" width="88" height="88" fill="#1d1926"/><rect x="176" y="792" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="264" y="792" width="88" height="88" fill="#1d1926"/><rect x="264" y="792" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="440.5" y="792.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="704.5" y="792.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="880.5" y="792.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="1056" y="792" width="88" height="88" fill="url(#dt)"/><rect x="176" y="880" width="88" height="88" fill="#1d1926"/><rect x="176" y="880" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="264" y="880" width="88" height="88" fill="url(#dt)"/><rect x="352" y="880" width="88" height="88" fill="#1d1926"/><rect x="352" y="880" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="440" y="880" width="88" height="88" fill="#1d1926"/><rect x="440" y="880" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="528.5" y="880.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="616" y="880" width="88" height="88" fill="#1d1926"/><rect x="616" y="880" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="704" y="880" width="88" height="88" fill="url(#dt)"/><rect x="968" y="880" width="88" height="88" fill="#1d1926"/><rect x="968" y="880" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="184" y="40" width="826" height="514" fill="#15121d" filter="url(#sh)"/><rect x="184" y="40" width="826" height="514" fill="#15121d"/><g transform="translate(184 40)"><g clip-path="url(#c1)"><rect x="24" y="33" width="10" height="10" fill="#f2a14b"/><text x="46" y="44.3" font-size="18" fill="#f4f4f5" font-weight="500">Blocks</text><line x1="134.8" y1="20" x2="134.8" y2="56" stroke="#2b2636" stroke-width="1"/><text x="166.8" y="44" font-size="17" fill="#f4f4f5">Installed</text><rect x="148.8" y="73" width="127.8" height="3" fill="#f4f4f5"/><text x="298.6" y="44" font-size="17" fill="#a1a1aa">Registry</text><text x="721" y="43.3" font-size="15" fill="#d4d4d8">Overwrite</text><rect x="661" y="27" width="46" height="22" fill="#3f3a4b"/><rect x="664" y="30" width="19" height="16" fill="#15121d"/><line x1="0" y1="76" x2="826" y2="76" stroke="#2b2636" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">BLOCK</text><text x="332" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">FILES</text><text x="794" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">UPSTREAM</text><line x1="0" y1="130" x2="826" y2="130" stroke="#221e2b" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#f4f4f5">wishlist</text><text x="332" y="167.6" font-size="16" fill="#f4f4f5">9</text><rect x="692.4" y="146" width="101.6" height="32" fill="#1f1b29"/><rect x="704.4" y="157" width="10" height="10" fill="#6fbf68"/><text x="726.4" y="166.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">SYNCED</text><line x1="0" y1="194" x2="826" y2="194" stroke="#221e2b" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#f4f4f5">algolia</text><text x="332" y="231.6" font-size="16" fill="#f4f4f5">6</text><rect x="711.6" y="210" width="82.4" height="32" fill="#1f1b29"/><rect x="723.6" y="221" width="10" height="10" fill="#f2a14b"/><text x="745.6" y="230.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">DIFF</text><line x1="0" y1="258" x2="826" y2="258" stroke="#221e2b" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#f4f4f5">vendor-chat</text><text x="332" y="295.6" font-size="16" fill="#f4f4f5">21</text><rect x="692.4" y="274" width="101.6" height="32" fill="#1f1b29"/><rect x="704.4" y="285" width="10" height="10" fill="#6fbf68"/><text x="726.4" y="294.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">SYNCED</text><line x1="0" y1="322" x2="826" y2="322" stroke="#221e2b" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#f4f4f5">requests</text><text x="332" y="359.6" font-size="16" fill="#f4f4f5">17</text><rect x="692.4" y="338" width="101.6" height="32" fill="#1f1b29"/><rect x="704.4" y="349" width="10" height="10" fill="#6fbf68"/><text x="726.4" y="358.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">SYNCED</text><line x1="0" y1="386" x2="826" y2="386" stroke="#221e2b" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#f4f4f5">vendor-notifications</text><text x="332" y="423.6" font-size="16" fill="#f4f4f5">11</text><rect x="711.6" y="402" width="82.4" height="32" fill="#1f1b29"/><rect x="723.6" y="413" width="10" height="10" fill="#f2a14b"/><text x="745.6" y="422.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">DIFF</text><line x1="0" y1="450" x2="826" y2="450" stroke="#221e2b" stroke-width="1"/><text x="32" y="487.6" font-size="16" fill="#f4f4f5">meilisearch</text><text x="332" y="487.6" font-size="16" fill="#f4f4f5">6</text><rect x="692.4" y="466" width="101.6" height="32" fill="#1f1b29"/><rect x="704.4" y="477" width="10" height="10" fill="#6fbf68"/><text x="726.4" y="486.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">SYNCED</text><line x1="0" y1="514" x2="826" y2="514" stroke="#221e2b" stroke-width="1"/></g></g><rect x="184.5" y="40.5" width="825" height="513" fill="none" stroke="#2b2636" stroke-width="1"/><rect x="136" y="126" width="826" height="514" fill="#15121d" filter="url(#sh)"/><rect x="136" y="126" width="826" height="514" fill="#15121d"/><g transform="translate(136 126)"><g clip-path="url(#c2)"><rect x="24" y="33" width="10" height="10" fill="#6fbf68"/><text x="46" y="44.3" font-size="18" fill="#f4f4f5" font-weight="500">Panels</text><line x1="134.8" y1="20" x2="134.8" y2="56" stroke="#2b2636" stroke-width="1"/><text x="166.8" y="44" font-size="17" fill="#a1a1aa">Pages</text><text x="257.8" y="44" font-size="17" fill="#f4f4f5">Widgets</text><rect x="239.8" y="73" width="107.4" height="3" fill="#f4f4f5"/><text x="369.2" y="44" font-size="17" fill="#a1a1aa">Fields</text><text x="470.4" y="44" font-size="17" fill="#a1a1aa">Navigation</text><text x="757" y="43.3" font-size="15" fill="#d4d4d8">Typed</text><rect x="697" y="27" width="46" height="22" fill="#6fbf68"/><rect x="721" y="30" width="19" height="16" fill="#15121d"/><line x1="0" y1="76" x2="826" y2="76" stroke="#2b2636" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">FILE</text><text x="794" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">ZONE</text><line x1="0" y1="130" x2="826" y2="130" stroke="#221e2b" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#f4f4f5">payout-summary.tsx</text><text x="794" y="167.6" font-size="16" fill="#f4f4f5" text-anchor="end">orders.detail.side.after</text><line x1="0" y1="194" x2="826" y2="194" stroke="#221e2b" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#f4f4f5">order-sla.tsx</text><text x="794" y="231.6" font-size="16" fill="#f4f4f5" text-anchor="end">orders.list.before</text><line x1="0" y1="258" x2="826" y2="258" stroke="#221e2b" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#f4f4f5">offer-badges.tsx</text><text x="794" y="295.6" font-size="16" fill="#f4f4f5" text-anchor="end">offers.list.after</text><line x1="0" y1="322" x2="826" y2="322" stroke="#221e2b" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#f4f4f5">offer-docs.tsx</text><text x="794" y="359.6" font-size="16" fill="#f4f4f5" text-anchor="end">offers.detail.main.after</text><line x1="0" y1="386" x2="826" y2="386" stroke="#221e2b" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#f4f4f5">vip-note.tsx</text><text x="794" y="423.6" font-size="16" fill="#f4f4f5" text-anchor="end">customers.detail.side</text><line x1="0" y1="450" x2="826" y2="450" stroke="#221e2b" stroke-width="1"/></g></g><rect x="136.5" y="126.5" width="825" height="513" fill="none" stroke="#2b2636" stroke-width="1"/><rect x="88" y="212" width="826" height="514" fill="#15121d" filter="url(#sh)"/><rect x="88" y="212" width="826" height="514" fill="#15121d"/><g transform="translate(88 212)"><g clip-path="url(#c3)"><rect x="24" y="33" width="10" height="10" fill="#f4f4f5"/><text x="46" y="44.3" font-size="18" fill="#f4f4f5" font-weight="500">Backend</text><line x1="145.6" y1="20" x2="145.6" y2="56" stroke="#2b2636" stroke-width="1"/><text x="177.6" y="44" font-size="17" fill="#f4f4f5">Hooks</text><rect x="159.6" y="73" width="87" height="3" fill="#f4f4f5"/><text x="268.6" y="44" font-size="17" fill="#a1a1aa">Routes</text><text x="369.8" y="44" font-size="17" fill="#a1a1aa">Modules</text><text x="802" y="43.3" font-size="15" fill="#71717a" text-anchor="end">src/</text><line x1="0" y1="76" x2="826" y2="76" stroke="#2b2636" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">NAME</text><text x="794" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">WORKFLOW</text><line x1="0" y1="130" x2="826" y2="130" stroke="#221e2b" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#f4f4f5">sellerApproved</text><text x="794" y="167.6" font-size="16" fill="#f4f4f5" text-anchor="end">approveSellerWorkflow</text><line x1="0" y1="194" x2="826" y2="194" stroke="#221e2b" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#f4f4f5">orderGroupCreated</text><text x="794" y="231.6" font-size="16" fill="#f4f4f5" text-anchor="end">completeCartWithSplitOrdersWorkflow</text><line x1="0" y1="258" x2="826" y2="258" stroke="#221e2b" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#f4f4f5">offersCreated</text><text x="794" y="295.6" font-size="16" fill="#f4f4f5" text-anchor="end">createOffersWorkflow</text><line x1="0" y1="322" x2="826" y2="322" stroke="#221e2b" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#f4f4f5">productChangeConfirmed</text><text x="794" y="359.6" font-size="16" fill="#f4f4f5" text-anchor="end">confirmProductChangeWorkflow</text><line x1="0" y1="386" x2="826" y2="386" stroke="#221e2b" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#f4f4f5">payoutCreated</text><text x="794" y="423.6" font-size="16" fill="#f4f4f5" text-anchor="end">createPayoutWorkflow</text><line x1="0" y1="450" x2="826" y2="450" stroke="#221e2b" stroke-width="1"/></g></g><rect x="88.5" y="212.5" width="825" height="513" fill="none" stroke="#2b2636" stroke-width="1"/><rect x="40" y="298" width="826" height="514" fill="#15121d" filter="url(#sh)"/><rect x="40" y="298" width="826" height="514" fill="#15121d"/><g transform="translate(40 298)"><g clip-path="url(#c4)"><rect x="24" y="33" width="10" height="10" fill="#a78bfa"/><text x="46" y="44.3" font-size="18" fill="#f4f4f5" font-weight="500">Extensions</text><line x1="178" y1="20" x2="178" y2="56" stroke="#2b2636" stroke-width="1"/><text x="210" y="44" font-size="17" fill="#f4f4f5">All</text><rect x="192" y="73" width="66.6" height="3" fill="#f4f4f5"/><text x="280.6" y="44" font-size="17" fill="#a1a1aa">Backend</text><text x="392" y="44" font-size="17" fill="#a1a1aa">Panels</text><text x="721" y="43.3" font-size="15" fill="#d4d4d8">Typecheck</text><rect x="661" y="27" width="46" height="22" fill="#6fbf68"/><rect x="685" y="30" width="19" height="16" fill="#15121d"/><line x1="0" y1="76" x2="826" y2="76" stroke="#2b2636" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">PATH</text><text x="446" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">ZONE</text><text x="574" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">TARGET</text><line x1="0" y1="130" x2="826" y2="130" stroke="#221e2b" stroke-width="1"/><rect x="0" y="130" width="3" height="64" fill="#a78bfa"/><text x="32" y="167.6" font-size="16" fill="#f4f4f5">src/workflows/hooks/seller-approved.ts</text><rect x="446" y="147" width="60" height="30" fill="#1f1b29"/><text x="458" y="167.3" font-size="15" fill="#a1a1aa">hook</text><text x="574" y="167.6" font-size="16" fill="#f4f4f5">sellerApproved</text><line x1="0" y1="194" x2="826" y2="194" stroke="#221e2b" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#f4f4f5">src/api/vendor/sellers/documents/route.ts</text><rect x="446" y="211" width="69" height="30" fill="#1f1b29"/><text x="458" y="231.3" font-size="15" fill="#a1a1aa">route</text><text x="574" y="231.6" font-size="16" fill="#d4d4d8">/vendor/sellers/…</text><line x1="0" y1="258" x2="826" y2="258" stroke="#221e2b" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#f4f4f5">src/modules/subscription/index.ts</text><rect x="446" y="275" width="78" height="30" fill="#1f1b29"/><text x="458" y="295.3" font-size="15" fill="#a1a1aa">module</text><text x="574" y="295.6" font-size="16" fill="#d4d4d8">↔ seller</text><line x1="0" y1="322" x2="826" y2="322" stroke="#221e2b" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#f4f4f5">medusa-config.ts</text><rect x="446" y="339" width="69" height="30" fill="#1f1b29"/><text x="458" y="359.3" font-size="15" fill="#a1a1aa">field</text><text x="574" y="359.6" font-size="16" fill="#d4d4d8">Product.is_featured</text><line x1="0" y1="386" x2="826" y2="386" stroke="#221e2b" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#f4f4f5">src/routes/reports/page.tsx</text><rect x="446" y="403" width="60" height="30" fill="#1f1b29"/><text x="458" y="423.3" font-size="15" fill="#a1a1aa">page</text><text x="574" y="423.6" font-size="16" fill="#d4d4d8">/reports</text><line x1="0" y1="450" x2="826" y2="450" stroke="#221e2b" stroke-width="1"/><text x="32" y="487.6" font-size="16" fill="#f4f4f5">src/widgets/payout-summary.tsx</text><rect x="446" y="467" width="78" height="30" fill="#1f1b29"/><text x="458" y="487.3" font-size="15" fill="#a1a1aa">widget</text><text x="574" y="487.6" font-size="16" fill="#d4d4d8">orders.detail.side</text><line x1="0" y1="514" x2="826" y2="514" stroke="#221e2b" stroke-width="1"/></g></g><rect x="40.5" y="298.5" width="825" height="513" fill="none" stroke="#2b2636" stroke-width="1"/>
+<rect x="-87.5" y="-87.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="88.5" y="-87.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="176" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="440" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="528.5" y="-87.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="968" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="0" y="0" width="88" height="88" fill="#1d1926"/><rect x="0" y="0" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="88.5" y="0.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="264" y="0" width="88" height="88" fill="url(#dt)"/><rect x="-87.5" y="88.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="616.5" y="88.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="792" y="88" width="88" height="88" fill="url(#dt)"/><rect x="1056" y="88" width="88" height="88" fill="url(#dt)"/><rect x="264.5" y="176.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="352" y="176" width="88" height="88" fill="url(#dt)"/><rect x="440" y="176" width="88" height="88" fill="url(#dt)"/><rect x="704.5" y="176.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="968.5" y="176.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="176.5" y="264.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="968" y="264" width="88" height="88" fill="url(#dt)"/><rect x="-88" y="352" width="88" height="88" fill="#1d1926"/><rect x="-88" y="352" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="528" y="352" width="88" height="88" fill="url(#dt)"/><rect x="-88" y="440" width="88" height="88" fill="url(#dt)"/><rect x="0" y="440" width="88" height="88" fill="#1d1926"/><rect x="0" y="440" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="176.5" y="440.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="528.5" y="440.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="616" y="440" width="88" height="88" fill="#1d1926"/><rect x="616" y="440" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="1056.5" y="440.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="0" y="528" width="88" height="88" fill="url(#dt)"/><rect x="352.5" y="528.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="792" y="528" width="88" height="88" fill="#1d1926"/><rect x="792" y="528" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="968" y="528" width="88" height="88" fill="url(#dt)"/><rect x="-87.5" y="616.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="264.5" y="616.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="352" y="616" width="88" height="88" fill="#1d1926"/><rect x="352" y="616" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="792" y="616" width="88" height="88" fill="url(#dt)"/><rect x="-88" y="704" width="88" height="88" fill="url(#dt)"/><rect x="0" y="704" width="88" height="88" fill="url(#dt)"/><rect x="704.5" y="704.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="1056.5" y="704.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="0.5" y="792.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="88" y="792" width="88" height="88" fill="url(#dt)"/><rect x="176" y="792" width="88" height="88" fill="#1d1926"/><rect x="176" y="792" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="264" y="792" width="88" height="88" fill="#1d1926"/><rect x="264" y="792" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="440.5" y="792.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="704.5" y="792.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="880.5" y="792.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="1056" y="792" width="88" height="88" fill="url(#dt)"/><rect x="176" y="880" width="88" height="88" fill="#1d1926"/><rect x="176" y="880" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="264" y="880" width="88" height="88" fill="url(#dt)"/><rect x="352" y="880" width="88" height="88" fill="#1d1926"/><rect x="352" y="880" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="440" y="880" width="88" height="88" fill="#1d1926"/><rect x="440" y="880" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="528.5" y="880.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="616" y="880" width="88" height="88" fill="#1d1926"/><rect x="616" y="880" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="704" y="880" width="88" height="88" fill="url(#dt)"/><rect x="968" y="880" width="88" height="88" fill="#1d1926"/><rect x="968" y="880" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="184" y="40" width="826" height="514" fill="#15121d" filter="url(#sh)"/><rect x="184" y="40" width="826" height="514" fill="#15121d"/><g transform="translate(184 40)"><g clip-path="url(#c1)"><rect x="24" y="33" width="10" height="10" fill="#f2a14b"/><text x="46" y="44.3" font-size="18" fill="#f4f4f5" font-weight="500">Blocks</text><line x1="134.8" y1="20" x2="134.8" y2="56" stroke="#2b2636" stroke-width="1"/><text x="166.8" y="44" font-size="17" fill="#f4f4f5">Installed</text><rect x="148.8" y="73" width="127.8" height="3" fill="#f4f4f5"/><text x="298.6" y="44" font-size="17" fill="#a1a1aa">Registry</text><text x="721" y="43.3" font-size="15" fill="#d4d4d8">Overwrite</text><rect x="661" y="27" width="46" height="22" fill="#3f3a4b"/><rect x="664" y="30" width="19" height="16" fill="#15121d"/><line x1="0" y1="76" x2="826" y2="76" stroke="#2b2636" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">BLOCK</text><text x="332" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">FILES</text><text x="794" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">UPSTREAM</text><line x1="0" y1="130" x2="826" y2="130" stroke="#221e2b" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#f4f4f5">wishlist</text><text x="332" y="167.6" font-size="16" fill="#f4f4f5">9</text><rect x="692.4" y="146" width="101.6" height="32" fill="#1f1b29"/><rect x="704.4" y="157" width="10" height="10" fill="#6fbf68"/><text x="726.4" y="166.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">SYNCED</text><line x1="0" y1="194" x2="826" y2="194" stroke="#221e2b" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#f4f4f5">algolia</text><text x="332" y="231.6" font-size="16" fill="#f4f4f5">6</text><rect x="711.6" y="210" width="82.4" height="32" fill="#1f1b29"/><rect x="723.6" y="221" width="10" height="10" fill="#f2a14b"/><text x="745.6" y="230.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">DIFF</text><line x1="0" y1="258" x2="826" y2="258" stroke="#221e2b" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#f4f4f5">vendor-chat</text><text x="332" y="295.6" font-size="16" fill="#f4f4f5">21</text><rect x="692.4" y="274" width="101.6" height="32" fill="#1f1b29"/><rect x="704.4" y="285" width="10" height="10" fill="#6fbf68"/><text x="726.4" y="294.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">SYNCED</text><line x1="0" y1="322" x2="826" y2="322" stroke="#221e2b" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#f4f4f5">requests</text><text x="332" y="359.6" font-size="16" fill="#f4f4f5">17</text><rect x="692.4" y="338" width="101.6" height="32" fill="#1f1b29"/><rect x="704.4" y="349" width="10" height="10" fill="#6fbf68"/><text x="726.4" y="358.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">SYNCED</text><line x1="0" y1="386" x2="826" y2="386" stroke="#221e2b" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#f4f4f5">vendor-notifications</text><text x="332" y="423.6" font-size="16" fill="#f4f4f5">11</text><rect x="711.6" y="402" width="82.4" height="32" fill="#1f1b29"/><rect x="723.6" y="413" width="10" height="10" fill="#f2a14b"/><text x="745.6" y="422.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">DIFF</text><line x1="0" y1="450" x2="826" y2="450" stroke="#221e2b" stroke-width="1"/><text x="32" y="487.6" font-size="16" fill="#f4f4f5">meilisearch</text><text x="332" y="487.6" font-size="16" fill="#f4f4f5">6</text><rect x="692.4" y="466" width="101.6" height="32" fill="#1f1b29"/><rect x="704.4" y="477" width="10" height="10" fill="#6fbf68"/><text x="726.4" y="486.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">SYNCED</text><line x1="0" y1="514" x2="826" y2="514" stroke="#221e2b" stroke-width="1"/></g></g><rect x="184.5" y="40.5" width="825" height="513" fill="none" stroke="#2b2636" stroke-width="1"/><rect x="136" y="126" width="826" height="514" fill="#15121d" filter="url(#sh)"/><rect x="136" y="126" width="826" height="514" fill="#15121d"/><g transform="translate(136 126)"><g clip-path="url(#c2)"><rect x="24" y="33" width="10" height="10" fill="#6fbf68"/><text x="46" y="44.3" font-size="18" fill="#f4f4f5" font-weight="500">Panels</text><line x1="134.8" y1="20" x2="134.8" y2="56" stroke="#2b2636" stroke-width="1"/><text x="166.8" y="44" font-size="17" fill="#a1a1aa">Pages</text><text x="257.8" y="44" font-size="17" fill="#f4f4f5">Widgets</text><rect x="239.8" y="73" width="107.4" height="3" fill="#f4f4f5"/><text x="369.2" y="44" font-size="17" fill="#a1a1aa">Fields</text><text x="470.4" y="44" font-size="17" fill="#a1a1aa">Navigation</text><text x="757" y="43.3" font-size="15" fill="#d4d4d8">Typed</text><rect x="697" y="27" width="46" height="22" fill="#6fbf68"/><rect x="721" y="30" width="19" height="16" fill="#15121d"/><line x1="0" y1="76" x2="826" y2="76" stroke="#2b2636" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">FILE</text><text x="794" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">ZONE</text><line x1="0" y1="130" x2="826" y2="130" stroke="#221e2b" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#f4f4f5">payout-summary.tsx</text><text x="794" y="167.6" font-size="16" fill="#f4f4f5" text-anchor="end">orders.detail.side.after</text><line x1="0" y1="194" x2="826" y2="194" stroke="#221e2b" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#f4f4f5">order-sla.tsx</text><text x="794" y="231.6" font-size="16" fill="#f4f4f5" text-anchor="end">orders.list.before</text><line x1="0" y1="258" x2="826" y2="258" stroke="#221e2b" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#f4f4f5">offer-badges.tsx</text><text x="794" y="295.6" font-size="16" fill="#f4f4f5" text-anchor="end">offers.list.after</text><line x1="0" y1="322" x2="826" y2="322" stroke="#221e2b" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#f4f4f5">offer-docs.tsx</text><text x="794" y="359.6" font-size="16" fill="#f4f4f5" text-anchor="end">offers.detail.main.after</text><line x1="0" y1="386" x2="826" y2="386" stroke="#221e2b" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#f4f4f5">vip-note.tsx</text><text x="794" y="423.6" font-size="16" fill="#f4f4f5" text-anchor="end">customers.detail.side</text><line x1="0" y1="450" x2="826" y2="450" stroke="#221e2b" stroke-width="1"/></g></g><rect x="136.5" y="126.5" width="825" height="513" fill="none" stroke="#2b2636" stroke-width="1"/><rect x="88" y="212" width="826" height="514" fill="#15121d" filter="url(#sh)"/><rect x="88" y="212" width="826" height="514" fill="#15121d"/><g transform="translate(88 212)"><g clip-path="url(#c3)"><rect x="24" y="33" width="10" height="10" fill="#f4f4f5"/><text x="46" y="44.3" font-size="18" fill="#f4f4f5" font-weight="500">Backend</text><line x1="145.6" y1="20" x2="145.6" y2="56" stroke="#2b2636" stroke-width="1"/><text x="177.6" y="44" font-size="17" fill="#f4f4f5">Hooks</text><rect x="159.6" y="73" width="87" height="3" fill="#f4f4f5"/><text x="268.6" y="44" font-size="17" fill="#a1a1aa">Routes</text><text x="369.8" y="44" font-size="17" fill="#a1a1aa">Modules</text><text x="802" y="43.3" font-size="15" fill="#71717a" text-anchor="end">src/</text><line x1="0" y1="76" x2="826" y2="76" stroke="#2b2636" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">NAME</text><text x="794" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">WORKFLOW</text><line x1="0" y1="130" x2="826" y2="130" stroke="#221e2b" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#f4f4f5">sellerApproved</text><text x="794" y="167.6" font-size="16" fill="#f4f4f5" text-anchor="end">approveSellerWorkflow</text><line x1="0" y1="194" x2="826" y2="194" stroke="#221e2b" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#f4f4f5">orderGroupCreated</text><text x="794" y="231.6" font-size="16" fill="#f4f4f5" text-anchor="end">completeCartWithSplitOrdersWorkflow</text><line x1="0" y1="258" x2="826" y2="258" stroke="#221e2b" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#f4f4f5">offersCreated</text><text x="794" y="295.6" font-size="16" fill="#f4f4f5" text-anchor="end">createOffersWorkflow</text><line x1="0" y1="322" x2="826" y2="322" stroke="#221e2b" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#f4f4f5">productChangeConfirmed</text><text x="794" y="359.6" font-size="16" fill="#f4f4f5" text-anchor="end">confirmProductChangeWorkflow</text><line x1="0" y1="386" x2="826" y2="386" stroke="#221e2b" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#f4f4f5">payoutsCreated</text><text x="794" y="423.6" font-size="16" fill="#f4f4f5" text-anchor="end">createOrderPayoutsWorkflow</text><line x1="0" y1="450" x2="826" y2="450" stroke="#221e2b" stroke-width="1"/></g></g><rect x="88.5" y="212.5" width="825" height="513" fill="none" stroke="#2b2636" stroke-width="1"/><rect x="40" y="298" width="826" height="514" fill="#15121d" filter="url(#sh)"/><rect x="40" y="298" width="826" height="514" fill="#15121d"/><g transform="translate(40 298)"><g clip-path="url(#c4)"><rect x="24" y="33" width="10" height="10" fill="#a78bfa"/><text x="46" y="44.3" font-size="18" fill="#f4f4f5" font-weight="500">Extensions</text><line x1="178" y1="20" x2="178" y2="56" stroke="#2b2636" stroke-width="1"/><text x="210" y="44" font-size="17" fill="#f4f4f5">All</text><rect x="192" y="73" width="66.6" height="3" fill="#f4f4f5"/><text x="280.6" y="44" font-size="17" fill="#a1a1aa">Backend</text><text x="392" y="44" font-size="17" fill="#a1a1aa">Panels</text><text x="721" y="43.3" font-size="15" fill="#d4d4d8">Typecheck</text><rect x="661" y="27" width="46" height="22" fill="#6fbf68"/><rect x="685" y="30" width="19" height="16" fill="#15121d"/><line x1="0" y1="76" x2="826" y2="76" stroke="#2b2636" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">PATH</text><text x="446" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">ZONE</text><text x="574" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">TARGET</text><line x1="0" y1="130" x2="826" y2="130" stroke="#221e2b" stroke-width="1"/><rect x="0" y="130" width="3" height="64" fill="#a78bfa"/><text x="32" y="167.6" font-size="16" fill="#f4f4f5">src/workflows/hooks/seller-approved.ts</text><rect x="446" y="147" width="60" height="30" fill="#1f1b29"/><text x="458" y="167.3" font-size="15" fill="#a1a1aa">hook</text><text x="574" y="167.6" font-size="16" fill="#f4f4f5">sellerApproved</text><line x1="0" y1="194" x2="826" y2="194" stroke="#221e2b" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#f4f4f5">src/api/vendor/sellers/documents/route.ts</text><rect x="446" y="211" width="69" height="30" fill="#1f1b29"/><text x="458" y="231.3" font-size="15" fill="#a1a1aa">route</text><text x="574" y="231.6" font-size="16" fill="#d4d4d8">/vendor/sellers/…</text><line x1="0" y1="258" x2="826" y2="258" stroke="#221e2b" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#f4f4f5">src/modules/subscription/index.ts</text><rect x="446" y="275" width="78" height="30" fill="#1f1b29"/><text x="458" y="295.3" font-size="15" fill="#a1a1aa">module</text><text x="574" y="295.6" font-size="16" fill="#d4d4d8">↔ seller</text><line x1="0" y1="322" x2="826" y2="322" stroke="#221e2b" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#f4f4f5">medusa-config.ts</text><rect x="446" y="339" width="69" height="30" fill="#1f1b29"/><text x="458" y="359.3" font-size="15" fill="#a1a1aa">field</text><text x="574" y="359.6" font-size="16" fill="#d4d4d8">Product.is_featured</text><line x1="0" y1="386" x2="826" y2="386" stroke="#221e2b" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#f4f4f5">src/routes/reports/page.tsx</text><rect x="446" y="403" width="60" height="30" fill="#1f1b29"/><text x="458" y="423.3" font-size="15" fill="#a1a1aa">page</text><text x="574" y="423.6" font-size="16" fill="#d4d4d8">/reports</text><line x1="0" y1="450" x2="826" y2="450" stroke="#221e2b" stroke-width="1"/><text x="32" y="487.6" font-size="16" fill="#f4f4f5">src/widgets/payout-summary.tsx</text><rect x="446" y="467" width="78" height="30" fill="#1f1b29"/><text x="458" y="487.3" font-size="15" fill="#a1a1aa">widget</text><text x="574" y="487.6" font-size="16" fill="#d4d4d8">orders.detail.side</text><line x1="0" y1="514" x2="826" y2="514" stroke="#221e2b" stroke-width="1"/></g></g><rect x="40.5" y="298.5" width="825" height="513" fill="none" stroke="#2b2636" stroke-width="1"/>
</svg>
\ No newline at end of file
diff --git a/apps/docs/images/figures/extension-zones-light.svg b/apps/docs/images/figures/extension-zones-light.svg
index eed44b9da..dfc0cccfb 100644
--- a/apps/docs/images/figures/extension-zones-light.svg
+++ b/apps/docs/images/figures/extension-zones-light.svg
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1040" height="870" viewBox="0 0 1040 870" font-family="JetBrains Mono, SF Mono, SFMono-Regular, Menlo, Consolas, Liberation Mono, monospace" role="img" aria-label="Stacked panels for Blocks, Panels, and Backend, with an Extensions table in front listing one file per zone: a workflow hook, an API route, a module, a custom field, a page, and a widget, each with its typed target.">
<title>Stacked panels for Blocks, Panels, and Backend, with an Extensions table in front listing one file per zone: a workflow hook, an API route, a module, a custom field, a page, and a widget, each with its typed target.</title>
<defs><filter id="sh" x="-30%" y="-30%" width="160%" height="170%"><feDropShadow dx="0" dy="18" stdDeviation="22" flood-color="#18181b" flood-opacity="0.07"/></filter><filter id="gr" x="0" y="0" width="100%" height="100%"><feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" seed="7" stitchTiles="stitch"/><feColorMatrix type="saturate" values="0"/><feComponentTransfer><feFuncA type="table" tableValues="0 1"/></feComponentTransfer><feComposite in2="SourceGraphic" operator="in"/></filter><pattern id="dt" width="11" height="11" patternUnits="userSpaceOnUse"><rect x="4.5" y="4.5" width="1.6" height="1.6" fill="#d9d9de"/></pattern><clipPath id="c1"><rect x="0" y="0" width="826" height="514"/></clipPath><clipPath id="c2"><rect x="0" y="0" width="826" height="514"/></clipPath><clipPath id="c3"><rect x="0" y="0" width="826" height="514"/></clipPath><clipPath id="c4"><rect x="0" y="0" width="826" height="514"/></clipPath></defs>
-<rect x="-87.5" y="-87.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="88.5" y="-87.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="176" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="440" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="528.5" y="-87.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="968" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="0" y="0" width="88" height="88" fill="#e4e4e7"/><rect x="0" y="0" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="88.5" y="0.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="264" y="0" width="88" height="88" fill="url(#dt)"/><rect x="-87.5" y="88.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="616.5" y="88.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="792" y="88" width="88" height="88" fill="url(#dt)"/><rect x="1056" y="88" width="88" height="88" fill="url(#dt)"/><rect x="264.5" y="176.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="352" y="176" width="88" height="88" fill="url(#dt)"/><rect x="440" y="176" width="88" height="88" fill="url(#dt)"/><rect x="704.5" y="176.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="968.5" y="176.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="176.5" y="264.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="968" y="264" width="88" height="88" fill="url(#dt)"/><rect x="-88" y="352" width="88" height="88" fill="#e4e4e7"/><rect x="-88" y="352" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="528" y="352" width="88" height="88" fill="url(#dt)"/><rect x="-88" y="440" width="88" height="88" fill="url(#dt)"/><rect x="0" y="440" width="88" height="88" fill="#e4e4e7"/><rect x="0" y="440" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="176.5" y="440.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="528.5" y="440.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="616" y="440" width="88" height="88" fill="#e4e4e7"/><rect x="616" y="440" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="1056.5" y="440.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="0" y="528" width="88" height="88" fill="url(#dt)"/><rect x="352.5" y="528.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="792" y="528" width="88" height="88" fill="#e4e4e7"/><rect x="792" y="528" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="968" y="528" width="88" height="88" fill="url(#dt)"/><rect x="-87.5" y="616.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="264.5" y="616.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="352" y="616" width="88" height="88" fill="#e4e4e7"/><rect x="352" y="616" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="792" y="616" width="88" height="88" fill="url(#dt)"/><rect x="-88" y="704" width="88" height="88" fill="url(#dt)"/><rect x="0" y="704" width="88" height="88" fill="url(#dt)"/><rect x="704.5" y="704.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="1056.5" y="704.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="0.5" y="792.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="88" y="792" width="88" height="88" fill="url(#dt)"/><rect x="176" y="792" width="88" height="88" fill="#e4e4e7"/><rect x="176" y="792" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="264" y="792" width="88" height="88" fill="#e4e4e7"/><rect x="264" y="792" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="440.5" y="792.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="704.5" y="792.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="880.5" y="792.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="1056" y="792" width="88" height="88" fill="url(#dt)"/><rect x="176" y="880" width="88" height="88" fill="#e4e4e7"/><rect x="176" y="880" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="264" y="880" width="88" height="88" fill="url(#dt)"/><rect x="352" y="880" width="88" height="88" fill="#e4e4e7"/><rect x="352" y="880" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="440" y="880" width="88" height="88" fill="#e4e4e7"/><rect x="440" y="880" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="528.5" y="880.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="616" y="880" width="88" height="88" fill="#e4e4e7"/><rect x="616" y="880" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="704" y="880" width="88" height="88" fill="url(#dt)"/><rect x="968" y="880" width="88" height="88" fill="#e4e4e7"/><rect x="968" y="880" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="184" y="40" width="826" height="514" fill="#ffffff" filter="url(#sh)"/><rect x="184" y="40" width="826" height="514" fill="#ffffff"/><g transform="translate(184 40)"><g clip-path="url(#c1)"><rect x="24" y="33" width="10" height="10" fill="#c2680c"/><text x="46" y="44.3" font-size="18" fill="#18181b" font-weight="500">Blocks</text><line x1="134.8" y1="20" x2="134.8" y2="56" stroke="#e4e4e7" stroke-width="1"/><text x="166.8" y="44" font-size="17" fill="#18181b">Installed</text><rect x="148.8" y="73" width="127.8" height="3" fill="#18181b"/><text x="298.6" y="44" font-size="17" fill="#71717a">Registry</text><text x="721" y="43.3" font-size="15" fill="#3f3f46">Overwrite</text><rect x="661" y="27" width="46" height="22" fill="#d4d4d8"/><rect x="664" y="30" width="19" height="16" fill="#ffffff"/><line x1="0" y1="76" x2="826" y2="76" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">BLOCK</text><text x="332" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">FILES</text><text x="794" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">UPSTREAM</text><line x1="0" y1="130" x2="826" y2="130" stroke="#ededf0" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#18181b">wishlist</text><text x="332" y="167.6" font-size="16" fill="#18181b">9</text><rect x="692.4" y="146" width="101.6" height="32" fill="#f4f4f5"/><rect x="704.4" y="157" width="10" height="10" fill="#3f7d3a"/><text x="726.4" y="166.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">SYNCED</text><line x1="0" y1="194" x2="826" y2="194" stroke="#ededf0" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#18181b">algolia</text><text x="332" y="231.6" font-size="16" fill="#18181b">6</text><rect x="711.6" y="210" width="82.4" height="32" fill="#f4f4f5"/><rect x="723.6" y="221" width="10" height="10" fill="#c2680c"/><text x="745.6" y="230.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">DIFF</text><line x1="0" y1="258" x2="826" y2="258" stroke="#ededf0" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#18181b">vendor-chat</text><text x="332" y="295.6" font-size="16" fill="#18181b">21</text><rect x="692.4" y="274" width="101.6" height="32" fill="#f4f4f5"/><rect x="704.4" y="285" width="10" height="10" fill="#3f7d3a"/><text x="726.4" y="294.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">SYNCED</text><line x1="0" y1="322" x2="826" y2="322" stroke="#ededf0" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#18181b">requests</text><text x="332" y="359.6" font-size="16" fill="#18181b">17</text><rect x="692.4" y="338" width="101.6" height="32" fill="#f4f4f5"/><rect x="704.4" y="349" width="10" height="10" fill="#3f7d3a"/><text x="726.4" y="358.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">SYNCED</text><line x1="0" y1="386" x2="826" y2="386" stroke="#ededf0" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#18181b">vendor-notifications</text><text x="332" y="423.6" font-size="16" fill="#18181b">11</text><rect x="711.6" y="402" width="82.4" height="32" fill="#f4f4f5"/><rect x="723.6" y="413" width="10" height="10" fill="#c2680c"/><text x="745.6" y="422.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">DIFF</text><line x1="0" y1="450" x2="826" y2="450" stroke="#ededf0" stroke-width="1"/><text x="32" y="487.6" font-size="16" fill="#18181b">meilisearch</text><text x="332" y="487.6" font-size="16" fill="#18181b">6</text><rect x="692.4" y="466" width="101.6" height="32" fill="#f4f4f5"/><rect x="704.4" y="477" width="10" height="10" fill="#3f7d3a"/><text x="726.4" y="486.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">SYNCED</text><line x1="0" y1="514" x2="826" y2="514" stroke="#ededf0" stroke-width="1"/></g></g><rect x="184.5" y="40.5" width="825" height="513" fill="none" stroke="#e4e4e7" stroke-width="1"/><rect x="136" y="126" width="826" height="514" fill="#ffffff" filter="url(#sh)"/><rect x="136" y="126" width="826" height="514" fill="#ffffff"/><g transform="translate(136 126)"><g clip-path="url(#c2)"><rect x="24" y="33" width="10" height="10" fill="#3f7d3a"/><text x="46" y="44.3" font-size="18" fill="#18181b" font-weight="500">Panels</text><line x1="134.8" y1="20" x2="134.8" y2="56" stroke="#e4e4e7" stroke-width="1"/><text x="166.8" y="44" font-size="17" fill="#71717a">Pages</text><text x="257.8" y="44" font-size="17" fill="#18181b">Widgets</text><rect x="239.8" y="73" width="107.4" height="3" fill="#18181b"/><text x="369.2" y="44" font-size="17" fill="#71717a">Fields</text><text x="470.4" y="44" font-size="17" fill="#71717a">Navigation</text><text x="757" y="43.3" font-size="15" fill="#3f3f46">Typed</text><rect x="697" y="27" width="46" height="22" fill="#3f7d3a"/><rect x="721" y="30" width="19" height="16" fill="#ffffff"/><line x1="0" y1="76" x2="826" y2="76" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">FILE</text><text x="794" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">ZONE</text><line x1="0" y1="130" x2="826" y2="130" stroke="#ededf0" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#18181b">payout-summary.tsx</text><text x="794" y="167.6" font-size="16" fill="#18181b" text-anchor="end">orders.detail.side.after</text><line x1="0" y1="194" x2="826" y2="194" stroke="#ededf0" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#18181b">order-sla.tsx</text><text x="794" y="231.6" font-size="16" fill="#18181b" text-anchor="end">orders.list.before</text><line x1="0" y1="258" x2="826" y2="258" stroke="#ededf0" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#18181b">offer-badges.tsx</text><text x="794" y="295.6" font-size="16" fill="#18181b" text-anchor="end">offers.list.after</text><line x1="0" y1="322" x2="826" y2="322" stroke="#ededf0" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#18181b">offer-docs.tsx</text><text x="794" y="359.6" font-size="16" fill="#18181b" text-anchor="end">offers.detail.main.after</text><line x1="0" y1="386" x2="826" y2="386" stroke="#ededf0" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#18181b">vip-note.tsx</text><text x="794" y="423.6" font-size="16" fill="#18181b" text-anchor="end">customers.detail.side</text><line x1="0" y1="450" x2="826" y2="450" stroke="#ededf0" stroke-width="1"/></g></g><rect x="136.5" y="126.5" width="825" height="513" fill="none" stroke="#e4e4e7" stroke-width="1"/><rect x="88" y="212" width="826" height="514" fill="#ffffff" filter="url(#sh)"/><rect x="88" y="212" width="826" height="514" fill="#ffffff"/><g transform="translate(88 212)"><g clip-path="url(#c3)"><rect x="24" y="33" width="10" height="10" fill="#18181b"/><text x="46" y="44.3" font-size="18" fill="#18181b" font-weight="500">Backend</text><line x1="145.6" y1="20" x2="145.6" y2="56" stroke="#e4e4e7" stroke-width="1"/><text x="177.6" y="44" font-size="17" fill="#18181b">Hooks</text><rect x="159.6" y="73" width="87" height="3" fill="#18181b"/><text x="268.6" y="44" font-size="17" fill="#71717a">Routes</text><text x="369.8" y="44" font-size="17" fill="#71717a">Modules</text><text x="802" y="43.3" font-size="15" fill="#a1a1aa" text-anchor="end">src/</text><line x1="0" y1="76" x2="826" y2="76" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">NAME</text><text x="794" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">WORKFLOW</text><line x1="0" y1="130" x2="826" y2="130" stroke="#ededf0" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#18181b">sellerApproved</text><text x="794" y="167.6" font-size="16" fill="#18181b" text-anchor="end">approveSellerWorkflow</text><line x1="0" y1="194" x2="826" y2="194" stroke="#ededf0" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#18181b">orderGroupCreated</text><text x="794" y="231.6" font-size="16" fill="#18181b" text-anchor="end">completeCartWithSplitOrdersWorkflow</text><line x1="0" y1="258" x2="826" y2="258" stroke="#ededf0" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#18181b">offersCreated</text><text x="794" y="295.6" font-size="16" fill="#18181b" text-anchor="end">createOffersWorkflow</text><line x1="0" y1="322" x2="826" y2="322" stroke="#ededf0" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#18181b">productChangeConfirmed</text><text x="794" y="359.6" font-size="16" fill="#18181b" text-anchor="end">confirmProductChangeWorkflow</text><line x1="0" y1="386" x2="826" y2="386" stroke="#ededf0" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#18181b">payoutCreated</text><text x="794" y="423.6" font-size="16" fill="#18181b" text-anchor="end">createPayoutWorkflow</text><line x1="0" y1="450" x2="826" y2="450" stroke="#ededf0" stroke-width="1"/></g></g><rect x="88.5" y="212.5" width="825" height="513" fill="none" stroke="#e4e4e7" stroke-width="1"/><rect x="40" y="298" width="826" height="514" fill="#ffffff" filter="url(#sh)"/><rect x="40" y="298" width="826" height="514" fill="#ffffff"/><g transform="translate(40 298)"><g clip-path="url(#c4)"><rect x="24" y="33" width="10" height="10" fill="#7c3aed"/><text x="46" y="44.3" font-size="18" fill="#18181b" font-weight="500">Extensions</text><line x1="178" y1="20" x2="178" y2="56" stroke="#e4e4e7" stroke-width="1"/><text x="210" y="44" font-size="17" fill="#18181b">All</text><rect x="192" y="73" width="66.6" height="3" fill="#18181b"/><text x="280.6" y="44" font-size="17" fill="#71717a">Backend</text><text x="392" y="44" font-size="17" fill="#71717a">Panels</text><text x="721" y="43.3" font-size="15" fill="#3f3f46">Typecheck</text><rect x="661" y="27" width="46" height="22" fill="#3f7d3a"/><rect x="685" y="30" width="19" height="16" fill="#ffffff"/><line x1="0" y1="76" x2="826" y2="76" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">PATH</text><text x="446" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">ZONE</text><text x="574" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">TARGET</text><line x1="0" y1="130" x2="826" y2="130" stroke="#ededf0" stroke-width="1"/><rect x="0" y="130" width="3" height="64" fill="#7c3aed"/><text x="32" y="167.6" font-size="16" fill="#18181b">src/workflows/hooks/seller-approved.ts</text><rect x="446" y="147" width="60" height="30" fill="#f4f4f5"/><text x="458" y="167.3" font-size="15" fill="#71717a">hook</text><text x="574" y="167.6" font-size="16" fill="#18181b">sellerApproved</text><line x1="0" y1="194" x2="826" y2="194" stroke="#ededf0" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#18181b">src/api/vendor/sellers/documents/route.ts</text><rect x="446" y="211" width="69" height="30" fill="#f4f4f5"/><text x="458" y="231.3" font-size="15" fill="#71717a">route</text><text x="574" y="231.6" font-size="16" fill="#3f3f46">/vendor/sellers/…</text><line x1="0" y1="258" x2="826" y2="258" stroke="#ededf0" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#18181b">src/modules/subscription/index.ts</text><rect x="446" y="275" width="78" height="30" fill="#f4f4f5"/><text x="458" y="295.3" font-size="15" fill="#71717a">module</text><text x="574" y="295.6" font-size="16" fill="#3f3f46">↔ seller</text><line x1="0" y1="322" x2="826" y2="322" stroke="#ededf0" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#18181b">medusa-config.ts</text><rect x="446" y="339" width="69" height="30" fill="#f4f4f5"/><text x="458" y="359.3" font-size="15" fill="#71717a">field</text><text x="574" y="359.6" font-size="16" fill="#3f3f46">Product.is_featured</text><line x1="0" y1="386" x2="826" y2="386" stroke="#ededf0" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#18181b">src/routes/reports/page.tsx</text><rect x="446" y="403" width="60" height="30" fill="#f4f4f5"/><text x="458" y="423.3" font-size="15" fill="#71717a">page</text><text x="574" y="423.6" font-size="16" fill="#3f3f46">/reports</text><line x1="0" y1="450" x2="826" y2="450" stroke="#ededf0" stroke-width="1"/><text x="32" y="487.6" font-size="16" fill="#18181b">src/widgets/payout-summary.tsx</text><rect x="446" y="467" width="78" height="30" fill="#f4f4f5"/><text x="458" y="487.3" font-size="15" fill="#71717a">widget</text><text x="574" y="487.6" font-size="16" fill="#3f3f46">orders.detail.side</text><line x1="0" y1="514" x2="826" y2="514" stroke="#ededf0" stroke-width="1"/></g></g><rect x="40.5" y="298.5" width="825" height="513" fill="none" stroke="#e4e4e7" stroke-width="1"/>
+<rect x="-87.5" y="-87.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="88.5" y="-87.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="176" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="440" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="528.5" y="-87.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="968" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="0" y="0" width="88" height="88" fill="#e4e4e7"/><rect x="0" y="0" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="88.5" y="0.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="264" y="0" width="88" height="88" fill="url(#dt)"/><rect x="-87.5" y="88.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="616.5" y="88.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="792" y="88" width="88" height="88" fill="url(#dt)"/><rect x="1056" y="88" width="88" height="88" fill="url(#dt)"/><rect x="264.5" y="176.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="352" y="176" width="88" height="88" fill="url(#dt)"/><rect x="440" y="176" width="88" height="88" fill="url(#dt)"/><rect x="704.5" y="176.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="968.5" y="176.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="176.5" y="264.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="968" y="264" width="88" height="88" fill="url(#dt)"/><rect x="-88" y="352" width="88" height="88" fill="#e4e4e7"/><rect x="-88" y="352" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="528" y="352" width="88" height="88" fill="url(#dt)"/><rect x="-88" y="440" width="88" height="88" fill="url(#dt)"/><rect x="0" y="440" width="88" height="88" fill="#e4e4e7"/><rect x="0" y="440" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="176.5" y="440.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="528.5" y="440.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="616" y="440" width="88" height="88" fill="#e4e4e7"/><rect x="616" y="440" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="1056.5" y="440.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="0" y="528" width="88" height="88" fill="url(#dt)"/><rect x="352.5" y="528.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="792" y="528" width="88" height="88" fill="#e4e4e7"/><rect x="792" y="528" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="968" y="528" width="88" height="88" fill="url(#dt)"/><rect x="-87.5" y="616.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="264.5" y="616.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="352" y="616" width="88" height="88" fill="#e4e4e7"/><rect x="352" y="616" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="792" y="616" width="88" height="88" fill="url(#dt)"/><rect x="-88" y="704" width="88" height="88" fill="url(#dt)"/><rect x="0" y="704" width="88" height="88" fill="url(#dt)"/><rect x="704.5" y="704.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="1056.5" y="704.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="0.5" y="792.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="88" y="792" width="88" height="88" fill="url(#dt)"/><rect x="176" y="792" width="88" height="88" fill="#e4e4e7"/><rect x="176" y="792" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="264" y="792" width="88" height="88" fill="#e4e4e7"/><rect x="264" y="792" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="440.5" y="792.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="704.5" y="792.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="880.5" y="792.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="1056" y="792" width="88" height="88" fill="url(#dt)"/><rect x="176" y="880" width="88" height="88" fill="#e4e4e7"/><rect x="176" y="880" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="264" y="880" width="88" height="88" fill="url(#dt)"/><rect x="352" y="880" width="88" height="88" fill="#e4e4e7"/><rect x="352" y="880" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="440" y="880" width="88" height="88" fill="#e4e4e7"/><rect x="440" y="880" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="528.5" y="880.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="616" y="880" width="88" height="88" fill="#e4e4e7"/><rect x="616" y="880" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="704" y="880" width="88" height="88" fill="url(#dt)"/><rect x="968" y="880" width="88" height="88" fill="#e4e4e7"/><rect x="968" y="880" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="184" y="40" width="826" height="514" fill="#ffffff" filter="url(#sh)"/><rect x="184" y="40" width="826" height="514" fill="#ffffff"/><g transform="translate(184 40)"><g clip-path="url(#c1)"><rect x="24" y="33" width="10" height="10" fill="#c2680c"/><text x="46" y="44.3" font-size="18" fill="#18181b" font-weight="500">Blocks</text><line x1="134.8" y1="20" x2="134.8" y2="56" stroke="#e4e4e7" stroke-width="1"/><text x="166.8" y="44" font-size="17" fill="#18181b">Installed</text><rect x="148.8" y="73" width="127.8" height="3" fill="#18181b"/><text x="298.6" y="44" font-size="17" fill="#71717a">Registry</text><text x="721" y="43.3" font-size="15" fill="#3f3f46">Overwrite</text><rect x="661" y="27" width="46" height="22" fill="#d4d4d8"/><rect x="664" y="30" width="19" height="16" fill="#ffffff"/><line x1="0" y1="76" x2="826" y2="76" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">BLOCK</text><text x="332" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">FILES</text><text x="794" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">UPSTREAM</text><line x1="0" y1="130" x2="826" y2="130" stroke="#ededf0" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#18181b">wishlist</text><text x="332" y="167.6" font-size="16" fill="#18181b">9</text><rect x="692.4" y="146" width="101.6" height="32" fill="#f4f4f5"/><rect x="704.4" y="157" width="10" height="10" fill="#3f7d3a"/><text x="726.4" y="166.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">SYNCED</text><line x1="0" y1="194" x2="826" y2="194" stroke="#ededf0" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#18181b">algolia</text><text x="332" y="231.6" font-size="16" fill="#18181b">6</text><rect x="711.6" y="210" width="82.4" height="32" fill="#f4f4f5"/><rect x="723.6" y="221" width="10" height="10" fill="#c2680c"/><text x="745.6" y="230.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">DIFF</text><line x1="0" y1="258" x2="826" y2="258" stroke="#ededf0" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#18181b">vendor-chat</text><text x="332" y="295.6" font-size="16" fill="#18181b">21</text><rect x="692.4" y="274" width="101.6" height="32" fill="#f4f4f5"/><rect x="704.4" y="285" width="10" height="10" fill="#3f7d3a"/><text x="726.4" y="294.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">SYNCED</text><line x1="0" y1="322" x2="826" y2="322" stroke="#ededf0" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#18181b">requests</text><text x="332" y="359.6" font-size="16" fill="#18181b">17</text><rect x="692.4" y="338" width="101.6" height="32" fill="#f4f4f5"/><rect x="704.4" y="349" width="10" height="10" fill="#3f7d3a"/><text x="726.4" y="358.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">SYNCED</text><line x1="0" y1="386" x2="826" y2="386" stroke="#ededf0" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#18181b">vendor-notifications</text><text x="332" y="423.6" font-size="16" fill="#18181b">11</text><rect x="711.6" y="402" width="82.4" height="32" fill="#f4f4f5"/><rect x="723.6" y="413" width="10" height="10" fill="#c2680c"/><text x="745.6" y="422.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">DIFF</text><line x1="0" y1="450" x2="826" y2="450" stroke="#ededf0" stroke-width="1"/><text x="32" y="487.6" font-size="16" fill="#18181b">meilisearch</text><text x="332" y="487.6" font-size="16" fill="#18181b">6</text><rect x="692.4" y="466" width="101.6" height="32" fill="#f4f4f5"/><rect x="704.4" y="477" width="10" height="10" fill="#3f7d3a"/><text x="726.4" y="486.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">SYNCED</text><line x1="0" y1="514" x2="826" y2="514" stroke="#ededf0" stroke-width="1"/></g></g><rect x="184.5" y="40.5" width="825" height="513" fill="none" stroke="#e4e4e7" stroke-width="1"/><rect x="136" y="126" width="826" height="514" fill="#ffffff" filter="url(#sh)"/><rect x="136" y="126" width="826" height="514" fill="#ffffff"/><g transform="translate(136 126)"><g clip-path="url(#c2)"><rect x="24" y="33" width="10" height="10" fill="#3f7d3a"/><text x="46" y="44.3" font-size="18" fill="#18181b" font-weight="500">Panels</text><line x1="134.8" y1="20" x2="134.8" y2="56" stroke="#e4e4e7" stroke-width="1"/><text x="166.8" y="44" font-size="17" fill="#71717a">Pages</text><text x="257.8" y="44" font-size="17" fill="#18181b">Widgets</text><rect x="239.8" y="73" width="107.4" height="3" fill="#18181b"/><text x="369.2" y="44" font-size="17" fill="#71717a">Fields</text><text x="470.4" y="44" font-size="17" fill="#71717a">Navigation</text><text x="757" y="43.3" font-size="15" fill="#3f3f46">Typed</text><rect x="697" y="27" width="46" height="22" fill="#3f7d3a"/><rect x="721" y="30" width="19" height="16" fill="#ffffff"/><line x1="0" y1="76" x2="826" y2="76" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">FILE</text><text x="794" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">ZONE</text><line x1="0" y1="130" x2="826" y2="130" stroke="#ededf0" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#18181b">payout-summary.tsx</text><text x="794" y="167.6" font-size="16" fill="#18181b" text-anchor="end">orders.detail.side.after</text><line x1="0" y1="194" x2="826" y2="194" stroke="#ededf0" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#18181b">order-sla.tsx</text><text x="794" y="231.6" font-size="16" fill="#18181b" text-anchor="end">orders.list.before</text><line x1="0" y1="258" x2="826" y2="258" stroke="#ededf0" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#18181b">offer-badges.tsx</text><text x="794" y="295.6" font-size="16" fill="#18181b" text-anchor="end">offers.list.after</text><line x1="0" y1="322" x2="826" y2="322" stroke="#ededf0" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#18181b">offer-docs.tsx</text><text x="794" y="359.6" font-size="16" fill="#18181b" text-anchor="end">offers.detail.main.after</text><line x1="0" y1="386" x2="826" y2="386" stroke="#ededf0" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#18181b">vip-note.tsx</text><text x="794" y="423.6" font-size="16" fill="#18181b" text-anchor="end">customers.detail.side</text><line x1="0" y1="450" x2="826" y2="450" stroke="#ededf0" stroke-width="1"/></g></g><rect x="136.5" y="126.5" width="825" height="513" fill="none" stroke="#e4e4e7" stroke-width="1"/><rect x="88" y="212" width="826" height="514" fill="#ffffff" filter="url(#sh)"/><rect x="88" y="212" width="826" height="514" fill="#ffffff"/><g transform="translate(88 212)"><g clip-path="url(#c3)"><rect x="24" y="33" width="10" height="10" fill="#18181b"/><text x="46" y="44.3" font-size="18" fill="#18181b" font-weight="500">Backend</text><line x1="145.6" y1="20" x2="145.6" y2="56" stroke="#e4e4e7" stroke-width="1"/><text x="177.6" y="44" font-size="17" fill="#18181b">Hooks</text><rect x="159.6" y="73" width="87" height="3" fill="#18181b"/><text x="268.6" y="44" font-size="17" fill="#71717a">Routes</text><text x="369.8" y="44" font-size="17" fill="#71717a">Modules</text><text x="802" y="43.3" font-size="15" fill="#a1a1aa" text-anchor="end">src/</text><line x1="0" y1="76" x2="826" y2="76" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">NAME</text><text x="794" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">WORKFLOW</text><line x1="0" y1="130" x2="826" y2="130" stroke="#ededf0" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#18181b">sellerApproved</text><text x="794" y="167.6" font-size="16" fill="#18181b" text-anchor="end">approveSellerWorkflow</text><line x1="0" y1="194" x2="826" y2="194" stroke="#ededf0" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#18181b">orderGroupCreated</text><text x="794" y="231.6" font-size="16" fill="#18181b" text-anchor="end">completeCartWithSplitOrdersWorkflow</text><line x1="0" y1="258" x2="826" y2="258" stroke="#ededf0" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#18181b">offersCreated</text><text x="794" y="295.6" font-size="16" fill="#18181b" text-anchor="end">createOffersWorkflow</text><line x1="0" y1="322" x2="826" y2="322" stroke="#ededf0" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#18181b">productChangeConfirmed</text><text x="794" y="359.6" font-size="16" fill="#18181b" text-anchor="end">confirmProductChangeWorkflow</text><line x1="0" y1="386" x2="826" y2="386" stroke="#ededf0" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#18181b">payoutsCreated</text><text x="794" y="423.6" font-size="16" fill="#18181b" text-anchor="end">createOrderPayoutsWorkflow</text><line x1="0" y1="450" x2="826" y2="450" stroke="#ededf0" stroke-width="1"/></g></g><rect x="88.5" y="212.5" width="825" height="513" fill="none" stroke="#e4e4e7" stroke-width="1"/><rect x="40" y="298" width="826" height="514" fill="#ffffff" filter="url(#sh)"/><rect x="40" y="298" width="826" height="514" fill="#ffffff"/><g transform="translate(40 298)"><g clip-path="url(#c4)"><rect x="24" y="33" width="10" height="10" fill="#7c3aed"/><text x="46" y="44.3" font-size="18" fill="#18181b" font-weight="500">Extensions</text><line x1="178" y1="20" x2="178" y2="56" stroke="#e4e4e7" stroke-width="1"/><text x="210" y="44" font-size="17" fill="#18181b">All</text><rect x="192" y="73" width="66.6" height="3" fill="#18181b"/><text x="280.6" y="44" font-size="17" fill="#71717a">Backend</text><text x="392" y="44" font-size="17" fill="#71717a">Panels</text><text x="721" y="43.3" font-size="15" fill="#3f3f46">Typecheck</text><rect x="661" y="27" width="46" height="22" fill="#3f7d3a"/><rect x="685" y="30" width="19" height="16" fill="#ffffff"/><line x1="0" y1="76" x2="826" y2="76" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">PATH</text><text x="446" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">ZONE</text><text x="574" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">TARGET</text><line x1="0" y1="130" x2="826" y2="130" stroke="#ededf0" stroke-width="1"/><rect x="0" y="130" width="3" height="64" fill="#7c3aed"/><text x="32" y="167.6" font-size="16" fill="#18181b">src/workflows/hooks/seller-approved.ts</text><rect x="446" y="147" width="60" height="30" fill="#f4f4f5"/><text x="458" y="167.3" font-size="15" fill="#71717a">hook</text><text x="574" y="167.6" font-size="16" fill="#18181b">sellerApproved</text><line x1="0" y1="194" x2="826" y2="194" stroke="#ededf0" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#18181b">src/api/vendor/sellers/documents/route.ts</text><rect x="446" y="211" width="69" height="30" fill="#f4f4f5"/><text x="458" y="231.3" font-size="15" fill="#71717a">route</text><text x="574" y="231.6" font-size="16" fill="#3f3f46">/vendor/sellers/…</text><line x1="0" y1="258" x2="826" y2="258" stroke="#ededf0" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#18181b">src/modules/subscription/index.ts</text><rect x="446" y="275" width="78" height="30" fill="#f4f4f5"/><text x="458" y="295.3" font-size="15" fill="#71717a">module</text><text x="574" y="295.6" font-size="16" fill="#3f3f46">↔ seller</text><line x1="0" y1="322" x2="826" y2="322" stroke="#ededf0" stroke-width="1"/><text x="32" y="359.6" font-size="16" fill="#18181b">medusa-config.ts</text><rect x="446" y="339" width="69" height="30" fill="#f4f4f5"/><text x="458" y="359.3" font-size="15" fill="#71717a">field</text><text x="574" y="359.6" font-size="16" fill="#3f3f46">Product.is_featured</text><line x1="0" y1="386" x2="826" y2="386" stroke="#ededf0" stroke-width="1"/><text x="32" y="423.6" font-size="16" fill="#18181b">src/routes/reports/page.tsx</text><rect x="446" y="403" width="60" height="30" fill="#f4f4f5"/><text x="458" y="423.3" font-size="15" fill="#71717a">page</text><text x="574" y="423.6" font-size="16" fill="#3f3f46">/reports</text><line x1="0" y1="450" x2="826" y2="450" stroke="#ededf0" stroke-width="1"/><text x="32" y="487.6" font-size="16" fill="#18181b">src/widgets/payout-summary.tsx</text><rect x="446" y="467" width="78" height="30" fill="#f4f4f5"/><text x="458" y="487.3" font-size="15" fill="#71717a">widget</text><text x="574" y="487.6" font-size="16" fill="#3f3f46">orders.detail.side</text><line x1="0" y1="514" x2="826" y2="514" stroke="#ededf0" stroke-width="1"/></g></g><rect x="40.5" y="298.5" width="825" height="513" fill="none" stroke="#e4e4e7" stroke-width="1"/>
</svg>
\ No newline at end of file
diff --git a/apps/docs/learn/architecture.mdx b/apps/docs/learn/architecture.mdx
index c75ef946e..a4e3679d0 100644
--- a/apps/docs/learn/architecture.mdx
+++ b/apps/docs/learn/architecture.mdx
@@ -51,11 +51,11 @@ Everything else in this file is standard Medusa configuration.
[Source](https://github.com/mercurjs/mercur/tree/main/packages/core) · [Platform modules](/platform/store/overview)
-### `@mercurjs/payout-stripe-connect`
+### `@mercurjs/stripe-connector-plugin`
-A payout provider built on Stripe Connect. It creates a connected account per seller, returns onboarding links, transfers each seller’s share, and maps Stripe webhooks to payout account statuses.
+A Stripe payment provider and a payout provider built on Stripe Connect. It creates a connected account per seller, returns onboarding links, transfers each seller’s share, and maps Stripe webhooks to payout account statuses. It also brings the payout operations core leaves out: the scheduled capture, payout, reversal, and settlement jobs, settlements and bank payouts, operator adjustments, and the Integrations → Stripe screens.
-[Source](https://github.com/mercurjs/mercur/tree/main/packages/providers/payout-stripe-connect) · [Stripe Connect guide](/resources/integrations/stripe-connect)
+[Source](https://github.com/mercurjs/mercur/tree/main/packages/plugins/stripe-connector) · [Stripe Connect guide](/resources/integrations/stripe-connect/overview)
### PostgreSQL and Redis
@@ -68,7 +68,7 @@ Mercur doesn’t choose your payment gateway, carrier, email service, or search
| Concern | Provider interface | Available implementations |
| --- | --- | --- |
| Payments | Medusa payment module | Stripe, or your own provider |
-| Seller payouts | Mercur payout module | `@mercurjs/payout-stripe-connect`, a `system` provider for development |
+| Seller payouts | Mercur payout module, one provider per marketplace | `@mercurjs/stripe-connector-plugin` (Stripe Connect), the built-in `system` provider for development |
| Fulfillment | Medusa fulfillment module | Manual, or a carrier provider |
| Notifications | Medusa notification module | Local, SendGrid |
| Files | Medusa file module | Local, S3 |
diff --git a/apps/docs/learn/payouts.mdx b/apps/docs/learn/payouts.mdx
index 590dd8f95..376c42d12 100644
--- a/apps/docs/learn/payouts.mdx
+++ b/apps/docs/learn/payouts.mdx
@@ -1,9 +1,9 @@
---
title: "Payout"
-description: "How seller payouts work in Mercur — accounts, onboarding, payment capture, and the transfer pipeline."
+description: "How seller payouts work in Mercur — accounts, onboarding, one payout per order, and reversals of refunds."
---
-The payout module handles the financial side of a marketplace — onboarding sellers to a payment provider, capturing authorized payments, and transferring funds to sellers after fulfillment.
+The payout module handles the financial side of a marketplace — onboarding sellers to a payout provider, paying each seller their share of an order after fulfillment, and taking refunded shares back.
## Payout account
@@ -28,91 +28,66 @@ PENDING → ACTIVE
When a payout account is created, an **Onboarding** record is attached to it. This stores provider-specific data needed for identity verification or account setup (e.g. Stripe Connect onboarding links).
-## The payout pipeline
-
-The payout flow is fully automated through two scheduled jobs and event-driven subscribers. No manual intervention is needed after configuration.
-
-### 1. Capture check (every 15 minutes)
-
-A scheduled job scans for orders that are ready for payment capture. For each order, it checks:
-
-- Payment is in `authorized` status
-- Seller has an `ACTIVE` payout account
-- Order meets the required fulfillment status (configurable, default: `fulfilled`)
-- No payout has been created yet
-
-When the capture deadline approaches (authorization window minus safety buffer), the job emits an `order.capture_requested` event. If the authorization has already expired, it emits `order.authorization_expired` instead.
-
-### 2. Payment capture (event-driven)
-
-A subscriber listens for `order.capture_requested` events and runs the Medusa `capturePaymentWorkflow` to capture the authorized payment. On success, the order is marked as captured. On failure, the order is flagged so it won't be retried.
-
-### 3. Daily payouts (once per day)
+## Payouts and reversals
-A daily scheduled job (1 AM UTC) scans for captured orders that haven't been paid out yet. For each eligible order, it emits a `payout.requested` event.
+A **Payout** is the seller's share of one order: the order total minus the order's commission lines, sent to the seller's payout account. Each order gets at most one payout. A later refund gets a **PayoutReversal** under that payout, for the refund minus its share of the commission, the way Medusa keeps a `Refund` under a `Payment`.
-An order qualifies for payout when:
-- Payment has been captured (`metadata.captured = true`)
-- No existing payout transfer
-- Seller has an `ACTIVE` payout account
+`createOrderPayoutsWorkflow` decides each order's payout. It pays the order when:
-### 4. Payout transfer (event-driven)
+- The seller has a payout account with payouts enabled
+- The order isn't canceled and has reached the required fulfillment status (default `fulfilled`)
+- The order's payment is captured, and not canceled or fully refunded
+- Total minus commission is positive
-A subscriber listens for `payout.requested` events and runs the `createPayoutWorkflow`:
-
-1. **Fetch order** — Loads the order with its seller, payout account, and commission lines
-2. **Calculate payout amount** — Subtracts commission from the order total:
- ```
- payout_amount = order.total - total_commission
- ```
-3. **Create payout** — Calls the payment provider to initiate the transfer and creates a `Payout` record
-4. **Link payout** — Associates the payout with the seller
+Otherwise the payout is `on_hold` with a reason, and the next run re-decides it; a canceled order or payment `aborts` it. `createPayoutReversalsWorkflow` does the same for refunds, once the payout is paid.
### Payout statuses
| Status | Description |
|--------|-------------|
-| `PENDING` | Payout created, transfer initiated |
-| `PROCESSING` | Provider is processing the transfer |
-| `PAID` | Funds successfully transferred |
-| `FAILED` | Transfer failed |
-| `CANCELED` | Transfer was canceled |
+| `PENDING` | Every check passed, about to be sent |
+| `ON_HOLD` | Waiting for the account, fulfillment, or capture |
+| `PROCESSING` | Provider is processing the payout |
+| `PAID` | Funds reached the seller's account |
+| `FAILED` | The provider refused it; retried on the next run |
+| `ABORTED` | Canceled order or payment, or a final provider error |
-Payout statuses are updated via webhook events from the payment provider.
+## The payout pipeline
-### Webhook handling
+`@mercurjs/core` ships the workflows, not a schedule. Something has to call `createOrderPayoutsWorkflow` and `createPayoutReversalsWorkflow`:
-A subscriber listens for `payout.webhook_received` events and delegates to the `processPayoutForWebhookWorkflow`. The provider parses the raw webhook payload and returns an action:
+- **With the Stripe connector plugin**, its jobs do it: they capture the cart payment once every seller order is decided, pay out fulfilled and captured orders every five minutes, reverse refunds, net a nightly settlement per seller, and send it to the seller's bank. Subscribers on fulfillment, cancellation, capture, and refunds run the passes right away. See [Stripe Connect](/resources/integrations/stripe-connect/overview).
+- **With another provider**, call the workflows from your own job or subscriber. They're safe to run repeatedly: an order already paid is never paid again.
+
+### Webhook handling
-**Account events:**
-- `account.activated` → Status set to `ACTIVE`
-- `account.restricted` → Status set to `RESTRICTED`
-- `account.rejected` → Status set to `REJECTED`
+The provider posts to `/hooks/payout`. A subscriber listens for `payout.webhook_received`, the provider parses the payload into an action, and `processPayoutForWebhookWorkflow` applies it:
-**Payout events:**
-- `payout.processing` → Status set to `PROCESSING`
-- `payout.paid` → Status set to `PAID`
-- `payout.failed` → Status set to `FAILED`
-- `payout.canceled` → Status set to `CANCELED`
+- `account.*` → the account is re-read from the provider, and its status, flags, and KYC status are stored
+- `payout.paid` → the payout is set to `PAID` and keeps the provider's payout id for later reversals
+- `payout.failed` → the payout is set to `FAILED` with `status_reason: "provider_error"`
## Configuration
-The payout module accepts the following options in `medusa-config.ts`:
+The payout module accepts these options in `medusa-config.ts`, plus exactly one entry in `providers`:
| Option | Default | Description |
|--------|---------|-------------|
-| `disabled` | `false` | Disables both scheduled jobs |
-| `authorizationWindowMs` | 7 days | How long a payment authorization is valid |
-| `sellerActionWindowMs` | 72 hours | Time for seller to fulfill the order |
-| `captureSafetyBufferMs` | 24 hours | Safety margin before authorization expiry to trigger capture |
-| `requiredFulfillmentStatus` | `"fulfilled"` | Minimum fulfillment status before capture is allowed |
+| `onboarding.returnUrl` | - | Where the provider sends the seller after onboarding |
+| `onboarding.refreshBaseUrl` | - | API origin of the public refresh URL for expired onboarding links |
+| `onboarding.prefill` | `false` | Prefill the provider's forms from the seller's profile |
+| `onboarding.defaultCountry` | - | Country used when the seller has no address |
+| `onboarding.tokenTtlSeconds` | `86400` | How long the token in an onboarding refresh URL stays valid. Each refresh rotates it |
+
+Scheduling options, such as the capture window and the required fulfillment status, belong to the integration that runs the payouts.
## Data model overview
```
PayoutAccount
├── Onboarding (one-to-one)
-└── Payout (one-to-many, per-order transfers)
+└── Payout (one-to-many, one per order)
+ └── PayoutReversal (one-to-many, one per refund)
```
## Configuration example
@@ -120,19 +95,22 @@ PayoutAccount
```typescript
// medusa-config.ts
{
- resolve: "./modules/payout",
+ resolve: "@mercurjs/core/modules/payout",
options: {
- // How long payment authorizations are valid
- authorizationWindowMs: 7 * 24 * 60 * 60 * 1000, // 7 days
-
- // Time for seller to fulfill before capture
- sellerActionWindowMs: 72 * 60 * 60 * 1000, // 72 hours
-
- // Safety margin before authorization expiry
- captureSafetyBufferMs: 24 * 60 * 60 * 1000, // 24 hours
-
- // Minimum fulfillment status before capture
- requiredFulfillmentStatus: "fulfilled",
+ providers: [
+ {
+ resolve: "@mercurjs/stripe-connector-plugin/providers/payout-stripe-connect",
+ id: "stripe",
+ options: {
+ apiKey: process.env.STRIPE_SECRET_KEY,
+ webhookSecret: process.env.STRIPE_SELLERS_WEBHOOK_SECRET,
+ },
+ },
+ ],
+ onboarding: {
+ returnUrl: `${process.env.VENDOR_URL}/stripe`,
+ refreshBaseUrl: process.env.BACKEND_URL,
+ },
},
}
```
@@ -148,18 +126,13 @@ curl http://localhost:9000/vendor/payout-accounts/<account-id> \
### Create payout onboarding (Vendor API)
-Initiates provider onboarding (e.g. Stripe Connect account setup). The `data` and `context` fields are passed to the payout provider:
+Initiates provider onboarding (e.g. Stripe Connect account setup). `refresh_url` and `return_url` come from the module's `onboarding` options:
```bash
curl -X POST http://localhost:9000/vendor/payout-accounts/<account-id>/onboarding \
-H "Authorization: Bearer <seller-token>" \
-H "Content-Type: application/json" \
- -d '{
- "data": {
- "refresh_url": "https://my-store.com/settings/payouts",
- "return_url": "https://my-store.com/settings/payouts"
- }
- }'
+ -d '{}'
```
### List payouts (Admin API)
@@ -173,4 +146,4 @@ curl http://localhost:9000/admin/payouts \
The payout module is **provider-agnostic**. A `PayoutProviderService` acts as a bridge to the external payment processor. It delegates all external operations — creating accounts, processing payouts, parsing webhooks — to a pluggable provider implementation.
-The module expects exactly one payout provider to be registered. Provider-specific data is stored in the `data` JSON fields on accounts, payouts, and onboarding records.
+The module expects exactly one payout provider per marketplace, and loads the built-in `system` provider when none is registered. Provider-specific data is stored in the `data` JSON fields on accounts, payouts, reversals, and onboarding records.
diff --git a/apps/docs/platform/commission/concepts/order-commission-lines.mdx b/apps/docs/platform/commission/concepts/order-commission-lines.mdx
index 514b8141a..a13a2e567 100644
--- a/apps/docs/platform/commission/concepts/order-commission-lines.mdx
+++ b/apps/docs/platform/commission/concepts/order-commission-lines.mdx
@@ -58,7 +58,7 @@ Computed lines carry no `id`. The module’s `upsertCommissionLines` first delet
## How payouts use the lines
-`createPayoutWorkflow` reads every commission line whose `item_id` or `shipping_method_id` belongs to the order. It sums their `amount` and transfers the order `total` minus that sum to the seller’s payout account. With the lines from the [overview figure](/platform/commission/overview), an order total of € 92.00 and commission of € 10.14 pays the seller € 81.86.
+`createOrderPayoutsWorkflow` reads every commission line whose `item_id` or `shipping_method_id` belongs to the order. It sums their `amount` and pays the order `total` minus that sum to the seller’s payout account. A refund taken back later is reduced by its share of the same sum. With the lines from the [overview figure](/platform/commission/overview), an order total of € 92.00 and commission of € 10.14 pays the seller € 81.86.
## Related
diff --git a/apps/docs/platform/commission/reference/links.mdx b/apps/docs/platform/commission/reference/links.mdx
index e5f5a7ca0..4b6c47ce8 100644
--- a/apps/docs/platform/commission/reference/links.mdx
+++ b/apps/docs/platform/commission/reference/links.mdx
@@ -43,7 +43,7 @@ const { data: lines } = await query.graph({
})
```
-`createPayoutWorkflow` and the order commission-lines routes read lines the same way.
+`createOrderPayoutsWorkflow` and the order commission-lines routes read lines the same way.
## Lines point at their rate
diff --git a/apps/docs/platform/payout/concepts/account-lifecycle.mdx b/apps/docs/platform/payout/concepts/account-lifecycle.mdx
index 214859588..64198b932 100644
--- a/apps/docs/platform/payout/concepts/account-lifecycle.mdx
+++ b/apps/docs/platform/payout/concepts/account-lifecycle.mdx
@@ -1,69 +1,84 @@
---
title: "Payout account and payout statuses"
sidebarTitle: "Account lifecycle"
-description: "The statuses a payout account and a payout move through, and the provider webhooks that move them."
+description: "The statuses a payout account, a payout, and a reversal move through, and the provider webhooks that move them."
---
-A payout account’s status says whether the seller can receive money, and a payout’s status says where one transfer stands. Neither is set by an operator. The provider decides, sends a webhook, and `processPayoutForWebhookWorkflow` writes the new status. Read this page to know when `createPayoutWorkflow` will accept an account, and what each webhook does.
+A payout account’s status says whether the seller can receive money, and a payout’s status says where one order’s payout stands. Neither is set by an operator. The provider decides, sends a webhook, and Mercur re-reads the provider’s view. Read this page to know when `createOrderPayoutsWorkflow` will pay an account, and what each webhook does.
## Account statuses
-An account’s state is the `status` field on `PayoutAccount`, typed by the `PayoutAccountStatus` enum from `@mercurjs/types`. It defaults to `pending`, and the provider’s `createPayoutAccount` response can overwrite it.
+An account’s state is the `status` field on `PayoutAccount`, typed by the `PayoutAccountStatus` enum from `@mercurjs/types`. It defaults to `pending`.
| Status | Value | Meaning |
| --- | --- | --- |
-| `PENDING` | `pending` | Created, setup not finished |
-| `ACTIVE` | `active` | Can receive payouts |
-| `RESTRICTED` | `restricted` | Missing information or a compliance issue |
+| `PENDING` | `pending` | Created, details not submitted yet |
+| `ACTIVE` | `active` | Payouts and charges enabled, nothing outstanding |
+| `RESTRICTED` | `restricted` | Details submitted, but the provider disabled something |
| `REJECTED` | `rejected` | Permanently disabled by the provider |
-Only `active` matters to the rest of the module. `createPayouts` throws `Account 'pacc_…' is not active` for any other status, so a payout never starts on a pending, restricted, or rejected account.
+The account also mirrors the provider’s flags: `payouts_enabled`, `charges_enabled`, `details_submitted`, `disabled_reason`, and a derived `kyc_status` (`pending_submission`, `pending_approval`, `approved`, `refused`). `createOrderPayoutsWorkflow` checks `payouts_enabled` and holds the payout until it’s `true`.
-## Webhooks set the account status
+## How the status is derived
-The provider owns the account status, and a webhook carries each change. The provider’s `getWebhookActionAndData` turns a raw webhook into an action and the `pacc` id it applies to. `processPayoutForWebhookWorkflow` then runs the matching step.
+Mercur doesn’t take a status from the webhook body. It asks the provider for the account with `retrieveAccount` and derives the status from what comes back:
-<img className="block dark:hidden" src="/images/figures/payout-account-lifecycle-light.svg" alt="A Stripe account.updated webhook behind the process-payout-for-webhook workflow. The workflow maps account.activated to the activate-payout-account step and the Active status, account.restricted to Restricted, account.rejected to Rejected, and not_supported to no change." />
-<img className="hidden dark:block" src="/images/figures/payout-account-lifecycle-dark.svg" alt="A Stripe account.updated webhook behind the process-payout-for-webhook workflow. The workflow maps account.activated to the activate-payout-account step and the Active status, account.restricted to Restricted, account.rejected to Rejected, and not_supported to no change." />
+1. `rejected` when the provider says so, or `disabled_reason` starts with `rejected`
+2. `pending` while `details_submitted` is `false`
+3. `active` when payouts and charges are enabled and there’s no `disabled_reason`
+4. `restricted` in every other case
-The workflow doesn’t check the current status before it writes. Any action can move an account from any status, so the provider’s view always wins:
-
-| Action | Step | New status |
-| --- | --- | --- |
-| `account.activated` | `activate-payout-account` | `active` |
-| `account.restricted` | `restrict-payout-account` | `restricted` |
-| `account.rejected` | `reject-payout-account` | `rejected` |
-| `not_supported` | none | unchanged |
+`kyc_status` follows the requirements: anything currently or past due is `pending_submission`, anything pending verification is `pending_approval`, a `rejected.*` disabled reason is `refused`, and an account with nothing outstanding is `approved`.
-Each step is `updatePayoutAccountStep`, renamed with `.config({ name })`. It saves the previous status and restores it if the workflow rolls back.
+## Webhooks refresh the account
-## How Stripe Connect maps account updates
+The provider’s `getWebhookActionAndData` turns a raw webhook into an action and the **provider’s** account id. `processPayoutForWebhookWorkflow` finds the account by `external_id` and runs `syncPayoutAccountWorkflow`, which:
-The Stripe Connect provider handles only Stripe’s `account.updated` event, and it reads the `pacc` id from the Stripe account’s `metadata.account_id`. It picks the action in this order:
+1. Re-reads the account from the provider and stores the derived status, flags, and `kyc_status`
+2. Swaps the onboarding link for a provider dashboard login link once details are submitted
+3. Emits `payout_account.updated` with the account id
-1. `account.rejected` when `requirements.disabled_reason` starts with `rejected.`
-2. `account.activated` when every enabled `accountValidation` check passes
-3. `account.restricted` in every other case
+<img className="block dark:hidden" src="/images/figures/payout-account-lifecycle-light.svg" alt="A Stripe account.updated webhook behind the process-payout-for-webhook workflow. The workflow maps account.activated to the activate-payout-account step and the Active status, account.restricted to Restricted, account.rejected to Rejected, and not_supported to no change." />
+<img className="hidden dark:block" src="/images/figures/payout-account-lifecycle-dark.svg" alt="A Stripe account.updated webhook behind the process-payout-for-webhook workflow. The workflow maps account.activated to the activate-payout-account step and the Active status, account.restricted to Restricted, account.rejected to Rejected, and not_supported to no change." />
-The default checks are `detailsSubmitted`, `chargesEnabled`, `payoutsEnabled`, and `noOutstandingRequirements`, all `true`, with no `requiredCapabilities`.
+Every `account.*` action runs the same sync, so the provider’s current view always wins, whatever order the webhooks arrive in. You can run the same sync by hand with `POST /admin/payout-accounts/:id/sync`.
-<Note>
- With Stripe Connect, an account can skip `pending` and go to `restricted` first. Stripe sends `account.updated` while the seller is still onboarding, and an account with outstanding requirements maps to `account.restricted`. It becomes `active` on a later update.
-</Note>
+The Stripe Connect provider handles Stripe’s `account.updated` event and reports `account.rejected`, `account.activated`, `account.restricted`, or `account.updated`, depending on the account it receives.
## Payout statuses
-Each payout carries its own `PayoutStatus`. The module creates the row as `pending`, then stores the status the provider’s `createPayout` returns.
+Each payout and each reversal carries a `PayoutStatus`:
| Status | Value | Set by |
| --- | --- | --- |
-| `PENDING` | `pending` | Row creation |
-| `PROCESSING` | `processing` | A `payout.processing` webhook |
+| `PENDING` | `pending` | Every check passed; the payout is about to be sent |
+| `ON_HOLD` | `on_hold` | A check failed that can still pass later, such as an uncaptured payment |
+| `PROCESSING` | `processing` | The provider accepted the payout but hasn’t settled it |
| `PAID` | `paid` | The provider response or a `payout.paid` webhook |
-| `FAILED` | `failed` | A `payout.failed` webhook |
-| `CANCELED` | `canceled` | A `payout.canceled` webhook |
+| `FAILED` | `failed` | A provider error, or a `payout.failed` webhook |
+| `ABORTED` | `aborted` | A canceled order or payment, a non-positive amount, or a final provider error |
-The Stripe Connect provider returns `paid` as soon as Stripe creates the transfer, and it maps no Stripe event to a `payout.*` action. The `payout.*` branches exist for providers that settle asynchronously.
+`status_reason` holds a stable code that says why a payout or reversal is `on_hold`, `failed`, or `aborted`, from `PayoutStatusReason` in `@mercurjs/types`. The details behind it, such as an id, a status, or the provider’s error message, are in `data.status_detail`, for example `Order is not ready yet, status is not_fulfilled`.
+
+| Code | Status | Meaning |
+| --- | --- | --- |
+| `account_not_ready` | `on_hold` | The seller has no payout account |
+| `account_payouts_disabled` | `on_hold` | The provider hasn’t enabled payouts on the account |
+| `order_not_ready` | `on_hold` | The order isn’t fulfilled far enough yet |
+| `order_aborted` | `aborted` | The order is canceled |
+| `payment_not_ready` | `on_hold` | The payment is missing or not captured yet |
+| `payment_failed` | `aborted` | The payment failed |
+| `payment_canceled` | `aborted` | The payment was canceled |
+| `payment_refunded` | `aborted` | The payment was refunded in full |
+| `payout_not_ready` | `on_hold` | A reversal waits for its payout to be paid |
+| `refund_aborted` | `aborted` | A reversal’s payout was aborted |
+| `refund_absorbed` | `aborted` | The refund was deducted from the payout before it was sent |
+| `invalid_amount` | `aborted` | The amount to send isn’t positive |
+| `provider_error` | `failed`, `aborted` | The provider threw or a `payout.failed` webhook arrived |
+
+`on_hold` and `failed` payouts are re-decided by the next `createOrderPayoutsWorkflow` run, and operators can retry one, or a `pending` one, with `POST /admin/payouts/:id/retry`. A canceled order’s payout is aborted even when the seller has no usable account yet. `paid`, `processing`, and `aborted` payouts are never sent again.
+
+The Stripe Connect provider returns `paid` as soon as Stripe creates the transfer, so no webhook is needed to confirm it. Transfers are platform-account events and never reach the Connect endpoint.
## Related
diff --git a/apps/docs/platform/payout/concepts/accounts-and-onboarding.mdx b/apps/docs/platform/payout/concepts/accounts-and-onboarding.mdx
index 64058656d..2619e457e 100644
--- a/apps/docs/platform/payout/concepts/accounts-and-onboarding.mdx
+++ b/apps/docs/platform/payout/concepts/accounts-and-onboarding.mdx
@@ -10,7 +10,7 @@ A payout account is a seller’s connection to the payout provider, and onboardi
A payout account is the record a payout is sent to. It’s the `PayoutAccount` data model (table `payout_account`, id prefix `pacc`), and the `seller_payout_account` link ties it to exactly one seller.
-You create one with `createPayoutAccountWorkflow`. The workflow checks the seller has no account yet, asks the module to create the account, and links it to the seller:
+You create one with `createPayoutAccountWorkflow`. The workflow checks the seller has no account yet, asks the module to create the account with the seller's profile, links it to the seller, and publishes the first onboarding link:
```ts
import { createPayoutAccountWorkflow } from "@mercurjs/core/workflows"
@@ -26,20 +26,24 @@ const { result } = await createPayoutAccountWorkflow(container).run({
Inside the module, `createPayoutAccount` runs 3 writes in order:
1. Create the `PayoutAccount` row with your `data` and `context`
-2. Call the provider’s `createPayoutAccount` with `data.account_id` set to the new `pacc` id and `context.idempotency_key` defaulting to the same id
-3. Overwrite the row’s `data` and `status` with what the provider returns
+2. Call the provider’s `createAccount` with `data.account_id` and `metadata.account_id` set to the new `pacc` id, and `context.idempotency_key` defaulting to the same id
+3. Store the provider’s account id as `external_id`, its flags, the derived `status` and `kyc_status`, and its `data`
-If the provider call throws, the module deletes the new row and rethrows. The Stripe Connect provider returns `pending` and the full Stripe account object. The built-in `system` provider returns `active` and an empty object.
+If the provider call throws before an account exists, the module deletes the new row and rethrows. The Stripe Connect provider creates an Express account and returns it as `pending`. The built-in `system` provider returns an `active` account at once.
+
+With the `onboarding.prefill` option, the module also passes the seller’s name, website, email, phone, country, and business type, so the provider can prefill its forms. `onboarding.defaultCountry` applies when the seller has no address.
+
+`createOrRefreshSellerPayoutAccountWorkflow` does this for one seller only when needed: it creates the account when it’s missing, and otherwise publishes a fresh onboarding link until the seller has submitted their details. Run it again as often as you like.
<Note>
- A seller can have only one payout account. `validateSellerPayoutAccountStep` queries `seller_payout_account` and fails with `Seller already has a payout account` when a row exists.
+ A seller can have only one payout account. `validateSellerWithoutPayoutAccountStep` fails with a `409` when the seller already has one.
</Note>
## Onboarding
Onboarding is the provider’s setup flow: identity checks, bank details, and anything else the provider needs. Its state lives in the `Onboarding` data model (table `onboarding`, id prefix `onb`), a one-to-one child of the payout account.
-`createOnboardingWorkflow` takes an `account_id` and calls the provider’s `createOnboarding`. The module merges the account’s stored `data` with the `data` you pass, so the provider sees both. With Stripe Connect, the account’s `data.id` is the Stripe account id, and you pass `refresh_url` and `return_url`:
+`createOnboardingWorkflow` takes an `account_id` and calls the provider’s `createOnboarding` with the account’s `external_id`, a `refresh_url`, and a `return_url`. By default both URLs come from the module’s `onboarding` options: `return_url` is `onboarding.returnUrl`, and `refresh_url` is `<onboarding.refreshBaseUrl>/payout/onboarding/refresh?token=<onboarding_token>`. Pass them in `data` to override:
```ts
import { createOnboardingWorkflow } from "@mercurjs/core/workflows"
@@ -55,7 +59,7 @@ const { result } = await createOnboardingWorkflow(container).run({
})
```
-The result’s `data` holds what the provider returned. For Stripe Connect, that’s an account link object, and `data.url` is the hosted onboarding page. The workflow is safe to re-run:
+The result’s `data` holds what the provider returned, plus `url`, `kind` (`onboarding` or `login`), and `expires_at`. For Stripe Connect, `data.url` is the hosted onboarding page. The workflow is safe to re-run:
- **First run**: creates the `Onboarding` record
- **Later runs**: update the same record with new provider data, which you need when a Stripe link expires
@@ -64,7 +68,7 @@ The result’s `data` holds what the provider returned. For Stripe Connect, that
Every payout record has a `data` JSON field, and accounts and onboarding records also have `context`. They play different roles:
-- **`data`**: the provider’s durable payload, such as the Stripe account, the account link, or the transfer
+- **`data`**: the provider’s durable payload, such as the Stripe account, the account link, or the transfer behind a payout
- **`context`**: per-call hints for the provider, today only `idempotency_key`
The module never interprets `data`. It passes it to the provider and stores what comes back. When you switch providers, the records keep the same shape.
diff --git a/apps/docs/platform/payout/concepts/payout-pipeline.mdx b/apps/docs/platform/payout/concepts/payout-pipeline.mdx
index 0a1e20474..85b9aef31 100644
--- a/apps/docs/platform/payout/concepts/payout-pipeline.mdx
+++ b/apps/docs/platform/payout/concepts/payout-pipeline.mdx
@@ -1,71 +1,84 @@
---
title: "How a payout reaches a seller"
sidebarTitle: "The payout pipeline"
-description: "What Mercur ships for payouts, what you trigger yourself, and how the provider interface fits in."
+description: "What core ships for payouts, what decides when they run, and how the provider interface fits in."
---
-The payout pipeline is the path from a placed order to money in a seller’s account. Mercur ships the building blocks: the workflows, the webhook route and subscriber, and the provider interface. It doesn’t ship the scheduler that decides when an order is paid out. You choose that moment and call `createPayoutWorkflow` yourself.
+The payout pipeline is the path from a placed order to money in a seller’s account. `@mercurjs/core` ships the building blocks: the workflows that decide and send payouts, the webhook route and subscriber, and the provider interface. It doesn’t ship a scheduler. The Stripe connector plugin brings one, and without it you call the workflows yourself.
## What ships in `@mercurjs/core`
The core plugin gives you every piece that talks to the provider or writes payout records:
-- **Workflows**: `createPayoutAccountWorkflow`, `createOnboardingWorkflow`, `createPayoutWorkflow`, and `processPayoutForWebhookWorkflow`
+- **Account workflows**: `createPayoutAccountWorkflow`, `createOrRefreshSellerPayoutAccountWorkflow`, `createOnboardingWorkflow`, and `syncPayoutAccountWorkflow`
+- **Payout workflows**: `createOrderPayoutsWorkflow`, `createPayoutReversalsWorkflow`, `processPayoutWorkflow`, and `processPayoutReversalWorkflow`
- **Webhook route**: `POST /hooks/payout` keeps the raw body and emits `payout.webhook_received` with a 5000 ms delay and 3 attempts
- **Webhook subscriber**: `payout-webhook` parses the event through the provider and runs `processPayoutForWebhookWorkflow`
-- **Providers**: the built-in `system` provider, plus `@mercurjs/payout-stripe-connect` as a separate package
+- **Admin and vendor routes**: payout accounts (`sync`, `refresh-link`, map an existing provider account) and payouts (list, detail, `POST /admin/payouts/:id/retry`)
+- **Providers**: the built-in `system` provider, plus `@mercurjs/stripe-connector-plugin` as a separate package
-## What you wire yourself
+## What decides when payouts run
-No scheduled job, subscriber, or route in core calls `createPayoutWorkflow`. Core also has no `jobs` directory, so nothing captures authorized payments on a timer.
+No scheduled job or subscriber in core calls `createOrderPayoutsWorkflow` or `createPayoutReversalsWorkflow`. Core has no `jobs` directory.
-`@mercurjs/types` exports a `PayoutEvents` enum with `order.capture_requested`, `order.authorization_expired`, and `payout.requested`, but nothing emits these events or subscribes to them. The enum carries a TODO to move them to order events. Treat the names as reserved, not as hooks you can listen to.
+The Stripe connector plugin owns the schedule. It ships seven jobs, `payout-sync-onboarding`, `payout-validate-captures`, `payout-process-transfers`, `payout-process-reversals`, `payout-process-settlements`, `payout-alert-failed-operations`, and `payout-monitor-kyc`, plus subscribers that run a payout pass on fulfillment, cancellation, payment capture, and refunds. It also owns settlements, operator adjustments, job runs, checkpoints, and the operator notification log, in its own `stripe_connector` module. See [Stripe Connect](/resources/integrations/stripe-connect/overview).
-The module options also describe a capture and payout schedule. `PayoutModuleOptions` and `PAYOUT_MODULE_OPTION_DEFAULTS` define them, and `getOptions()` returns them with defaults applied, but no core code reads them:
+If you build on another provider, schedule the workflows from your own job or subscriber.
-| Option | Default | Intended meaning |
-| --- | --- | --- |
-| `disabled` | `false` | Turn off capture checks and daily payouts |
-| `authorizationWindowMs` | `604800000` (7 days) | How long an authorization stays valid |
-| `sellerActionWindowMs` | `259200000` (72 hours) | How long a seller has to act on an order |
-| `captureSafetyBufferMs` | `86400000` (24 hours) | Margin before authorization expiry |
-| `requiredFulfillmentStatus` | `"fulfilled"` | Minimum fulfillment status for a payout |
+## How createOrderPayoutsWorkflow decides
+
+`createOrderPayoutsWorkflow` takes `order_ids` and an optional `required_fulfillment_status` (default `fulfilled`). For each order it loads the total, the fulfillments, the seller’s payout account, the payment, and the commission lines, then decides:
+
+| Check | When it fails |
+| --- | --- |
+| The seller has a payout account with payouts enabled | `on_hold`, `Cannot find payout account for seller …` |
+| The order isn’t canceled | `aborted` |
+| The order reached `required_fulfillment_status` | `on_hold`, `Order is not ready yet, status is …` |
+| The payment exists, isn’t canceled or fully refunded | `on_hold` or `aborted` |
+| The payment is captured | `on_hold`, `Payment … is not ready yet, status is authorized` |
+| Total minus commission is positive | `aborted`, `Amount must be positive, …` |
-<Tip>
- Read these options in your own job with `container.resolve(MercurModules.PAYOUT).getOptions()`. That keeps your schedule configurable from `medusa-config.ts`.
-</Tip>
+When every check passes, the payout is `pending` and the workflow sends it to the provider in the same run. The amount is the order total minus its commission lines. For an order with a total of 47.00 and 4.70 in commission lines, the payout amount is 42.30.
-## How createPayoutWorkflow computes the amount
+A refund that lands before the payout is deducted from it, with its share of the commission. The reversal pass then skips that refund.
-`createPayoutWorkflow` takes one `order_id` and pays the seller’s share of that order. It runs 4 stages:
+Each order gets at most one payout, because `order_id` is unique on `payout`. Running the workflow again re-decides payouts that are `on_hold` or `failed` and leaves `paid`, `processing`, and `aborted` ones alone, so it’s safe to call on a timer or from several subscribers.
-1. Load the order with `total`, `currency_code`, `seller.payout_account`, items, and shipping methods
-2. Load every `commission_line` for those items and shipping methods, then sum their `amount`
-3. Call `createPayoutStep` with `order.total` minus the commission sum, in the order’s currency
-4. Link the payout to the seller and run the `payoutCreated` hook with `order_id` and `payout_id`
+```ts
+import { createOrderPayoutsWorkflow } from "@mercurjs/core/workflows"
-For an order with a total of 47.00 and 4.70 in commission lines, the payout amount is 42.30. The workflow throws `Seller does not have a payout account` when the seller has none, and the module throws when the account isn’t `active`.
+const { result } = await createOrderPayoutsWorkflow(container).run({
+ input: { order_ids: ["order_01JD8Q1234567"] },
+})
+
+// result.counts, e.g. { paid: 1 } or { on_hold: 1 }
+// result.payouts, the payouts sent to the provider in this run
+```
-The provider receives the order id as its idempotency key. With Stripe Connect, the order id also becomes the transfer’s `transfer_group`, and the seller id goes into its metadata.
+## How reversals work
-<Warning>
- `createPayoutWorkflow` doesn’t check payment capture, fulfillment status, or earlier payouts for the order. Each run creates a new `Payout` row. Put those checks in the code that triggers it.
-</Warning>
+`createPayoutReversalsWorkflow` takes `order_ids`. For every refund on an order whose payout exists, it writes one `payout_reversal`, the way Medusa keeps a `Refund` under a `Payment`:
+
+- The amount is the refund minus its share of the commission: `refund − commission × refund / order total`
+- The reversal waits `on_hold` until the payout is `paid`
+- A refund already deducted from the payout is skipped
+
+The workflow then calls the provider’s `reversePayout`. Running it again leaves reversals that are already `paid` alone.
## Trigger payouts from your own code
-You decide when an order is ready. This subscriber pays out when Medusa emits `order.fulfillment_created`:
+Without the Stripe connector plugin, decide when an order is ready yourself. This subscriber runs a payout pass when Medusa emits `order.fulfillment_created`:
```ts title="src/subscribers/payout-on-fulfillment.ts"
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
-import { createPayoutWorkflow } from "@mercurjs/core/workflows"
+import { createOrderPayoutsWorkflow } from "@mercurjs/core/workflows"
export default async function payoutOnFulfillment({
event,
container,
}: SubscriberArgs<{ order_id: string }>) {
- await createPayoutWorkflow(container).run({
- input: { order_id: event.data.order_id },
+ await createOrderPayoutsWorkflow(container).run({
+ input: { order_ids: [event.data.order_id] },
})
}
@@ -74,7 +87,7 @@ export const config: SubscriberConfig = {
}
```
-This fires once per fulfillment, so a partially fulfilled order would be paid more than once. Before you ship it, add a guard that skips orders already paid and orders whose payment isn’t captured. A scheduled job in `src/jobs` that scans orders works the same way.
+A partially fulfilled order gets an `on_hold` payout that the next pass re-decides. A payment captured after fulfillment is picked up the same way, so pair the subscriber with a scheduled job that retries `on_hold` and `failed` payouts.
## The provider interface
@@ -82,15 +95,25 @@ Every external call goes through `IPayoutProvider` from `@mercurjs/types`. The m
| Method | Called by | Returns |
| --- | --- | --- |
-| `createPayoutAccount` | `createPayoutAccount` | Provider `id`, optional `status`, `data` |
-| `createOnboarding` | `createOnboarding` | `data`, such as a Stripe account link |
-| `createPayout` | `createPayouts` | Optional `status`, `data` |
+| `createAccount` | `createPayoutAccount` | An `AccountOutput`: provider `id`, `status`, flags, requirements, `data` |
+| `retrieveAccount` | `syncPayoutAccount` | An `AccountOutput` |
+| `deleteAccount` (optional) | `deletePayoutAccount`, when an account creation rolls back | Nothing |
+| `createOnboarding` | `createOnboarding` | A `LinkOutput`: `url`, `expires_at`, `data` |
+| `createLoginLink` (optional) | `createOnboarding`, once details are submitted | A `LinkOutput` for the provider dashboard |
+| `createPayout` | `processPayout` | A `PayoutOutput`: provider `id`, `status`, `data` |
+| `reversePayout` | `processPayoutReversal` | A `PayoutOutput` |
| `getWebhookActionAndData` | `getWebhookActionAndData` | A `PayoutWebhookResult` |
-When you register no provider, the module loads `system`. It returns `active` accounts and `paid` payouts without moving money, which suits local development and tests. Register Stripe Connect in `medusa-config.ts` with the [Stripe Connect integration](/resources/integrations/stripe-connect).
+Write a provider as a class that implements `IPayoutProvider` and has a static `identifier`; the module registers it under `pop_<identifier>_<id>`. Throw a `PayoutProviderError` from `createPayout` or `reversePayout` to tell the module what happened:
+
+- `{ code: PayoutProviderErrorCode.REFUSED }` when the provider rejected the request and created nothing, such as a validation or balance error. The row is `failed` and the retry gets a new idempotency key.
+- `{ code: PayoutProviderErrorCode.FINAL }` (or `{ final: true }`) when a retry can’t succeed. The row is `aborted`.
+- Anything else, including a plain `Error` from a timeout, counts as an unknown outcome. The row is `failed` and the retry reuses the idempotency key, so a payout the provider did make isn’t made twice.
+
+When you register no provider, the module loads `system`. It returns `active` accounts and `paid` payouts without moving money, which suits local development and tests. Register Stripe Connect in `medusa-config.ts` with the [Stripe Connect integration](/resources/integrations/stripe-connect/overview).
## Related
- [Account lifecycle](/platform/payout/concepts/account-lifecycle) for the statuses the webhooks set
-- [Workflows reference](/platform/payout/reference/workflows) for the `payoutCreated` hook
+- [Workflows reference](/platform/payout/reference/workflows) for inputs, steps, and the `payoutsCreated` hook
- [Order commission lines](/platform/commission/concepts/order-commission-lines) for where the commission sum comes from
diff --git a/apps/docs/platform/payout/guides/create-a-payout-account.mdx b/apps/docs/platform/payout/guides/create-a-payout-account.mdx
index 52dc12423..ff287f1ab 100644
--- a/apps/docs/platform/payout/guides/create-a-payout-account.mdx
+++ b/apps/docs/platform/payout/guides/create-a-payout-account.mdx
@@ -12,7 +12,7 @@ You need:
- A seller id, such as `sel_01JD8Q1234567`
- A payout provider. Without one, the `system` provider creates accounts that are `active` at once
-- For Stripe Connect, `@mercurjs/payout-stripe-connect` registered on the payout module, as in the [Stripe Connect integration](/resources/integrations/stripe-connect)
+- For Stripe Connect, `@mercurjs/stripe-connector-plugin/providers/payout-stripe-connect` registered on the payout module, as in the [Stripe Connect integration](/resources/integrations/stripe-connect/configuration)
## Create the account
@@ -44,10 +44,10 @@ You need:
}
```
- The workflow validates the seller has no account, creates it through the provider, and links it to the seller. The response returns only the id, because `result.data` holds the full provider object.
+ The workflow validates the seller has no account, creates it through the provider, links it to the seller, and publishes the onboarding link. The response returns only the id, because `result.data` holds the full provider object.
</Step>
<Step title="Call the route">
- Send the seller’s country. Stripe Connect requires `country` and throws `"country" is required` without it:
+ Send the seller’s country. The module passes `data.country` to the provider, falling back to the seller’s address and then the `onboarding.defaultCountry` option:
```bash
curl -X POST http://localhost:9000/admin/payout-setup/sel_01JD8Q1234567 \
@@ -56,7 +56,7 @@ You need:
-d '{ "country": "US" }'
```
- With Stripe Connect, the new account is `pending` and its `data` holds the Express account Stripe created.
+ With Stripe Connect, the new account is `pending`, `external_id` holds the Stripe `acct_…` id, and `data` holds the Express account Stripe created.
</Step>
</Steps>
@@ -74,7 +74,9 @@ const { data: [seller] } = await query.graph({
## What happens when the provider call fails
-The module creates the `PayoutAccount` row before it calls the provider. If the provider throws, the module deletes that row and rethrows, so no orphaned account is left. The provider receives the new `pacc` id as `data.account_id` and as the default `context.idempotency_key`. Stripe Connect stores that id in the Stripe account’s `metadata.account_id`, which is how webhooks find the account later.
+The module creates the `PayoutAccount` row before it calls the provider. If the provider throws, the module deletes that row and rethrows, so no orphaned account is left. The provider receives the new `pacc` id as `data.account_id`, `metadata.account_id`, and the default `context.idempotency_key`, so a retried call doesn’t create a second provider account. Webhooks find the account later by its `external_id`.
+
+If you already have an account at the provider, map it instead of creating one: `POST /admin/payout-accounts` with `seller_id` and `external_id` links it to the seller and syncs it from the provider.
## Next steps
diff --git a/apps/docs/platform/payout/guides/process-a-provider-webhook.mdx b/apps/docs/platform/payout/guides/process-a-provider-webhook.mdx
index 45eed3951..f69cc88da 100644
--- a/apps/docs/platform/payout/guides/process-a-provider-webhook.mdx
+++ b/apps/docs/platform/payout/guides/process-a-provider-webhook.mdx
@@ -20,10 +20,10 @@ Mercur ships the route, the subscriber, and the workflow. You point the provider
<Steps>
<Step title="Point the provider at /hooks/payout">
- In production, add a Stripe webhook endpoint for events on connected accounts, with the URL `https://your_backend_url/hooks/payout` and the `account.updated` event. Locally, forward Connect events with the Stripe CLI:
+ In production, add a Stripe webhook endpoint for events on connected accounts, with the URL `https://your_backend_url/hooks/payout` and the `account.updated` event. The Stripe connector plugin also needs the bank `payout.*` events, see [its webhooks](/resources/integrations/stripe-connect/configuration#webhooks). Locally, forward Connect events with the Stripe CLI:
```bash
- stripe listen --events account.updated \
+ stripe listen --events account.updated,payout.paid,payout.failed,payout.canceled,payout.updated \
--forward-connect-to localhost:9000/hooks/payout
```
@@ -33,9 +33,13 @@ Mercur ships the route, the subscriber, and the workflow. You point the provider
The route emits `payout.webhook_received` with the body, raw body, and headers. It delays the event by 5000 ms and retries up to 3 times. The shipped `payout-webhook` subscriber then parses it and runs the workflow:
```ts title="src/subscribers/payout-webhook.ts (in @mercurjs/core)"
- const processedEvent = await payoutService.getWebhookActionAndData(input)
+ const processedEvent = await payoutService.getWebhookActionAndData({
+ data: input.data as Record<string, unknown>,
+ rawData: input.rawData,
+ headers: input.headers as Record<string, unknown>,
+ })
- if (!processedEvent.data) {
+ if (!processedEvent.data || processedEvent.action === "not_supported") {
return
}
@@ -58,13 +62,13 @@ Mercur ships the route, the subscriber, and the workflow. You point the provider
)
```
- The `status` is `active`, `restricted`, or `rejected`, depending on what Stripe reported.
+ The workflow re-read the account from Stripe, so `status`, `payouts_enabled`, `kyc_status`, and `last_synced_at` match Stripe’s current view.
</Step>
</Steps>
## Run the workflow directly
-`processPayoutForWebhookWorkflow` takes a `PayoutWebhookResult`, so you can apply a status change without a webhook, for example in a test or a backfill script:
+`processPayoutForWebhookWorkflow` takes a `PayoutWebhookResult`, so you can apply a provider event without a webhook, for example in a test or a backfill script:
```ts
import { processPayoutForWebhookWorkflow } from "@mercurjs/core/workflows"
@@ -72,25 +76,25 @@ import { processPayoutForWebhookWorkflow } from "@mercurjs/core/workflows"
await processPayoutForWebhookWorkflow(container).run({
input: {
action: "payout.paid",
- data: { id: "pout_01JD8Q1234567" },
+ data: { id: "tr_1QxYz" },
},
})
```
-The workflow runs at most one step: the one that matches `action`. An `account.*` action needs a `pacc` id, and a `payout.*` action needs a `pout` id. A missing `data.id` or the `not_supported` action changes nothing.
+`data.id` is the **provider’s** id. An `account.*` action looks the account up by `external_id` and re-syncs it from the provider. `payout.paid` and `payout.failed` carry Mercur’s payout id in `data.payout_id`, which providers echo from the `payout_id` metadata sent with the payout, and set that payout’s status. `payout.paid` also stores `data.id` as the payout’s `data.provider.id`, which a later reversal is sent against; `payout.failed` stores `status_reason: "provider_error"` with the webhook’s `data.status_reason` in `data.status_detail`. Any other action, an unknown id, or a missing `data.id` changes nothing.
## Map webhooks in your own provider
-When you write a provider, `getWebhookActionAndData` decides what each webhook means. Return the action and the Mercur id, not the provider’s id:
+When you write a provider, `getWebhookActionAndData` decides what each webhook means. Return the action and the provider’s own id for the account or payout:
```ts title="src/providers/acme-payouts/service.ts"
async getWebhookActionAndData(
payload: PayoutWebhookActionInput
): Promise<PayoutWebhookResult> {
- const body = payload.data as { type: string; reference: string }
+ const body = payload.data as { type: string; transfer_id: string }
if (body.type === "transfer.settled") {
- return { action: "payout.paid", data: { id: body.reference } }
+ return { action: "payout.paid", data: { id: body.transfer_id } }
}
return { action: "not_supported" }
@@ -101,7 +105,7 @@ Verify the provider’s signature here with `payload.rawData` and `payload.heade
## Emit the event from another route
-If your provider must post to a different URL, emit `payout.webhook_received` yourself with the same shape. The shipped subscriber picks it up:
+If your provider must post to a different URL, emit `payout.webhook_received` yourself with the same shape. The shipped subscriber picks it up, and so does any other subscriber on that event, such as the Stripe connector plugin’s handler for bank payout events:
```ts
const eventBus = container.resolve(Modules.EVENT_BUS)
diff --git a/apps/docs/platform/payout/guides/start-provider-onboarding.mdx b/apps/docs/platform/payout/guides/start-provider-onboarding.mdx
index e38ca0936..4f978e270 100644
--- a/apps/docs/platform/payout/guides/start-provider-onboarding.mdx
+++ b/apps/docs/platform/payout/guides/start-provider-onboarding.mdx
@@ -11,7 +11,7 @@ Create or refresh a seller’s onboarding link from server code, so they can fin
You need:
- A payout account for the seller, created with [Create a payout account](/platform/payout/guides/create-a-payout-account)
-- For Stripe Connect, a `refresh_url` and a `return_url` in your vendor app
+- `onboarding.returnUrl` and `onboarding.refreshBaseUrl` set on the payout module, or your own `refresh_url` and `return_url`
## Create the onboarding link
@@ -38,7 +38,7 @@ You need:
```
</Step>
<Step title="Run the workflow from a route">
- Pass the URLs in `data`. The module merges them with the account’s stored `data`, which carries the Stripe account `id`:
+ The module fills in `refresh_url` and `return_url` from its `onboarding` options. Pass them in `data` only to override those defaults:
```ts title="src/api/admin/payout-setup/[id]/onboarding/route.ts"
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
@@ -66,27 +66,28 @@ You need:
}
```
- For Stripe Connect, `result.data` is the Stripe account link, and `url` is the page you redirect the seller to.
+ `result.data.url` is the page you redirect the seller to. For Stripe Connect, the rest of `result.data` is the Stripe account link.
</Step>
</Steps>
## Refresh an expired link
-Stripe account links expire. Call the same route again: the module finds the account’s existing `Onboarding` record and updates its `data` instead of creating a second one. Point `refresh_url` at a page in your vendor app that calls this route, so Stripe can send the seller back for a fresh link.
+Provider onboarding links expire. Call the same route again: the module finds the account’s existing `Onboarding` record and updates its `data` instead of creating a second one.
-## Required data for Stripe Connect
+The default `refresh_url` already handles this. It points at core’s public `GET /payout/onboarding/refresh?token=<onboarding_token>` route, which creates a fresh link for the account that owns the token and redirects the seller to it. The module's `createOnboarding` sets the `onboarding_token` before it publishes the first link. Each refresh rotates the token, so a refresh URL works once, and a token older than `onboarding.tokenTtlSeconds` (24 hours by default) is rejected with `400`; the seller then gets a new link from the vendor panel.
-The Stripe Connect provider checks 3 values and throws a `MedusaError` of type `INVALID_DATA` when one is missing:
+## Where Stripe Connect reads its inputs
-- **`id`**: the Stripe account id, read from the payout account’s stored `data`
-- **`refresh_url`**: where Stripe sends the seller when the link is no longer valid
-- **`return_url`**: where Stripe sends the seller after they leave the flow
+The Stripe Connect provider uses:
-Put the URLs in `data`, not `context`. The module forwards `context` to the provider, but Stripe Connect reads the URLs only from `data`.
+- **The account**: the payout account’s `external_id`, the Stripe `acct_…` id
+- **`refresh_url`** and **`return_url`**: from the module’s defaults or your `data`
+
+It requests the Express capabilities first when the account doesn’t have them yet, then creates an `account_onboarding` account link.
## The account becomes active by webhook
-Finishing onboarding doesn’t change the account by itself. Stripe sends `account.updated`, the `payout-webhook` subscriber maps it to an action, and `processPayoutForWebhookWorkflow` sets the status.
+Finishing onboarding doesn’t change the account by itself. Stripe sends `account.updated`, the `payout-webhook` subscriber maps it to an action, and `processPayoutForWebhookWorkflow` re-reads the account from Stripe and stores its new status. Once the seller has submitted their details, the onboarding record switches to a Stripe dashboard login link.
## Next steps
diff --git a/apps/docs/platform/payout/overview.mdx b/apps/docs/platform/payout/overview.mdx
index 3a86ab1dd..334ec2b68 100644
--- a/apps/docs/platform/payout/overview.mdx
+++ b/apps/docs/platform/payout/overview.mdx
@@ -1,12 +1,12 @@
---
title: "Payouts"
sidebarTitle: "Overview"
-description: "Connect each seller to a payout provider, onboard them, and transfer their share of an order to their own account."
+description: "Connect each seller to the marketplace's payout provider, onboard them, and pay their share of each order to their own account."
---
Use Mercur to connect each seller to a payment provider and send them their share of every order.
-A payout is a transfer from the marketplace to one seller, for one order. The Payout module holds 3 records: the seller’s payout account, its onboarding state, and the payouts made to it. Every external call goes through a single payout provider. Stripe Connect ships as a package, and a built-in `system` provider runs when you register none.
+A payout is the seller’s share of one order, sent from the marketplace to the seller’s account. The Payout module holds 4 records: the seller’s payout account, its onboarding state, the payouts made to it, and the reversals that take a refunded share back. Every external call goes through the one payout provider the marketplace registers. Stripe Connect ships as a plugin, and a built-in `system` provider runs when you register none.
<img className="block dark:hidden" src="/images/figures/payout-overview-light.svg" alt="A Payouts list in front of a Payout accounts list. Payout #12 for ACME is accented: an order total of € 47.00 minus € 4.70 commission gives a € 42.30 payout, marked Paid. Behind it, ACME's payout account is Active and GLOBEX's is Restricted." />
<img className="hidden dark:block" src="/images/figures/payout-overview-dark.svg" alt="A Payouts list in front of a Payout accounts list. Payout #12 for ACME is accented: an order total of € 47.00 minus € 4.70 commission gives a € 42.30 payout, marked Paid. Behind it, ACME's payout account is Active and GLOBEX's is Restricted." />
@@ -17,32 +17,33 @@ A payout is a transfer from the marketplace to one seller, for one order. The Pa
## Key features
-The Payout module covers a seller’s connection to the provider and each transfer made through it:
+The Payout module covers a seller’s connection to the provider and the money sent through it:
-- **One provider interface**: `IPayoutProvider` has 4 methods, and the module loads exactly one implementation
-- **Stripe Connect provider**: `@mercurjs/payout-stripe-connect` creates Express accounts, onboarding links, and transfers
+- **One provider per marketplace**: the module loads exactly one `IPayoutProvider`, shaped like Medusa’s payment providers
+- **Stripe Connect plugin**: `@mercurjs/stripe-connector-plugin` creates Express accounts, onboarding and login links, and pays each payout as a Connect transfer
- **One account per store**: `createPayoutAccountWorkflow` refuses a second account for the same seller
- **Re-runnable onboarding**: `createOnboardingWorkflow` creates the onboarding record once and updates it after that
-- **Webhook-driven statuses**: provider webhooks move accounts and payouts between statuses through `processPayoutForWebhookWorkflow`
-- **Commission-aware amounts**: `createPayoutWorkflow` pays the order total minus the order’s commission lines
+- **One payout per order**: `createOrderPayoutsWorkflow` pays the order total minus the order’s commission lines, puts orders that aren’t ready on hold, and never pays an order twice
+- **Reversals like refunds**: `createPayoutReversalsWorkflow` takes each later refund’s share back, net of its commission
+- **Webhook-driven statuses**: provider webhooks refresh accounts and settle payouts through `processPayoutForWebhookWorkflow`
## How it works
A seller moves from no account to a paid order in 5 steps:
-1. Run `createPayoutAccountWorkflow` for the seller. The provider creates a connected account.
+1. Run `createPayoutAccountWorkflow` (or `createOrRefreshSellerPayoutAccountWorkflow`) for the seller. The provider creates a connected account.
2. Run `createOnboardingWorkflow`. The provider returns onboarding data, such as a Stripe onboarding link.
-3. The provider posts webhooks to `/hooks/payout`, and the `payout-webhook` subscriber sets the account to `active`, `restricted`, or `rejected`.
-4. Run `createPayoutWorkflow` with an order id. It computes the seller’s share and asks the provider to transfer it.
-5. Later provider webhooks update the payout’s status.
+3. The provider posts webhooks to `/hooks/payout`, and the `payout-webhook` subscriber re-reads the account from the provider and sets it to `pending`, `active`, `restricted`, or `rejected`.
+4. Run `createOrderPayoutsWorkflow` with order ids. It computes each seller’s share and asks the provider to pay it.
+5. Run `createPayoutReversalsWorkflow` after refunds. Provider webhooks update payout statuses along the way.
<Warning>
- Mercur doesn’t trigger step 4 for you. No scheduled job or subscriber in `@mercurjs/core` captures payments or runs `createPayoutWorkflow`. Call it from your own job, subscriber, or route. See [The payout pipeline](/platform/payout/concepts/payout-pipeline).
+ `@mercurjs/core` ships no scheduled jobs, so it doesn’t decide when steps 4 and 5 run. The Stripe connector plugin brings its own schedule. Without it, call the workflows from your own job, subscriber, or route. See [The payout pipeline](/platform/payout/concepts/payout-pipeline).
</Warning>
## Get started
-Learn how accounts, onboarding, and transfers fit together.
+Learn how accounts, onboarding, and payouts fit together.
<CardGroup cols={2}>
<Card title="Accounts & onboarding" icon="id-card" href="/platform/payout/concepts/accounts-and-onboarding">
@@ -52,7 +53,7 @@ Learn how accounts, onboarding, and transfers fit together.
Account and payout statuses, and the webhooks that change them.
</Card>
<Card title="The payout pipeline" icon="arrows-turn-right" href="/platform/payout/concepts/payout-pipeline">
- What ships, what you wire yourself, and the provider interface.
+ What core ships, what the plugin or your code schedules, and the provider interface.
</Card>
</CardGroup>
@@ -78,18 +79,18 @@ The data models, links, workflows, service methods, and events behind payouts.
<CardGroup cols={2}>
<Card title="Data models" icon="table" href="/platform/payout/reference/data-models">
- `PayoutAccount`, `Onboarding`, and `Payout`, with every field.
+ `PayoutAccount`, `Onboarding`, `Payout`, and `PayoutReversal`, with every field.
</Card>
<Card title="Links" icon="link" href="/platform/payout/reference/links">
How payout records link to sellers and orders.
</Card>
<Card title="Workflows" icon="diagram-project" href="/platform/payout/reference/workflows">
- The 4 payout workflows, their steps, and their hooks.
+ The payout workflows, their steps, and their hooks.
</Card>
<Card title="Service" icon="gear" href="/platform/payout/reference/service">
Generated and provider-backed methods on the module service.
</Card>
<Card title="Events" icon="bell" href="/platform/payout/reference/events">
- The webhook event, the data-model events, and the reserved event names.
+ The webhook event, the failure events, and the data-model events.
</Card>
</CardGroup>
diff --git a/apps/docs/platform/payout/reference/data-models.mdx b/apps/docs/platform/payout/reference/data-models.mdx
index f7f4897cf..32b6fbc3b 100644
--- a/apps/docs/platform/payout/reference/data-models.mdx
+++ b/apps/docs/platform/payout/reference/data-models.mdx
@@ -1,10 +1,12 @@
---
title: "Payout data models"
sidebarTitle: "Data models"
-description: "Every field of PayoutAccount, Onboarding, and Payout, plus the PayoutAccountStatus and PayoutStatus enums."
+description: "Every field of PayoutAccount, Onboarding, Payout, and PayoutReversal, plus the payout enums."
---
-The Payout module owns 3 data models: `PayoutAccount`, `Onboarding`, and `Payout`. They’re defined in `packages/core/src/modules/payout/models`, and the module service is registered as `MercurModules.PAYOUT`. Every model also gets Medusa’s `created_at`, `updated_at`, and `deleted_at` columns.
+The Payout module owns 4 data models: `PayoutAccount`, `Onboarding`, `Payout`, and `PayoutReversal`. They’re defined in `packages/core/src/modules/payout/models`, and the module service is registered as `MercurModules.PAYOUT`. Every model also gets Medusa’s `created_at`, `updated_at`, and `deleted_at` columns.
+
+The module has no provider table and no `provider_id` columns: a marketplace has exactly one payout provider.
## PayoutAccount
@@ -13,8 +15,17 @@ A seller’s connection to the payout provider. Table `payout_account`, id prefi
| Field | Type | Description |
| --- | --- | --- |
| `id` | `text` | Primary key, such as `pacc_01JD8Q1234567` |
+| `external_id` | `text`, nullable | The provider’s account id, such as a Stripe `acct_…` id. Unique when set, like `external_id` on Medusa’s `AccountHolder` |
| `status` | `enum` | `PayoutAccountStatus`, default `pending` |
-| `data` | `json` | Provider account data, default `{}` |
+| `kyc_status` | `enum`, nullable | `PayoutKycStatus`, derived from the provider’s requirements |
+| `payouts_enabled` | `boolean` | Mirrors the provider, default `false` |
+| `charges_enabled` | `boolean` | Mirrors the provider, default `false` |
+| `details_submitted` | `boolean` | Mirrors the provider, default `false` |
+| `disabled_reason` | `text`, nullable | The provider’s reason for disabling the account |
+| `onboarding_token` | `text`, nullable | Secret for the public refresh URL. Unique when set, rotated on every refresh, cleared once details are submitted |
+| `onboarding_token_issued_at` | `dateTime`, nullable | When `onboarding_token` was issued. The refresh URL rejects a token older than `onboarding.tokenTtlSeconds` |
+| `last_synced_at` | `dateTime`, nullable | When the account was last read from the provider |
+| `data` | `json` | The provider’s account object, default `{}`. Provider details such as outstanding requirements live here |
| `context` | `json`, nullable | Provider context passed at creation |
Relations:
@@ -31,7 +42,7 @@ The provider’s onboarding state for one payout account. Table `onboarding`, id
| Field | Type | Description |
| --- | --- | --- |
| `id` | `text` | Primary key, such as `onb_01JD8Q1234567` |
-| `data` | `json`, nullable | Provider onboarding data, such as a Stripe account link |
+| `data` | `json`, nullable | Provider link data plus `url`, `kind` (`onboarding` or `login`), and `expires_at` |
| `context` | `json`, nullable | Provider context from the last onboarding call |
| `account_id` | `text` | Foreign key to `PayoutAccount` |
@@ -41,32 +52,53 @@ Relations:
## Payout
-One transfer to a seller’s payout account. Table `payout`, id prefix `pout`.
+The seller’s share of one order, sent to their payout account. Table `payout`, id prefix `pout`.
| Field | Type | Description |
| --- | --- | --- |
| `id` | `text` | Primary key, such as `pout_01JD8Q1234567` |
| `display_id` | `autoincrement` | Human-readable sequence number |
-| `currency_code` | `text` | Currency of the transfer |
-| `amount` | `bigNumber` | Amount sent to the seller |
-| `data` | `json`, nullable | Provider transfer data, such as a Stripe transfer |
+| `order_id` | `text`, nullable | The order paid out. Unique when set, so an order is paid once |
+| `currency_code` | `text` | Currency of the payout |
+| `amount` | `bigNumber` | Order total minus commission, net of refunds that landed before the payout |
| `status` | `enum` | `PayoutStatus`, default `pending` |
+| `status_reason` | `text`, nullable | A `PayoutStatusReason` code saying why the payout is on hold, failed, or aborted |
+| `data` | `json`, nullable | `attempts`, `idempotency_key`, `status_detail` (the details behind `status_reason`), `source_payment`, `absorbed_refund_ids`, and the provider response under `provider`, whose `id` is the provider’s payout id, such as a Stripe transfer id |
+| `metadata` | `json`, nullable | Your own data |
| `account_id` | `text` | Foreign key to `PayoutAccount` |
Relations:
- **`account`**: `belongsTo` `PayoutAccount`, mapped by `payouts`
+- **`reversals`**: `hasMany` `PayoutReversal`, mapped by `payout`, deleted with the payout
-Indexes, both limited to rows where `deleted_at IS NULL`:
+Indexes, all limited to rows where `deleted_at IS NULL`:
- **`IDX_payout_account_id_created_at`**: on `account_id`, `created_at`
- **`IDX_payout_status_created_at`**: on `status`, `created_at`
+- **`IDX_payout_order_id`**: unique on `order_id` when set
+
+## PayoutReversal
-`createPayoutWorkflow` sets `amount` to the order total minus the order’s commission lines. The model itself doesn’t store an order id. The order travels to the provider as the idempotency key, and Stripe Connect stores it as the transfer’s `transfer_group` in `data`.
+One refund’s share taken back from a payout, the way Medusa keeps a `Refund` under a `Payment`. Table `payout_reversal`, id prefix `pourev`.
+
+| Field | Type | Description |
+| --- | --- | --- |
+| `id` | `text` | Primary key |
+| `refund_id` | `text`, nullable | The Medusa refund reversed. Unique when set |
+| `amount` | `bigNumber` | The refund minus its share of the commission |
+| `status` | `enum` | `PayoutStatus`, default `pending` |
+| `status_reason` | `text`, nullable | A `PayoutStatusReason` code saying why the reversal is on hold, failed, or aborted |
+| `data` | `json`, nullable | `attempts`, `idempotency_key`, `status_detail`, and the provider response under `provider`, whose `id` is the provider’s reversal id |
+| `payout_id` | `text` | Foreign key to `Payout` |
+
+Relations:
+
+- **`payout`**: `belongsTo` `Payout`, mapped by `reversals`
## Enums
-Both enums are exported from `@mercurjs/types`.
+The enums are exported from `@mercurjs/types`.
`PayoutAccountStatus`:
@@ -77,12 +109,22 @@ Both enums are exported from `@mercurjs/types`.
| `RESTRICTED` | `restricted` |
| `REJECTED` | `rejected` |
-`PayoutStatus`:
+`PayoutKycStatus`:
+
+| Member | Value |
+| --- | --- |
+| `PENDING_SUBMISSION` | `pending_submission` |
+| `PENDING_APPROVAL` | `pending_approval` |
+| `APPROVED` | `approved` |
+| `REFUSED` | `refused` |
+
+`PayoutStatus`, used by both `Payout` and `PayoutReversal`:
| Member | Value |
| --- | --- |
| `PENDING` | `pending` |
+| `ON_HOLD` | `on_hold` |
| `PROCESSING` | `processing` |
| `PAID` | `paid` |
| `FAILED` | `failed` |
-| `CANCELED` | `canceled` |
+| `ABORTED` | `aborted` |
diff --git a/apps/docs/platform/payout/reference/events.mdx b/apps/docs/platform/payout/reference/events.mdx
index 109cd8b99..cdcb1702c 100644
--- a/apps/docs/platform/payout/reference/events.mdx
+++ b/apps/docs/platform/payout/reference/events.mdx
@@ -1,20 +1,27 @@
---
title: "Payout events"
sidebarTitle: "Events"
-description: "The payout webhook event, the data-model events the Payout module emits, and the reserved PayoutEvents names that nothing emits yet."
+description: "The payout webhook event, the events the payout workflows emit, and the data-model events of the Payout module."
---
-The Payout module has one event of its own, `payout.webhook_received`, which carries provider webhooks to the shipped subscriber. Medusa also emits a created, updated, or deleted event whenever a payout record changes. Subscribe to those for side effects such as seller notifications or ledger syncs.
+The Payout module’s events are named in `PayoutModuleEvents` from `@mercurjs/types`. `payout.webhook_received` carries provider webhooks to the shipped subscriber; the others come from the payout workflows. Medusa also emits a created, updated, or deleted event whenever a payout record changes. Subscribe to these for side effects such as seller notifications or operator alerts.
-## Webhook event
+## PayoutModuleEvents
+
+| Member | Name | Emitted by | Payload |
+| --- | --- | --- | --- |
+| `WEBHOOK_RECEIVED` | `payout.webhook_received` | `POST /hooks/payout` | `{ data, rawData, headers }` |
+| `ACCOUNT_UPDATED` | `payout_account.updated` | `syncPayoutAccountWorkflow` | `{ id }` |
+| `PAYOUT_FAILED` | `payout.failed` | `createOrderPayoutsWorkflow`, `processPayoutWorkflow` | `{ id }` |
+| `PAYOUT_REVERSAL_FAILED` | `payout.reversal_failed` | `createPayoutReversalsWorkflow`, `processPayoutReversalWorkflow` | `{ id }` |
-The `POST /hooks/payout` route emits this event with a 5000 ms delay and 3 attempts.
+Like Medusa’s payment events, the payloads carry only the row’s id; retrieve the account, payout or reversal in the subscriber for anything else. `payout.failed` and `payout.reversal_failed` are emitted once per row that the provider refused in that run. A row the provider refused for good is `aborted` and emits nothing.
-| Event | Emitted when | Payload |
-| --- | --- | --- |
-| `payout.webhook_received` | The provider posts to `/hooks/payout` | `{ data, rawData, headers }` |
+## Webhook event
-`data` is the parsed body, `rawData` is the raw body, and `headers` are the request headers. The `payout-webhook` subscriber, with subscriber id `payout-webhook-handler`, handles it and runs `processPayoutForWebhookWorkflow`. The event bus serializes `rawData` as a buffer object, and the subscriber turns it back into a `Buffer` before signature checks.
+The `POST /hooks/payout` route emits `payout.webhook_received` with a 5000 ms delay and 3 attempts. `data` is the parsed body, `rawData` is the raw body, and `headers` are the request headers.
+
+The `payout-webhook` subscriber, with subscriber id `payout-webhook-handler`, parses it through the provider and runs `processPayoutForWebhookWorkflow`. The event bus serializes `rawData` as a buffer object, and the subscriber turns it back into a `Buffer` before signature checks. Other subscribers can listen to the same event; the Stripe connector plugin uses it to record bank payout events on its settlements.
## Data-model events
@@ -23,25 +30,31 @@ The `POST /hooks/payout` route emits this event with a 5000 ms delay and 3 attem
| Event | Emitted when |
| --- | --- |
| `payout.payout-account.created` | `createPayoutAccount` inserts an account |
-| `payout.payout-account.updated` | The provider response is stored, or a webhook changes the status |
-| `payout.payout-account.deleted` | The provider call fails and the new account is removed |
+| `payout.payout-account.updated` | The provider response is stored, or a sync refreshes the account |
+| `payout.payout-account.deleted` | The provider call fails and the new account is removed, or a rollback deletes it with `deletePayoutAccount` |
| `payout.onboarding.created` | `createOnboarding` runs for the first time on an account |
| `payout.onboarding.updated` | `createOnboarding` runs again on the same account |
-| `payout.payout.created` | `createPayouts` inserts a `pending` payout |
-| `payout.payout.updated` | The provider response is stored, or a webhook changes the status |
-| `payout.payout.deleted` | The provider call fails and the new payout is removed |
+| `payout.payout.created` | `createOrderPayoutsWorkflow` inserts a payout |
+| `payout.payout.updated` | A payout is re-decided, sent, or changed by a webhook |
+| `payout.payout-reversal.created` | `createPayoutReversalsWorkflow` inserts a reversal |
+| `payout.payout-reversal.updated` | A reversal is re-decided or sent |
-An `updated` event doesn’t say which field changed. Retrieve the record in your subscriber and read its `status`.
+An `updated` event fires for every write. Subscribe to `payout_account.updated` instead when you only care about provider syncs, and read the account’s new status in the subscriber:
```ts title="src/subscribers/payout-account-updated.ts"
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
-import { MercurModules, PayoutAccountStatus } from "@mercurjs/types"
+import {
+ IPayoutModuleService,
+ MercurModules,
+ PayoutAccountStatus,
+ PayoutModuleEvents,
+} from "@mercurjs/types"
export default async function payoutAccountUpdated({
event,
container,
}: SubscriberArgs<{ id: string }>) {
- const payoutService = container.resolve(MercurModules.PAYOUT)
+ const payoutService = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
const account = await payoutService.retrievePayoutAccount(event.data.id)
if (account.status === PayoutAccountStatus.RESTRICTED) {
@@ -51,24 +64,12 @@ export default async function payoutAccountUpdated({
}
export const config: SubscriberConfig = {
- event: "payout.payout-account.updated",
+ event: PayoutModuleEvents.ACCOUNT_UPDATED,
}
```
This subscriber logs a warning each time an account lands in `restricted`, which is where you’d send the seller a reminder to finish onboarding.
-## Reserved event names
-
-`@mercurjs/types` exports a `PayoutEvents` enum. Nothing in `@mercurjs/core` emits these events or subscribes to them, and the enum carries a TODO to move them to order events.
-
-| Member | Name |
-| --- | --- |
-| `OrderCaptureRequested` | `order.capture_requested` |
-| `OrderAuthorizationExpired` | `order.authorization_expired` |
-| `PayoutRequested` | `payout.requested` |
-
-You can emit them from your own payout trigger and subscribe to them in your project. See [The payout pipeline](/platform/payout/concepts/payout-pipeline).
-
## Workflow hook
-`createPayoutWorkflow` exposes a `payoutCreated` hook with `{ order_id, payout_id }`. Use it instead of `payout.payout.created` when you need the order id, because the data-model event carries only the payout id.
+`createOrderPayoutsWorkflow` exposes a `payoutsCreated` hook with `{ order_ids, payouts }`, where `payouts` are the payouts sent to the provider in that run. Use it when you need the order ids with the result.
diff --git a/apps/docs/platform/payout/reference/links.mdx b/apps/docs/platform/payout/reference/links.mdx
index ba94d7542..d5c1f7740 100644
--- a/apps/docs/platform/payout/reference/links.mdx
+++ b/apps/docs/platform/payout/reference/links.mdx
@@ -9,8 +9,8 @@ The Payout module never references other modules directly. 3 module links in `pa
| Link | Entry name | Cardinality | Created by |
| --- | --- | --- | --- |
| Seller ↔ payout account | `seller_payout_account` | One to one | `createPayoutAccountWorkflow` |
-| Payout ↔ seller | `payout_seller` | Many payouts to one seller | `createPayoutWorkflow` |
-| Order ↔ payout | `order_payout` | One order to many payouts | Nothing in core |
+| Payout ↔ seller | `payout_seller` | Many payouts to one seller | `createOrderPayoutsWorkflow` |
+| Order ↔ payout | `order_payout` | One order to its payout | `createOrderPayoutsWorkflow` |
## Seller and payout account
@@ -26,7 +26,7 @@ const { data: [seller] } = await query.graph({
## Payout and seller
-Defined in `payout-seller-link.ts` between `PayoutModule.linkable.payout`, marked `isList: true`, and `SellerModule.linkable.seller`. A seller has many payouts, and each payout has one seller. `createPayoutWorkflow` creates this link right after the payout.
+Defined in `payout-seller-link.ts` between `PayoutModule.linkable.payout`, marked `isList: true`, and `SellerModule.linkable.seller`. A seller has many payouts, and each payout has one seller. `createOrderPayoutsWorkflow` creates this link when it creates a payout.
```ts
const { data: payouts } = await query.graph({
@@ -40,27 +40,14 @@ The Vendor API scopes payouts by querying the link table directly, with `entity:
## Order and payout
-Defined in `order-payout-link.ts` between Medusa’s `OrderModule.linkable.order` and `PayoutModule.linkable.payout`, marked `isList: true`. An order can have many payouts.
+Defined in `order-payout-link.ts` between Medusa’s `OrderModule.linkable.order` and `PayoutModule.linkable.payout`, marked `isList: true`. `createOrderPayoutsWorkflow` creates it with the payout. The payout also stores `order_id` in its own unique column, which is what keeps an order from being paid twice; the link is there so you can read across modules with `query.graph`:
-<Warning>
- No workflow in core creates `order_payout` rows, so `order.payouts` is empty by default. To use this link, create it in the `payoutCreated` hook of `createPayoutWorkflow`, which receives `order_id` and `payout_id`.
-</Warning>
-
-```ts title="src/workflows/hooks/link-payout-to-order.ts"
-import { createPayoutWorkflow } from "@mercurjs/core/workflows"
-import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
-import { MercurModules } from "@mercurjs/types"
-
-createPayoutWorkflow.hooks.payoutCreated(
- async ({ order_id, payout_id }, { container }) => {
- const link = container.resolve(ContainerRegistrationKeys.LINK)
-
- await link.create({
- [Modules.ORDER]: { order_id },
- [MercurModules.PAYOUT]: { payout_id },
- })
- }
-)
+```ts
+const { data: [order] } = await query.graph({
+ entity: "order",
+ fields: ["id", "payouts.id", "payouts.status", "payouts.reversals.*"],
+ filters: { id: "order_01JD8Q1234567" },
+})
```
-Once the hook runs, read an order’s payouts with `fields: ["id", "payouts.id", "payouts.status"]` on the `order` entity.
+Reversals aren’t linked to anything: they’re children of their payout, and `refund_id` names the Medusa refund they reverse.
diff --git a/apps/docs/platform/payout/reference/service.mdx b/apps/docs/platform/payout/reference/service.mdx
index 173f64e8d..8105d027b 100644
--- a/apps/docs/platform/payout/reference/service.mdx
+++ b/apps/docs/platform/payout/reference/service.mdx
@@ -4,34 +4,35 @@ sidebarTitle: "Service"
description: "Resolve the Payout module service, and use its generated data methods and its provider-backed methods."
---
-`PayoutModuleService` reads and writes payout records, and it’s the only code that calls the payout provider. Resolve it from the container in subscribers, jobs, steps, and routes. Prefer the [workflows](/platform/payout/reference/workflows) when you also need links or a rollback.
+`PayoutModuleService` reads and writes payout records, and it’s the only code that calls the payout provider. Resolve it from the container in subscribers, jobs, steps, and routes. Prefer the [workflows](/platform/payout/reference/workflows) when you also need links, events, or a rollback.
## Resolve the service
The service is registered under `MercurModules.PAYOUT`, whose value is `"payout"`:
```ts
-import { MercurModules } from "@mercurjs/types"
+import { IPayoutModuleService, MercurModules } from "@mercurjs/types"
-const payoutService = container.resolve(MercurModules.PAYOUT)
+const payoutService = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
const [payouts, count] = await payoutService.listAndCountPayouts(
- { status: "paid" },
+ { status: "on_hold" },
{ take: 20, order: { created_at: "DESC" } }
)
```
## Generated methods
-The service extends `MedusaService({ Onboarding, Payout, PayoutAccount })`, so each model gets Medusa’s standard methods:
+The service extends `MedusaService({ Onboarding, Payout, PayoutAccount, PayoutReversal })` and implements `IPayoutModuleService` from `@mercurjs/types`, so each model gets Medusa’s standard methods. Resolve it with that interface: `container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)`.
| Model | Methods |
| --- | --- |
| `PayoutAccount` | `retrievePayoutAccount`, `listPayoutAccounts`, `listAndCountPayoutAccounts`, `createPayoutAccounts`, `updatePayoutAccounts`, `deletePayoutAccounts`, `softDeletePayoutAccounts`, `restorePayoutAccounts` |
| `Onboarding` | `retrieveOnboarding`, `listOnboardings`, `listAndCountOnboardings`, `createOnboardings`, `updateOnboardings`, `deleteOnboardings`, `softDeleteOnboardings`, `restoreOnboardings` |
-| `Payout` | `retrievePayout`, `listPayouts`, `listAndCountPayouts`, `updatePayouts`, `deletePayouts`, `softDeletePayouts`, `restorePayouts` |
+| `Payout` | `retrievePayout`, `listPayouts`, `listAndCountPayouts`, `createPayouts`, `updatePayouts`, `deletePayouts`, `softDeletePayouts`, `restorePayouts` |
+| `PayoutReversal` | `retrievePayoutReversal`, `listPayoutReversals`, `listAndCountPayoutReversals`, `createPayoutReversals`, `updatePayoutReversals`, `deletePayoutReversals`, `softDeletePayoutReversals`, `restorePayoutReversals` |
-`createPayouts` isn’t in the `Payout` row because the service overrides it. The generated create and update methods write rows only. They never call the provider.
+The generated create and update methods write rows only. They never call the provider.
## Provider-backed methods
@@ -43,7 +44,23 @@ These methods call the payout provider as part of the write.
createPayoutAccount(input: CreatePayoutAccountDTO): Promise<PayoutAccountDTO>
```
-Creates the row, calls the provider with `data.account_id` set to the new id, then stores the provider’s `data` and `status`. Deletes the row if the provider throws. `input` takes optional `data` and `context`.
+Creates the row, calls the provider’s `createAccount` with `data.account_id` and `metadata.account_id` set to the new id, then stores `external_id`, the flags, the derived `status` and `kyc_status`, and the provider’s `data`. Deletes the row if the provider throws. `input` takes optional `data`, `context`, and `seller` (used when `onboarding.prefill` is on).
+
+### syncPayoutAccount
+
+```ts
+syncPayoutAccount(accountId: string): Promise<PayoutAccountDTO>
+```
+
+Re-reads the account with the provider’s `retrieveAccount` and stores the same fields as `createPayoutAccount`, plus `last_synced_at`. Clears `onboarding_token` once details are submitted. The account `status` and `kyc_status` are derived here from the provider’s flags, requirements and `disabled_reason`.
+
+### deletePayoutAccount
+
+```ts
+deletePayoutAccount(accountId: string): Promise<void>
+```
+
+Deletes the account at the provider with its optional `deleteAccount`, then the row. `createPayoutAccountWorkflow` calls it when it rolls back, so the provider isn’t left with an account no seller is linked to. A provider without `deleteAccount` keeps its account.
### createOnboarding
@@ -51,15 +68,28 @@ Creates the row, calls the provider with `data.account_id` set to the new id, th
createOnboarding(input: CreateOnboardingDTO): Promise<OnboardingDTO>
```
-Calls the provider with the account’s `data` merged with `input.data`, then creates the onboarding record or updates the existing one. `input` takes `account_id` and optional `data` and `context`.
+Publishes the link the seller follows next and stores it on the account’s onboarding record:
-### createPayouts
+- Before the seller submits their details, it calls the provider’s `createOnboarding` with `refresh_url` and `return_url` from `input.data` or the module’s `onboarding` options, and stores the link with `kind: "onboarding"`. The refresh URL carries the account’s `onboarding_token`. A new token is issued when the account has none, when the current one is older than `onboarding.tokenTtlSeconds`, or when `input.rotate_token` is set, and `onboarding_token_issued_at` records when.
+- Once `details_submitted` is set, it asks the provider’s `createLoginLink` for a dashboard link and stores it with `kind: "login"`. A provider without `createLoginLink` gets a new onboarding link instead.
+
+`input` takes `account_id` and optional `data`, `context` and `rotate_token`.
+
+### processPayout
```ts
-createPayouts(input: CreatePayoutDTO): Promise<PayoutDTO>
+processPayout(payoutId: string): Promise<PayoutDTO>
```
-Takes one payout, not an array. Throws a `NOT_ALLOWED` error when the account isn’t `active`. Otherwise it creates a `pending` row, calls the provider, and stores the provider’s `data` and `status`. Deletes the row if the provider throws. `input` takes `account_id`, `amount`, `currency_code`, and optional `data` and `context`.
+Sends a `pending` or `failed` payout with the provider’s `createPayout`, passing the order id as `group`, the payment in `data.source_payment`, and `{ payout_id, order_id }` as metadata. Like Medusa’s `capturePayment`, it locks the row and marks it `processing` in a transaction, then calls the provider outside it, so the lock is never held across the provider call. Stores the provider’s `status` and id. A provider error doesn’t throw: the row gets `status_reason: "provider_error"`, the message in `data.status_detail`, and the status `failed`, or `aborted` when the error is a `PayoutProviderError` with code `final`. Any other status is returned unchanged.
+
+### processPayoutReversal
+
+```ts
+processPayoutReversal(reversalId: string): Promise<PayoutReversalDTO>
+```
+
+Sends a `pending` or `failed` reversal with the provider’s `reversePayout`, against the provider id kept in the payout’s `data.provider.id`. Locks and records errors the same way as `processPayout`.
### getWebhookActionAndData
@@ -69,24 +99,33 @@ getWebhookActionAndData(
): Promise<PayoutWebhookResult>
```
-Passes `{ data, rawData, headers }` to the provider and returns its action and Mercur id. It doesn’t change any record.
+Passes `{ data, rawData, headers }` to the provider and returns its action and the provider’s object id. It doesn’t change any record.
### getOptions
```ts
-getOptions(): PayoutModuleOptions
+getOptions(): ResolvedPayoutModuleOptions
```
-Returns the module options merged over `PAYOUT_MODULE_OPTION_DEFAULTS`. Core reads none of the timing options, so use them in your own payout trigger. See [The payout pipeline](/platform/payout/concepts/payout-pipeline).
+Returns the resolved module options, `onboarding.returnUrl`, `onboarding.refreshBaseUrl`, `onboarding.prefill`, `onboarding.defaultCountry`, and `onboarding.tokenTtlSeconds` (24 hours by default), with defaults applied. Scheduling options belong to the integration that runs the payouts, such as the Stripe connector plugin.
## Idempotency keys
-Each provider-backed method sets `context.idempotency_key` before it calls the provider, unless you pass one:
+Each provider-backed method sets `context.idempotency_key` before it calls the provider:
-| Method | Default key |
+| Method | Key |
| --- | --- |
-| `createPayoutAccount` | The new `pacc` id |
-| `createOnboarding` | The `account_id` |
-| `createPayouts` | The new `pout` id |
+| `createPayoutAccount` | The new `pacc` id, unless you pass one |
+| `createOnboarding` | The `account_id`, unless you pass one |
+| `processPayout` | The `pout` id, then `<id>:<attempt>` after a refusal |
+| `processPayoutReversal` | The reversal id, then `<id>:<attempt>` after a refusal |
+
+The key in use is stored in the row’s `data.idempotency_key` and the attempt count in `data.attempts`. What happens to the key depends on the error the provider throws:
+
+| Error | Row | Next attempt |
+| --- | --- | --- |
+| `PayoutProviderError` with code `refused` | `failed` | A fresh key: the provider refused the request and created nothing, and it would return the cached refusal for the old key |
+| `PayoutProviderError` with code `final` | `aborted` | None |
+| Any other error (timeout, network, provider 5xx), or code `unknown` | `failed` | The same key, so if the provider did make the payout, the retry gets that payout back instead of a second one |
-`createPayoutWorkflow` passes the order id, which replaces the `pout` default. Stripe Connect forwards the key to Stripe on account and transfer creation.
+A `payout.failed` webhook also clears the key, because the provider failed the payout it made under it. Stripe Connect forwards the key to Stripe on account, transfer, and reversal creation.
diff --git a/apps/docs/platform/payout/reference/workflows.mdx b/apps/docs/platform/payout/reference/workflows.mdx
index 5ec5fb47d..fdfc358e4 100644
--- a/apps/docs/platform/payout/reference/workflows.mdx
+++ b/apps/docs/platform/payout/reference/workflows.mdx
@@ -1,79 +1,160 @@
---
title: "Payout workflows"
sidebarTitle: "Workflows"
-description: "The 4 payout workflows and 6 payout steps exported from @mercurjs/core/workflows, with their inputs, steps, and hooks."
+description: "The payout workflows and steps exported from @mercurjs/core/workflows, with their inputs, steps, events, and hooks."
---
-The Payout module ships 4 workflows in `packages/core/src/workflows/payout`. Import them, and their steps, from `@mercurjs/core/workflows`. None of them emits a custom event. Medusa’s data-model events still fire for the records they write, as listed in [Events](/platform/payout/reference/events).
+The Payout module ships its workflows in `packages/core/src/workflows/payout`. Import them, and their steps, from `@mercurjs/core/workflows`. The events they emit are listed in [Events](/platform/payout/reference/events). Core doesn’t schedule any of them; see [The payout pipeline](/platform/payout/concepts/payout-pipeline).
## createPayoutAccountWorkflow
-Creates a payout account for a seller through the provider and links it to the seller. Workflow id `create-payout-account-for-seller`.
+Creates a payout account for a seller through the provider, links it to the seller and publishes the onboarding link. Workflow id `create-payout-account-workflow`.
| Input | Type | Description |
| --- | --- | --- |
| `seller_id` | `string` | Seller to create the account for |
-| `data` | `Record<string, unknown>`, optional | Passed to the provider; Stripe Connect needs `country` |
+| `data` | `Record<string, unknown>`, optional | Passed to the provider; `country` and `business_type` are read from it |
| `context` | `PayoutProviderContext`, optional | Provider context, such as `idempotency_key` |
Steps, in order:
-1. `validate-seller-payout-account`: fails with `Seller already has a payout account` when a `seller_payout_account` row exists
-2. `create-payout-account`: calls the service’s `createPayoutAccount`
-3. `create-remote-links`: links the seller and the account
+1. `use-query-graph-step` (`payout-account-seller-query`): loads the seller's profile and current account
+2. `validate-seller-without-payout-account`: fails with `409` when the seller already has an account
+3. `create-payout-account`: calls the service's `createPayoutAccount` with the seller's profile; on rollback, deletes the account with `deletePayoutAccount`, at the provider too when it supports `deleteAccount`
+4. `create-remote-links`: links the seller and the account
+5. `create-onboarding`: publishes the onboarding link
Returns the `PayoutAccountDTO`. Exposes no hooks.
+## createOrRefreshSellerPayoutAccountWorkflow
+
+Makes sure one seller has an account and, until they submit their details, a current onboarding link. Workflow id `create-or-refresh-seller-payout-account`. Safe to run on every seller change.
+
+| Input | Type | Description |
+| --- | --- | --- |
+| `seller_id` | `string` | The seller |
+| `data`, `context` | optional | Passed to `createPayoutAccountWorkflow` when the account is created |
+
+It loads the seller, runs `createPayoutAccountWorkflow` when no account exists, and otherwise publishes a fresh onboarding link while the account still needs onboarding, because provider links expire. Returns `{ account_id, onboarding_published }`.
+
+## linkPayoutAccountWorkflow
+
+Attaches an account that already exists at the provider to a seller, behind `POST /admin/payout-accounts`. Workflow id `link-payout-account`.
+
+| Input | Type | Description |
+| --- | --- | --- |
+| `seller_id` | `string` | The seller |
+| `external_id` | `string` | The account's id at the provider |
+
+It validates that the seller has no account, stores the account without calling the provider (`create-payout-accounts`, deleted on rollback), links it, then runs `syncPayoutAccountWorkflow`. Returns the synced `PayoutAccountDTO`.
+
## createOnboardingWorkflow
-Creates or updates the onboarding record for a payout account through the provider. Workflow id `create-onboarding`.
+Publishes the next link for a payout account. Workflow id `create-onboarding-workflow`, exported as `createOnboardingWorkflowId`.
| Input | Type | Description |
| --- | --- | --- |
| `account_id` | `string` | The `pacc` id |
-| `data` | `Record<string, unknown>`, optional | Merged over the account’s `data`; Stripe Connect needs `refresh_url` and `return_url` |
+| `data` | `Record<string, unknown>`, optional | `refresh_url` and `return_url` override the module defaults |
| `context` | `PayoutProviderContext`, optional | Provider context, stored on the record |
+| `rotate_token` | `boolean`, optional | Issue a new `onboarding_token` even when the current one is still valid |
-It runs one step, `create-onboarding`, and returns the `OnboardingDTO`. Exposes no hooks.
+It runs one step, `create-onboarding`, and returns the `OnboardingDTO`. The service picks an onboarding link or, once details are submitted, a dashboard login link.
+
+## refreshPayoutAccountLinkWorkflow
+
+Publishes a new link for an account, behind `POST /admin/payout-accounts/:id/refresh-link`. Workflow id `refresh-payout-account-link`. Input `{ id }`; it runs `create-onboarding` and returns the `OnboardingDTO`.
+
+## refreshOnboardingWorkflow
+
+Exchanges an expired onboarding link for a fresh one, behind the public `GET /payout/onboarding/refresh?token=`. Workflow id `refresh-onboarding`. Input `{ token }`; it finds the account by `onboarding_token` and fails (`validate-onboarding-token`) with `404` when none matches, or with `400` when the token is older than the module's `onboarding.tokenTtlSeconds` (24 hours by default). It then runs `create-onboarding` with `rotate_token`, so the used token stops working and the new link's refresh URL carries a new one, and returns `{ url }`.
+
+## syncPayoutAccountWorkflow
+
+Re-reads an account from the provider. Workflow id `sync-payout-account`.
+
+| Input | Type | Description |
+| --- | --- | --- |
+| `id` | `string` | The `pacc` id |
+
+Steps, in order:
-## createPayoutWorkflow
+1. `sync-payout-account-step`: calls the service's `syncPayoutAccount`; restores the previous fields on rollback
+2. `create-onboarding`: only when `details_submitted` is `true`, to publish the dashboard login link
+3. Emits `payout_account.updated` with `{ id }`
-Pays the seller’s share of one order through the provider. Workflow id `create-payout`, exported as `createPayoutWorkflowId`.
+Returns the `PayoutAccountDTO`.
+
+## createOrderPayoutsWorkflow
+
+Pays each order's seller their share. Workflow id `create-order-payouts`, exported as `createOrderPayoutsWorkflowId`.
+
+| Input | Type | Description |
+| --- | --- | --- |
+| `order_ids` | `string[]` | Orders to evaluate |
+| `required_fulfillment_status` | `FulfillmentStatus`, optional | How far an order must be fulfilled, default `fulfilled` |
```ts
-const { result } = await createPayoutWorkflow(container).run({
- input: { order_id: "order_01JD8Q1234567" },
+const { result } = await createOrderPayoutsWorkflow(container).run({
+ input: { order_ids: ["order_01JD8Q1234567"] },
})
```
Steps, in order:
-1. `fetch-order`: loads `total`, `currency_code`, `seller.payout_account`, items, and shipping methods
-2. `fetch-commission-lines`: loads the `commission_line` rows for those items and shipping methods
-3. `create-payout-step`: creates the payout for `total` minus the commission sum, with the order id as `context.idempotency_key`
-4. `create-remote-links`: links the payout to the seller
+1. `use-query-graph-step` (`payout-orders-query`, `existing-payouts-query`, `payout-commission-lines-query`): loads the orders with their fulfillments and payments, their existing payouts, and their commission lines
+2. `create-payouts`: one new payout per order without one; deleted on rollback unless it was already sent
+3. `update-payouts`: re-decides payouts that are `on_hold` or `failed`; restored on rollback unless it was already sent
+4. `create-remote-links`: links new payouts to the seller and the order
+5. `process-payouts`: sends each `pending` payout with the service's `processPayout`
+6. Emits `payout.failed` with `{ id }` for every payout the provider refused
-It throws `Seller does not have a payout account` when the seller has none. Returns the `PayoutDTO`.
+Returns `{ counts, payouts }`: the number of payouts per resulting status, such as `{ paid: 2, on_hold: 1 }`, and the payouts sent in this run. Payouts that are already `paid`, `processing`, or `aborted` are skipped.
| Hook | Payload | Use it to |
| --- | --- | --- |
-| `payoutCreated` | `{ order_id, payout_id }` | Link the payout to the order, notify the seller, or sync a ledger |
+| `payoutsCreated` | `{ order_ids, payouts }` | Notify sellers or sync a ledger |
-## processPayoutForWebhookWorkflow
+## createPayoutReversalsWorkflow
+
+Takes refunded shares back. Workflow id `create-payout-reversals`.
+
+| Input | Type | Description |
+| --- | --- | --- |
+| `order_ids` | `string[]` | Orders whose refunds to evaluate |
+
+It loads the orders' refunds, payouts and commission lines, then creates or re-decides one reversal per refund on an order whose payout exists, net of commission, skipping refunds already deducted from the payout (`create-payout-reversals-step`, `update-payout-reversals`). It sends each pending reversal with `process-payout-reversals` and emits `payout.reversal_failed` for refusals. Returns `{ counts, reversals }`.
-Applies a parsed provider webhook to an account or a payout. Workflow id `process-payout-for-webhook`, exported as `processPayoutForWebhookWorkflowId`. Its input is a `PayoutWebhookResult`: an `action` and an optional `data.id`.
+## processPayoutWorkflow
-| Action | Step name | Effect |
+Sends existing payouts again. Workflow id `process-payout`.
+
+| Input | Type | Description |
| --- | --- | --- |
-| `account.activated` | `activate-payout-account` | Account `status` to `active` |
-| `account.restricted` | `restrict-payout-account` | Account `status` to `restricted` |
-| `account.rejected` | `reject-payout-account` | Account `status` to `rejected` |
-| `payout.processing` | `processing-payout` | Payout `status` to `processing` |
-| `payout.paid` | `paid-payout` | Payout `status` to `paid` |
-| `payout.failed` | `failed-payout` | Payout `status` to `failed` |
-| `payout.canceled` | `canceled-payout` | Payout `status` to `canceled` |
+| `payout_ids` | `string[]` | Payouts to send |
+
+It runs `process-payouts` and emits `payout.failed` for refusals. Payouts that aren't `pending` or `failed` are returned unchanged.
+
+## retryPayoutWorkflow
+
+Retries one payout, behind `POST /admin/payouts/:id/retry`. Workflow id `retry-payout`. Input `{ id }`. It fails with `400` unless the payout is `failed`, `on_hold` or `pending` (`validate-payout-retry`). A `failed` or `on_hold` order payout runs `createOrderPayoutsWorkflow` for its order, so it is re-decided first. A `pending` payout, and any payout without an order, runs `processPayoutWorkflow` and is sent as is.
+
+## processPayoutReversalWorkflow
+
+Sends existing reversals again. Workflow id `process-payout-reversal`. Input `{ reversal_ids: string[] }`; it runs `process-payout-reversals` and emits `payout.reversal_failed` for refusals.
+
+## processPayoutForWebhookWorkflow
+
+Applies a parsed provider webhook. Workflow id `process-payout-for-webhook`, exported as `processPayoutForWebhookWorkflowId`. Its input is a `PayoutWebhookResult`: an `action` and an optional `data` with `id`, the provider's object id, and for payout events `payout_id`, Mercur's payout id.
+
+| Action | Effect |
+| --- | --- |
+| `account.updated`, `account.activated`, `account.restricted`, `account.rejected` | Finds the account by `external_id` and runs `syncPayoutAccountWorkflow` |
+| `payout.paid` | Finds the payout by `data.payout_id`, sets it to `paid` and stores `data.id` as its `data.provider.id`, which a later reversal needs |
+| `payout.failed` | Sets the payout to `failed` with `status_reason: "provider_error"`, the webhook's `data.status_reason` in `data.status_detail`, and clears `data.idempotency_key` so a retry is a new request |
+| `payout.reversed`, `not_supported` | No change |
-Each branch runs only when `data.id` is set. `not_supported` runs no step. Returns nothing and exposes no hooks.
+The status update runs `update-payouts`. Returns nothing.
## Steps
@@ -81,13 +162,20 @@ You can compose these steps into your own workflows:
| Step | Id | Compensation |
| --- | --- | --- |
-| `validateSellerPayoutAccountStep` | `validate-seller-payout-account` | None |
-| `createPayoutAccountStep` | `create-payout-account` | None |
+| `validateSellerWithoutPayoutAccountStep` | `validate-seller-without-payout-account` | None |
+| `validatePayoutRetryStep` | `validate-payout-retry` | None |
+| `validateOnboardingTokenStep` | `validate-onboarding-token` | None |
+| `createPayoutAccountStep` | `create-payout-account` | Deletes the account, at the provider too when it supports `deleteAccount` |
+| `createPayoutAccountsStep` | `create-payout-accounts` | Deletes the stored accounts; the provider accounts predate the workflow |
+| `syncPayoutAccountStep` | `sync-payout-account-step` | Restores the previous status, flags and data |
| `createOnboardingStep` | `create-onboarding` | None |
-| `createPayoutStep` | `create-payout-step` | None |
-| `updatePayoutAccountStep` | `update-payout-account-step` | Restores the previous status |
-| `updatePayoutStep` | `update-payout-step` | Restores the previous status |
+| `createPayoutsStep` | `create-payouts` | Deletes the payouts that weren't sent |
+| `updatePayoutsStep` | `update-payouts` | Restores the previous values of payouts that weren't sent |
+| `createPayoutReversalsStep` | `create-payout-reversals-step` | Deletes the reversals that weren't sent |
+| `updatePayoutReversalsStep` | `update-payout-reversals` | Restores the previous values of reversals that weren't sent |
+| `processPayoutsStep` | `process-payouts` | None |
+| `processPayoutReversalsStep` | `process-payout-reversals` | None |
<Note>
- The create steps have no compensation. If a later step fails, the account, onboarding record, or payout stays, and the provider-side object stays too. The service only deletes a new row when the provider call itself throws.
+ The process steps and `create-onboarding` have no compensation. Money that reached the provider, or a link a seller already received, can't be undone by a rollback; a payout's status, `status_reason`, and `data.attempts` record what happened instead, and the next run picks up where it stopped. For the same reason, the create and update compensations skip a payout or reversal that is `processing` or `paid`, or was attempted after the step ran.
</Note>
diff --git a/apps/docs/references/api/admin/payouts/list-payouts.mdx b/apps/docs/references/api/admin/payouts/list-payouts.mdx
index 96fa1c786..2a4c4668f 100644
--- a/apps/docs/references/api/admin/payouts/list-payouts.mdx
+++ b/apps/docs/references/api/admin/payouts/list-payouts.mdx
@@ -15,6 +15,8 @@ Returns payouts with their payout account and seller details.
<ParamField query="id" type="string | string[]">Filter by payout ID(s).</ParamField>
<ParamField query="status" type="string | string[]">Filter by payout status.</ParamField>
<ParamField query="account_id" type="string | string[]">Filter by payout account ID(s).</ParamField>
+<ParamField query="seller_id" type="string | string[]">Filter by the seller(s) owning the payout account.</ParamField>
+<ParamField query="order_id" type="string | string[]">Filter by order ID(s).</ParamField>
<ParamField query="created_at" type="object">Filter by creation date using operators like `$gte` and `$lte`.</ParamField>
<ParamField query="updated_at" type="object">Filter by update date using operators like `$gte` and `$lte`.</ParamField>
@@ -27,7 +29,8 @@ Returns payouts with their payout account and seller details.
<ResponseField name="amount" type="number">The payout amount.</ResponseField>
<ResponseField name="currency_code" type="string">The payout currency.</ResponseField>
<ResponseField name="status" type="string">The payout status.</ResponseField>
- <ResponseField name="data" type="object | null">Provider-specific payout data.</ResponseField>
+ <ResponseField name="status_reason" type="string | null">Why the payout is `on_hold`, `failed` or `aborted`: a `PayoutStatusReason` code such as `order_not_ready` or `provider_error`. The details behind it are in `data.status_detail`.</ResponseField>
+ <ResponseField name="data" type="object | null">Payout data: `attempts`, `status_detail`, and the provider's response under `provider`.</ResponseField>
<ResponseField name="account" type="object">The payout account, with `id` and `status`.</ResponseField>
<ResponseField name="seller" type="object">The seller, with `id`, `name`, and `handle`.</ResponseField>
<ResponseField name="created_at" type="string">Creation timestamp.</ResponseField>
diff --git a/apps/docs/references/api/admin/payouts/retrieve-payout.mdx b/apps/docs/references/api/admin/payouts/retrieve-payout.mdx
index 35be1ccc6..9f094e320 100644
--- a/apps/docs/references/api/admin/payouts/retrieve-payout.mdx
+++ b/apps/docs/references/api/admin/payouts/retrieve-payout.mdx
@@ -23,7 +23,8 @@ Returns a single payout with its payout account and seller details.
<ResponseField name="amount" type="number">The payout amount.</ResponseField>
<ResponseField name="currency_code" type="string">The payout currency.</ResponseField>
<ResponseField name="status" type="string">The payout status.</ResponseField>
- <ResponseField name="data" type="object | null">Provider-specific payout data.</ResponseField>
+ <ResponseField name="status_reason" type="string | null">Why the payout is `on_hold`, `failed` or `aborted`: a `PayoutStatusReason` code such as `order_not_ready` or `provider_error`. The details behind it are in `data.status_detail`.</ResponseField>
+ <ResponseField name="data" type="object | null">Payout data: `attempts`, `status_detail`, and the provider's response under `provider`.</ResponseField>
<ResponseField name="account" type="object">The payout account, with `id` and `status`.</ResponseField>
<ResponseField name="seller" type="object">The seller, with `id`, `name`, and `handle`.</ResponseField>
<ResponseField name="created_at" type="string">Creation timestamp.</ResponseField>
diff --git a/apps/docs/references/api/vendor/payout-accounts/create-onboarding.mdx b/apps/docs/references/api/vendor/payout-accounts/create-onboarding.mdx
index d42df5221..071e4979c 100644
--- a/apps/docs/references/api/vendor/payout-accounts/create-onboarding.mdx
+++ b/apps/docs/references/api/vendor/payout-accounts/create-onboarding.mdx
@@ -15,7 +15,7 @@ Creates an onboarding session with the payout provider. For Stripe Connect, the
## Body parameters
<ParamField body="data" type="object">
- Provider-specific data forwarded when creating the onboarding (e.g. `refresh_url` and `return_url` for Stripe Connect). Merged over the payout account's stored `data`.
+ Provider-specific data forwarded when creating the onboarding, merged over the payout account's stored `data`. `refresh_url` and `return_url` are ignored: the links always use the module's `onboarding` options.
</ParamField>
<ParamField body="context" type="object">
@@ -40,16 +40,12 @@ curl -X POST 'http://localhost:9000/vendor/payout-accounts/pacc_01HXYZ/onboardin
-H 'Authorization: Bearer <token>' \
-H 'x-seller-id: <seller_id>' \
-H 'Content-Type: application/json' \
- -d '{"data": {"refresh_url": "https://vendor.example.com/payouts", "return_url": "https://vendor.example.com/payouts"}}'
+ -d '{}'
```
```ts JS Client
const { onboarding } = await client.vendor.payoutAccounts.$id.onboarding.mutate({
$id: "pacc_01HXYZ",
- data: {
- refresh_url: "https://vendor.example.com/payouts",
- return_url: "https://vendor.example.com/payouts",
- },
})
```
</RequestExample>
diff --git a/apps/docs/references/api/vendor/payout-accounts/retrieve-payout-account-by-id.mdx b/apps/docs/references/api/vendor/payout-accounts/retrieve-payout-account-by-id.mdx
index 09272fffd..f5734efe1 100644
--- a/apps/docs/references/api/vendor/payout-accounts/retrieve-payout-account-by-id.mdx
+++ b/apps/docs/references/api/vendor/payout-accounts/retrieve-payout-account-by-id.mdx
@@ -15,7 +15,7 @@ Returns a payout account, verifying it belongs to the current seller.
## Query parameters
<ParamField query="fields" type="string">
- Comma-separated fields to include in the response.
+ Comma-separated fields to include in the response. Only the fields returned by default can be selected; any other field, including linked relations, is ignored.
</ParamField>
## Response
diff --git a/apps/docs/references/api/vendor/payout-accounts/retrieve-payout-account.mdx b/apps/docs/references/api/vendor/payout-accounts/retrieve-payout-account.mdx
index 3ce51d3fd..19d88afdf 100644
--- a/apps/docs/references/api/vendor/payout-accounts/retrieve-payout-account.mdx
+++ b/apps/docs/references/api/vendor/payout-accounts/retrieve-payout-account.mdx
@@ -25,7 +25,7 @@ Returns the payout accounts linked to the current seller, each with its onboardi
</ParamField>
<ParamField query="fields" type="string">
- Comma-separated fields to include in the response.
+ Comma-separated fields to include in the response. Only the fields returned by default can be selected; any other field, including linked relations, is ignored.
</ParamField>
## Response
diff --git a/apps/docs/references/api/vendor/payouts/list-payouts.mdx b/apps/docs/references/api/vendor/payouts/list-payouts.mdx
index 75d4e859c..c12f56fb1 100644
--- a/apps/docs/references/api/vendor/payouts/list-payouts.mdx
+++ b/apps/docs/references/api/vendor/payouts/list-payouts.mdx
@@ -21,7 +21,7 @@ Returns the payouts belonging to the current seller.
</ParamField>
<ParamField query="fields" type="string">
- Comma-separated fields to include in the response.
+ Comma-separated fields to include in the response. Only the fields returned by default can be selected; any other field, including linked relations, is ignored.
</ParamField>
<ParamField query="status" type="string | string[]">
@@ -44,8 +44,8 @@ Returns the payouts belonging to the current seller.
<ResponseField name="display_id" type="number">Human-readable payout number.</ResponseField>
<ResponseField name="amount" type="number">The payout amount.</ResponseField>
<ResponseField name="currency_code" type="string">The payout currency.</ResponseField>
- <ResponseField name="status" type="enum">One of `pending`, `processing`, `paid`, `failed`, `canceled`.</ResponseField>
- <ResponseField name="data" type="object">Provider-specific data.</ResponseField>
+ <ResponseField name="status" type="enum">One of `pending`, `on_hold`, `processing`, `paid`, `failed`, `aborted`.</ResponseField>
+ <ResponseField name="status_reason" type="string | null">A `PayoutStatusReason` code, such as `order_not_ready`, saying why the payout is `on_hold`, `failed` or `aborted`.</ResponseField>
<ResponseField name="created_at" type="string">Creation timestamp.</ResponseField>
<ResponseField name="updated_at" type="string">Update timestamp.</ResponseField>
</Expandable>
diff --git a/apps/docs/references/api/vendor/payouts/retrieve-payout.mdx b/apps/docs/references/api/vendor/payouts/retrieve-payout.mdx
index 00d0fe15a..29bd08fe8 100644
--- a/apps/docs/references/api/vendor/payouts/retrieve-payout.mdx
+++ b/apps/docs/references/api/vendor/payouts/retrieve-payout.mdx
@@ -15,7 +15,7 @@ Returns a payout, verifying it belongs to the current seller.
## Query parameters
<ParamField query="fields" type="string">
- Comma-separated fields to include in the response.
+ Comma-separated fields to include in the response. Only the fields returned by default can be selected; any other field, including linked relations, is ignored.
</ParamField>
## Response
@@ -26,8 +26,8 @@ Returns a payout, verifying it belongs to the current seller.
<ResponseField name="display_id" type="number">Human-readable payout number.</ResponseField>
<ResponseField name="amount" type="number">The payout amount.</ResponseField>
<ResponseField name="currency_code" type="string">The payout currency.</ResponseField>
- <ResponseField name="status" type="enum">One of `pending`, `processing`, `paid`, `failed`, `canceled`.</ResponseField>
- <ResponseField name="data" type="object">Provider-specific data.</ResponseField>
+ <ResponseField name="status" type="enum">One of `pending`, `on_hold`, `processing`, `paid`, `failed`, `aborted`.</ResponseField>
+ <ResponseField name="status_reason" type="string | null">A `PayoutStatusReason` code, such as `order_not_ready`, saying why the payout is `on_hold`, `failed` or `aborted`.</ResponseField>
<ResponseField name="created_at" type="string">Creation timestamp.</ResponseField>
<ResponseField name="updated_at" type="string">Update timestamp.</ResponseField>
</Expandable>
diff --git a/apps/docs/references/configuration.mdx b/apps/docs/references/configuration.mdx
index 42761c246..8e9ae7e82 100644
--- a/apps/docs/references/configuration.mdx
+++ b/apps/docs/references/configuration.mdx
@@ -99,7 +99,7 @@ modules: [
## Stripe Connect payout provider
-Register `@mercurjs/payout-stripe-connect` as a provider of the payout module:
+Register the Stripe connector plugin's payout provider on the payout module. A marketplace has exactly one payout provider; with none registered, the module loads the built-in `system` provider:
```ts
{
@@ -107,14 +107,19 @@ Register `@mercurjs/payout-stripe-connect` as a provider of the payout module:
options: {
providers: [
{
- resolve: "@mercurjs/payout-stripe-connect",
+ resolve: "@mercurjs/stripe-connector-plugin/providers/payout-stripe-connect",
id: "stripe-connect",
options: {
apiKey: process.env.STRIPE_SECRET_KEY,
webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
+ manualPayouts: true,
},
},
],
+ onboarding: {
+ returnUrl: `${process.env.VENDOR_URL}/stripe`,
+ refreshBaseUrl: process.env.BACKEND_URL,
+ },
},
}
```
@@ -123,17 +128,18 @@ Register `@mercurjs/payout-stripe-connect` as a provider of the payout module:
| --- | --- | --- | --- |
| `apiKey` | `string` | Required | Stripe secret key |
| `webhookSecret` | `string` | Required | Verifies incoming Stripe webhook signatures |
+| `manualPayouts` | `boolean` | `false` | Put new connected accounts on a manual payout schedule, so the plugin's settlements send bank payouts |
| `accountValidation.detailsSubmitted` | `boolean` | `true` | Require onboarding details submitted before the account is active |
| `accountValidation.chargesEnabled` | `boolean` | `true` | Require charges enabled |
| `accountValidation.payoutsEnabled` | `boolean` | `true` | Require payouts enabled |
| `accountValidation.noOutstandingRequirements` | `boolean` | `true` | Treat pending Stripe requirements as `restricted` |
| `accountValidation.requiredCapabilities` | `string[]` | `[]` | Stripe capabilities that must be `active` |
-The payout module itself also accepts scheduling options (`authorizationWindowMs`, `sellerActionWindowMs`, `captureSafetyBufferMs`, `requiredFulfillmentStatus`). See the [Payout module](/platform/payout/overview).
+The payout module itself accepts only `onboarding` options (`returnUrl`, `refreshBaseUrl`, `prefill`, `defaultCountry`). Scheduling options (`capture`, `transfers`, `reversals`, `settlements`, `notifications`, `alerting`, `kycMonitor`) belong to the Stripe connector plugin's entry under `plugins`. See the [Stripe Connect integration](/resources/integrations/stripe-connect/configuration).
## Next steps
<CardGroup cols={2}>
<Card title="Installation" href="/learn/introduction" />
- <Card title="Stripe Connect integration" href="/rc/resources/integrations/stripe-connect" />
+ <Card title="Stripe Connect integration" href="/rc/resources/integrations/stripe-connect/configuration" />
</CardGroup>
diff --git a/apps/docs/resources/deployment/medusa-cloud.mdx b/apps/docs/resources/deployment/medusa-cloud.mdx
index 8f2da31dd..dba071cfc 100644
--- a/apps/docs/resources/deployment/medusa-cloud.mdx
+++ b/apps/docs/resources/deployment/medusa-cloud.mdx
@@ -112,7 +112,7 @@ silently point at `http://localhost:9000`. Make sure to set it as described belo
<Info>
For Stripe setup, including which keys go where and how to wire both webhooks,
see the [Stripe Connect integration
- guide](/rc/resources/integrations/stripe-connect).
+ guide](/rc/resources/integrations/stripe-connect/overview).
</Info>
</Step>
<Step title="Create and deploy">
@@ -159,7 +159,7 @@ Open the admin panel and sign in with the **Initial user** you configured in the
## Next steps
<CardGroup cols={2}>
- <Card title="Stripe Connect" href="/rc/resources/integrations/stripe-connect">
+ <Card title="Stripe Connect" href="/rc/resources/integrations/stripe-connect/overview">
Wire payments and payouts on the deployed environment.
</Card>
<Card title="Overview" href="/learn/introduction">
diff --git a/apps/docs/resources/deployment/self-host.mdx b/apps/docs/resources/deployment/self-host.mdx
index 4c70924e6..0d8142475 100644
--- a/apps/docs/resources/deployment/self-host.mdx
+++ b/apps/docs/resources/deployment/self-host.mdx
@@ -117,7 +117,7 @@ then host the static output on any static host or CDN.
<Card title="Medusa Cloud" icon="cloud" href="/resources/deployment/medusa-cloud">
Deploy without managing infrastructure yourself.
</Card>
- <Card title="Stripe Connect" icon="credit-card" href="/resources/integrations/stripe-connect">
+ <Card title="Stripe Connect" icon="credit-card" href="/resources/integrations/stripe-connect/overview">
Wire up payments and payouts for production.
</Card>
</CardGroup>
diff --git a/apps/docs/resources/integrations/magento2.mdx b/apps/docs/resources/integrations/magento2.mdx
new file mode 100644
index 000000000..aff212f6a
--- /dev/null
+++ b/apps/docs/resources/integrations/magento2.mdx
@@ -0,0 +1,162 @@
+---
+title: "Magento 2 marketplace integration"
+sidebarTitle: "Magento 2"
+description: "Turn your Magento 2 or Adobe Commerce store into a multi-vendor marketplace with Mercur. Install the connector, sync seller offers, and split each order per seller."
+---
+
+The Magento 2 connector lets a store you already run sell marketplace offers next to its own catalog. Magento keeps the storefront, cart, checkout, payment capture and your first-party products. Mercur keeps sellers, their offers, the split of one checkout into one order per seller, commission lines and payouts.
+
+The integration has two halves:
+
+- **`@mercurjs/magento2-connector-plugin`**, a plugin for your Mercur API that adds outbound webhooks, an external payment provider and a few admin routes
+- **`mercurjs/magento2-connector`**, a Composer package of Magento modules that mirrors sellers and offers into Magento and talks to Mercur during checkout
+
+<Tip>
+ This page is the setup guide. The connector's source, module layout and development workflow live in the [magento2-connector repository](https://github.com/mercurjs/magento2-connector).
+</Tip>
+
+## Quick start
+
+<Steps>
+ <Step title="Install the plugin in Mercur">
+ Add the plugin and register its payment provider in `medusa-config.ts`:
+
+ ```ts
+ module.exports = withMercur({
+ plugins: [
+ { resolve: "@mercurjs/magento2-connector-plugin", options: {} },
+ ],
+ modules: [
+ {
+ resolve: "@medusajs/medusa/payment",
+ options: {
+ providers: [
+ {
+ resolve: "@mercurjs/magento2-connector-plugin/providers/payment-external",
+ id: "external",
+ },
+ ],
+ },
+ },
+ ],
+ })
+ ```
+
+ Run `medusa db:migrate` afterwards. The provider is registered as `pp_external_external`; it records a payment Magento already captured instead of charging anyone.
+
+ Then enable it for the region your Magento website sells in: open the region in the Mercur admin and add **pp_external_external** to its payment providers. The shadow cart cannot complete without it.
+ </Step>
+ <Step title="Install the Magento package">
+ In your Magento root. The package is installed from its Git repository until it is published to Packagist, so add the repository first:
+
+ ```bash
+ composer config repositories.mercur vcs https://github.com/mercurjs/magento2-connector
+ composer require mercurjs/magento2-connector:dev-main
+ bin/magento module:enable Mercur_Core Mercur_Process Mercur_Connector \
+ Mercur_OfferIndexer Mercur_Catalog Mercur_Settlement Mercur_Frontend Mercur_GraphQl
+ # Only on stores that run Multi-Source Inventory:
+ bin/magento module:enable Mercur_Inventory
+ bin/magento setup:upgrade
+ bin/magento setup:di:compile
+ bin/magento cache:flush
+ ```
+ </Step>
+ <Step title="Get API details">
+ You need four values from Mercur:
+
+ - **Admin API key**: create a secret API key under **Settings → API keys**. If your deployment runs a roles module, bind it to a role that holds only the `integrations` permission; without one the key has full admin access, so treat it like an admin password
+ - **Publishable API key**: the publishable key of the sales channel the shadow cart is created in
+ - **Sales channel ID** and **Region ID**: the channel and the region whose prices the Magento website shows, one region per website
+ </Step>
+ <Step title="Connect Magento">
+ In Magento open **Stores → Configuration → Mercur → Marketplace** and enter the API URL and the four values above. Choose a best offer rule: lowest price, your own stock first, or premium sellers first.
+ </Step>
+ <Step title="Register the webhook">
+ In the Mercur admin open **Settings → Magento → Add endpoint**, enter `https://your_shop_domain/mercur/webhook`, keep every event selected, and copy the signing secret. The connector needs the fulfillment, shipment, delivery, return and refund events to keep orders in step. It is shown once. Paste it into the Magento configuration under **Webhooks → Signing secret**.
+ </Step>
+ <Step title="Run the first sync">
+ Push your taxonomy, then mirror everything:
+
+ ```bash
+ bin/magento mercur:sync taxonomy
+ bin/magento mercur:sync full
+ ```
+
+ Cron keeps the mirror current afterwards: sellers every 15 minutes, offers every 5 minutes, published products hourly, a full resync every night. Each run is a process under **Mercur → Processes** in the Magento admin.
+ </Step>
+</Steps>
+
+## How a mixed order flows
+
+A shopper buys one of your own products and one seller offer in the same checkout and pays once:
+
+1. The product page lists every active seller offer next to your own stock, with its price for that website, any price list strike-through, quantity tiers and an estimated delivery date. Adding an offer marks the cart line as a marketplace line priced by the offer and labels it "Sold by" the seller. The same works through REST and GraphQL with `mercur_offer_id`.
+2. The cart and the checkout group the marketplace lines by seller. Magento copies them into a shadow Mercur cart, asks Mercur for each seller's shipping options and lets the shopper pick one per seller; the sum is the "Seller shipping" total. Your own carriers only price your own lines, and a cart of seller lines only gets the "Shipped by the sellers" method.
+3. The shopper pays in Magento. The invoice includes seller shipping.
+4. After the order is placed, Magento records the capture on the external payment provider and completes the Mercur cart. Mercur answers with an order group, one order per seller, and Magento stores those ids on the order and its lines.
+5. Sellers fulfill in the vendor panel. Each shipped fulfillment becomes its own Magento shipment with its tracking numbers, so partial and multi-parcel deliveries show up as they happen. Deliveries, returns and cancellations update the line's marketplace status, shown to the shopper in their account and to you in the admin.
+6. Mercur computes commission lines when the cart completes and pays sellers from the recorded capture.
+
+If Mercur is unreachable at step 4, the Magento order still succeeds and the `order_retry` process completes the Mercur side on its next run.
+
+## Refunds
+
+| Starts in | What happens |
+| --- | --- |
+| Magento | A credit memo on marketplace lines is reported to Mercur per seller order, with seller shipping split by what each seller charged, so commission lines and payout balances follow |
+| Mercur, a seller or operator refund | Mercur sends `order.refund_requested`; Magento creates an adjustment credit memo and refunds the shopper online when the invoice was captured online |
+| Mercur, a canceled seller order | Magento refunds that seller's lines and shipping |
+
+A `refunds` process every 15 minutes picks up any refund whose webhook did not arrive.
+
+## Essential practices
+
+### One region per website
+
+Offer prices are read for the region configured on each Magento website, including Mercur price lists. A store with a US and an EU website needs two Mercur regions and two website-scoped values of **Mercur region ID**, and each website's base currency must match its region's currency.
+
+### Set delivery estimates
+
+Under **Mercur → Marketplace → Delivery estimates** set the order cut-off time, business days and transit days for each website. A Mercur shipping option can carry its own `transit_days_min` and `transit_days_max` in its data.
+
+### Keep the operator's stock as a candidate
+
+Your own product is always one of the ways to buy a SKU. The best offer rule decides whether it wins over a cheaper seller; `operator_first` keeps your stock on top whenever it is in stock.
+
+### Let webhooks drive, keep cron as the floor
+
+Offer, seller and product events enqueue the matching delta sync within a minute. The cron schedules exist so the mirror heals after a missed delivery; a full nightly resync removes anything a delta could not see.
+
+## Your products or seller offers
+
+| Situation | What happens |
+| --- | --- |
+| A product only you sell | A normal Magento line: your price, your stock, your carriers |
+| A product only sellers sell | Imported from Mercur, as a configurable product when its variant axes are Magento attributes; it is in stock while an offer is available and every line is a marketplace line |
+| A product both you and sellers sell | Same SKU, one buy box; the best offer rule picks the default and the shopper can choose another. When you run out, the product stays buyable from sellers |
+
+Each seller has a page at `/seller/{handle}` listing what they sell on your store. In the Magento admin, **Mercur → Sellers** and **Mercur → Offers** show the mirror, orders show each seller order with its status, and the product page lists the offers for that SKU.
+
+## Not supported yet
+
+- Buyer and seller messaging, order incidents and seller ratings
+- Documents sellers attach to orders
+- A third-party tax engine for seller lines; Magento taxes them with the product's tax class
+- Mercur promotions; Magento cart rules still apply to seller lines
+
+## Next steps
+
+<CardGroup cols={2}>
+ <Card title="Connector repository" icon="github" href="https://github.com/mercurjs/magento2-connector">
+ Modules, development workflow, and the webhook handler registry.
+ </Card>
+ <Card title="Offer module" icon="tag" href="/platform/offer/overview">
+ How offers carry seller SKU, price, inventory and shipping.
+ </Card>
+ <Card title="Order Group module" icon="layer-group" href="/platform/order-group/overview">
+ How one checkout becomes one order per seller.
+ </Card>
+ <Card title="Commission module" icon="percent" href="/platform/commission/overview">
+ How commission lines are computed at completion.
+ </Card>
+</CardGroup>
diff --git a/apps/docs/resources/integrations/overview.mdx b/apps/docs/resources/integrations/overview.mdx
index 446c1d853..9c7c44ae8 100644
--- a/apps/docs/resources/integrations/overview.mdx
+++ b/apps/docs/resources/integrations/overview.mdx
@@ -12,14 +12,14 @@ top of the core platform.
A payout provider settles seller earnings to their connected accounts. Stripe
Connect ships out of the box. You can add your own provider against the same
-interface.
+interface, described in the [Payout module](/platform/payout/overview).
<CardGroup cols={2}>
- <Card title="Stripe Connect" icon="credit-card" href="/resources/integrations/stripe-connect">
- Configure the Stripe Connect payout provider.
+ <Card title="Stripe Connect" icon="credit-card" href="/resources/integrations/stripe-connect/overview">
+ Charge the cart once, pay each seller per order and settle to their bank.
</Card>
- <Card title="Payout module" icon="wallet" href="/platform/payout/overview">
- Accounts, onboarding, and the transfer pipeline.
+ <Card title="Stripe Connect quickstart" icon="rocket" href="/resources/integrations/stripe-connect/quickstart">
+ Onboard a test seller and pay out a first order.
</Card>
</CardGroup>
diff --git a/apps/docs/resources/integrations/stripe-connect.mdx b/apps/docs/resources/integrations/stripe-connect.mdx
deleted file mode 100644
index 717378167..000000000
--- a/apps/docs/resources/integrations/stripe-connect.mdx
+++ /dev/null
@@ -1,406 +0,0 @@
----
-title: "Stripe Connect"
-sidebarTitle: "Stripe Connect"
-description: "Set up Stripe Connect for marketplace payments and seller payouts, from Stripe Dashboard configuration to the full end-to-end payment lifecycle."
----
-
-A Mercur marketplace needs **two** Stripe integrations working together. The first is the standard Medusa payment provider, which charges customers at checkout. The second is the Mercur payout provider, which transfers funds from the platform to sellers after orders are fulfilled.
-
-This guide covers both. It walks through setting up Stripe, configuring both providers, wiring up webhooks, and understanding how money flows from customer to seller.
-
-<Tip>
- This page is the configuration reference. For how payout accounts, onboarding, and the transfer pipeline work, see the [Payout](/platform/payout/overview) module.
-</Tip>
-
-<Info>
- Mercur uses Stripe's [Separate Charges and Transfers](https://docs.stripe.com/connect/separate-charges-and-transfers) model. The platform collects the full payment from the customer, then creates transfers to each seller's connected account. This makes the platform the **Merchant of Record**, responsible for VAT, disputes, and chargebacks.
-</Info>
-
-## Prerequisites
-
-- A [Stripe account](https://dashboard.stripe.com) with Connect enabled
-- Stripe Secret API key and Publishable API key
-- A running Mercur project ([installation guide](/learn/introduction))
-- Node.js 22.22+
-
-## Architecture overview
-
-The payment lifecycle in a Mercur marketplace flows through two distinct Stripe integrations:
-
-```mermaid
-flowchart LR
- C[Customer] -->|PaymentIntent| P[Platform Stripe Account]
- P -->|Transfer| S1[Seller A Connected Account]
- P -->|Transfer| S2[Seller B Connected Account]
- S1 -->|Payout| B1[Seller A Bank]
- S2 -->|Payout| B2[Seller B Bank]
-```
-
-The two integrations serve different purposes:
-
-| Integration | Package | Purpose | Webhook endpoint |
-|---|---|---|---|
-| Customer payments | `@medusajs/medusa/payment-stripe` | Charges customers at checkout | `/hooks/payment/stripe_stripe` |
-| Seller payouts | `@mercurjs/payout-stripe-connect` | Transfers funds to sellers | `/hooks/payout` |
-
-## Stripe Dashboard setup
-
-<Steps>
- <Step title="Enable Connect">
- In your Stripe Dashboard, go to **Settings → Connect settings** and enable Connect. If you're starting fresh, Stripe will walk you through an onboarding flow to activate your platform account.
- </Step>
- <Step title="Find your API keys">
- Go to **Developers → API keys**. You'll need:
-
- - **Secret key:** starts with `sk_test_` (test mode) or `sk_live_` (production)
- - **Publishable key:** starts with `pk_test_` or `pk_live_`
- </Step>
- <Step title="Set environment variables">
- Add the following to your `.env` file:
-
- ```bash
- STRIPE_API_KEY=sk_test_...
- STRIPE_WEBHOOK_SECRET=whsec_...
- STRIPE_PAYOUT_WEBHOOK_SECRET=whsec_...
- ```
- </Step>
-</Steps>
-
-## Configure Medusa payment provider
-
-The Medusa payment provider handles customer-facing charges. Add it to your `medusa-config.ts`:
-
-```ts
-module.exports = defineConfig({
- // ...
- modules: [
- {
- resolve: "@medusajs/medusa/payment",
- options: {
- providers: [
- {
- resolve: "@medusajs/medusa/payment-stripe",
- id: "stripe",
- options: {
- apiKey: process.env.STRIPE_API_KEY,
- webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
- capture: false, // Use manual capture for marketplace flow
- automatic_payment_methods: true,
- },
- },
- ],
- },
- },
- ],
-})
-```
-
-### Provider options
-
-| Option | Type | Description |
-|--------|------|-------------|
-| `apiKey` | `string` | Stripe secret API key |
-| `webhookSecret` | `string` | Signing secret for the payment webhook endpoint |
-| `capture` | `boolean` | Set to `false` for manual capture (required for marketplace split flow) |
-| `automatic_payment_methods` | `boolean` | Enable Stripe's automatic payment method detection |
-| `paymentDescription` | `string` | Optional description shown on customer's bank statement |
-
-<Info>
- After configuring the provider, enable Stripe as a payment method in your Admin Panel: **Settings → Regions → Edit region → Payment providers → Stripe**.
-</Info>
-
-## Configure Mercur payout provider
-
-The payout provider handles transfers from the platform to seller connected accounts. Add it alongside the payment provider in `medusa-config.ts`:
-
-```ts
-module.exports = defineConfig({
- // ...
- modules: [
- // ... payment provider above
- {
- resolve: "@mercurjs/core/modules/payout",
- options: {
- providers: [
- {
- resolve: "@mercurjs/payout-stripe-connect",
- id: "stripe-connect",
- options: {
- apiKey: process.env.STRIPE_API_KEY,
- webhookSecret: process.env.STRIPE_PAYOUT_WEBHOOK_SECRET,
- accountValidation: {
- detailsSubmitted: true,
- chargesEnabled: true,
- payoutsEnabled: true,
- noOutstandingRequirements: true,
- requiredCapabilities: [],
- },
- },
- },
- ],
- },
- },
- ],
-})
-```
-
-### Payout provider options
-
-| Option | Type | Default | Description |
-|--------|------|---------|-------------|
-| `apiKey` | `string` | - | Stripe secret API key |
-| `webhookSecret` | `string` | - | Signing secret for the payout webhook endpoint |
-| `accountValidation` | `object` | See below | Controls when a connected account is considered `ACTIVE` |
-
-### Account validation options
-
-These options determine what conditions a Stripe connected account must meet before Mercur marks it as `ACTIVE` and allows payouts:
-
-| Option | Type | Default | Description |
-|--------|------|---------|-------------|
-| `detailsSubmitted` | `boolean` | `true` | Require Stripe to mark onboarding details as submitted |
-| `chargesEnabled` | `boolean` | `true` | Require the account to be enabled for charges |
-| `payoutsEnabled` | `boolean` | `true` | Require the account to be enabled for payouts |
-| `noOutstandingRequirements` | `boolean` | `true` | Treat any pending Stripe requirements as a restricted account |
-| `requiredCapabilities` | `string[]` | `[]` | Require specific Stripe capabilities to be active (e.g. `["card_payments", "transfers"]`) |
-
-### Payout module options
-
-The payout module itself accepts timing options that control the capture and payout pipeline:
-
-| Option | Type | Default | Description |
-|--------|------|---------|-------------|
-| `disabled` | `boolean` | `false` | Disable automatic capture checks and daily payout jobs |
-| `authorizationWindowMs` | `number` | `604800000` (7 days) | How long a payment authorization remains valid |
-| `sellerActionWindowMs` | `number` | `259200000` (72 hours) | How long sellers have to accept/fulfill before cancellation |
-| `captureSafetyBufferMs` | `number` | `86400000` (24 hours) | Safety margin before authorization expiry. Capture happens before `authorization expiry - buffer` |
-| `requiredFulfillmentStatus` | `string` | `"fulfilled"` | Minimum fulfillment status before an order is eligible for capture |
-
-## Set up webhooks
-
-You need **two separate webhook endpoints** in Stripe: one for payment events, one for payout events.
-
-<Warning>
- These are two distinct webhook endpoints, each with its own signing secret. Do not combine them into a single endpoint.
-</Warning>
-
-<Steps>
- <Step title="Add the payment webhook (Medusa)">
- In the Stripe Dashboard, go to **Developers → Webhooks → Add endpoint**.
-
- - **Endpoint URL**: `https://{your-backend-url}/hooks/payment/stripe_stripe`
- - **Events to subscribe to**:
- - `payment_intent.succeeded`
- - `payment_intent.amount_capturable_updated`
- - `payment_intent.payment_failed`
- - `payment_intent.partially_funded` (optional, only if you support that recovery flow)
-
- Copy the signing secret and set it as `STRIPE_WEBHOOK_SECRET` in your `.env`.
-
- <Note>
- With `capture: false`, Stripe sends `payment_intent.amount_capturable_updated` as soon as the payment is authorized, which can be before the storefront calls `POST /store/carts/:id/complete`. A webhook-driven completion runs `completeCartWithSplitOrdersWorkflow` under the same cart lock as the store route, so it still produces an order group with per-seller orders. It also completes carts whose customer left right after authenticating, so keep it enabled.
- </Note>
-
- <Warning>
- Don't rely on `charge.refunded` for seller reconciliation. The Medusa Stripe provider doesn't act on it, and it never reverses Stripe Connect Transfers. See [Refunds and reversals](#refunds-and-reversals).
- </Warning>
- </Step>
- <Step title="Add the payout webhook (Mercur)">
- Add a second webhook endpoint in the Stripe Dashboard.
-
- - **Endpoint URL**: `https://{your-backend-url}/hooks/payout`
- - **Events to subscribe to**:
- - `account.updated`
-
- Copy the signing secret and set it as `STRIPE_PAYOUT_WEBHOOK_SECRET` in your `.env`.
- </Step>
-</Steps>
-
-## How the payment flow works
-
-Here's a concrete example. A customer buys items from two sellers:
-
-- **Seller A**: €40 (product)
-- **Seller B**: €30 (product)
-- **Shipping**: €10
-- **Cart total**: €80
-
-### Step 1: Authorize payment
-
-At checkout, a single `PaymentIntent` is created for €80 with `capture_method: "manual"`. The customer authenticates once (SCA-compliant). No money moves yet. The funds are held on the customer's card.
-
-### Step 2: Split orders
-
-Mercur's `completeCartWithSplitOrdersWorkflow` groups items by seller and creates separate orders: one for Seller A (€40) and one for Seller B (€30), plus shipping allocation.
-
-### Step 3: Seller acceptance and fulfillment
-
-Each seller reviews and fulfills their order through the Vendor Portal. The payout module's `sellerActionWindowMs` (default: 72 hours) defines how long sellers have to act.
-
-### Step 4: Capture payment
-
-Once orders meet the `requiredFulfillmentStatus` (default: `"fulfilled"`), the platform captures the authorized payment. The capture-check job runs automatically and respects the `captureSafetyBufferMs` to ensure capture happens before authorization expiry.
-
-<Warning>
- Card authorizations typically expire after **7 days**. The default configuration gives sellers 72 hours to fulfill, with a 24-hour safety buffer before capture. If your business requires longer seller action windows, consider whether the 7-day authorization window is sufficient.
-</Warning>
-
-### Step 5: Commission calculation and transfers
-
-After capture, Mercur calculates commission for each order and creates Stripe Transfers for the net amounts:
-
-```
-Seller A net = €40 - commission
-Seller B net = €30 - commission
-```
-
-Each transfer is linked to the original charge via `source_transaction` and grouped by `transfer_group` (the order ID).
-
-### Step 6: Bank payouts
-
-Stripe automatically pays out connected account balances to sellers' bank accounts on the configured payout schedule. Mercur tracks payout status changes via the `account.updated` webhook.
-
-## Seller onboarding
-
-When a seller creates a payout account, the following lifecycle begins:
-
-```
-PENDING → (Stripe onboarding) → ACTIVE
- ↓
- RESTRICTED → ACTIVE (remediation)
- ↓
- REJECTED (permanent)
-```
-
-1. **Account creation.** Mercur calls `stripe.accounts.create({ type: "express" })`, creating a Stripe Express connected account. The payout account starts in `PENDING` status.
-
-2. **Onboarding link.** The seller receives a Stripe-hosted onboarding URL via `stripe.accountLinks.create()`. They complete identity verification, bank account setup, and any required compliance steps directly on Stripe.
-
-3. **Webhook activation.** When the seller completes onboarding, Stripe sends an `account.updated` webhook. The provider evaluates the account against the `accountValidation` options and transitions the status:
- - All validation checks pass → `ACTIVE`
- - Missing requirements or disabled reason → `RESTRICTED`
- - Disabled reason starts with `rejected.` → `REJECTED`
-
-4. **Ongoing monitoring.** Stripe may send additional `account.updated` events if requirements change. The provider re-evaluates and updates the status accordingly.
-
-For more details on payout accounts, balances, and transactions, see [Payout](/rc/learn/payouts).
-
-## Transfers vs payouts
-
-Stripe uses two distinct concepts for moving money, and it's important to understand the difference:
-
-| | Transfer | Payout |
-|---|---|---|
-| **What it does** | Moves funds from platform balance to connected account balance | Moves funds from connected account balance to seller's bank account |
-| **Speed** | Instant ledger movement | 1–3 business days (varies by country) |
-| **Status lifecycle** | None. Transfers are immediate | `pending` → `in_transit` → `paid` / `failed` |
-| **Who triggers it** | Mercur (via `stripe.transfers.create()`) | Stripe (on the connected account's payout schedule) |
-| **Mercur tracking** | Transfer created with status `PAID` immediately | Status tracked via webhooks |
-
-When Mercur's `createPayout` method is called, the Stripe Connect provider creates a **Transfer** (platform → connected account). The actual bank payout (connected account → bank) happens automatically on Stripe's schedule.
-
-## Refunds and reversals
-
-Refunding a charge does **not** automatically reverse the associated transfers. These are two separate operations:
-
-1. **Refund the PaymentIntent.** Returns funds to the customer's payment method
-2. **Reverse the Transfer(s).** Claws back funds from the connected account(s)
-
-Mercur doesn't reverse transfers for you. The Stripe Connect payout provider only handles `account.updated`, and a `charge.refunded` event is not confirmation that any seller transfer was reversed. If you refund after a seller has been paid out, reconcile their side yourself, either with a transfer reversal or by deducting the amount from their next payout.
-
-For a full refund of a multi-seller order, you would need to reverse each seller's transfer individually. For partial refunds, you need to calculate how much to reverse from each seller based on which items are being refunded.
-
-<Info>
- Refund and transfer reversal orchestration is an area where custom workflow logic may be needed depending on your business rules. See Stripe's documentation on [reversing transfers](https://docs.stripe.com/connect/separate-charges-and-transfers#reverse-transfers) for the API details.
-</Info>
-
-## EU/EEA considerations
-
-### Merchant of Record
-
-Using Separate Charges and Transfers makes the platform the Merchant of Record. This means:
-
-- The platform collects and remits VAT
-- The platform handles consumer disputes and chargebacks
-- The platform is responsible for PSD2 compliance
-
-### Strong Customer Authentication (SCA)
-
-SCA is enforced at **authorization time**, not capture time. Since the customer authenticates once during checkout, no additional SCA step is needed when the platform captures later. The single authorization at checkout satisfies the SCA requirement for the entire order.
-
-### Authorization windows
-
-Card authorizations in Europe typically last **7 days**. Design your seller acceptance workflow to complete well within this window. The payout module options give you control over the timing:
-
-```ts
-{
- resolve: "@mercurjs/core/modules/payout",
- options: {
- authorizationWindowMs: 7 * 24 * 60 * 60 * 1000, // 7 days
- sellerActionWindowMs: 72 * 60 * 60 * 1000, // 72 hours
- captureSafetyBufferMs: 24 * 60 * 60 * 1000, // 24 hours
- // ...providers
- },
-}
-```
-
-## Testing
-
-### Test mode
-
-Use Stripe test mode keys (`sk_test_`, `pk_test_`) during development. All connected accounts and payments created in test mode are isolated from production.
-
-**Test card number**: `4242 4242 4242 4242` (any future expiry, any CVC)
-
-### Webhook forwarding with Stripe CLI
-
-Since webhooks need to reach your local machine during development, use the [Stripe CLI](https://docs.stripe.com/stripe-cli) to forward events. You need **two separate listeners**, one for each webhook endpoint:
-
-```bash
-# Terminal 1: Payment webhooks
-stripe listen --forward-to localhost:9000/hooks/payment/stripe_stripe
-
-# Terminal 2: Payout webhooks
-stripe listen --forward-to localhost:9000/hooks/payout
-```
-
-<Tip>
- Each `stripe listen` process outputs its own webhook signing secret. Use these as your `STRIPE_WEBHOOK_SECRET` and `STRIPE_PAYOUT_WEBHOOK_SECRET` respectively during local development.
-</Tip>
-
-### Testing the full flow
-
-1. Create a seller and complete Stripe's test onboarding flow
-2. Add products from the seller to a cart
-3. Complete checkout using the test card
-4. Verify orders are split by seller in the Admin Panel
-5. Fulfill the orders through the Vendor Portal
-6. Confirm transfers appear in the Stripe Dashboard under the connected account
-
-## FAQ
-
-<AccordionGroup>
- <Accordion title="Why do I need two webhook endpoints with two secrets?">
- They belong to two different integrations: the payment webhook feeds Medusa's payment provider (charges, captures, refunds), while the payout webhook feeds Mercur's payout provider (connected-account status, transfer status). Each endpoint verifies its own signing secret. Combining them silently breaks whichever side's signature doesn't match.
- </Accordion>
- <Accordion title="Why must capture be set to false on the payment provider?">
- The marketplace flow authorizes at checkout and captures later, after sellers fulfill. Automatic capture would take the money before the split-order pipeline (fulfillment checks, commission, payouts) has run. `capture: false` hands that timing to the payout module's capture job.
- </Accordion>
- <Accordion title="A seller finished Stripe onboarding but is still not ACTIVE. Why?">
- Check the `accountValidation` options: by default the account must have details submitted, charges and payouts enabled, and **no outstanding requirements**. Stripe often adds follow-up requirements (e.g. extra KYC) after initial onboarding. The account shows as `RESTRICTED` until they're cleared.
- </Accordion>
- <Accordion title="Who handles VAT, disputes, and chargebacks?">
- The platform. Separate Charges and Transfers makes the platform the Merchant of Record. See [EU/EEA considerations](#eueea-considerations) for what that entails.
- </Accordion>
-</AccordionGroup>
-
-## Next steps
-
-<CardGroup cols={2}>
- <Card title="Payout" href="/platform/payout/overview">
- Payout accounts, onboarding, and the transfer pipeline.
- </Card>
- <Card title="The payout pipeline" href="/platform/payout/concepts/payout-pipeline">
- Statuses, jobs, and webhook events.
- </Card>
-</CardGroup>
diff --git a/apps/docs/resources/integrations/stripe-connect/architecture.mdx b/apps/docs/resources/integrations/stripe-connect/architecture.mdx
new file mode 100644
index 000000000..ae7266da6
--- /dev/null
+++ b/apps/docs/resources/integrations/stripe-connect/architecture.mdx
@@ -0,0 +1,93 @@
+---
+title: "Stripe Connect architecture"
+sidebarTitle: "Architecture"
+description: "What Mercur core owns, what the Stripe connector plugin adds on top, which Stripe objects each step creates, and how one order's money travels from the customer's card to the seller's bank."
+---
+
+The integration has three layers. Stripe holds the money and the connected accounts. Mercur core's payout module records what each seller is owed per order. The Stripe connector plugin decides when each step runs and adds everything that is Stripe-specific.
+
+```mermaid
+flowchart LR
+ C[Customer] -->|PaymentIntent, manual capture| P[Platform Stripe account]
+ P -->|Transfer per order| S1[Seller A connected account]
+ P -->|Transfer per order| S2[Seller B connected account]
+ S1 -->|Payout per settlement| B1[Seller A bank]
+ S2 -->|Payout per settlement| B2[Seller B bank]
+```
+
+## What runs where
+
+| Layer | Package | Owns |
+| --- | --- | --- |
+| Payment provider | `@mercurjs/stripe-connector-plugin/providers/payment-stripe` | The PaymentIntent for the whole cart on the platform account, with manual capture, and its refunds |
+| Payout provider | `@mercurjs/stripe-connector-plugin/providers/payout-stripe-connect` | Express accounts, onboarding and login links, a Transfer per payout, a Transfer reversal per refund, and Connect webhooks |
+| Payout module | `@mercurjs/core/modules/payout` | `payout_account`, its `onboarding` link, one `payout` per seller order and one `payout_reversal` per later refund, with their statuses |
+| Plugin module | `stripe_connector` | Captures, settlements and their lines, adjustments, job runs, checkpoints and the notification log |
+| Plugin jobs and subscribers | `@mercurjs/stripe-connector-plugin` | When to capture, pay out, reverse and settle |
+| Plugin screens | `@mercurjs/stripe-connector-plugin/admin`, `/vendor` | **Integrations → Stripe** and **Settings → Stripe** in the admin, widgets on the order and payout account pages, and the vendor **Stripe** page |
+
+Core ships no schedule. Its workflows, `createOrderPayoutsWorkflow` and `createPayoutReversalsWorkflow`, decide and send whatever they're called with. The plugin's jobs and subscribers call them, and add the backlog, checkpoints and run records around them.
+
+## Stripe objects
+
+| Mercur record | Stripe object | Created by | On |
+| --- | --- | --- | --- |
+| Payment on the order group | PaymentIntent with `capture_method: manual` | Payment provider | The platform account |
+| `payout_account` | Express Account | Payout provider | The platform account |
+| `onboarding` | Account Link (onboarding) or Login Link | Payout provider | The connected account |
+| `payout` | Transfer with `source_transaction` set to the charge | Payout provider | The platform account, to the connected account |
+| `payout_reversal` | Transfer reversal | Payout provider | The original Transfer |
+| Adjustment credit | Transfer | Plugin | The platform account, to the connected account |
+| Adjustment debit | Transfer from the connected account | Plugin | The connected account, to the platform |
+| Settlement | Payout | Plugin | The connected account, to its bank |
+
+Every call that moves money carries an idempotency key built from the Mercur record id and its attempt number, so a job that resends the same attempt never moves money twice.
+
+Transfers use `source_transaction`, so a payout can be sent as soon as the charge is captured, even while the funds are still pending on the platform balance.
+
+## Anatomy of an order
+
+A customer buys from two sellers in one cart, and pays once.
+
+1. **Checkout.** The payment provider creates one PaymentIntent for the cart with manual capture. The card is authorized, not charged. Mercur splits the cart into an order group with one order per seller and writes commission lines. The plugin opens a **capture** for the order group.
+2. **Orders are decided.** Each seller fulfills or cancels their order. Every fulfillment and cancellation refreshes the capture.
+3. **Capture.** Once every order is decided, the capture job captures the authorized amount minus canceled orders. If every order was canceled, it cancels the authorization instead. Medusa then gives each seller order its own captured payment on the same charge.
+4. **Payout.** The capture runs the payout pass. For each fulfilled, captured order, core writes a `payout` of the order total minus commission, net of refunds that already landed, and the provider sends it as a Transfer.
+5. **Refund.** A refund on a paid order writes a `payout_reversal` of the seller's share, net of its commission share, and the provider reverses that much of the Transfer.
+6. **Settlement.** Every night the settlement job nets the seller's paid payouts, reversals and adjustments since the previous settlement, per currency, and sends the total to the seller's bank as a Stripe Payout.
+7. **Webhooks.** `account.updated` keeps the payout account in step with Stripe. Bank `payout.*` events move the settlement to **Paid out** or **Failed**.
+
+## When each step runs
+
+Every step runs from a scheduled job, so nothing is lost if an event is missed. Most also run right away from a subscriber, so sellers don't wait for the next tick.
+
+| Trigger | Runs |
+| --- | --- |
+| Order group created | Opens the group's capture |
+| Order fulfilled or canceled | Refreshes the group's capture, then the order's payout pass |
+| Payment captured | The payout pass for the captured orders |
+| Refund created | The reversal pass for the order |
+| Payout account becomes active | Queues the seller's orders that were waiting for an account, for the next payout run |
+| Stripe `account.updated` | Syncs the payout account |
+| Stripe `payout.*` | Updates the settlement's bank payout |
+
+The scheduled jobs and their default times are listed in the [reference](/resources/integrations/stripe-connect/reference#scheduled-jobs).
+
+## Job runs and checkpoints
+
+Every run of every job, whether scheduled, started with **Run now** or started by a subscriber, writes a **job run** with its trigger, its status and counts of what it did. A job that is already running isn't started twice.
+
+Jobs that scan for new work keep a **checkpoint**, the timestamp they last read up to, so each run reads only what changed. A job that fails leaves its checkpoint where it was and reads the same window again next time.
+
+Jobs that act on many sellers or orders run one workflow per item. A seller whose account Stripe rejects is recorded as failed, and the rest go through.
+
+## Settlement modes
+
+`settlements.mode` decides who sends the bank payout:
+
+| Mode | Bank payout sent by | Connected accounts | Settlement records |
+| --- | --- | --- | --- |
+| `plugin` (default) | The plugin, as one Stripe Payout per settlement | Manual payout schedule, with `manualPayouts: true` on the payout provider | Open until Stripe confirms the bank payout |
+| `provider` | Stripe, on the account's automatic payout schedule | Stripe's default schedule | Recorded as paid out, for the seller's statement only |
+
+Use `plugin` when you want one deposit per period that matches the seller's statement to the cent. Use `provider` when you prefer Stripe's daily or weekly schedule and only need the netting for reporting.
diff --git a/apps/docs/resources/integrations/stripe-connect/configuration.mdx b/apps/docs/resources/integrations/stripe-connect/configuration.mdx
new file mode 100644
index 000000000..70ab4b8c4
--- /dev/null
+++ b/apps/docs/resources/integrations/stripe-connect/configuration.mdx
@@ -0,0 +1,212 @@
+---
+title: "Configure the Stripe connector"
+sidebarTitle: "Configuration"
+description: "Every option of the Stripe payment provider, the Stripe Connect payout provider, the payout module and the plugin, the two webhook endpoints, and what to change when you go live."
+---
+
+The integration is configured in four places in `medusa-config.ts`, plus two webhook endpoints in the Stripe Dashboard:
+
+| Where | Configures |
+| --- | --- |
+| The plugin entry under `plugins` | Jobs, capture timing, settlements, notifications and alerts |
+| The payment provider on `@medusajs/medusa/payment` | How the cart is charged |
+| The payout provider on `@mercurjs/core/modules/payout` | How connected accounts are created and validated |
+| The payout module's own options | Where sellers land after onboarding |
+
+## Credentials
+
+| Secret | Created in | Used by |
+| --- | --- | --- |
+| Secret API key | Stripe, **Developers → API keys** | The payment provider, the payout provider and the plugin |
+| Platform webhook signing secret | Stripe, when you create the endpoint that listens to **Your account** | The payment provider |
+| Connect webhook signing secret | Stripe, when you create the endpoint that listens to **Connected accounts** | The payout provider and the plugin |
+
+## Full example
+
+```ts medusa-config.ts
+module.exports = withMercur({
+ plugins: [
+ {
+ resolve: "@mercurjs/stripe-connector-plugin",
+ options: {
+ apiKey: process.env.STRIPE_SECRET_KEY,
+ webhookSecret: process.env.STRIPE_SELLERS_WEBHOOK_SECRET,
+ settlements: { mode: "plugin" },
+ alerting: {
+ technicalEmail: "[email protected]",
+ },
+ },
+ },
+ ],
+ modules: [
+ {
+ resolve: "@medusajs/medusa/payment",
+ options: {
+ providers: [
+ {
+ resolve: "@mercurjs/stripe-connector-plugin/providers/payment-stripe",
+ id: "stripe",
+ options: {
+ apiKey: process.env.STRIPE_SECRET_KEY,
+ webhookSecret: process.env.STRIPE_OPERATOR_WEBHOOK_SECRET,
+ },
+ },
+ ],
+ },
+ },
+ {
+ resolve: "@mercurjs/core/modules/payout",
+ options: {
+ providers: [
+ {
+ resolve: "@mercurjs/stripe-connector-plugin/providers/payout-stripe-connect",
+ id: "stripe",
+ options: {
+ apiKey: process.env.STRIPE_SECRET_KEY,
+ webhookSecret: process.env.STRIPE_SELLERS_WEBHOOK_SECRET,
+ manualPayouts: true,
+ },
+ },
+ ],
+ onboarding: {
+ returnUrl: `${process.env.VENDOR_URL}/stripe`,
+ refreshBaseUrl: process.env.BACKEND_URL,
+ },
+ },
+ },
+ ],
+})
+```
+
+Run `bunx medusa db:migrate` after adding the plugin. It creates the plugin's `stripe_connector` tables. Then add `pp_stripe-connector_stripe` to the payment providers of every region that sells through Stripe, under **Settings → Regions**.
+
+## Payment provider
+
+Registered with the id `stripe`, so Medusa exposes it as `pp_stripe-connector_stripe`.
+
+| Option | Type | Default | Description |
+| --- | --- | --- | --- |
+| `apiKey` | `string` | Required | Stripe secret API key |
+| `webhookSecret` | `string` | Required | Signing secret of the platform-account webhook |
+| `automaticPaymentMethods` | `boolean` | `false` | Turn on Stripe's automatic payment methods on the PaymentIntent |
+| `paymentDescription` | `string` | - | Description set on the PaymentIntent |
+| `orderGroupMetadataKey` | `string` | `mercur_order_group_id` | Metadata key carrying the order group id on the PaymentIntent |
+
+Capture is always manual. The plugin's capture job decides when to capture, so there's no `capture` option.
+
+## Payout provider
+
+Registered with the id `stripe`, so Mercur exposes it as `pop_stripe-connect_stripe`. The payout module takes exactly one provider.
+
+| Option | Type | Default | Description |
+| --- | --- | --- | --- |
+| `apiKey` | `string` | Required | Stripe secret API key |
+| `webhookSecret` | `string` | Required | Signing secret of the Connect webhook |
+| `manualPayouts` | `boolean` | `false` | Put new connected accounts on a manual payout schedule, so only the plugin's settlements pay them out. Pair with `settlements.mode: "plugin"` |
+| `accountValidation` | `object` | See below | When a connected account counts as `active` |
+
+### Account validation
+
+A connected account is `active` when every enabled check passes. An account that fails a check after submitting its details is `restricted`, and one Stripe rejected is `rejected`.
+
+| Option | Type | Default | Description |
+| --- | --- | --- | --- |
+| `detailsSubmitted` | `boolean` | `true` | Require onboarding details to be submitted |
+| `chargesEnabled` | `boolean` | `true` | Require charges to be enabled |
+| `payoutsEnabled` | `boolean` | `true` | Require payouts to be enabled |
+| `noOutstandingRequirements` | `boolean` | `true` | Treat any currently due or past due requirement as restricted |
+| `requiredCapabilities` | `string[]` | `[]` | Capabilities that must be `active`, for example `["transfers"]` |
+
+<Note>
+ `manualPayouts` only applies to accounts the provider creates from then on. To move existing accounts to a manual schedule, update their payout settings in Stripe.
+</Note>
+
+## Payout module
+
+These options belong to `@mercurjs/core/modules/payout` and apply to any provider.
+
+| Option | Default | Description |
+| --- | --- | --- |
+| `onboarding.returnUrl` | - | Where Stripe sends the seller after onboarding. Point it at the vendor Stripe page, `<vendor url>/stripe` |
+| `onboarding.refreshBaseUrl` | - | Your API's public origin. When an onboarding link expires, Stripe sends the seller to `<base>/payout/onboarding/refresh?token=...`, which issues a fresh link |
+| `onboarding.prefill` | `false` | Prefill the Express account from the seller: country, business type and business profile |
+| `onboarding.defaultCountry` | - | Country used for a new account when the seller has no address |
+
+## Plugin
+
+These go on the plugin entry under `plugins`, typed by `StripeConnectorPluginOptions` from `@mercurjs/stripe-connector-plugin/types`.
+
+### Credentials
+
+| Option | Default | Description |
+| --- | --- | --- |
+| `apiKey` | - | Platform secret key, used for adjustments and settlement bank payouts |
+| `webhookSecret` | - | Signing secret of the Connect webhook, used to read bank `payout.*` events |
+
+### Onboarding
+
+| Option | Default | Description |
+| --- | --- | --- |
+| `onboarding.enabled` | `true` | Create an Express account for every new seller and publish their onboarding link. Turn off to create accounts only when sellers ask from the vendor Stripe page |
+
+### Capture
+
+| Option | Default | Description |
+| --- | --- | --- |
+| `capture.captureBeforeAcceptance` | `false` | Count an order as decided once it is no longer awaiting acceptance, instead of once it reaches the fulfillment threshold |
+| `capture.authorizationWindowMs` | 7 days | How long a card authorization stays valid. Match your Stripe account's authorization validity |
+| `capture.safetyBufferMs` | 24 hours | How long before expiry to capture what is decided, even if some orders aren't |
+
+### Payouts and reversals
+
+| Option | Default | Description |
+| --- | --- | --- |
+| `transfers.enabled` | `true` | Run the payout job and its subscribers |
+| `transfers.requiredFulfillmentStatus` | `"fulfilled"` | Minimum fulfillment status before an order counts as decided for capture and is paid out. Use `"shipped"` or `"delivered"` to pay later |
+| `reversals.enabled` | `true` | Run the reversal job and its subscriber |
+
+### Settlements
+
+| Option | Default | Description |
+| --- | --- | --- |
+| `settlements.enabled` | `true` | Run the settlement job |
+| `settlements.mode` | `"plugin"` | `plugin` nets each period and sends the bank payout. Pair with `manualPayouts: true`. `provider` records each period's settlement and lets Stripe's automatic schedule pay. See [settlement modes](/resources/integrations/stripe-connect/architecture#settlement-modes) |
+
+### Notifications and alerts
+
+| Option | Default | Description |
+| --- | --- | --- |
+| `notifications.url` | - | Endpoint that receives a JSON `POST` for every failed payout, reversal and settlement bank payout. See [notification endpoint](/resources/integrations/stripe-connect/operations#notification-endpoint) |
+| `notifications.secret` | - | Signs each notification. See [notification signatures](/resources/integrations/stripe-connect/reference#notification-signatures) |
+| `notifications.mailOnEndpointDown` | `true` | Email the technical contact when the endpoint keeps failing |
+| `notifications.endpointDownCooldownMinutes` | `10` | Minimum time between two of those emails |
+| `alerting.technicalEmail` | - | Recipient of the daily failed-operations digest, KYC alerts and endpoint-down emails |
+| `alerting.from` | - | Sender of those emails |
+| `kycMonitor.enabled` | `false` | Run the KYC monitor job every six hours |
+
+Alert emails go through Medusa's notification module on the `email` channel, so register a notification provider for that channel to receive them.
+
+## Webhooks
+
+Create two endpoints under **Developers → Webhooks** in the Stripe Dashboard. **Settings → Stripe** in the admin prints both URLs for your deployment.
+
+| Endpoint | Listen to | Events |
+| --- | --- | --- |
+| `https://<api>/hooks/payment/pp_stripe-connector_stripe` | Your account | `payment_intent.succeeded`, `payment_intent.amount_capturable_updated`, `payment_intent.payment_failed`, `payment_intent.canceled`, `charge.refunded` |
+| `https://<api>/hooks/payout` | Connected accounts | `account.updated`, `payout.paid`, `payout.failed`, `payout.canceled`, `payout.updated` |
+
+Paste the first endpoint's signing secret into the payment provider's `webhookSecret`, and the second's into the payout provider's and the plugin's `webhookSecret`.
+
+Both endpoints verify the `stripe-signature` header against the raw body. An event with a bad signature is logged and ignored.
+
+## Go live
+
+1. Activate your Stripe account and complete the Connect platform profile under **Settings → Connect**.
+2. Replace every `sk_test_` key with its `sk_live_` counterpart.
+3. Create both webhook endpoints again in live mode, and replace both signing secrets. Test-mode endpoints never receive live events.
+4. Set `onboarding.returnUrl` and `onboarding.refreshBaseUrl` to your production vendor and API URLs. Stripe rejects `http://` links in live mode.
+5. Set `alerting.technicalEmail` and register an email notification provider, so failed operations reach someone.
+6. Check **Settings → Stripe**: the API key is set and **Last webhook** updates after the first live event.
+
+Payout accounts created with test keys point at test-mode connected accounts, which live keys can't reach. Start production on a fresh database, or remove those payout accounts so sellers onboard again in live mode.
diff --git a/apps/docs/resources/integrations/stripe-connect/operations.mdx b/apps/docs/resources/integrations/stripe-connect/operations.mdx
new file mode 100644
index 000000000..45339dfd2
--- /dev/null
+++ b/apps/docs/resources/integrations/stripe-connect/operations.mdx
@@ -0,0 +1,102 @@
+---
+title: "Operations"
+sidebarTitle: "Operations"
+description: "The admin screens for running the Stripe connector day to day: settlements, adjustments, captures, job runs, retries, alerts, the notification endpoint and the Stripe settings page."
+---
+
+The plugin adds a **Stripe** item under **Integrations** in the admin sidebar, a **Stripe** page under **Settings**, and Stripe sections on the order and payout account pages. Every screen needs the `payouts:view` permission, and every action needs `payouts:edit`.
+
+## Integrations → Stripe
+
+| Page | Shows | Actions |
+| --- | --- | --- |
+| **Stripe** (Settlements) | Every settlement: store, period end, status and bank payout status. Filter by status, bank payout status or period end. Open one for its totals, its payouts, reversals and adjustments, and its Stripe bank payout | **Retry bank payout** |
+| **Adjustments** | Every adjustment: store, type, amount, reason and status. Filter by type or status | **Create** |
+| **Captures** | Every order group's capture: orders decided, authorized amount, expiry and status. Filter by status or expiry | **Capture now**, **Cancel authorization** |
+| **Jobs** | The seven jobs with their schedule, last run and failing items | **Run now** |
+
+### Jobs
+
+Each job's page shows its schedule in words and as a cron expression, its checkpoint, its next run and how many items are failing, followed by its run history. Each run lists its trigger (schedule, manual or subscriber), its status, when it started and finished, and counts of what it did, such as **Paid**, **On hold** or **Blocked**.
+
+**Run now** starts the job straight away. If a run is already in progress, the new one is skipped, so pressing it twice is harmless.
+
+Use **Run now** after fixing the cause of a failure, for example after a seller completes onboarding or after you top up your platform balance, instead of waiting for the next scheduled run.
+
+## Order and payout account pages
+
+- **Orders**: the **Stripe payouts** section in the sidebar lists the order's payout and every reversal, with amount, status and the reason in plain words. A failed, held or pending payout has **Retry** in its menu.
+- **Payout accounts**: the **Stripe** section shows the Stripe account, Stripe's disabled reason and the outstanding requirements, with **Open in Stripe** and **Ignore store**.
+- **Stores**: the **Payout account** section links to the store's payout account.
+
+## Settings → Stripe
+
+The settings page has three sections:
+
+- **Stripe**: whether the API key is set and when the last webhook arrived. Its menu has **Map existing account** and **Send test notification**
+- **Webhooks**: both endpoint URLs for your deployment and the events each one needs. Copy them into the Stripe Dashboard
+- **Notifications**: the notification endpoint's origin and the last deliveries, with their type, attempts, status and response
+
+If **Last webhook** stays empty after you create a seller account or pay out an order, Stripe isn't reaching your API. Check the endpoint URLs and signing secrets.
+
+## Failures and retries
+
+Nothing in the plugin needs manual cleanup after a failure. Every failed or held record is retried by its job:
+
+| Record | Retried by | When it gives up |
+| --- | --- | --- |
+| Capture | `payout-validate-captures`, every five minutes | When the authorization expires |
+| Payout | `payout-process-transfers`, every five minutes | Never. Aborted payouts aren't retried |
+| Reversal | `payout-process-reversals`, every five minutes | Never |
+| Adjustment | `payout-process-settlements`, nightly | Never |
+| Bank payout | `payout-process-settlements`, nightly | Never |
+
+Stripe errors are split in two. A definitive refusal, such as an invalid account or an amount Stripe won't accept, marks the record **failed** with Stripe's message. After a network error or timeout the outcome is unknown, so the record keeps its idempotency key, and the retry sends the same key again. Stripe either completes the request once or returns the result it already gave. Only a definitive refusal gives the next attempt a fresh key.
+
+## Alerts
+
+Set `alerting.technicalEmail` and `alerting.from` on the plugin, and register an email provider on Medusa's notification module.
+
+| Email | Sent | Lists |
+| --- | --- | --- |
+| Failed operations | Daily at 08:04 UTC, only when something is failed | Captures, payouts, reversals, settlement bank payouts and adjustments that are still failed, with their reason |
+| KYC attention | Every six hours, with `kycMonitor.enabled` | Accounts whose KYC status isn't `approved` |
+| Endpoint down | When a notification can't be delivered, at most every `endpointDownCooldownMinutes` | The delivery error |
+
+## Notification endpoint
+
+Set `notifications.url` to hear about failures as they happen, instead of in the next morning's digest. The endpoint, for example your back-office service or a chat webhook, receives a JSON `POST` for each of these:
+
+| Type | Sent when |
+| --- | --- |
+| `payout.failed` | Stripe refuses a payout's transfer |
+| `payout_reversal.failed` | Stripe refuses a reversal |
+| `settlement.payout_failed` | A settlement's bank payout fails, whether Stripe refuses it or reports it failed or canceled through a webhook |
+| `test` | You choose **Send test notification** |
+
+```json
+{
+ "type": "payout.failed",
+ "payload": {
+ "id": "pout_01...",
+ "display_id": 42,
+ "order_id": "order_01...",
+ "account_id": "pacc_01...",
+ "seller_id": "sel_01...",
+ "amount": 84.5,
+ "currency_code": "eur",
+ "status_reason": "provider_error",
+ "status_detail": "Your destination account needs to have at least one of the following capabilities enabled: transfers"
+ }
+}
+```
+
+A reversal's payload carries `payout_id`, `refund_id`, `order_id`, `account_id`, `seller_id`, `amount`, `currency_code`, `status_reason` and `status_detail`. A settlement's carries `display_id`, `account_id`, `seller_id`, `amount`, `currency_code`, `period_start`, `period_end`, `provider_payout_id` and `status_reason`.
+
+Each failure is sent once. Payouts that keep failing on every retry don't notify again, and they stay in the daily digest until they're resolved. A settlement whose retried bank payout is accepted and later fails again notifies again, because it's a new bank payout.
+
+Each delivery is tried up to four times, after 1, 5 and 25 seconds, and logged under **Settings → Stripe → Notifications**. When every attempt fails and `mailOnEndpointDown` is on, the technical contact gets an email.
+
+Use **Send test notification** to check the endpoint and its signature check. The admin only ever shows the URL's origin, because chat webhook URLs carry their secret in the path.
+
+With `notifications.secret` set, every request carries a signature. See [notification signatures](/resources/integrations/stripe-connect/reference#notification-signatures).
diff --git a/apps/docs/resources/integrations/stripe-connect/overview.mdx b/apps/docs/resources/integrations/stripe-connect/overview.mdx
new file mode 100644
index 000000000..9c841f818
--- /dev/null
+++ b/apps/docs/resources/integrations/stripe-connect/overview.mdx
@@ -0,0 +1,93 @@
+---
+title: "Stripe Connect"
+sidebarTitle: "Overview"
+description: "Charge customers once on your platform Stripe account, pay each seller their share of every order, and settle it to their bank, with one Mercur plugin."
+---
+
+The Stripe connector plugin runs a marketplace's money on Stripe. The customer pays once for a cart that spans several sellers. Each seller gets their share of every order they fulfill, minus your commission, in a Stripe Connect account. Their earnings reach their bank on a schedule you control.
+
+You install one package, `@mercurjs/stripe-connector-plugin`, in your Mercur API. It registers a payment provider for checkout, a payout provider for seller accounts, the scheduled jobs that decide when money moves, and the admin and vendor screens to watch it.
+
+## Who owns what
+
+| | Stripe | Mercur core | Stripe connector plugin |
+| --- | --- | --- | --- |
+| Card payment, authorization, capture | ✓ | | Decides when to capture |
+| Connected accounts, KYC, onboarding forms | ✓ | Mirrors the account as a `payout_account` | Creates accounts and links |
+| Seller's share of each order (`payout`) | Moves it as a Transfer | Computes total − commission, keeps the status | Decides when to run |
+| Refunds taken back from the seller (`payout_reversal`) | Moves it as a Transfer reversal | Computes the refunded share | Decides when to run |
+| Bank payout to the seller | Moves it as a Payout | | Nets each period into a settlement |
+| Fees and credits to a seller | Moves them as Transfers | | Adjustments entered by the operator |
+| Alerts, job history, retries | | | ✓ |
+
+The platform account is the **Merchant of Record**. Customers see your statement descriptor, and refunds and disputes land on your account first.
+
+## Two layers of money
+
+Every seller sees money move twice, and the plugin keeps both visible:
+
+1. **Per order.** When an order is fulfilled and its payment captured, the seller's share moves from your platform balance to the seller's Stripe balance. A refund later takes the seller's share of it back.
+2. **Per period.** Every night the plugin nets everything that reached the seller's balance since the last run (payouts, minus reversals, plus or minus adjustments) into one **settlement**, and sends that amount to the seller's bank.
+
+The per-order layer lets sellers and operators trace every order to the cent. The per-period layer gives the seller one bank deposit per period, with a statement that explains it.
+
+## What you get
+
+- **One payment, split per seller**: the cart is authorized once with manual capture, and captured only when every seller order in it is decided, for the authorized amount minus canceled orders
+- **Automatic seller onboarding**: every new seller gets a Stripe Express account and an onboarding link, refreshed when it expires, and a login link once onboarding is done
+- **Payouts on fulfillment**: each fulfilled, captured order pays the seller its total minus commission, net of refunds that landed before it
+- **Refunds taken back**: each later refund reverses the seller's share of it on the original transfer, net of the commission share
+- **Nightly settlements**: one bank payout per seller and currency, held and retried while the balance is short or the account can't receive payouts
+- **Adjustments**: subscription fees, extra invoices and extra credits you enter in the admin, sent on the next settlement run
+- **Operations screens**: settlements, adjustments, captures and every job's run history under **Integrations → Stripe**, with **Run now** and retry actions
+- **Alerts**: a daily email of everything still failed, and KYC monitoring on request
+- **A vendor Stripe page**: account setup, what Stripe still needs from the seller, and their settlements
+
+## Compatibility
+
+| Requirement | Version |
+| --- | --- |
+| Mercur | 2.3.9 and later, with `@mercurjs/stripe-connector-plugin` |
+| Node.js | 22.22 and later |
+| Stripe | An account with Connect enabled, using Express connected accounts |
+
+## Not supported yet
+
+- Standard and Custom connected accounts. The provider creates Express accounts only
+- Separate charges per seller (direct charges or destination charges). The plugin uses one platform charge and separate transfers
+- Billing-cycle calendars for settlements. The settlement job runs nightly, and each settlement covers the time since the previous one
+- More than one payout provider at a time. The payout module takes exactly one
+
+## Get started
+
+<CardGroup cols={2}>
+ <Card title="Quickstart" icon="rocket" href="/resources/integrations/stripe-connect/quickstart">
+ Install the plugin, onboard a test seller and pay out a first order.
+ </Card>
+ <Card title="Architecture" icon="sitemap" href="/resources/integrations/stripe-connect/architecture">
+ What core owns, what the plugin adds and how an order's money travels.
+ </Card>
+ <Card title="Configuration" icon="sliders" href="/resources/integrations/stripe-connect/configuration">
+ Every option of the providers, the payout module and the plugin.
+ </Card>
+ <Card title="Reference" icon="book" href="/resources/integrations/stripe-connect/reference">
+ Jobs, webhooks, routes, statuses, reasons and tables.
+ </Card>
+</CardGroup>
+
+## Guides
+
+<CardGroup cols={2}>
+ <Card title="Seller onboarding" icon="user-check" href="/resources/integrations/stripe-connect/seller-onboarding">
+ Express accounts, links, requirements and the vendor Stripe page.
+ </Card>
+ <Card title="Payments and capture" icon="credit-card" href="/resources/integrations/stripe-connect/payments-and-capture">
+ Checkout, the capture decision, cancellations and refunds.
+ </Card>
+ <Card title="Payouts and settlements" icon="building-columns" href="/resources/integrations/stripe-connect/payouts-and-settlements">
+ Per-order payouts, reversals, adjustments and bank payouts.
+ </Card>
+ <Card title="Operations" icon="gauge" href="/resources/integrations/stripe-connect/operations">
+ The admin screens, retries, alerts and notifications.
+ </Card>
+</CardGroup>
diff --git a/apps/docs/resources/integrations/stripe-connect/payments-and-capture.mdx b/apps/docs/resources/integrations/stripe-connect/payments-and-capture.mdx
new file mode 100644
index 000000000..8a286f9b6
--- /dev/null
+++ b/apps/docs/resources/integrations/stripe-connect/payments-and-capture.mdx
@@ -0,0 +1,77 @@
+---
+title: "Payments and capture"
+sidebarTitle: "Payments and capture"
+description: "How the customer is charged once for a multi-seller cart, when the plugin captures or cancels the authorization, and how cancellations and refunds flow back to sellers."
+---
+
+The customer pays once, on your platform account, for every seller in the cart. The card is only authorized at checkout. The plugin captures it once every seller has decided their order, for exactly what will ship.
+
+## Checkout
+
+The payment provider, `pp_stripe-connector_stripe`, creates one PaymentIntent for the cart with `capture_method: manual`. It sets the order group id on the PaymentIntent's metadata, under `mercur_order_group_id` unless you change `orderGroupMetadataKey`.
+
+When the cart completes, Mercur splits it into an order group with one order per seller and writes each order's commission lines. The plugin opens a **capture** for the order group. It tracks the authorized amount, the expiry of the authorization and how many orders are decided.
+
+## When an order is decided
+
+An order is **decided** when it is canceled, or when it reaches the fulfillment threshold, `transfers.requiredFulfillmentStatus`, which is `fulfilled` by default.
+
+With `capture.captureBeforeAcceptance: true`, an order is decided as soon as it is no longer awaiting the seller's acceptance, so you capture before anything ships.
+
+Every fulfillment and cancellation refreshes the order group's capture right away.
+
+## The capture decision
+
+The capture job runs every five minutes. For every open capture it decides what to do:
+
+| Situation | Action | Amount |
+| --- | --- | --- |
+| Some orders aren't decided yet, and expiry is more than `capture.safetyBufferMs` away | Wait | |
+| Every order is decided and at least one wasn't canceled | Capture | Authorized amount minus the totals of canceled orders |
+| Every order was canceled | Cancel the authorization | |
+| Expiry is within `capture.safetyBufferMs` | Capture what is left, even if some orders aren't decided | Authorized amount minus canceled orders |
+| The authorization has expired | Mark expired | |
+
+The authorization expires `capture.authorizationWindowMs` after it was created, 7 days by default. That matches Stripe's default for card payments. If your account has [extended authorization](https://docs.stripe.com/payments/extended-authorization), raise it to match.
+
+After a capture, Medusa gives each seller order its own captured payment on the same charge, so each order's payout can use that charge as its `source_transaction`.
+
+## Capture statuses
+
+| Status | Label in the admin | Meaning |
+| --- | --- | --- |
+| `pending` | Awaiting orders | Some orders aren't decided yet |
+| `ready` | Ready to capture | Every order is decided, or expiry is close. The next run captures |
+| `cancelable` | Ready to cancel | Every order was canceled. The next run cancels the authorization |
+| `captured` | Captured | The payment is captured |
+| `canceled` | Canceled | The authorization was released |
+| `expired` | Expired | The authorization expired before it could be captured |
+| `failed` | Failed | Stripe refused the capture or cancellation. The next run tries again |
+
+## Captures in the admin
+
+**Integrations → Stripe → Captures** lists every order group's capture, with the orders decided out of the total, the authorized amount, the expiry and the status. Filter by status or by expiry date.
+
+Each open row has two actions:
+
+- **Capture now**: capture the capturable amount without waiting for the next run
+- **Cancel authorization**: release the authorization, for example when you are cancelling the whole order group
+
+Both ask for confirmation first.
+
+## Refunds
+
+Refunds are made the usual Medusa way, from the order in the admin or by the seller. The payment provider refunds the charge on the platform account.
+
+The refund then has to come back out of the seller's share:
+
+- **Before the order's payout is sent**, the payout is computed net of the refund. Nothing is reversed, and the payout's reason says `refund_absorbed`.
+- **After the payout is sent**, the refund writes a `payout_reversal` of the seller's share, net of its commission share, and Stripe reverses that much of the original Transfer.
+
+The reversal runs right away from the refund, and again from the reversal job every five minutes for anything left over. See [reversals](/resources/integrations/stripe-connect/payouts-and-settlements#reversals).
+
+## Cancellations
+
+A canceled order before capture is simply left out of the capture amount, so the customer is never charged for it.
+
+A canceled order after capture needs a refund like any other, which reverses the seller's share if it was already paid out.
diff --git a/apps/docs/resources/integrations/stripe-connect/payouts-and-settlements.mdx b/apps/docs/resources/integrations/stripe-connect/payouts-and-settlements.mdx
new file mode 100644
index 000000000..b9a4b8948
--- /dev/null
+++ b/apps/docs/resources/integrations/stripe-connect/payouts-and-settlements.mdx
@@ -0,0 +1,101 @@
+---
+title: "Payouts and settlements"
+sidebarTitle: "Payouts and settlements"
+description: "How each order's share reaches the seller's Stripe balance, how refunds are taken back, how operator adjustments work, and how the nightly settlement nets it all into one bank payout."
+---
+
+Money reaches a seller in two steps. Each order's share moves to the seller's Stripe balance as soon as the order is fulfilled and paid. Then, every night, everything that moved since the last settlement is netted and paid to the seller's bank in one deposit.
+
+| | Payout | Settlement |
+| --- | --- | --- |
+| One per | Seller order | Seller, currency and period |
+| Moves money | Platform balance → seller's Stripe balance | Seller's Stripe balance → seller's bank |
+| Stripe object | Transfer | Payout |
+| Owned by | Mercur core (`payout`, `payout_reversal`) | The plugin (`settlement`) |
+| Shown under | **Payouts** in the admin, the order's **Stripe payouts** section | **Integrations → Stripe** in the admin, the vendor **Stripe** page |
+
+## Payouts
+
+The payout job runs every five minutes, and right away when an order is fulfilled or canceled or a payment is captured. For each order it asks core's `createOrderPayoutsWorkflow` to decide:
+
+| The order is | Result |
+| --- | --- |
+| Fulfilled to `transfers.requiredFulfillmentStatus` and captured, and the seller's account is `active` | A `payout` of the order total minus commission, net of refunds that already landed, sent as a Transfer |
+| Not fulfilled, not captured, or its seller's account isn't `active` | A `payout` **on hold**, with a reason. It is decided again on every run |
+| Canceled, or refunded in full | No money moves. The payout is **aborted** with the reason |
+| Already paid | Nothing. Each order has one payout |
+
+The Transfer uses the order's charge as `source_transaction`, so it doesn't wait for the funds to become available on your platform balance.
+
+A seller with no payout account yet gets no payout row. When their account becomes `active`, their orders are queued and the next run pays them.
+
+Orders of a store you [ignore](/resources/integrations/stripe-connect/seller-onboarding#ignoring-a-store) are skipped until you stop ignoring it.
+
+### The backlog
+
+Every run first re-decides payouts that are **failed** or **on hold**, then looks for newly fulfilled orders since its checkpoint. A payout held because the order wasn't fulfilled is paid on the first run after fulfillment. One held because the account wasn't ready is paid on the first run after Stripe activates it.
+
+Payout statuses and their reasons are listed in the [reference](/resources/integrations/stripe-connect/reference#payout-statuses).
+
+## Reversals
+
+A refund on an order that was already paid out writes a `payout_reversal` of the seller's share of the refund: the refund amount minus its proportional share of commission. Stripe reverses that much of the order's Transfer, which moves it back from the seller's balance to yours.
+
+The reversal job runs every five minutes, and right away when a refund is created. A refund that lands before the payout is sent never needs a reversal. The payout is simply smaller.
+
+## Adjustments
+
+Adjustments are amounts that don't belong to an order: a monthly subscription fee, an extra invoice for a service, or a goodwill credit.
+
+Create one under **Integrations → Stripe → Adjustments → Create**. Pick the store, the type, the amount and currency, and an optional reason.
+
+| Type | Moves |
+| --- | --- |
+| Subscription | From the seller's Stripe balance to yours |
+| Extra invoice | From the seller's Stripe balance to yours |
+| Extra credit | From your balance to the seller's |
+
+The settlement job sends pending adjustments at the start of every run, as Transfers in the right direction, and includes them in that run's settlements. An adjustment for a store whose account isn't ready waits, with the reason, and is retried every run.
+
+## Settlements
+
+The settlement job runs every night at 01:03 UTC. For every seller and currency it builds one **settlement** covering the time since that seller's previous settlement in that currency, or since the account was created.
+
+A settlement nets every line that reached the seller's balance in that period and isn't in another settlement yet:
+
+```
+amount = paid payouts − paid reversals + extra credits − subscriptions − extra invoices
+```
+
+Each line keeps a link to its payout, reversal or adjustment, so the settlement page lists every order behind the amount.
+
+### The bank payout
+
+In `plugin` mode the job then pays each settlement to the seller's bank as a Stripe Payout:
+
+1. It checks the connected account's available balance in the settlement currency.
+2. If the balance covers the amount, it creates the Payout, and the settlement waits for Stripe's `payout.paid` webhook to become **Paid out**.
+3. If the balance is short, usually because funds from recent captures aren't available yet, the bank payout is held with `insufficient_available_balance` and retried on the next run.
+
+A settlement whose bank payout failed or is held blocks the next settlement in that currency, so periods never overlap and the seller never gets two deposits for the same money. Once the bank payout goes through, the next run settles the time since.
+
+In `provider` mode the job records each settlement as **Paid out** right away, and Stripe's automatic schedule moves the money. Use the settlement as the seller's statement.
+
+### Settlement statuses
+
+| Status | Meaning |
+| --- | --- |
+| `open` | The bank payout is pending or on its way |
+| `paid_out` | Stripe paid it to the seller's bank, or Stripe's own schedule pays it in `provider` mode |
+| `failed` | The bank payout failed or is held: the account can't receive payouts, or Stripe refused it. Retried on the next run |
+| `aborted` | The net amount is zero or negative. Nothing is paid, and the lines are kept for the record |
+
+A negative period, where refunds and fees exceed sales, is aborted rather than charged. Its lines still appear on the seller's statement.
+
+### Retrying a bank payout
+
+Failed and held bank payouts are retried at the start of every settlement run. To retry one now, open the settlement in **Integrations → Stripe** and choose **Retry bank payout**. Retry works for bank payouts that are failed, held or pending.
+
+## What sellers see
+
+The vendor **Stripe** page lists the seller's settlements: the period, the net amount, the status and the bank payout that paid it, so the seller can match each bank deposit to a period. The seller's per-order payouts are on their **Payouts** page.
diff --git a/apps/docs/resources/integrations/stripe-connect/quickstart.mdx b/apps/docs/resources/integrations/stripe-connect/quickstart.mdx
new file mode 100644
index 000000000..7e74358a3
--- /dev/null
+++ b/apps/docs/resources/integrations/stripe-connect/quickstart.mdx
@@ -0,0 +1,145 @@
+---
+title: "Stripe Connect quickstart"
+sidebarTitle: "Quickstart"
+description: "Install the Stripe connector plugin, forward webhooks in test mode, onboard a test seller and follow a two-seller order from checkout to the seller's bank."
+---
+
+By the end of this guide a test customer pays for a cart with products from two sellers, each seller receives their share in their Stripe test account, and a settlement sends it to their bank. Plan for about 30 minutes.
+
+<Note>
+ Use Stripe **test mode** keys throughout. Nothing in this guide moves real money.
+</Note>
+
+Before you start, make sure you have:
+
+- A running Mercur project on 2.3.9 or later ([installation guide](/learn/introduction))
+- A Stripe account with **Connect** enabled under **Settings → Connect**
+- The [Stripe CLI](https://docs.stripe.com/stripe-cli), logged in to that account
+- Two approved sellers with products in a region
+
+## Step 1: Install the plugin
+
+```bash
+bun add @mercurjs/stripe-connector-plugin
+```
+
+## Step 2: Set environment variables
+
+Start the two webhook forwarders first, so you have their signing secrets:
+
+```bash
+stripe listen --forward-to localhost:9000/hooks/payment/pp_stripe-connector_stripe
+stripe listen --forward-connect-to localhost:9000/hooks/payout
+```
+
+Each command prints a `whsec_...` secret. Add both to your API's `.env`, with your test secret key:
+
+```bash .env
+STRIPE_SECRET_KEY=sk_test_...
+STRIPE_OPERATOR_WEBHOOK_SECRET=whsec_... # from the first command
+STRIPE_SELLERS_WEBHOOK_SECRET=whsec_... # from the second command
+BACKEND_URL=http://localhost:9000
+VENDOR_URL=http://localhost:7001
+```
+
+Leave both forwarders running.
+
+## Step 3: Register the plugin and the providers
+
+```ts medusa-config.ts
+module.exports = withMercur({
+ plugins: [
+ {
+ resolve: "@mercurjs/stripe-connector-plugin",
+ options: {
+ apiKey: process.env.STRIPE_SECRET_KEY,
+ webhookSecret: process.env.STRIPE_SELLERS_WEBHOOK_SECRET,
+ },
+ },
+ ],
+ modules: [
+ {
+ resolve: "@medusajs/medusa/payment",
+ options: {
+ providers: [
+ {
+ resolve: "@mercurjs/stripe-connector-plugin/providers/payment-stripe",
+ id: "stripe",
+ options: {
+ apiKey: process.env.STRIPE_SECRET_KEY,
+ webhookSecret: process.env.STRIPE_OPERATOR_WEBHOOK_SECRET,
+ },
+ },
+ ],
+ },
+ },
+ {
+ resolve: "@mercurjs/core/modules/payout",
+ options: {
+ providers: [
+ {
+ resolve: "@mercurjs/stripe-connector-plugin/providers/payout-stripe-connect",
+ id: "stripe",
+ options: {
+ apiKey: process.env.STRIPE_SECRET_KEY,
+ webhookSecret: process.env.STRIPE_SELLERS_WEBHOOK_SECRET,
+ manualPayouts: true,
+ },
+ },
+ ],
+ onboarding: {
+ returnUrl: `${process.env.VENDOR_URL}/stripe`,
+ refreshBaseUrl: process.env.BACKEND_URL,
+ },
+ },
+ },
+ ],
+})
+```
+
+Run the migrations, which create the plugin's `stripe_connector` tables, and restart the API:
+
+```bash
+bunx medusa db:migrate
+```
+
+Open **Settings → Stripe** in the admin. The **API key** row shows **Set in the plugin options**.
+
+## Step 4: Enable Stripe on your region
+
+Go to **Settings → Regions**, edit the region your sellers sell in, and add `pp_stripe-connector_stripe` to its payment providers.
+
+## Step 5: Onboard both sellers
+
+The onboarding job runs every minute. Within a minute of the API starting, each seller has a Stripe Express account.
+
+Log in to the vendor panel as the first seller and open **Payouts**. Choose **Continue onboarding**, and complete Stripe's form with [test data](https://docs.stripe.com/connect/testing): phone `000 000 0000`, SMS code `000000`, and bank account `000123456789` with routing number `110000000`.
+
+Stripe sends the seller back to the vendor **Stripe** page, under **Integrations** in the sidebar. Within a few seconds the `account.updated` webhook arrives, and the account shows as **Active** with payouts enabled. Repeat for the second seller.
+
+## Step 6: Place a two-seller order
+
+From your storefront, add one product from each seller to a cart and pay with the test card `4242 4242 4242 4242`. Mercur splits the cart into two seller orders. The payment stays authorized, not captured.
+
+Open **Integrations → Stripe → Captures** in the admin. The order group shows **Awaiting orders**, with 0 of 2 orders decided.
+
+## Step 7: Fulfill both orders
+
+Fulfill both seller orders, from the admin or each seller's vendor panel. Each fulfillment refreshes the order group's capture right away:
+
+1. Once the second order is fulfilled, **Captures** shows **Ready to capture**. The capture job captures the full authorized amount on its next run, within five minutes, or choose **Capture now** on the row. The row moves to **Captured**.
+2. The capture runs the payout pass for both orders. Each gets a payout of its total minus commission, sent as a Stripe Transfer. Open either order in the admin: the **Stripe payouts** section in the sidebar shows the payout as **Paid**.
+
+In the Stripe test dashboard, under **Connect → Accounts**, each seller's balance holds their share.
+
+## Step 8: Settle to the bank
+
+Settlements run nightly. To run one now, open **Integrations → Stripe → Jobs**, open **Settlements** and choose **Run now**.
+
+**Integrations → Stripe** now lists one settlement per seller. Open one: it shows the period, the payout it nets and the Stripe bank payout that paid it. In test mode Stripe marks the bank payout paid within a few minutes, and the `payout.paid` webhook moves the settlement to **Paid out**.
+
+## Next steps
+
+- [Architecture](/resources/integrations/stripe-connect/architecture): how the order's money travelled through those steps
+- [Configuration](/resources/integrations/stripe-connect/configuration): capture timing, fulfillment thresholds, settlement mode and alerts
+- [Go live](/resources/integrations/stripe-connect/configuration#go-live): live keys and webhook endpoints in the Stripe Dashboard
diff --git a/apps/docs/resources/integrations/stripe-connect/reference.mdx b/apps/docs/resources/integrations/stripe-connect/reference.mdx
new file mode 100644
index 000000000..0a06ac071
--- /dev/null
+++ b/apps/docs/resources/integrations/stripe-connect/reference.mdx
@@ -0,0 +1,203 @@
+---
+title: "Stripe Connect reference"
+sidebarTitle: "Reference"
+description: "Scheduled jobs, subscribers, webhook events, admin and vendor routes, events, statuses and reasons, notification signatures and the tables the Stripe connector plugin adds."
+---
+
+## Scheduled jobs
+
+All times are UTC. Every job writes a [job run](/resources/integrations/stripe-connect/architecture#job-runs-and-checkpoints), and only one run of a job is active at a time.
+
+| Job | Admin label | Schedule | Cron | Does | Turned off by |
+| --- | --- | --- | --- | --- | --- |
+| `payout-sync-onboarding` | Onboarding | Every minute | `* * * * *` | Creates an Express account and an onboarding link for sellers created or updated since the checkpoint | `onboarding.enabled: false` |
+| `payout-validate-captures` | Captures | Every 5 minutes | `0-59/5 * * * *` | Captures or cancels every order group whose orders are decided, or whose authorization is about to expire | |
+| `payout-process-transfers` | Payouts | Every 5 minutes, at minute 1 | `1-59/5 * * * *` | Re-decides failed and held payouts, then pays newly fulfilled and captured orders | `transfers.enabled: false` |
+| `payout-process-reversals` | Reversals | Every 5 minutes, at minute 2 | `2-59/5 * * * *` | Reverses the seller's share of every refund made after its payout | `reversals.enabled: false` |
+| `payout-process-settlements` | Settlements | Daily at 01:03 | `3 1 * * *` | Sends pending adjustments, retries failed bank payouts, builds settlements and pays them out | `settlements.enabled: false` |
+| `payout-alert-failed-operations` | Alerts | Daily at 08:04 | `4 8 * * *` | Emails the technical contact everything still failed | No `alerting.technicalEmail` |
+| `payout-monitor-kyc` | KYC | Every 6 hours | `0 */6 * * *` | Re-reads every account from Stripe and emails accounts that need KYC attention | Off unless `kycMonitor.enabled: true` |
+
+The jobs are staggered by a minute so captures land before the payout run that pays them.
+
+## Subscribers
+
+| Event | Runs |
+| --- | --- |
+| `order_group.created` | Opens the order group's capture |
+| `order.fulfillment_created`, `order.canceled` | Refreshes the capture, then the order's payout pass, recorded as a `payout-process-transfers` run |
+| `payment.captured` | The payout pass for the captured orders |
+| `refundPaymentWorkflow` hook `paymentRefunded` | The reversal pass for the order, recorded as a `payout-process-reversals` run |
+| `payout_account.updated` | Queues the seller's orders that were waiting for an active account |
+| `payout.webhook_received` | Applies Stripe bank `payout.*` events to settlements |
+| `payout.failed`, `payout.reversal_failed`, `stripe_connector.settlement_payout_failed` | Posts the failure to `notifications.url`, once per failure, when it is set |
+
+## Webhook events
+
+### Platform account
+
+`POST /hooks/payment/pp_stripe-connector_stripe`, verified with the payment provider's `webhookSecret`. Handled by Medusa's payment module.
+
+| Event | Effect |
+| --- | --- |
+| `payment_intent.amount_capturable_updated` | The payment is authorized |
+| `payment_intent.succeeded` | The payment is captured |
+| `payment_intent.payment_failed` | The payment failed |
+| `payment_intent.canceled` | The authorization was canceled |
+| `charge.refunded` | A refund completed |
+
+### Connected accounts
+
+`POST /hooks/payout`, verified with the payout provider's `webhookSecret`. Core's payout webhook subscriber and the plugin's subscriber both read it.
+
+| Event | Effect |
+| --- | --- |
+| `account.updated` | Syncs the payout account. Mercur records it as `account.activated`, `account.restricted`, `account.rejected` or `account.updated` |
+| `payout.paid` | The settlement's bank payout is paid. The settlement becomes `paid_out` |
+| `payout.failed`, `payout.canceled` | The bank payout failed. The settlement becomes `failed` and is retried on the next run |
+| `payout.updated` | Updates the bank payout's status |
+
+Every verified event also updates **Last webhook** on **Settings → Stripe**.
+
+## Admin routes
+
+All routes need an authenticated admin user. `GET` routes need `payouts:view`, the others `payouts:edit`.
+
+| Method | Path | Does |
+| --- | --- | --- |
+| `GET` | `/admin/stripe/status` | Whether the plugin is configured, its options without secrets, the jobs, failing counts and the last webhook time |
+| `GET` | `/admin/stripe/jobs` | Every job with its schedule, checkpoint, last run, next run and failing items |
+| `GET` | `/admin/stripe/jobs/:job/runs` | A job's run history |
+| `POST` | `/admin/stripe/jobs/:job/run` | Runs a job now |
+| `GET` | `/admin/stripe/captures` | Lists captures. Filter by `status` and `expires_at` |
+| `GET` | `/admin/stripe/captures/:order_group_id` | One order group's capture |
+| `POST` | `/admin/stripe/captures/:order_group_id/capture` | Captures it now |
+| `POST` | `/admin/stripe/captures/:order_group_id/cancel` | Cancels the authorization |
+| `GET` | `/admin/stripe/settlements` | Lists settlements. Filter by `status`, `payout_status` and `period_end` |
+| `GET` | `/admin/stripe/settlements/:id` | One settlement with its lines |
+| `POST` | `/admin/stripe/settlements/:id/retry` | Retries the settlement's bank payout |
+| `GET` | `/admin/stripe/adjustments` | Lists adjustments. Filter by `type` and `status` |
+| `POST` | `/admin/stripe/adjustments` | Creates an adjustment: `seller_id`, `type`, `amount`, `currency_code`, optional `reason` |
+| `POST` | `/admin/stripe/accounts/:id/ignore` | Ignores a store's payouts, or stops ignoring them: `{ "ignored": true }` |
+| `GET` | `/admin/stripe/notifications` | The notification delivery log |
+| `POST` | `/admin/stripe/notifications/test` | Sends a test notification |
+
+Payout accounts, payouts and their retries use core's routes under `/admin/payout-accounts` and `/admin/payouts`. See the [Payout module](/platform/payout/overview).
+
+## Vendor routes
+
+Scoped to the authenticated seller, with `payouts:view`.
+
+| Method | Path | Does |
+| --- | --- | --- |
+| `GET` | `/vendor/stripe/settlements` | The seller's settlements |
+| `GET` | `/vendor/stripe/settlements/:id` | One of the seller's settlements with its lines |
+
+The seller's payout account and onboarding use core's `/vendor/payout-accounts` routes.
+
+## Events
+
+| Event | Emitted by | Data |
+| --- | --- | --- |
+| `stripe_connector.settlement_created` | The settlement job, once per settlement | `{ id, account_id, seller_id, currency_code, amount }` |
+| `stripe_connector.settlement_payout_failed` | The settlement job, a bank payout retry, or a `payout.failed` / `payout.canceled` webhook, once per failed bank payout | `{ id }` |
+
+Core's payout module emits `payout_account.updated`, `payout.failed`, `payout.reversal_failed` and `payout.webhook_received`.
+
+## Payout statuses
+
+Payouts, reversals, adjustments and settlement bank payouts share core's status machine.
+
+| Status | Meaning |
+| --- | --- |
+| `pending` | Decided, not sent yet |
+| `on_hold` | Waiting for the order, the payment or the account. Decided again on every run |
+| `processing` | Sent to Stripe. Final once Stripe answers |
+| `paid` | Stripe accepted it |
+| `failed` | Stripe refused it. Retried on every run |
+| `aborted` | Nothing to pay, for good |
+
+### Reasons
+
+Each held, failed or aborted record carries a stable `status_reason`:
+
+| Reason | Shown as |
+| --- | --- |
+| `account_not_ready` | The store's payout account cannot receive payouts yet |
+| `account_payouts_disabled` | Payouts are disabled on the store's payout account |
+| `order_not_ready` | The order is not fulfilled yet |
+| `order_aborted` | The order was canceled |
+| `payment_not_ready` | The order's payment is not captured yet |
+| `payment_failed` | The order's payment failed |
+| `payment_canceled` | The order's payment was canceled |
+| `payment_refunded` | The order's payment was refunded in full |
+| `payout_not_ready` | The payout for this order has not been sent yet |
+| `refund_aborted` | The refund was canceled |
+| `refund_absorbed` | The refund was deducted before the payout was sent |
+| `invalid_amount` | The amount to pay out is not valid |
+| `provider_error` | Stripe returned an error. Stripe's message is kept on the record |
+| `insufficient_available_balance` | Settlements only: the connected account's available balance doesn't cover the bank payout yet |
+
+## Notification types
+
+| Type | Payload |
+| --- | --- |
+| `payout.failed` | `id`, `display_id`, `order_id`, `account_id`, `seller_id`, `amount`, `currency_code`, `status_reason`, `status_detail` |
+| `payout_reversal.failed` | `id`, `payout_id`, `refund_id`, `order_id`, `account_id`, `seller_id`, `amount`, `currency_code`, `status_reason`, `status_detail` |
+| `settlement.payout_failed` | `id`, `display_id`, `account_id`, `seller_id`, `amount`, `currency_code`, `period_start`, `period_end`, `provider_payout_id`, `status_reason` |
+| `test` | `sent_at`, `actor_id` |
+
+Every request body is `{ "type": "...", "payload": { ... } }`.
+
+## Notification signatures
+
+With `notifications.secret` set, every notification carries:
+
+```
+x-mercur-signature: sha256=<hex>
+```
+
+where `<hex>` is the HMAC-SHA256 of the raw request body with your secret, hex-encoded. Verify it against the raw body, before parsing:
+
+```ts
+import { createHmac, timingSafeEqual } from "crypto"
+
+export function isMercurSignatureValid(rawBody: string, header: string | undefined, secret: string) {
+ const expected = `sha256=${createHmac("sha256", secret).update(rawBody).digest("hex")}`
+ return !!header && header.length === expected.length && timingSafeEqual(Buffer.from(header), Buffer.from(expected))
+}
+```
+
+## Tables
+
+The plugin's `stripe_connector` module adds:
+
+| Table | Holds |
+| --- | --- |
+| `stripe_capture` | One row per order group: authorized and capturable amounts, orders decided, expiry and status |
+| `stripe_settlement` | One row per seller, currency and period: the totals, the net amount, the status and the Stripe bank payout |
+| `stripe_settlement_line` | Each payout, reversal or adjustment a settlement nets |
+| `stripe_adjustment` | Operator adjustments with their Stripe transfer |
+| `connector_job_run` | Every job run with its trigger, status and counts |
+| `connector_checkpoint` | Each job's checkpoint and the last webhook time |
+| `connector_notification` | Every notification delivery with its attempts and response |
+
+### Links
+
+| From | To |
+| --- | --- |
+| `stripe_capture.order_group_id` | Order group |
+| `stripe_settlement.account_id` | Payout account |
+| `stripe_settlement_line.payout_id` | Payout |
+| `stripe_settlement_line.payout_reversal_id` | Payout reversal |
+| `stripe_adjustment.account_id` | Payout account |
+
+The links are read-only, so traverse them from the plugin's side. For example, a seller's settlements with their store and the orders behind each payout:
+
+```ts
+const { data: settlements } = await query.graph({
+ entity: "settlement",
+ fields: ["*", "payout_account.seller.name", "lines.*", "lines.payout.order.display_id"],
+ filters: { account_id: payoutAccountId },
+})
+```
diff --git a/apps/docs/resources/integrations/stripe-connect/seller-onboarding.mdx b/apps/docs/resources/integrations/stripe-connect/seller-onboarding.mdx
new file mode 100644
index 000000000..bf131ea92
--- /dev/null
+++ b/apps/docs/resources/integrations/stripe-connect/seller-onboarding.mdx
@@ -0,0 +1,88 @@
+---
+title: "Seller onboarding"
+sidebarTitle: "Seller onboarding"
+description: "How sellers get a Stripe Express account, finish onboarding, and keep their account able to receive payouts, and what operators see and can do on the way."
+---
+
+Every seller needs a Stripe Express connected account before they can be paid. The plugin creates it, and Stripe hosts the forms where the seller enters their identity and bank details. Mercur mirrors the account as a `payout_account` and keeps it in step through webhooks.
+
+## Account creation
+
+The onboarding job runs every minute. It picks up sellers that are **open** or **pending approval** and were created or updated since its last run. For each seller without a payout account it:
+
+1. Creates an Express account in Stripe, with `manualPayouts` applied when you set it.
+2. Saves it as the seller's `payout_account`, with status `pending`.
+3. Creates an onboarding link and saves it on the account's `onboarding` record.
+
+A seller who signs up before the job runs can also create the account themselves. The vendor **Stripe** page asks for a country and a business type, individual or company, and optionally a business name, website, support email and phone, then creates the account straight away.
+
+Set `onboarding.enabled: false` on the plugin to stop the job from creating accounts. Sellers then create theirs from the vendor Stripe page.
+
+With `onboarding.prefill: true` on the payout module, new accounts start with the seller's country, business type and business profile, so the seller types less in Stripe's form.
+
+## Onboarding links
+
+Stripe's onboarding links expire after a few minutes and can be opened once. Mercur never shows a seller a stale one:
+
+- The vendor **Payouts** page shows the account's status and a **Continue onboarding** action, which always asks for a fresh link.
+- When a seller opens an expired link, Stripe sends them to `<refreshBaseUrl>/payout/onboarding/refresh?token=...`. Mercur checks the account's onboarding token, creates a new link and redirects the seller to it.
+- When onboarding is done, Stripe sends the seller to `onboarding.returnUrl`, usually the vendor Stripe page.
+
+Once the seller has submitted their details, the link becomes a **login link** to their Stripe Express dashboard, where they manage their bank account and see their balance. The vendor Payouts page shows it as **Manage payout details**.
+
+## Account status
+
+Every `account.updated` webhook re-reads the account from Stripe and recomputes its status:
+
+| Status | Meaning |
+| --- | --- |
+| `pending` | The seller hasn't submitted their details yet |
+| `active` | Every check in the payout provider's [`accountValidation`](/resources/integrations/stripe-connect/configuration#account-validation) passes. The seller can be paid |
+| `restricted` | Details were submitted, but a check fails: Stripe needs more information, or disabled charges or payouts |
+| `rejected` | Stripe rejected the account. It can't be paid |
+
+The KYC status is derived from Stripe's requirements on the same read:
+
+| KYC status | When |
+| --- | --- |
+| `pending_submission` | Stripe lists requirements that are currently due or past due |
+| `pending_approval` | Everything is submitted and Stripe is verifying it |
+| `approved` | Nothing is due or pending, and the account isn't disabled |
+| `refused` | Stripe disabled the account with a `rejected.*` reason |
+
+When an account becomes `active`, the seller's orders that were waiting for an account are queued, and the next payout run pays them.
+
+## What sellers see
+
+The vendor **Stripe** page, under **Integrations**, shows:
+
+- The Stripe account id and whether card payments are enabled
+- What Stripe still needs, grouped as **Currently due**, **Past due** and **Pending verification**. Each item is Stripe's requirement name, such as `individual.verification.document`
+- The seller's settlements, with the period, the net amount and the bank payout that paid it
+
+The vendor **Payouts** page shows the account status, whether payouts are enabled, the KYC status, and the onboarding or dashboard action.
+
+## What operators see
+
+Open a payout account in the admin, from **Payouts** or from the store page's **Payout account** section. The **Stripe** section in the sidebar shows the Stripe account id, Stripe's disabled reason in plain words, and the currently due and past due requirements. Its menu has:
+
+- **Open in Stripe**: the connected account in your Stripe Dashboard
+- **Ignore store** / **Stop ignoring**: see [Ignoring a store](#ignoring-a-store)
+
+The payout account's own menu has **Sync from provider**, which re-reads the account from Stripe, and **Refresh onboarding link**, which issues a new onboarding link, or a login link once the seller has submitted their details.
+
+### Map an existing account
+
+If a seller already has a connected account on your platform, for example from an earlier setup, attach it instead of creating a new one. In **Settings → Stripe**, choose **Map existing account**, pick the store and enter the `acct_...` id. Mercur creates the payout account, syncs it from Stripe and opens it.
+
+A store that already has a payout account can't be mapped again.
+
+### Ignoring a store
+
+Ignoring a store keeps its payout account and its onboarding, but the payout job skips its orders. Use it while you investigate a seller, or for a store you settle outside Stripe. Stop ignoring the store and the next payout run picks up the orders that waited.
+
+Ignoring sets `payout_ignored` on the seller's metadata.
+
+## KYC monitoring
+
+Webhooks keep accounts current, but a missed webhook leaves an account stale until its next change. Set `kycMonitor.enabled: true` on the plugin to re-read every account from Stripe every six hours. When any account's KYC status isn't `approved`, the technical contact gets one email listing those accounts with their KYC status and disabled reason.
diff --git a/bun.lock b/bun.lock
index ad33817a0..8fc131c35 100644
--- a/bun.lock
+++ b/bun.lock
@@ -74,6 +74,7 @@
"@medusajs/medusa": "2.22.0",
"@mercurjs/cli": "*",
"@mercurjs/core": "*",
+ "@mercurjs/stripe-connector-plugin": "*",
"@mercurjs/types": "*",
"http-proxy-middleware": "^3.0.3",
},
@@ -620,19 +621,66 @@
"react-router-dom": "^7.0.0",
},
},
- "packages/providers/payout-stripe-connect": {
- "name": "@mercurjs/payout-stripe-connect",
+ "packages/plugins/stripe-connector": {
+ "name": "@mercurjs/stripe-connector-plugin",
"version": "2.3.9-canary.4",
"dependencies": {
- "stripe": "^15.5.0",
+ "cronstrue": "3.27.0",
+ "stripe": "^19.1.0",
+ "zod": "4.6.5",
},
"devDependencies": {
+ "@hookform/resolvers": "5.4.0",
+ "@medusajs/cli": "2.22.0",
+ "@medusajs/core-flows": "2.22.0",
"@medusajs/framework": "2.22.0",
- "@mercurjs/types": "2.3.8",
- "tsup": "^8.5.0",
+ "@medusajs/icons": "2.22.0",
+ "@medusajs/medusa": "2.22.0",
+ "@medusajs/payment-stripe": "2.22.0",
+ "@medusajs/types": "2.22.0",
+ "@medusajs/ui": "4.2.3",
+ "@mercurjs/cli": "2.3.9-canary.4",
+ "@mercurjs/client": "2.3.9-canary.4",
+ "@mercurjs/core": "2.3.9-canary.4",
+ "@mercurjs/dashboard-sdk": "2.3.9-canary.4",
+ "@mercurjs/dashboard-shared": "2.3.9-canary.4",
+ "@mercurjs/types": "2.3.9-canary.4",
+ "@tanstack/react-query": "5.64.2",
+ "@tanstack/react-table": "8.21.3",
+ "@types/jest": "^29.5.14",
+ "@types/node": "^26.1.0",
+ "@types/react": "^18.3.2",
+ "i18next": "26.4.2",
+ "jest": "^29.7.0",
+ "radix-ui": "1.1.2",
+ "react": "^18.3.1",
+ "react-dom": "^18.3.1",
+ "react-hook-form": "7.88.0",
+ "react-i18next": "17.0.14",
+ "react-router-dom": "7.18.1",
+ "ts-jest": "^29.2.5",
+ "typescript": "5.9.3",
},
"peerDependencies": {
+ "@hookform/resolvers": "^5.4.0",
+ "@medusajs/core-flows": ">=2.22.0",
"@medusajs/framework": ">=2.22.0",
+ "@medusajs/icons": ">=2.22.0",
+ "@medusajs/medusa": ">=2.22.0",
+ "@medusajs/payment-stripe": ">=2.22.0",
+ "@medusajs/ui": ">=4.1.19",
+ "@mercurjs/client": ">=2.3.9-canary.4",
+ "@mercurjs/core": "*",
+ "@mercurjs/dashboard-sdk": ">=2.3.9-canary.4",
+ "@mercurjs/dashboard-shared": ">=2.3.9-canary.4",
+ "@tanstack/react-query": "^5.64.2",
+ "@tanstack/react-table": "^8.20.5",
+ "i18next": "26.4.2",
+ "react": "^18.0.0",
+ "react-dom": "^18.0.0",
+ "react-hook-form": "^7.49.1",
+ "react-i18next": "17.0.14",
+ "react-router-dom": "^7.0.0",
},
},
"packages/registry": {
@@ -1613,12 +1661,12 @@
"@mercurjs/magento2-connector-plugin": ["@mercurjs/magento2-connector-plugin@workspace:packages/plugins/magento2-connector"],
- "@mercurjs/payout-stripe-connect": ["@mercurjs/payout-stripe-connect@workspace:packages/providers/payout-stripe-connect"],
-
"@mercurjs/registry": ["@mercurjs/registry@workspace:packages/registry"],
"@mercurjs/storefront": ["@mercurjs/storefront@workspace:apps/storefront"],
+ "@mercurjs/stripe-connector-plugin": ["@mercurjs/stripe-connector-plugin@workspace:packages/plugins/stripe-connector"],
+
"@mercurjs/types": ["@mercurjs/types@workspace:packages/types"],
"@mercurjs/vendor": ["@mercurjs/vendor@workspace:packages/vendor"],
@@ -2329,6 +2377,8 @@
"@types/fs-extra": ["@types/[email protected]", "", { "dependencies": { "@types/jsonfile": "*", "@types/node": "*" } }, "sha512-yTbItCNreRooED33qjunPthRcSjERP1r4MqCZc7wv0u2sUkzTFp45tgUfS5+r7FrZPdmCCNflLhVSP/o+SemsQ=="],
+ "@types/graceful-fs": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ=="],
+
"@types/html-minifier-terser": ["@types/[email protected]", "", {}, "sha512-oh/6byDPnL1zeNXFrDXFLyZjkr1MsBG667IM792caf1L2UPOOMf65NFzjUH/ltyfwjAGfs1rsX1eftK0jC/KIg=="],
"@types/http-errors": ["@types/[email protected]", "", {}, "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg=="],
@@ -2761,6 +2811,8 @@
"browserslist": ["[email protected]", "", { "dependencies": { "baseline-browser-mapping": "^2.10.12", "caniuse-lite": "^1.0.30001782", "electron-to-chromium": "^1.5.328", "node-releases": "^2.0.36", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg=="],
+ "bs-logger": ["[email protected]", "", { "dependencies": { "fast-json-stable-stringify": "2.x" } }, "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog=="],
+
"bser": ["[email protected]", "", { "dependencies": { "node-int64": "^0.4.0" } }, "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ=="],
"buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA=="],
@@ -2941,12 +2993,16 @@
"create-hmac": ["[email protected]", "", { "dependencies": { "cipher-base": "^1.0.3", "create-hash": "^1.1.0", "inherits": "^2.0.1", "ripemd160": "^2.0.0", "safe-buffer": "^5.0.1", "sha.js": "^2.4.8" } }, "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg=="],
+ "create-jest": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "chalk": "^4.0.0", "exit": "^0.1.2", "graceful-fs": "^4.2.9", "jest-config": "^29.7.0", "jest-util": "^29.7.0", "prompts": "^2.0.1" }, "bin": { "create-jest": "bin/create-jest.js" } }, "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q=="],
+
"create-mercur-app": ["create-mercur-app@workspace:packages/create-mercur-app"],
"create-require": ["[email protected]", "", {}, "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ=="],
"cron-parser": ["[email protected]", "", { "dependencies": { "luxon": "^3.2.1" } }, "sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q=="],
+ "cronstrue": ["[email protected]", "", { "bin": { "cronstrue": "bin/cli.js" } }, "sha512-AKhV4ilvx73NmicrZCGASdszUIf2ew0A/6jQQTh4pu3lIUzgWOGjT3Gv3CGIcTQ/p8Qy/tZuCmlaOftj8PXaNg=="],
+
"cross-fetch": ["[email protected]", "", { "dependencies": { "node-fetch": "^2.7.0" } }, "sha512-uKm5PU+MHTootlWEY+mZ4vvXoCn4fLQxT9dSc1sXVMSFkINTJVN8cAQROpwcKm8bJ/c7rgZVIBWzH5T78sNZZw=="],
"cross-inspect": ["[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Pcw1JTvZLSJH83iiGWt6fRcT+BjZlCDRVwYLbUcHzv/CRpB7r0MlSrGbIyQvVSNyGnbt7G4AXuyCiDR3POvZ1A=="],
@@ -3039,6 +3095,8 @@
"diff": ["[email protected]", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="],
+ "diff-sequences": ["[email protected]", "", {}, "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q=="],
+
"diffie-hellman": ["[email protected]", "", { "dependencies": { "bn.js": "^4.1.0", "miller-rabin": "^4.0.0", "randombytes": "^2.0.0" } }, "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg=="],
"dijkstrajs": ["[email protected]", "", {}, "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA=="],
@@ -3201,6 +3259,8 @@
"execa": ["[email protected]", "", { "dependencies": { "@sindresorhus/merge-streams": "^4.0.0", "cross-spawn": "^7.0.6", "figures": "^6.1.0", "get-stream": "^9.0.0", "human-signals": "^8.0.1", "is-plain-obj": "^4.1.0", "is-stream": "^4.0.1", "npm-run-path": "^6.0.0", "pretty-ms": "^9.2.0", "signal-exit": "^4.1.0", "strip-final-newline": "^4.0.0", "yoctocolors": "^2.1.1" } }, "sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA=="],
+ "exit": ["[email protected]", "", {}, "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ=="],
+
"exit-x": ["[email protected]", "", {}, "sha512-+I6B/IkJc1o/2tiURyz/ivu/O0nKNEArIUB5O7zBrlDVJr22SCLH3xTeEry428LvFhRzIA1g8izguxJ/gbNcVQ=="],
"expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "30.4.1", "@jest/get-type": "30.1.0", "jest-matcher-utils": "30.4.1", "jest-message-util": "30.4.1", "jest-mock": "30.4.1", "jest-util": "30.4.1" } }, "sha512-PMARsyh/JtqC20HoGqlFcIlQAyqUtW4PlI1rup1uhYJtKuwAjbvWi3GQMAn+STdHum/dk8xrKfUM1+5SAwpolA=="],
@@ -3347,6 +3407,8 @@
"graphql-tag": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" }, "peerDependencies": { "graphql": "^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0" } }, "sha512-FdSNcu2QQcWnM2VNvSCCDCVS5PpPqpzgFT8+GXzqJuoDd0CBncxCY278u4mhRO7tMgo2JjgJA5aZ+nWSQ/Z+xg=="],
+ "handlebars": ["[email protected]", "", { "dependencies": { "minimist": "^1.2.8", "neo-async": "^2.6.2", "source-map": "^0.6.1", "wordwrap": "^1.0.0" }, "optionalDependencies": { "uglify-js": "^3.1.4" }, "bin": { "handlebars": "bin/handlebars" } }, "sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg=="],
+
"has-bigints": ["[email protected]", "", {}, "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg=="],
"has-flag": ["[email protected]", "", {}, "sha512-CsNUt5x9LUdx6hnk/E2SZLsDyvfqANZSUq4+D3D8RzDJ2M+HDTIkF60ibS1vHaK55vzgiZw1bEPFG9yH7l33wA=="],
@@ -3597,6 +3659,8 @@
"jest-environment-node": ["[email protected]", "", { "dependencies": { "@jest/environment": "30.4.1", "@jest/fake-timers": "30.4.1", "@jest/types": "30.4.1", "@types/node": "*", "jest-mock": "30.4.1", "jest-util": "30.4.1", "jest-validate": "30.4.1" } }, "sha512-4FZYVOk85hz2AyT6BbarKy9u37g6DbrDyCdFhsnDdXqyrueYQvB+0zO4f/kqLCRD0BsPRXPMNJeQwihKZV8naw=="],
+ "jest-get-type": ["[email protected]", "", {}, "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw=="],
+
"jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "30.4.1", "@types/node": "*", "anymatch": "^3.1.3", "fb-watchman": "^2.0.2", "graceful-fs": "^4.2.11", "jest-regex-util": "30.4.0", "jest-util": "30.4.1", "jest-worker": "30.4.1", "picomatch": "^4.0.3", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.3" } }, "sha512-rFrcONd8jeFsyw+Z9CrScJgglRf2+NFmNam8dKu7n+SoHqNYT47mn0DdEcVUZJpvh7Iz6/si7f7yUH7GJHVgnw=="],
"jest-leak-detector": ["[email protected]", "", { "dependencies": { "@jest/get-type": "30.1.0", "pretty-format": "30.4.1" } }, "sha512-IpmyiioeHxiWDhesHnUFmOxcTzwCwKpgACgWajtAP+nYQXiY7DakTxB6Bx9JFiRMljr0AX1PvnQdaU1KFoz6NQ=="],
@@ -4329,6 +4393,8 @@
"resolve-url-loader": ["[email protected]", "", { "dependencies": { "adjust-sourcemap-loader": "^4.0.0", "convert-source-map": "^1.7.0", "loader-utils": "^2.0.0", "postcss": "^8.2.14", "source-map": "0.6.1" } }, "sha512-uZtduh8/8srhBoMx//5bwqjQ+rfYOUq8zC9NrMUGtjBiGTtFJM42s58/36+hTqeqINcnYe08Nj3LkK9lW4N8Xg=="],
+ "resolve.exports": ["[email protected]", "", {}, "sha512-zepuGL0ulf+nt+XaFrlKeaiTJeyPFPLLY62+ncq1/VTHBdt3HsfXOH60priZ6tnXQozdGcDeIF5JVTanvIcYWQ=="],
+
"restore-cursor": ["[email protected]", "", { "dependencies": { "onetime": "^7.0.0", "signal-exit": "^4.1.0" } }, "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA=="],
"reusify": ["[email protected]", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="],
@@ -4509,7 +4575,7 @@
"strip-literal": ["[email protected]", "", { "dependencies": { "js-tokens": "^9.0.1" } }, "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg=="],
- "stripe": ["[email protected]", "", { "dependencies": { "@types/node": ">=8.1.0", "qs": "^6.11.0" } }, "sha512-slTbYS1WhRJXVB8YXU8fgHizkUrM9KJyrw4Dd8pLEwzKHYyQTIE46EePC2MVbSDZdE24o1GdNtzmJV4PrPpmJA=="],
+ "stripe": ["[email protected]", "", { "dependencies": { "qs": "^6.11.0" }, "peerDependencies": { "@types/node": ">=16" }, "optionalPeers": ["@types/node"] }, "sha512-FjgIiE98dMMTNssfdjMvFdD4eZyEzdWAOwPYqzhPRNZeg9ggFWlPXmX1iJKD5pPIwZBaPlC3SayQQkwsPo6/YQ=="],
"strnum": ["[email protected]", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="],
@@ -4605,6 +4671,8 @@
"ts-interface-checker": ["[email protected]", "", {}, "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA=="],
+ "ts-jest": ["[email protected]", "", { "dependencies": { "bs-logger": "^0.2.6", "fast-json-stable-stringify": "^2.1.0", "handlebars": "^4.7.10", "json5": "^2.2.3", "lodash.memoize": "^4.1.2", "make-error": "^1.3.6", "semver": "^7.8.5", "type-fest": "^4.41.0", "yargs-parser": "^21.1.1" }, "peerDependencies": { "@babel/core": ">=7.0.0-beta.0 <9", "@jest/transform": "^29.0.0 || ^30.0.0", "@jest/types": "^29.0.0 || ^30.0.0", "babel-jest": "^29.0.0 || ^30.0.0", "jest": "^29.0.0 || ^30.0.0", "jest-util": "^29.0.0 || ^30.0.0", "typescript": ">=4.3 <7" }, "optionalPeers": ["@babel/core", "@jest/transform", "@jest/types", "babel-jest", "jest-util"], "bin": { "ts-jest": "cli.js" } }, "sha512-s2qmEUYFRqbjz1wv0EmccNPVOb45HOFpFuhzQJLKShYVisuTbCFPIIAIV2EuK5rIxb4BejLDbH7dnBZfYjybUQ=="],
+
"ts-morph": ["[email protected]", "", { "dependencies": { "@ts-morph/common": "~0.29.0", "code-block-writer": "^13.0.3" } }, "sha512-Wp3tnZ2bzwxyTZMtgWVzXDfm7lB1Drz+y9DmmYH/L702PQhPyVrp3pkou3yIz4qjS14GY9kcpmLiOOMvl8oG1g=="],
"ts-node": ["[email protected]", "", { "dependencies": { "@cspotcode/source-map-support": "^0.8.0", "@tsconfig/node10": "^1.0.7", "@tsconfig/node12": "^1.0.7", "@tsconfig/node14": "^1.0.0", "@tsconfig/node16": "^1.0.2", "acorn": "^8.4.1", "acorn-walk": "^8.1.1", "arg": "^4.1.0", "create-require": "^1.1.0", "diff": "^4.0.1", "make-error": "^1.1.1", "v8-compile-cache-lib": "^3.0.1", "yn": "3.1.1" }, "peerDependencies": { "@swc/core": ">=1.2.50", "@swc/wasm": ">=1.2.50", "@types/node": "*", "typescript": ">=2.7" }, "optionalPeers": ["@swc/core", "@swc/wasm"], "bin": { "ts-node": "dist/bin.js", "ts-script": "dist/bin-script-deprecated.js", "ts-node-cwd": "dist/bin-cwd.js", "ts-node-esm": "dist/bin-esm.js", "ts-node-script": "dist/bin-script.js", "ts-node-transpile-only": "dist/bin-transpile.js" } }, "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ=="],
@@ -4631,7 +4699,7 @@
"type-detect": ["[email protected]", "", {}, "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g=="],
- "type-fest": ["[email protected]", "", {}, "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ=="],
+ "type-fest": ["[email protected]", "", {}, "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA=="],
"type-is": ["[email protected]", "", { "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" } }, "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g=="],
@@ -4651,6 +4719,8 @@
"ufo": ["[email protected]", "", {}, "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA=="],
+ "uglify-js": ["[email protected]", "", { "bin": { "uglifyjs": "bin/uglifyjs" } }, "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ=="],
+
"uid-safe": ["[email protected]", "", { "dependencies": { "random-bytes": "~1.0.0" } }, "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA=="],
"ulid": ["[email protected]", "", { "bin": { "ulid": "bin/cli.js" } }, "sha512-fIRiVTJNcSRmXKPZtGzFQv9WRrZ3M9eoptl/teFJvjOzmpU+/K/JH6HZ8deBfb5vMEpicJcLn7JmvdknlMq7Zg=="],
@@ -4775,6 +4845,8 @@
"word-wrap": ["[email protected]", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="],
+ "wordwrap": ["[email protected]", "", {}, "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q=="],
+
"wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA=="],
"wrap-ansi-cjs": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
@@ -4805,7 +4877,7 @@
"yargs": ["[email protected]", "", { "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.0", "y18n": "^5.0.5", "yargs-parser": "^20.2.2" } }, "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw=="],
- "yargs-parser": ["[email protected]", "", {}, "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w=="],
+ "yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
"yn": ["[email protected]", "", {}, "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q=="],
@@ -5201,7 +5273,7 @@
"@medusajs/framework/zod-validation-error": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" } }, "sha512-hmk+pkyKq7Q71PiWVSDUc3VfpzpvcRHZ3QPw9yEMVvmtCekaMeOHnbr3WbxfrgEnQTv6haGP4cmv0Ojmihzsxw=="],
- "@medusajs/payment/stripe": ["[email protected]", "", { "dependencies": { "qs": "^6.11.0" }, "peerDependencies": { "@types/node": ">=16" }, "optionalPeers": ["@types/node"] }, "sha512-FjgIiE98dMMTNssfdjMvFdD4eZyEzdWAOwPYqzhPRNZeg9ggFWlPXmX1iJKD5pPIwZBaPlC3SayQQkwsPo6/YQ=="],
+ "@medusajs/payment-stripe/stripe": ["[email protected]", "", { "dependencies": { "@types/node": ">=8.1.0", "qs": "^6.11.0" } }, "sha512-slTbYS1WhRJXVB8YXU8fgHizkUrM9KJyrw4Dd8pLEwzKHYyQTIE46EePC2MVbSDZdE24o1GdNtzmJV4PrPpmJA=="],
"@medusajs/telemetry/@babel/runtime": ["@babel/[email protected]", "", {}, "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw=="],
@@ -5237,6 +5309,10 @@
"@mercurjs/storefront/react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.8" } }, "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ=="],
+ "@mercurjs/stripe-connector-plugin/@types/jest": ["@types/[email protected]", "", { "dependencies": { "expect": "^29.0.0", "pretty-format": "^29.0.0" } }, "sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest": ["[email protected]", "", { "dependencies": { "@jest/core": "^29.7.0", "@jest/types": "^29.6.3", "import-local": "^3.0.2", "jest-cli": "^29.7.0" }, "peerDependencies": { "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" }, "optionalPeers": ["node-notifier"], "bin": { "jest": "bin/jest.js" } }, "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw=="],
+
"@mikro-orm/cli/fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-VWSRii4t0AFm6ixFFmLLx1t7wS1gh+ckoa84aOeapGum0h+EZd1EhEumSB+ZdDLnEPuucsVB9oB7cxJHap6Afg=="],
"@mikro-orm/cli/yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="],
@@ -5507,6 +5583,8 @@
"boxen/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
+ "boxen/type-fest": ["[email protected]", "", {}, "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ=="],
+
"boxen/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
"browserify-sign/readable-stream": ["[email protected]", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
@@ -5561,6 +5639,12 @@
"create-ecdh/bn.js": ["[email protected]", "", {}, "sha512-3aRg6/JxfffFD+OlOjOFR3Vo79l39ooBTFucxx+MT3dhCtzn3EmiUPQo+6/OZuI2jbXi3YKgmiTFBgChQMwIRQ=="],
+ "create-jest/@jest/types": ["@jest/[email protected]", "", { "dependencies": { "@jest/schemas": "^29.6.3", "@types/istanbul-lib-coverage": "^2.0.0", "@types/istanbul-reports": "^3.0.0", "@types/node": "*", "@types/yargs": "^17.0.8", "chalk": "^4.0.0" } }, "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw=="],
+
+ "create-jest/jest-config": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@jest/test-sequencer": "^29.7.0", "@jest/types": "^29.6.3", "babel-jest": "^29.7.0", "chalk": "^4.0.0", "ci-info": "^3.2.0", "deepmerge": "^4.2.2", "glob": "^7.1.3", "graceful-fs": "^4.2.9", "jest-circus": "^29.7.0", "jest-environment-node": "^29.7.0", "jest-get-type": "^29.6.3", "jest-regex-util": "^29.6.3", "jest-resolve": "^29.7.0", "jest-runner": "^29.7.0", "jest-util": "^29.7.0", "jest-validate": "^29.7.0", "micromatch": "^4.0.4", "parse-json": "^5.2.0", "pretty-format": "^29.7.0", "slash": "^3.0.0", "strip-json-comments": "^3.1.1" }, "peerDependencies": { "@types/node": "*", "ts-node": ">=9.0.0" }, "optionalPeers": ["@types/node", "ts-node"] }, "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ=="],
+
+ "create-jest/jest-util": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "ci-info": "^3.2.0", "graceful-fs": "^4.2.9", "picomatch": "^2.2.3" } }, "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA=="],
+
"create-mercur-app/execa": ["[email protected]", "", { "dependencies": { "@sindresorhus/merge-streams": "^4.0.0", "figures": "^6.1.0", "get-stream": "^9.0.1", "human-signals": "^8.0.1", "is-plain-obj": "^4.1.0", "is-stream": "^4.0.1", "npm-run-path": "^6.0.0", "path-key": "^4.0.0", "pretty-ms": "^9.3.0", "signal-exit": "^4.1.0", "strip-final-newline": "^4.0.0", "which-command": "^0.1.0", "yoctocolors": "^2.1.2" } }, "sha512-Cxl6MKxB1dr1H0FHmiizJ+lavKF7pV+fcDZFyqMB8d5m7qUPm/OtZYcD5vPWePKxSnTQ57KuBd9mtdZ3oNCvyQ=="],
"cross-inspect/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
@@ -5649,6 +5733,8 @@
"graphql-tag/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+ "handlebars/source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
+
"header-case/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
"html-minifier-terser/commander": ["[email protected]", "", {}, "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww=="],
@@ -5895,8 +5981,6 @@
"strip-literal/js-tokens": ["[email protected]", "", {}, "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ=="],
- "stripe/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-GUUEShf+PBCGW2KaXwcIt3Yk+e3pkKwWKb9GSyM9WQVE+ep2jzmHdGsHzu4wgcZy5fN9FBdVzjpBQsYlpfpgLA=="],
-
"sucrase/commander": ["[email protected]", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="],
"sucrase/tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg=="],
@@ -5925,14 +6009,14 @@
"to-buffer/isarray": ["[email protected]", "", {}, "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw=="],
+ "ts-jest/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
+
"ts-node/diff": ["[email protected]", "", {}, "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ=="],
"tsup/tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg=="],
"tsx/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.0", "@esbuild/android-arm": "0.28.0", "@esbuild/android-arm64": "0.28.0", "@esbuild/android-x64": "0.28.0", "@esbuild/darwin-arm64": "0.28.0", "@esbuild/darwin-x64": "0.28.0", "@esbuild/freebsd-arm64": "0.28.0", "@esbuild/freebsd-x64": "0.28.0", "@esbuild/linux-arm": "0.28.0", "@esbuild/linux-arm64": "0.28.0", "@esbuild/linux-ia32": "0.28.0", "@esbuild/linux-loong64": "0.28.0", "@esbuild/linux-mips64el": "0.28.0", "@esbuild/linux-ppc64": "0.28.0", "@esbuild/linux-riscv64": "0.28.0", "@esbuild/linux-s390x": "0.28.0", "@esbuild/linux-x64": "0.28.0", "@esbuild/netbsd-arm64": "0.28.0", "@esbuild/netbsd-x64": "0.28.0", "@esbuild/openbsd-arm64": "0.28.0", "@esbuild/openbsd-x64": "0.28.0", "@esbuild/openharmony-arm64": "0.28.0", "@esbuild/sunos-x64": "0.28.0", "@esbuild/win32-arm64": "0.28.0", "@esbuild/win32-ia32": "0.28.0", "@esbuild/win32-x64": "0.28.0" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw=="],
- "umzug/type-fest": ["[email protected]", "", {}, "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA=="],
-
"upper-case/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
"upper-case-first/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
@@ -5977,6 +6061,8 @@
"yargs/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
+ "yargs/yargs-parser": ["[email protected]", "", {}, "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w=="],
+
"@babel/core/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
"@babel/core/@babel/generator/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
@@ -6239,8 +6325,6 @@
"@grpc/proto-loader/yargs/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
- "@grpc/proto-loader/yargs/yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
-
"@ianvs/prettier-plugin-sort-imports/@babel/generator/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@ianvs/prettier-plugin-sort-imports/@babel/traverse/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
@@ -6359,8 +6443,6 @@
"@medusajs/cli/yargs/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
- "@medusajs/cli/yargs/yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
-
"@medusajs/dashboard/@radix-ui/react-dialog/@radix-ui/react-dismissable-layer": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.1", "@radix-ui/react-compose-refs": "1.1.1", "@radix-ui/react-primitive": "2.0.1", "@radix-ui/react-use-callback-ref": "1.1.0", "@radix-ui/react-use-escape-keydown": "1.1.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-onrWn/72lQoEucDmJnr8uczSNTujT0vJnA/X5+3AkChVPowr8n1yvIKIabhWyMQeMvvmdpsvcyDqx3X1LEXCPg=="],
"@medusajs/dashboard/@radix-ui/react-dialog/@radix-ui/react-id": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-EJUrI8yYh7WOjNOqpoJaf1jlFIH2LvtgAl+YcFqNCa+4hj64ZXmPkAKOFs/ukjz3byN6bdb/AVUqHkI8/uWWMA=="],
@@ -6373,6 +6455,8 @@
"@medusajs/dashboard/react-router-dom/react-router": ["[email protected]", "", { "dependencies": { "cookie": "^1.0.1", "set-cookie-parser": "^2.6.0" }, "peerDependencies": { "react": ">=18", "react-dom": ">=18" }, "optionalPeers": ["react-dom"] }, "sha512-aUVMjFm3GAPTTZL7oYr5E7ETiqfQCHRLH+B+5afnICvf0r7kkK4eR6SMuwbSTJw/7t+12khT/Kahij49fqOCIg=="],
+ "@medusajs/payment-stripe/stripe/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-GUUEShf+PBCGW2KaXwcIt3Yk+e3pkKwWKb9GSyM9WQVE+ep2jzmHdGsHzu4wgcZy5fN9FBdVzjpBQsYlpfpgLA=="],
+
"@medusajs/ui/@radix-ui/react-dialog/@radix-ui/react-dismissable-layer": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.1", "@radix-ui/react-compose-refs": "1.1.1", "@radix-ui/react-primitive": "2.0.1", "@radix-ui/react-use-callback-ref": "1.1.0", "@radix-ui/react-use-escape-keydown": "1.1.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-onrWn/72lQoEucDmJnr8uczSNTujT0vJnA/X5+3AkChVPowr8n1yvIKIabhWyMQeMvvmdpsvcyDqx3X1LEXCPg=="],
"@medusajs/ui/@radix-ui/react-dialog/@radix-ui/react-id": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-EJUrI8yYh7WOjNOqpoJaf1jlFIH2LvtgAl+YcFqNCa+4hj64ZXmPkAKOFs/ukjz3byN6bdb/AVUqHkI8/uWWMA=="],
@@ -6403,12 +6487,20 @@
"@mercurjs/storefront/react-dom/scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/pretty-format": ["[email protected]", "", { "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" } }, "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core": ["@jest/[email protected]", "", { "dependencies": { "@jest/console": "^29.7.0", "@jest/reporters": "^29.7.0", "@jest/test-result": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "ansi-escapes": "^4.2.1", "chalk": "^4.0.0", "ci-info": "^3.2.0", "exit": "^0.1.2", "graceful-fs": "^4.2.9", "jest-changed-files": "^29.7.0", "jest-config": "^29.7.0", "jest-haste-map": "^29.7.0", "jest-message-util": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-resolve": "^29.7.0", "jest-resolve-dependencies": "^29.7.0", "jest-runner": "^29.7.0", "jest-runtime": "^29.7.0", "jest-snapshot": "^29.7.0", "jest-util": "^29.7.0", "jest-validate": "^29.7.0", "jest-watcher": "^29.7.0", "micromatch": "^4.0.4", "pretty-format": "^29.7.0", "slash": "^3.0.0", "strip-ansi": "^6.0.0" }, "peerDependencies": { "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" }, "optionalPeers": ["node-notifier"] }, "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/types": ["@jest/[email protected]", "", { "dependencies": { "@jest/schemas": "^29.6.3", "@types/istanbul-lib-coverage": "^2.0.0", "@types/istanbul-reports": "^3.0.0", "@types/node": "*", "@types/yargs": "^17.0.8", "chalk": "^4.0.0" } }, "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli": ["[email protected]", "", { "dependencies": { "@jest/core": "^29.7.0", "@jest/test-result": "^29.7.0", "@jest/types": "^29.6.3", "chalk": "^4.0.0", "create-jest": "^29.7.0", "exit": "^0.1.2", "import-local": "^3.0.2", "jest-config": "^29.7.0", "jest-util": "^29.7.0", "jest-validate": "^29.7.0", "yargs": "^17.3.1" }, "peerDependencies": { "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" }, "optionalPeers": ["node-notifier"], "bin": { "jest": "bin/jest.js" } }, "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg=="],
+
"@mikro-orm/cli/yargs/cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
"@mikro-orm/cli/yargs/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
- "@mikro-orm/cli/yargs/yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
-
"@next/eslint-plugin-next/fast-glob/glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
"@oclif/errors/fs-extra/jsonfile": ["[email protected]", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],
@@ -6661,6 +6753,32 @@
"compression/debug/ms": ["[email protected]", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="],
+ "create-jest/@jest/types/@jest/schemas": ["@jest/[email protected]", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="],
+
+ "create-jest/jest-config/@jest/test-sequencer": ["@jest/[email protected]", "", { "dependencies": { "@jest/test-result": "^29.7.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "slash": "^3.0.0" } }, "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw=="],
+
+ "create-jest/jest-config/babel-jest": ["[email protected]", "", { "dependencies": { "@jest/transform": "^29.7.0", "@types/babel__core": "^7.1.14", "babel-plugin-istanbul": "^6.1.1", "babel-preset-jest": "^29.6.3", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "slash": "^3.0.0" }, "peerDependencies": { "@babel/core": "^7.8.0" } }, "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg=="],
+
+ "create-jest/jest-config/ci-info": ["[email protected]", "", {}, "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ=="],
+
+ "create-jest/jest-config/jest-circus": ["[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/expect": "^29.7.0", "@jest/test-result": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "co": "^4.6.0", "dedent": "^1.0.0", "is-generator-fn": "^2.0.0", "jest-each": "^29.7.0", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-runtime": "^29.7.0", "jest-snapshot": "^29.7.0", "jest-util": "^29.7.0", "p-limit": "^3.1.0", "pretty-format": "^29.7.0", "pure-rand": "^6.0.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" } }, "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw=="],
+
+ "create-jest/jest-config/jest-environment-node": ["[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw=="],
+
+ "create-jest/jest-config/jest-regex-util": ["[email protected]", "", {}, "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg=="],
+
+ "create-jest/jest-config/jest-resolve": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-pnp-resolver": "^1.2.2", "jest-util": "^29.7.0", "jest-validate": "^29.7.0", "resolve": "^1.20.0", "resolve.exports": "^2.0.0", "slash": "^3.0.0" } }, "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA=="],
+
+ "create-jest/jest-config/jest-runner": ["[email protected]", "", { "dependencies": { "@jest/console": "^29.7.0", "@jest/environment": "^29.7.0", "@jest/test-result": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "emittery": "^0.13.1", "graceful-fs": "^4.2.9", "jest-docblock": "^29.7.0", "jest-environment-node": "^29.7.0", "jest-haste-map": "^29.7.0", "jest-leak-detector": "^29.7.0", "jest-message-util": "^29.7.0", "jest-resolve": "^29.7.0", "jest-runtime": "^29.7.0", "jest-util": "^29.7.0", "jest-watcher": "^29.7.0", "jest-worker": "^29.7.0", "p-limit": "^3.1.0", "source-map-support": "0.5.13" } }, "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ=="],
+
+ "create-jest/jest-config/jest-validate": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "camelcase": "^6.2.0", "chalk": "^4.0.0", "jest-get-type": "^29.6.3", "leven": "^3.1.0", "pretty-format": "^29.7.0" } }, "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw=="],
+
+ "create-jest/jest-config/pretty-format": ["[email protected]", "", { "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" } }, "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ=="],
+
+ "create-jest/jest-util/ci-info": ["[email protected]", "", {}, "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ=="],
+
+ "create-jest/jest-util/picomatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
+
"css-select/domutils/dom-serializer": ["[email protected]", "", { "dependencies": { "domelementtype": "^2.0.1", "domhandler": "^4.2.0", "entities": "^2.0.0" } }, "sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag=="],
"eslint-plugin-import/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg=="],
@@ -6741,8 +6859,6 @@
"jest-cli/yargs/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
- "jest-cli/yargs/yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
-
"jest-config/glob/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="],
"jest-config/glob/path-scurry": ["[email protected]", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="],
@@ -6885,8 +7001,6 @@
"string-width-cjs/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
- "stripe/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
-
"tailwindcss/chokidar/glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
"tailwindcss/chokidar/readdirp": ["[email protected]", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="],
@@ -7275,12 +7389,82 @@
"@medusajs/dashboard/react-router-dom/react-router/cookie": ["[email protected]", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="],
+ "@medusajs/payment-stripe/stripe/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
+
"@mercurjs/core/pkg-dir/find-up/locate-path": ["[email protected]", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="],
"@mercurjs/storefront/eslint/@eslint/config-array/@eslint/object-schema": ["@eslint/[email protected]", "", {}, "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA=="],
"@mercurjs/storefront/eslint/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg=="],
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/@jest/expect-utils": ["@jest/[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3" } }, "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-matcher-utils": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-message-util": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.12.13", "@jest/types": "^29.6.3", "@types/stack-utils": "^2.0.0", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "micromatch": "^4.0.4", "pretty-format": "^29.7.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" } }, "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-util": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "ci-info": "^3.2.0", "graceful-fs": "^4.2.9", "picomatch": "^2.2.3" } }, "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/pretty-format/@jest/schemas": ["@jest/[email protected]", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/pretty-format/ansi-styles": ["[email protected]", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/pretty-format/react-is": ["[email protected]", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/console": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0", "slash": "^3.0.0" } }, "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/reporters": ["@jest/[email protected]", "", { "dependencies": { "@bcoe/v8-coverage": "^0.2.3", "@jest/console": "^29.7.0", "@jest/test-result": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "@jridgewell/trace-mapping": "^0.3.18", "@types/node": "*", "chalk": "^4.0.0", "collect-v8-coverage": "^1.0.0", "exit": "^0.1.2", "glob": "^7.1.3", "graceful-fs": "^4.2.9", "istanbul-lib-coverage": "^3.0.0", "istanbul-lib-instrument": "^6.0.0", "istanbul-lib-report": "^3.0.0", "istanbul-lib-source-maps": "^4.0.0", "istanbul-reports": "^3.1.3", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "slash": "^3.0.0", "string-length": "^4.0.1", "strip-ansi": "^6.0.0", "v8-to-istanbul": "^9.0.1" }, "peerDependencies": { "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" }, "optionalPeers": ["node-notifier"] }, "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/test-result": ["@jest/[email protected]", "", { "dependencies": { "@jest/console": "^29.7.0", "@jest/types": "^29.6.3", "@types/istanbul-lib-coverage": "^2.0.0", "collect-v8-coverage": "^1.0.0" } }, "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/transform": ["@jest/[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@jest/types": "^29.6.3", "@jridgewell/trace-mapping": "^0.3.18", "babel-plugin-istanbul": "^6.1.1", "chalk": "^4.0.0", "convert-source-map": "^2.0.0", "fast-json-stable-stringify": "^2.1.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "micromatch": "^4.0.4", "pirates": "^4.0.4", "slash": "^3.0.0", "write-file-atomic": "^4.0.2" } }, "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/ansi-escapes": ["[email protected]", "", { "dependencies": { "type-fest": "^0.21.3" } }, "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/ci-info": ["[email protected]", "", {}, "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-changed-files": ["[email protected]", "", { "dependencies": { "execa": "^5.0.0", "jest-util": "^29.7.0", "p-limit": "^3.1.0" } }, "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@jest/test-sequencer": "^29.7.0", "@jest/types": "^29.6.3", "babel-jest": "^29.7.0", "chalk": "^4.0.0", "ci-info": "^3.2.0", "deepmerge": "^4.2.2", "glob": "^7.1.3", "graceful-fs": "^4.2.9", "jest-circus": "^29.7.0", "jest-environment-node": "^29.7.0", "jest-get-type": "^29.6.3", "jest-regex-util": "^29.6.3", "jest-resolve": "^29.7.0", "jest-runner": "^29.7.0", "jest-util": "^29.7.0", "jest-validate": "^29.7.0", "micromatch": "^4.0.4", "parse-json": "^5.2.0", "pretty-format": "^29.7.0", "slash": "^3.0.0", "strip-json-comments": "^3.1.1" }, "peerDependencies": { "@types/node": "*", "ts-node": ">=9.0.0" }, "optionalPeers": ["@types/node", "ts-node"] }, "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "micromatch": "^4.0.4", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-message-util": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.12.13", "@jest/types": "^29.6.3", "@types/stack-utils": "^2.0.0", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "micromatch": "^4.0.4", "pretty-format": "^29.7.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" } }, "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-regex-util": ["[email protected]", "", {}, "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-resolve": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-pnp-resolver": "^1.2.2", "jest-util": "^29.7.0", "jest-validate": "^29.7.0", "resolve": "^1.20.0", "resolve.exports": "^2.0.0", "slash": "^3.0.0" } }, "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-resolve-dependencies": ["[email protected]", "", { "dependencies": { "jest-regex-util": "^29.6.3", "jest-snapshot": "^29.7.0" } }, "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner": ["[email protected]", "", { "dependencies": { "@jest/console": "^29.7.0", "@jest/environment": "^29.7.0", "@jest/test-result": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "emittery": "^0.13.1", "graceful-fs": "^4.2.9", "jest-docblock": "^29.7.0", "jest-environment-node": "^29.7.0", "jest-haste-map": "^29.7.0", "jest-leak-detector": "^29.7.0", "jest-message-util": "^29.7.0", "jest-resolve": "^29.7.0", "jest-runtime": "^29.7.0", "jest-util": "^29.7.0", "jest-watcher": "^29.7.0", "jest-worker": "^29.7.0", "p-limit": "^3.1.0", "source-map-support": "0.5.13" } }, "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime": ["[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/fake-timers": "^29.7.0", "@jest/globals": "^29.7.0", "@jest/source-map": "^29.6.3", "@jest/test-result": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "cjs-module-lexer": "^1.0.0", "collect-v8-coverage": "^1.0.0", "glob": "^7.1.3", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-resolve": "^29.7.0", "jest-snapshot": "^29.7.0", "jest-util": "^29.7.0", "slash": "^3.0.0", "strip-bom": "^4.0.0" } }, "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-snapshot": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@babel/generator": "^7.7.2", "@babel/plugin-syntax-jsx": "^7.7.2", "@babel/plugin-syntax-typescript": "^7.7.2", "@babel/types": "^7.3.3", "@jest/expect-utils": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "babel-preset-current-node-syntax": "^1.0.0", "chalk": "^4.0.0", "expect": "^29.7.0", "graceful-fs": "^4.2.9", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0", "natural-compare": "^1.4.0", "pretty-format": "^29.7.0", "semver": "^7.5.3" } }, "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-util": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "ci-info": "^3.2.0", "graceful-fs": "^4.2.9", "picomatch": "^2.2.3" } }, "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-validate": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "camelcase": "^6.2.0", "chalk": "^4.0.0", "jest-get-type": "^29.6.3", "leven": "^3.1.0", "pretty-format": "^29.7.0" } }, "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-watcher": ["[email protected]", "", { "dependencies": { "@jest/test-result": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "ansi-escapes": "^4.2.1", "chalk": "^4.0.0", "emittery": "^0.13.1", "jest-util": "^29.7.0", "string-length": "^4.0.1" } }, "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/pretty-format": ["[email protected]", "", { "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" } }, "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/types/@jest/schemas": ["@jest/[email protected]", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/@jest/test-result": ["@jest/[email protected]", "", { "dependencies": { "@jest/console": "^29.7.0", "@jest/types": "^29.6.3", "@types/istanbul-lib-coverage": "^2.0.0", "collect-v8-coverage": "^1.0.0" } }, "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@jest/test-sequencer": "^29.7.0", "@jest/types": "^29.6.3", "babel-jest": "^29.7.0", "chalk": "^4.0.0", "ci-info": "^3.2.0", "deepmerge": "^4.2.2", "glob": "^7.1.3", "graceful-fs": "^4.2.9", "jest-circus": "^29.7.0", "jest-environment-node": "^29.7.0", "jest-get-type": "^29.6.3", "jest-regex-util": "^29.6.3", "jest-resolve": "^29.7.0", "jest-runner": "^29.7.0", "jest-util": "^29.7.0", "jest-validate": "^29.7.0", "micromatch": "^4.0.4", "parse-json": "^5.2.0", "pretty-format": "^29.7.0", "slash": "^3.0.0", "strip-json-comments": "^3.1.1" }, "peerDependencies": { "@types/node": "*", "ts-node": ">=9.0.0" }, "optionalPeers": ["@types/node", "ts-node"] }, "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-util": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "ci-info": "^3.2.0", "graceful-fs": "^4.2.9", "picomatch": "^2.2.3" } }, "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-validate": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "camelcase": "^6.2.0", "chalk": "^4.0.0", "jest-get-type": "^29.6.3", "leven": "^3.1.0", "pretty-format": "^29.7.0" } }, "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="],
+
"@mikro-orm/cli/yargs/cliui/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"@mikro-orm/cli/yargs/cliui/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
@@ -7379,6 +7563,74 @@
"cli-progress/string-width/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+ "create-jest/@jest/types/@jest/schemas/@sinclair/typebox": ["@sinclair/[email protected]", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="],
+
+ "create-jest/jest-config/@jest/test-sequencer/@jest/test-result": ["@jest/[email protected]", "", { "dependencies": { "@jest/console": "^29.7.0", "@jest/types": "^29.6.3", "@types/istanbul-lib-coverage": "^2.0.0", "collect-v8-coverage": "^1.0.0" } }, "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA=="],
+
+ "create-jest/jest-config/@jest/test-sequencer/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "micromatch": "^4.0.4", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA=="],
+
+ "create-jest/jest-config/babel-jest/@jest/transform": ["@jest/[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@jest/types": "^29.6.3", "@jridgewell/trace-mapping": "^0.3.18", "babel-plugin-istanbul": "^6.1.1", "chalk": "^4.0.0", "convert-source-map": "^2.0.0", "fast-json-stable-stringify": "^2.1.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "micromatch": "^4.0.4", "pirates": "^4.0.4", "slash": "^3.0.0", "write-file-atomic": "^4.0.2" } }, "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw=="],
+
+ "create-jest/jest-config/babel-jest/babel-plugin-istanbul": ["[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-instrument": "^5.0.4", "test-exclude": "^6.0.0" } }, "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA=="],
+
+ "create-jest/jest-config/babel-jest/babel-preset-jest": ["[email protected]", "", { "dependencies": { "babel-plugin-jest-hoist": "^29.6.3", "babel-preset-current-node-syntax": "^1.0.0" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA=="],
+
+ "create-jest/jest-config/jest-circus/@jest/environment": ["@jest/[email protected]", "", { "dependencies": { "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0" } }, "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw=="],
+
+ "create-jest/jest-config/jest-circus/@jest/expect": ["@jest/[email protected]", "", { "dependencies": { "expect": "^29.7.0", "jest-snapshot": "^29.7.0" } }, "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ=="],
+
+ "create-jest/jest-config/jest-circus/@jest/test-result": ["@jest/[email protected]", "", { "dependencies": { "@jest/console": "^29.7.0", "@jest/types": "^29.6.3", "@types/istanbul-lib-coverage": "^2.0.0", "collect-v8-coverage": "^1.0.0" } }, "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA=="],
+
+ "create-jest/jest-config/jest-circus/jest-each": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "chalk": "^4.0.0", "jest-get-type": "^29.6.3", "jest-util": "^29.7.0", "pretty-format": "^29.7.0" } }, "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ=="],
+
+ "create-jest/jest-config/jest-circus/jest-matcher-utils": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g=="],
+
+ "create-jest/jest-config/jest-circus/jest-message-util": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.12.13", "@jest/types": "^29.6.3", "@types/stack-utils": "^2.0.0", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "micromatch": "^4.0.4", "pretty-format": "^29.7.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" } }, "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime": ["[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/fake-timers": "^29.7.0", "@jest/globals": "^29.7.0", "@jest/source-map": "^29.6.3", "@jest/test-result": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "cjs-module-lexer": "^1.0.0", "collect-v8-coverage": "^1.0.0", "glob": "^7.1.3", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-resolve": "^29.7.0", "jest-snapshot": "^29.7.0", "jest-util": "^29.7.0", "slash": "^3.0.0", "strip-bom": "^4.0.0" } }, "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@babel/generator": "^7.7.2", "@babel/plugin-syntax-jsx": "^7.7.2", "@babel/plugin-syntax-typescript": "^7.7.2", "@babel/types": "^7.3.3", "@jest/expect-utils": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "babel-preset-current-node-syntax": "^1.0.0", "chalk": "^4.0.0", "expect": "^29.7.0", "graceful-fs": "^4.2.9", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0", "natural-compare": "^1.4.0", "pretty-format": "^29.7.0", "semver": "^7.5.3" } }, "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw=="],
+
+ "create-jest/jest-config/jest-circus/pure-rand": ["[email protected]", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
+
+ "create-jest/jest-config/jest-environment-node/@jest/environment": ["@jest/[email protected]", "", { "dependencies": { "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0" } }, "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw=="],
+
+ "create-jest/jest-config/jest-environment-node/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
+
+ "create-jest/jest-config/jest-environment-node/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "create-jest/jest-config/jest-resolve/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "micromatch": "^4.0.4", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA=="],
+
+ "create-jest/jest-config/jest-runner/@jest/console": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0", "slash": "^3.0.0" } }, "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg=="],
+
+ "create-jest/jest-config/jest-runner/@jest/environment": ["@jest/[email protected]", "", { "dependencies": { "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0" } }, "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw=="],
+
+ "create-jest/jest-config/jest-runner/@jest/test-result": ["@jest/[email protected]", "", { "dependencies": { "@jest/console": "^29.7.0", "@jest/types": "^29.6.3", "@types/istanbul-lib-coverage": "^2.0.0", "collect-v8-coverage": "^1.0.0" } }, "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA=="],
+
+ "create-jest/jest-config/jest-runner/@jest/transform": ["@jest/[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@jest/types": "^29.6.3", "@jridgewell/trace-mapping": "^0.3.18", "babel-plugin-istanbul": "^6.1.1", "chalk": "^4.0.0", "convert-source-map": "^2.0.0", "fast-json-stable-stringify": "^2.1.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "micromatch": "^4.0.4", "pirates": "^4.0.4", "slash": "^3.0.0", "write-file-atomic": "^4.0.2" } }, "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw=="],
+
+ "create-jest/jest-config/jest-runner/jest-docblock": ["[email protected]", "", { "dependencies": { "detect-newline": "^3.0.0" } }, "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g=="],
+
+ "create-jest/jest-config/jest-runner/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "micromatch": "^4.0.4", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA=="],
+
+ "create-jest/jest-config/jest-runner/jest-leak-detector": ["[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw=="],
+
+ "create-jest/jest-config/jest-runner/jest-message-util": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.12.13", "@jest/types": "^29.6.3", "@types/stack-utils": "^2.0.0", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "micromatch": "^4.0.4", "pretty-format": "^29.7.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" } }, "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime": ["[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/fake-timers": "^29.7.0", "@jest/globals": "^29.7.0", "@jest/source-map": "^29.6.3", "@jest/test-result": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "cjs-module-lexer": "^1.0.0", "collect-v8-coverage": "^1.0.0", "glob": "^7.1.3", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-resolve": "^29.7.0", "jest-snapshot": "^29.7.0", "jest-util": "^29.7.0", "slash": "^3.0.0", "strip-bom": "^4.0.0" } }, "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ=="],
+
+ "create-jest/jest-config/jest-runner/jest-watcher": ["[email protected]", "", { "dependencies": { "@jest/test-result": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "ansi-escapes": "^4.2.1", "chalk": "^4.0.0", "emittery": "^0.13.1", "jest-util": "^29.7.0", "string-length": "^4.0.1" } }, "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g=="],
+
+ "create-jest/jest-config/jest-runner/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "create-jest/jest-config/jest-runner/source-map-support": ["[email protected]", "", { "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" } }, "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w=="],
+
+ "create-jest/jest-config/pretty-format/@jest/schemas": ["@jest/[email protected]", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="],
+
+ "create-jest/jest-config/pretty-format/ansi-styles": ["[email protected]", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
+
+ "create-jest/jest-config/pretty-format/react-is": ["[email protected]", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="],
+
"css-select/domutils/dom-serializer/entities": ["[email protected]", "", {}, "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A=="],
"eslint-plugin-import/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
@@ -7603,6 +7855,126 @@
"@mercurjs/storefront/eslint/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-matcher-utils/jest-diff": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^29.6.3", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-message-util/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-message-util/@jest/types": ["@jest/[email protected]", "", { "dependencies": { "@jest/schemas": "^29.6.3", "@types/istanbul-lib-coverage": "^2.0.0", "@types/istanbul-reports": "^3.0.0", "@types/node": "*", "@types/yargs": "^17.0.8", "chalk": "^4.0.0" } }, "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-util/@jest/types": ["@jest/[email protected]", "", { "dependencies": { "@jest/schemas": "^29.6.3", "@types/istanbul-lib-coverage": "^2.0.0", "@types/istanbul-reports": "^3.0.0", "@types/node": "*", "@types/yargs": "^17.0.8", "chalk": "^4.0.0" } }, "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-util/ci-info": ["[email protected]", "", {}, "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-util/picomatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/pretty-format/@jest/schemas/@sinclair/typebox": ["@sinclair/[email protected]", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/reporters/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/reporters/istanbul-lib-source-maps": ["[email protected]", "", { "dependencies": { "debug": "^4.1.1", "istanbul-lib-coverage": "^3.0.0", "source-map": "^0.6.1" } }, "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/reporters/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/transform/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/transform/babel-plugin-istanbul": ["[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-instrument": "^5.0.4", "test-exclude": "^6.0.0" } }, "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/transform/write-file-atomic": ["[email protected]", "", { "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^3.0.7" } }, "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/ansi-escapes/type-fest": ["[email protected]", "", {}, "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-changed-files/execa": ["[email protected]", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^6.0.0", "human-signals": "^2.1.0", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.1", "onetime": "^5.1.2", "signal-exit": "^3.0.3", "strip-final-newline": "^2.0.0" } }, "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/@jest/test-sequencer": ["@jest/[email protected]", "", { "dependencies": { "@jest/test-result": "^29.7.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "slash": "^3.0.0" } }, "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest": ["[email protected]", "", { "dependencies": { "@jest/transform": "^29.7.0", "@types/babel__core": "^7.1.14", "babel-plugin-istanbul": "^6.1.1", "babel-preset-jest": "^29.6.3", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "slash": "^3.0.0" }, "peerDependencies": { "@babel/core": "^7.8.0" } }, "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-circus": ["[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/expect": "^29.7.0", "@jest/test-result": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "co": "^4.6.0", "dedent": "^1.0.0", "is-generator-fn": "^2.0.0", "jest-each": "^29.7.0", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-runtime": "^29.7.0", "jest-snapshot": "^29.7.0", "jest-util": "^29.7.0", "p-limit": "^3.1.0", "pretty-format": "^29.7.0", "pure-rand": "^6.0.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" } }, "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-environment-node": ["[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-message-util/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner/@jest/environment": ["@jest/[email protected]", "", { "dependencies": { "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0" } }, "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner/jest-docblock": ["[email protected]", "", { "dependencies": { "detect-newline": "^3.0.0" } }, "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner/jest-environment-node": ["[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner/jest-leak-detector": ["[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner/source-map-support": ["[email protected]", "", { "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" } }, "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime/@jest/environment": ["@jest/[email protected]", "", { "dependencies": { "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0" } }, "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime/@jest/globals": ["@jest/[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/expect": "^29.7.0", "@jest/types": "^29.6.3", "jest-mock": "^29.7.0" } }, "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime/@jest/source-map": ["@jest/[email protected]", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.18", "callsites": "^3.0.0", "graceful-fs": "^4.2.9" } }, "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime/strip-bom": ["[email protected]", "", {}, "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-snapshot/@babel/generator": ["@babel/[email protected]", "", { "dependencies": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-snapshot/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-snapshot/@jest/expect-utils": ["@jest/[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3" } }, "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-snapshot/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-snapshot/jest-diff": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^29.6.3", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-snapshot/jest-matcher-utils": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-util/picomatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/pretty-format/@jest/schemas": ["@jest/[email protected]", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/pretty-format/ansi-styles": ["[email protected]", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/pretty-format/react-is": ["[email protected]", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/types/@jest/schemas/@sinclair/typebox": ["@sinclair/[email protected]", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/@jest/test-result/@jest/console": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0", "slash": "^3.0.0" } }, "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/@jest/test-sequencer": ["@jest/[email protected]", "", { "dependencies": { "@jest/test-result": "^29.7.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "slash": "^3.0.0" } }, "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest": ["[email protected]", "", { "dependencies": { "@jest/transform": "^29.7.0", "@types/babel__core": "^7.1.14", "babel-plugin-istanbul": "^6.1.1", "babel-preset-jest": "^29.6.3", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "slash": "^3.0.0" }, "peerDependencies": { "@babel/core": "^7.8.0" } }, "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/ci-info": ["[email protected]", "", {}, "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus": ["[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/expect": "^29.7.0", "@jest/test-result": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "co": "^4.6.0", "dedent": "^1.0.0", "is-generator-fn": "^2.0.0", "jest-each": "^29.7.0", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-runtime": "^29.7.0", "jest-snapshot": "^29.7.0", "jest-util": "^29.7.0", "p-limit": "^3.1.0", "pretty-format": "^29.7.0", "pure-rand": "^6.0.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" } }, "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-environment-node": ["[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-regex-util": ["[email protected]", "", {}, "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-resolve": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-pnp-resolver": "^1.2.2", "jest-util": "^29.7.0", "jest-validate": "^29.7.0", "resolve": "^1.20.0", "resolve.exports": "^2.0.0", "slash": "^3.0.0" } }, "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner": ["[email protected]", "", { "dependencies": { "@jest/console": "^29.7.0", "@jest/environment": "^29.7.0", "@jest/test-result": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "emittery": "^0.13.1", "graceful-fs": "^4.2.9", "jest-docblock": "^29.7.0", "jest-environment-node": "^29.7.0", "jest-haste-map": "^29.7.0", "jest-leak-detector": "^29.7.0", "jest-message-util": "^29.7.0", "jest-resolve": "^29.7.0", "jest-runtime": "^29.7.0", "jest-util": "^29.7.0", "jest-watcher": "^29.7.0", "jest-worker": "^29.7.0", "p-limit": "^3.1.0", "source-map-support": "0.5.13" } }, "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/pretty-format": ["[email protected]", "", { "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" } }, "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-util/ci-info": ["[email protected]", "", {}, "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-util/picomatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-validate/pretty-format": ["[email protected]", "", { "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" } }, "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/yargs/cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/yargs/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
+
"@mikro-orm/cli/yargs/cliui/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
"@mikro-orm/cli/yargs/string-width/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
@@ -7615,36 +7987,740 @@
"@storybook/react-docgen-typescript-plugin/find-cache-dir/pkg-dir/find-up/locate-path": ["[email protected]", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="],
- "find-cache-dir/pkg-dir/find-up/locate-path/p-locate": ["[email protected]", "", { "dependencies": { "p-limit": "^4.0.0" } }, "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw=="],
+ "create-jest/jest-config/@jest/test-sequencer/@jest/test-result/@jest/console": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0", "slash": "^3.0.0" } }, "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg=="],
- "import-local/pkg-dir/find-up/locate-path/p-locate": ["[email protected]", "", { "dependencies": { "p-limit": "^2.2.0" } }, "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A=="],
+ "create-jest/jest-config/@jest/test-sequencer/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
- "jest-cli/yargs/cliui/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+ "create-jest/jest-config/babel-jest/@jest/transform/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
- "jest-cli/yargs/string-width/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+ "create-jest/jest-config/babel-jest/@jest/transform/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "micromatch": "^4.0.4", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA=="],
- "jest-config/glob/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
+ "create-jest/jest-config/babel-jest/@jest/transform/write-file-atomic": ["[email protected]", "", { "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^3.0.7" } }, "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg=="],
- "jest-runtime/glob/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
+ "create-jest/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.12.3", "@babel/parser": "^7.14.7", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-coverage": "^3.2.0", "semver": "^6.3.0" } }, "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg=="],
- "qrcode/yargs/cliui/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+ "create-jest/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist": ["[email protected]", "", { "dependencies": { "@babel/template": "^7.3.3", "@babel/types": "^7.3.3", "@types/babel__core": "^7.1.14", "@types/babel__traverse": "^7.0.6" } }, "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg=="],
- "qrcode/yargs/find-up/locate-path/p-locate": ["[email protected]", "", { "dependencies": { "p-limit": "^2.2.0" } }, "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A=="],
+ "create-jest/jest-config/jest-circus/@jest/environment/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
- "qrcode/yargs/string-width/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+ "create-jest/jest-config/jest-circus/@jest/environment/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
- "@mercurjs/core/pkg-dir/find-up/locate-path/p-locate/p-limit": ["[email protected]", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
+ "create-jest/jest-config/jest-circus/@jest/expect/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw=="],
- "@storybook/react-docgen-typescript-plugin/find-cache-dir/pkg-dir/find-up/locate-path/p-locate": ["[email protected]", "", { "dependencies": { "p-limit": "^2.2.0" } }, "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A=="],
+ "create-jest/jest-config/jest-circus/@jest/test-result/@jest/console": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0", "slash": "^3.0.0" } }, "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg=="],
- "find-cache-dir/pkg-dir/find-up/locate-path/p-locate/p-limit": ["[email protected]", "", { "dependencies": { "yocto-queue": "^1.0.0" } }, "sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ=="],
+ "create-jest/jest-config/jest-circus/jest-matcher-utils/jest-diff": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^29.6.3", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw=="],
- "import-local/pkg-dir/find-up/locate-path/p-locate/p-limit": ["[email protected]", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
+ "create-jest/jest-config/jest-circus/jest-message-util/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
- "qrcode/yargs/find-up/locate-path/p-locate/p-limit": ["[email protected]", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
- "@storybook/react-docgen-typescript-plugin/find-cache-dir/pkg-dir/find-up/locate-path/p-locate/p-limit": ["[email protected]", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/globals": ["@jest/[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/expect": "^29.7.0", "@jest/types": "^29.6.3", "jest-mock": "^29.7.0" } }, "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ=="],
- "find-cache-dir/pkg-dir/find-up/locate-path/p-locate/p-limit/yocto-queue": ["[email protected]", "", {}, "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ=="],
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/source-map": ["@jest/[email protected]", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.18", "callsites": "^3.0.0", "graceful-fs": "^4.2.9" } }, "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/transform": ["@jest/[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@jest/types": "^29.6.3", "@jridgewell/trace-mapping": "^0.3.18", "babel-plugin-istanbul": "^6.1.1", "chalk": "^4.0.0", "convert-source-map": "^2.0.0", "fast-json-stable-stringify": "^2.1.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "micromatch": "^4.0.4", "pirates": "^4.0.4", "slash": "^3.0.0", "write-file-atomic": "^4.0.2" } }, "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "micromatch": "^4.0.4", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/strip-bom": ["[email protected]", "", {}, "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@babel/generator": ["@babel/[email protected]", "", { "dependencies": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@jest/expect-utils": ["@jest/[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3" } }, "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@jest/transform": ["@jest/[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@jest/types": "^29.6.3", "@jridgewell/trace-mapping": "^0.3.18", "babel-plugin-istanbul": "^6.1.1", "chalk": "^4.0.0", "convert-source-map": "^2.0.0", "fast-json-stable-stringify": "^2.1.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "micromatch": "^4.0.4", "pirates": "^4.0.4", "slash": "^3.0.0", "write-file-atomic": "^4.0.2" } }, "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/jest-diff": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^29.6.3", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw=="],
+
+ "create-jest/jest-config/jest-environment-node/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "create-jest/jest-config/jest-environment-node/@jest/fake-timers/jest-message-util": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.12.13", "@jest/types": "^29.6.3", "@types/stack-utils": "^2.0.0", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "micromatch": "^4.0.4", "pretty-format": "^29.7.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" } }, "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w=="],
+
+ "create-jest/jest-config/jest-resolve/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "create-jest/jest-config/jest-runner/@jest/environment/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
+
+ "create-jest/jest-config/jest-runner/@jest/environment/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "create-jest/jest-config/jest-runner/@jest/transform/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "create-jest/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul": ["[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-instrument": "^5.0.4", "test-exclude": "^6.0.0" } }, "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA=="],
+
+ "create-jest/jest-config/jest-runner/@jest/transform/write-file-atomic": ["[email protected]", "", { "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^3.0.7" } }, "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg=="],
+
+ "create-jest/jest-config/jest-runner/jest-message-util/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/@jest/globals": ["@jest/[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/expect": "^29.7.0", "@jest/types": "^29.6.3", "jest-mock": "^29.7.0" } }, "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/@jest/source-map": ["@jest/[email protected]", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.18", "callsites": "^3.0.0", "graceful-fs": "^4.2.9" } }, "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/jest-snapshot": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@babel/generator": "^7.7.2", "@babel/plugin-syntax-jsx": "^7.7.2", "@babel/plugin-syntax-typescript": "^7.7.2", "@babel/types": "^7.3.3", "@jest/expect-utils": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "babel-preset-current-node-syntax": "^1.0.0", "chalk": "^4.0.0", "expect": "^29.7.0", "graceful-fs": "^4.2.9", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0", "natural-compare": "^1.4.0", "pretty-format": "^29.7.0", "semver": "^7.5.3" } }, "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/strip-bom": ["[email protected]", "", {}, "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w=="],
+
+ "create-jest/jest-config/jest-runner/jest-watcher/ansi-escapes": ["[email protected]", "", { "dependencies": { "type-fest": "^0.21.3" } }, "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ=="],
+
+ "create-jest/jest-config/jest-runner/source-map-support/source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
+
+ "create-jest/jest-config/pretty-format/@jest/schemas/@sinclair/typebox": ["@sinclair/[email protected]", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="],
+
+ "find-cache-dir/pkg-dir/find-up/locate-path/p-locate": ["[email protected]", "", { "dependencies": { "p-limit": "^4.0.0" } }, "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw=="],
+
+ "import-local/pkg-dir/find-up/locate-path/p-locate": ["[email protected]", "", { "dependencies": { "p-limit": "^2.2.0" } }, "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A=="],
+
+ "jest-cli/yargs/cliui/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "jest-cli/yargs/string-width/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "jest-config/glob/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
+
+ "jest-runtime/glob/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
+
+ "qrcode/yargs/cliui/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "qrcode/yargs/find-up/locate-path/p-locate": ["[email protected]", "", { "dependencies": { "p-limit": "^2.2.0" } }, "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A=="],
+
+ "qrcode/yargs/string-width/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "@mercurjs/core/pkg-dir/find-up/locate-path/p-locate/p-limit": ["[email protected]", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-message-util/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-message-util/@jest/types/@jest/schemas": ["@jest/[email protected]", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-util/@jest/types/@jest/schemas": ["@jest/[email protected]", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/reporters/istanbul-lib-source-maps/source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.12.3", "@babel/parser": "^7.14.7", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-coverage": "^3.2.0", "semver": "^6.3.0" } }, "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/transform/write-file-atomic/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-changed-files/execa/get-stream": ["[email protected]", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-changed-files/execa/human-signals": ["[email protected]", "", {}, "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-changed-files/execa/is-stream": ["[email protected]", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-changed-files/execa/npm-run-path": ["[email protected]", "", { "dependencies": { "path-key": "^3.0.0" } }, "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-changed-files/execa/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-changed-files/execa/strip-final-newline": ["[email protected]", "", {}, "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-plugin-istanbul": ["[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-instrument": "^5.0.4", "test-exclude": "^6.0.0" } }, "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-preset-jest": ["[email protected]", "", { "dependencies": { "babel-plugin-jest-hoist": "^29.6.3", "babel-preset-current-node-syntax": "^1.0.0" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-circus/@jest/environment": ["@jest/[email protected]", "", { "dependencies": { "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0" } }, "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-circus/@jest/expect": ["@jest/[email protected]", "", { "dependencies": { "expect": "^29.7.0", "jest-snapshot": "^29.7.0" } }, "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-circus/jest-each": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "chalk": "^4.0.0", "jest-get-type": "^29.6.3", "jest-util": "^29.7.0", "pretty-format": "^29.7.0" } }, "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-circus/jest-matcher-utils": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-circus/pure-rand": ["[email protected]", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-environment-node/@jest/environment": ["@jest/[email protected]", "", { "dependencies": { "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0" } }, "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-environment-node/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-environment-node/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-message-util/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner/@jest/environment/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner/@jest/environment/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner/jest-environment-node/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner/jest-environment-node/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner/source-map-support/source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime/@jest/globals/@jest/expect": ["@jest/[email protected]", "", { "dependencies": { "expect": "^29.7.0", "jest-snapshot": "^29.7.0" } }, "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime/@jest/source-map/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-snapshot/@babel/generator/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-snapshot/@babel/generator/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-snapshot/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-snapshot/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/pretty-format/@jest/schemas/@sinclair/typebox": ["@sinclair/[email protected]", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/@jest/test-result/@jest/console/jest-message-util": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.12.13", "@jest/types": "^29.6.3", "@types/stack-utils": "^2.0.0", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "micromatch": "^4.0.4", "pretty-format": "^29.7.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" } }, "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/@jest/test-sequencer/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "micromatch": "^4.0.4", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/@jest/transform": ["@jest/[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@jest/types": "^29.6.3", "@jridgewell/trace-mapping": "^0.3.18", "babel-plugin-istanbul": "^6.1.1", "chalk": "^4.0.0", "convert-source-map": "^2.0.0", "fast-json-stable-stringify": "^2.1.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "micromatch": "^4.0.4", "pirates": "^4.0.4", "slash": "^3.0.0", "write-file-atomic": "^4.0.2" } }, "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-plugin-istanbul": ["[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-instrument": "^5.0.4", "test-exclude": "^6.0.0" } }, "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-preset-jest": ["[email protected]", "", { "dependencies": { "babel-plugin-jest-hoist": "^29.6.3", "babel-preset-current-node-syntax": "^1.0.0" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/@jest/environment": ["@jest/[email protected]", "", { "dependencies": { "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0" } }, "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/@jest/expect": ["@jest/[email protected]", "", { "dependencies": { "expect": "^29.7.0", "jest-snapshot": "^29.7.0" } }, "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-each": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "chalk": "^4.0.0", "jest-get-type": "^29.6.3", "jest-util": "^29.7.0", "pretty-format": "^29.7.0" } }, "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-matcher-utils": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-message-util": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.12.13", "@jest/types": "^29.6.3", "@types/stack-utils": "^2.0.0", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "micromatch": "^4.0.4", "pretty-format": "^29.7.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" } }, "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime": ["[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/fake-timers": "^29.7.0", "@jest/globals": "^29.7.0", "@jest/source-map": "^29.6.3", "@jest/test-result": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "cjs-module-lexer": "^1.0.0", "collect-v8-coverage": "^1.0.0", "glob": "^7.1.3", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-resolve": "^29.7.0", "jest-snapshot": "^29.7.0", "jest-util": "^29.7.0", "slash": "^3.0.0", "strip-bom": "^4.0.0" } }, "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@babel/generator": "^7.7.2", "@babel/plugin-syntax-jsx": "^7.7.2", "@babel/plugin-syntax-typescript": "^7.7.2", "@babel/types": "^7.3.3", "@jest/expect-utils": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "babel-preset-current-node-syntax": "^1.0.0", "chalk": "^4.0.0", "expect": "^29.7.0", "graceful-fs": "^4.2.9", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0", "natural-compare": "^1.4.0", "pretty-format": "^29.7.0", "semver": "^7.5.3" } }, "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/pure-rand": ["[email protected]", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-environment-node/@jest/environment": ["@jest/[email protected]", "", { "dependencies": { "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0" } }, "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-environment-node/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-environment-node/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-resolve/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "micromatch": "^4.0.4", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/console": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0", "slash": "^3.0.0" } }, "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/environment": ["@jest/[email protected]", "", { "dependencies": { "@jest/fake-timers": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "jest-mock": "^29.7.0" } }, "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/transform": ["@jest/[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@jest/types": "^29.6.3", "@jridgewell/trace-mapping": "^0.3.18", "babel-plugin-istanbul": "^6.1.1", "chalk": "^4.0.0", "convert-source-map": "^2.0.0", "fast-json-stable-stringify": "^2.1.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "micromatch": "^4.0.4", "pirates": "^4.0.4", "slash": "^3.0.0", "write-file-atomic": "^4.0.2" } }, "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-docblock": ["[email protected]", "", { "dependencies": { "detect-newline": "^3.0.0" } }, "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "micromatch": "^4.0.4", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-leak-detector": ["[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-message-util": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.12.13", "@jest/types": "^29.6.3", "@types/stack-utils": "^2.0.0", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "micromatch": "^4.0.4", "pretty-format": "^29.7.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" } }, "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime": ["[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/fake-timers": "^29.7.0", "@jest/globals": "^29.7.0", "@jest/source-map": "^29.6.3", "@jest/test-result": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "cjs-module-lexer": "^1.0.0", "collect-v8-coverage": "^1.0.0", "glob": "^7.1.3", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-resolve": "^29.7.0", "jest-snapshot": "^29.7.0", "jest-util": "^29.7.0", "slash": "^3.0.0", "strip-bom": "^4.0.0" } }, "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-watcher": ["[email protected]", "", { "dependencies": { "@jest/test-result": "^29.7.0", "@jest/types": "^29.6.3", "@types/node": "*", "ansi-escapes": "^4.2.1", "chalk": "^4.0.0", "emittery": "^0.13.1", "jest-util": "^29.7.0", "string-length": "^4.0.1" } }, "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/source-map-support": ["[email protected]", "", { "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" } }, "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/pretty-format/@jest/schemas": ["@jest/[email protected]", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/pretty-format/ansi-styles": ["[email protected]", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/pretty-format/react-is": ["[email protected]", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-validate/pretty-format/@jest/schemas": ["@jest/[email protected]", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-validate/pretty-format/ansi-styles": ["[email protected]", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-validate/pretty-format/react-is": ["[email protected]", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/yargs/cliui/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/yargs/cliui/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/yargs/string-width/emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/yargs/string-width/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
+
+ "@storybook/react-docgen-typescript-plugin/find-cache-dir/pkg-dir/find-up/locate-path/p-locate": ["[email protected]", "", { "dependencies": { "p-limit": "^2.2.0" } }, "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A=="],
+
+ "create-jest/jest-config/@jest/test-sequencer/@jest/test-result/@jest/console/jest-message-util": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.12.13", "@jest/types": "^29.6.3", "@types/stack-utils": "^2.0.0", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "micromatch": "^4.0.4", "pretty-format": "^29.7.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" } }, "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w=="],
+
+ "create-jest/jest-config/babel-jest/@jest/transform/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "create-jest/jest-config/babel-jest/@jest/transform/write-file-atomic/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+
+ "create-jest/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "create-jest/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "create-jest/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/template": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="],
+
+ "create-jest/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "create-jest/jest-config/jest-circus/@jest/environment/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "create-jest/jest-config/jest-circus/@jest/expect/expect/@jest/expect-utils": ["@jest/[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3" } }, "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA=="],
+
+ "create-jest/jest-config/jest-circus/jest-message-util/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/source-map/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/transform/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul": ["[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-instrument": "^5.0.4", "test-exclude": "^6.0.0" } }, "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/transform/write-file-atomic": ["[email protected]", "", { "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^3.0.7" } }, "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@babel/generator/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@babel/generator/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@jest/transform/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@jest/transform/babel-plugin-istanbul": ["[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-instrument": "^5.0.4", "test-exclude": "^6.0.0" } }, "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@jest/transform/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "micromatch": "^4.0.4", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@jest/transform/write-file-atomic": ["[email protected]", "", { "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^3.0.7" } }, "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg=="],
+
+ "create-jest/jest-config/jest-environment-node/@jest/fake-timers/jest-message-util/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "create-jest/jest-config/jest-runner/@jest/environment/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "create-jest/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.12.3", "@babel/parser": "^7.14.7", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-coverage": "^3.2.0", "semver": "^6.3.0" } }, "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg=="],
+
+ "create-jest/jest-config/jest-runner/@jest/transform/write-file-atomic/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+
+ "create-jest/jest-config/jest-runner/jest-message-util/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/@jest/globals/@jest/expect": ["@jest/[email protected]", "", { "dependencies": { "expect": "^29.7.0", "jest-snapshot": "^29.7.0" } }, "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/@jest/source-map/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/jest-snapshot/@babel/generator": ["@babel/[email protected]", "", { "dependencies": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/jest-snapshot/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/jest-snapshot/@jest/expect-utils": ["@jest/[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3" } }, "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/jest-snapshot/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/jest-snapshot/jest-diff": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^29.6.3", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/jest-snapshot/jest-matcher-utils": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g=="],
+
+ "create-jest/jest-config/jest-runner/jest-watcher/ansi-escapes/type-fest": ["[email protected]", "", {}, "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w=="],
+
+ "find-cache-dir/pkg-dir/find-up/locate-path/p-locate/p-limit": ["[email protected]", "", { "dependencies": { "yocto-queue": "^1.0.0" } }, "sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ=="],
+
+ "import-local/pkg-dir/find-up/locate-path/p-locate/p-limit": ["[email protected]", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
+
+ "qrcode/yargs/find-up/locate-path/p-locate/p-limit": ["[email protected]", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-message-util/@jest/types/@jest/schemas/@sinclair/typebox": ["@sinclair/[email protected]", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="],
+
+ "@mercurjs/stripe-connector-plugin/@types/jest/expect/jest-util/@jest/types/@jest/schemas/@sinclair/typebox": ["@sinclair/[email protected]", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-changed-files/execa/npm-run-path/path-key": ["[email protected]", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.12.3", "@babel/parser": "^7.14.7", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-coverage": "^3.2.0", "semver": "^6.3.0" } }, "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist": ["[email protected]", "", { "dependencies": { "@babel/template": "^7.3.3", "@babel/types": "^7.3.3", "@types/babel__core": "^7.1.14", "@types/babel__traverse": "^7.0.6" } }, "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-circus/@jest/environment/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-circus/@jest/environment/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-circus/@jest/expect/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-circus/jest-matcher-utils/jest-diff": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^29.6.3", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-environment-node/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner/@jest/environment/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runner/jest-environment-node/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime/@jest/globals/@jest/expect/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/@jest/test-result/@jest/console/jest-message-util/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/@jest/test-result/@jest/console/jest-message-util/pretty-format": ["[email protected]", "", { "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" } }, "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/@jest/test-sequencer/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/@jest/transform/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/@jest/transform/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "micromatch": "^4.0.4", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/@jest/transform/write-file-atomic": ["[email protected]", "", { "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^3.0.7" } }, "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.12.3", "@babel/parser": "^7.14.7", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-coverage": "^3.2.0", "semver": "^6.3.0" } }, "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist": ["[email protected]", "", { "dependencies": { "@babel/template": "^7.3.3", "@babel/types": "^7.3.3", "@types/babel__core": "^7.1.14", "@types/babel__traverse": "^7.0.6" } }, "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/@jest/environment/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/@jest/environment/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/@jest/expect/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-matcher-utils/jest-diff": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^29.6.3", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-message-util/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/globals": ["@jest/[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/expect": "^29.7.0", "@jest/types": "^29.6.3", "jest-mock": "^29.7.0" } }, "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/source-map": ["@jest/[email protected]", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.18", "callsites": "^3.0.0", "graceful-fs": "^4.2.9" } }, "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/transform": ["@jest/[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@jest/types": "^29.6.3", "@jridgewell/trace-mapping": "^0.3.18", "babel-plugin-istanbul": "^6.1.1", "chalk": "^4.0.0", "convert-source-map": "^2.0.0", "fast-json-stable-stringify": "^2.1.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "micromatch": "^4.0.4", "pirates": "^4.0.4", "slash": "^3.0.0", "write-file-atomic": "^4.0.2" } }, "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "micromatch": "^4.0.4", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/strip-bom": ["[email protected]", "", {}, "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@babel/generator": ["@babel/[email protected]", "", { "dependencies": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/expect-utils": ["@jest/[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3" } }, "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform": ["@jest/[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@jest/types": "^29.6.3", "@jridgewell/trace-mapping": "^0.3.18", "babel-plugin-istanbul": "^6.1.1", "chalk": "^4.0.0", "convert-source-map": "^2.0.0", "fast-json-stable-stringify": "^2.1.0", "graceful-fs": "^4.2.9", "jest-haste-map": "^29.7.0", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "micromatch": "^4.0.4", "pirates": "^4.0.4", "slash": "^3.0.0", "write-file-atomic": "^4.0.2" } }, "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/jest-diff": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^29.6.3", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-environment-node/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-environment-node/@jest/fake-timers/jest-message-util": ["[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.12.13", "@jest/types": "^29.6.3", "@types/stack-utils": "^2.0.0", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "micromatch": "^4.0.4", "pretty-format": "^29.7.0", "slash": "^3.0.0", "stack-utils": "^2.0.3" } }, "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-resolve/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/environment/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/environment/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/transform/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul": ["[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-instrument": "^5.0.4", "test-exclude": "^6.0.0" } }, "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/transform/write-file-atomic": ["[email protected]", "", { "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^3.0.7" } }, "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-message-util/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/fake-timers": ["@jest/[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@sinonjs/fake-timers": "^10.0.2", "@types/node": "*", "jest-message-util": "^29.7.0", "jest-mock": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/globals": ["@jest/[email protected]", "", { "dependencies": { "@jest/environment": "^29.7.0", "@jest/expect": "^29.7.0", "@jest/types": "^29.6.3", "jest-mock": "^29.7.0" } }, "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/source-map": ["@jest/[email protected]", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.18", "callsites": "^3.0.0", "graceful-fs": "^4.2.9" } }, "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/jest-mock": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "jest-util": "^29.7.0" } }, "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/jest-snapshot": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.11.6", "@babel/generator": "^7.7.2", "@babel/plugin-syntax-jsx": "^7.7.2", "@babel/plugin-syntax-typescript": "^7.7.2", "@babel/types": "^7.3.3", "@jest/expect-utils": "^29.7.0", "@jest/transform": "^29.7.0", "@jest/types": "^29.6.3", "babel-preset-current-node-syntax": "^1.0.0", "chalk": "^4.0.0", "expect": "^29.7.0", "graceful-fs": "^4.2.9", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0", "natural-compare": "^1.4.0", "pretty-format": "^29.7.0", "semver": "^7.5.3" } }, "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/strip-bom": ["[email protected]", "", {}, "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-watcher/ansi-escapes": ["[email protected]", "", { "dependencies": { "type-fest": "^0.21.3" } }, "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/source-map-support/source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/pretty-format/@jest/schemas/@sinclair/typebox": ["@sinclair/[email protected]", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-validate/pretty-format/@jest/schemas/@sinclair/typebox": ["@sinclair/[email protected]", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/yargs/cliui/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/yargs/string-width/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
+
+ "@storybook/react-docgen-typescript-plugin/find-cache-dir/pkg-dir/find-up/locate-path/p-locate/p-limit": ["[email protected]", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
+
+ "create-jest/jest-config/@jest/test-sequencer/@jest/test-result/@jest/console/jest-message-util/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "create-jest/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "create-jest/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/template/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "create-jest/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/template/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "create-jest/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "create-jest/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.12.3", "@babel/parser": "^7.14.7", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-coverage": "^3.2.0", "semver": "^6.3.0" } }, "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/transform/write-file-atomic/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.12.3", "@babel/parser": "^7.14.7", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-coverage": "^3.2.0", "semver": "^6.3.0" } }, "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@jest/transform/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@jest/transform/write-file-atomic/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+
+ "create-jest/jest-config/jest-environment-node/@jest/fake-timers/jest-message-util/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "create-jest/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "create-jest/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/@jest/globals/@jest/expect/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/jest-snapshot/@babel/generator/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/jest-snapshot/@babel/generator/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/jest-snapshot/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/jest-snapshot/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "find-cache-dir/pkg-dir/find-up/locate-path/p-locate/p-limit/yocto-queue": ["[email protected]", "", {}, "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/template": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-circus/@jest/environment/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/jest-circus/@jest/expect/expect/@jest/expect-utils": ["@jest/[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3" } }, "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime/@jest/globals/@jest/expect/expect/@jest/expect-utils": ["@jest/[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3" } }, "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime/@jest/globals/@jest/expect/expect/jest-matcher-utils": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/@jest/test-result/@jest/console/jest-message-util/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/@jest/test-result/@jest/console/jest-message-util/pretty-format/@jest/schemas": ["@jest/[email protected]", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/@jest/test-result/@jest/console/jest-message-util/pretty-format/ansi-styles": ["[email protected]", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/@jest/test-result/@jest/console/jest-message-util/pretty-format/react-is": ["[email protected]", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/@jest/transform/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/@jest/transform/write-file-atomic/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/template": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/@jest/environment/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/@jest/expect/expect/@jest/expect-utils": ["@jest/[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3" } }, "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-message-util/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/source-map/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/transform/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul": ["[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-instrument": "^5.0.4", "test-exclude": "^6.0.0" } }, "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/transform/write-file-atomic": ["[email protected]", "", { "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^3.0.7" } }, "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@babel/generator/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@babel/generator/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/babel-plugin-istanbul": ["[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-instrument": "^5.0.4", "test-exclude": "^6.0.0" } }, "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/jest-haste-map": ["[email protected]", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/graceful-fs": "^4.1.3", "@types/node": "*", "anymatch": "^3.0.3", "fb-watchman": "^2.0.0", "graceful-fs": "^4.2.9", "jest-regex-util": "^29.6.3", "jest-util": "^29.7.0", "jest-worker": "^29.7.0", "micromatch": "^4.0.4", "walker": "^1.0.8" }, "optionalDependencies": { "fsevents": "^2.3.2" } }, "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/write-file-atomic": ["[email protected]", "", { "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^3.0.7" } }, "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-environment-node/@jest/fake-timers/jest-message-util/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/environment/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.12.3", "@babel/parser": "^7.14.7", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-coverage": "^3.2.0", "semver": "^6.3.0" } }, "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/transform/write-file-atomic/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-message-util/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/fake-timers/@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^3.0.0" } }, "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/globals/@jest/expect": ["@jest/[email protected]", "", { "dependencies": { "expect": "^29.7.0", "jest-snapshot": "^29.7.0" } }, "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/source-map/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/jest-snapshot/@babel/generator": ["@babel/[email protected]", "", { "dependencies": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/jest-snapshot/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/jest-snapshot/@jest/expect-utils": ["@jest/[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3" } }, "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/jest-snapshot/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/jest-snapshot/jest-diff": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^29.6.3", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/jest-snapshot/jest-matcher-utils": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-watcher/ansi-escapes/type-fest": ["[email protected]", "", {}, "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w=="],
+
+ "create-jest/jest-config/@jest/test-sequencer/@jest/test-result/@jest/console/jest-message-util/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "create-jest/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "create-jest/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "create-jest/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/template/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "create-jest/jest-config/jest-circus/jest-snapshot/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "create-jest/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/@jest/globals/@jest/expect/expect/@jest/expect-utils": ["@jest/[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3" } }, "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/@jest/globals/@jest/expect/expect/jest-matcher-utils": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/template/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/template/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-runtime/@jest/globals/@jest/expect/expect/jest-matcher-utils/jest-diff": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^29.6.3", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/@jest/test-result/@jest/console/jest-message-util/pretty-format/@jest/schemas/@sinclair/typebox": ["@sinclair/[email protected]", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/template/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/template/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.12.3", "@babel/parser": "^7.14.7", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-coverage": "^3.2.0", "semver": "^6.3.0" } }, "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/transform/write-file-atomic/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.12.3", "@babel/parser": "^7.14.7", "@istanbuljs/schema": "^0.1.2", "istanbul-lib-coverage": "^3.2.0", "semver": "^6.3.0" } }, "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/jest-haste-map/jest-worker": ["[email protected]", "", { "dependencies": { "@types/node": "*", "jest-util": "^29.7.0", "merge-stream": "^2.0.0", "supports-color": "^8.0.0" } }, "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/write-file-atomic/signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-environment-node/@jest/fake-timers/jest-message-util/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/globals/@jest/expect/expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", "jest-matcher-utils": "^29.7.0", "jest-message-util": "^29.7.0", "jest-util": "^29.7.0" } }, "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/jest-snapshot/@babel/generator/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/jest-snapshot/@babel/generator/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/jest-snapshot/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/jest-snapshot/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "create-jest/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "create-jest/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "create-jest/jest-config/jest-runner/jest-runtime/@jest/globals/@jest/expect/expect/jest-matcher-utils/jest-diff": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^29.6.3", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/@jest/core/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/template/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/babel-jest/babel-preset-jest/babel-plugin-jest-hoist/@babel/template/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-snapshot/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/globals/@jest/expect/expect/@jest/expect-utils": ["@jest/[email protected]", "", { "dependencies": { "jest-get-type": "^29.6.3" } }, "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/globals/@jest/expect/expect/jest-matcher-utils": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "jest-diff": "^29.7.0", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "create-jest/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-runner/jest-runtime/@jest/globals/@jest/expect/expect/jest-matcher-utils/jest-diff": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^29.6.3", "jest-get-type": "^29.6.3", "pretty-format": "^29.7.0" } }, "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
+
+ "@mercurjs/stripe-connector-plugin/jest/jest-cli/jest-config/jest-circus/jest-runtime/@jest/transform/babel-plugin-istanbul/istanbul-lib-instrument/@babel/parser/@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
}
}
diff --git a/claude-progress.md b/claude-progress.md
index 7505620f9..72c98c5b7 100644
--- a/claude-progress.md
+++ b/claude-progress.md
@@ -64,32 +64,30 @@ the plugin's event list drops `order.shipment_created`, which nothing emits. Tes
## Session — Magento connector hardening sweep (2026-10-22), branches `feat/magento-external-payment-capture` (this repo) + `feat/checkout-orders-indexer-platform` (magento2-connector)
-Audited `mercurjs/magento2-connector` v0.2.0 for checkout, order, indexing and platform gaps and
-closed the ones that were in scope (user cut: no import/taxonomy/operator-export work, nothing without a Mercur
-backend). This repo: the external payment provider now authorizes at checkout and captures through
-`POST /admin/magento/order-groups/:id/payments/capture` (plus `/cancel`); core's `payment.captured` subscriber
-does the split. `external-payment.spec.ts` grew to 12 cases; `magento2-connector` suites 17/17, plugin+core
-build green. Connector: shipping-quote failure blocks checkout, cart rules exclude seller lines, seller shipping
-taxed, real billing address + customer metadata, price-change/auto-remove notices, cart configure keeps the
-offer, guest-merge reset, sync hash cache, status-gated post-commit order send, capture on invoice, offer-id line
-matching, seller refusal status, admin Send/Capture/Resync buttons, offer-sync robustness, real `mercur_offer_product`
-indexer with mview + configurable roll-up, stock/search plugins keeping offered SKUs salable, listing price
-plugin, configurable-page mixins, process runner locking/retry/timeout/admin actions, API client retries +
-logging + test button, per-store config scope, 12 extension events, webhook idempotency. Verified statically
-only (static PHP 8.3: lint, PHPStan L1, 84 unit tests, XSD validation); no Magento install, so runtime
-unverified. Unverifiable locally: MSI and swatch plugin targets (modules absent from vendor).
-
-## Session — Stripe connector spec (2026-10-22), branch `feat/magento2-connector`
-
-Wrote `docs/specs/spec-stripe-connector/` (enterprise-style folder: `brief.md`, `research.md`, `blueprint.md`,
-`assert.md`, `removals.md`, `deltas/example.md`; replaces the earlier single-file SPEC-004). Part A makes the core `payout`
-module provider-agnostic in the shape of Medusa's payment module (N providers via a `pop_<id>` registry,
-`IPayoutProvider` with account/onboarding/transfer/reversal/payout/webhook methods, new `transfer`,
-`settlement`, `adjustment`, `payout_checkpoint` models, seven scheduled jobs on the connector's crontab,
-workflows, admin/vendor routes, generic pages). Part B is `packages/plugins/stripe-connector` with two adapters
-only (Medusa payment provider + Mercur payout provider) plus a vendor "Stripe" page. Part C deletes
-`packages/providers`. Connector checkout lives in the session scratchpad. No code written yet; SPEC-003 stays
-the only `in_progress` spec.
+## Session — Stripe connector (2026-10-22), branch `feat/stripe-connector`, worktree `~/Desktop/mercur-stripe-connector`
+
+Spec: `docs/specs/spec-stripe-connector/` (local, gitignored; `brief.md`, `research.md`, `blueprint.md`, `assert.md`,
+`removals.md`, `deltas/D-001…D-012` all `done`). Scheduled payout pipeline in the shape of
+Medusa's payment module.
+- Core payout module is provider-agnostic: `pop_<identifier>_<id>` registry (`pop_system_default` always),
+ ten-method `IPayoutProvider` + `AbstractPayoutProvider`, new models `transfer`, `settlement`, `adjustment`,
+ `payout_provider`, `payout_checkpoint`, `payout_job_run`, `payout_notification`, extended `payout_account`/`payout`
+ (migration `Migration20261022120000`), `/hooks/payout/[provider]` (+ legacy alias).
+- Seven scheduled jobs (`packages/core/src/jobs`), pipeline functions under
+ `workflows/payout/pipeline`, pure rules under `workflows/payout/utils` (transfer factory, capture decision,
+ settlement builder), workflows for transfer/reversal/payout dispatch, account sync, capture/cancel, operator
+ notifications; admin routes for accounts, transfers, settlements, adjustments, jobs, status, captures,
+ notifications; vendor `payout-accounts/me`, `transfers`, `settlements`; public onboarding refresh.
+- Plugin `packages/plugins/stripe-connector` (`@mercurjs/stripe-connector-plugin`): Stripe payment provider
+ (manual capture, order-group metadata) + Stripe Connect payout provider, admin Finance → Stripe (tab per job),
+ Settings → Stripe, seller/order widgets, vendor Settings → Stripe. `packages/providers` deleted; docs rewritten.
+- Verified: core tsc + build, plugin server/admin/vendor tsc + `dashboard:build`, `bun test` unit specs 35/35
+ (core utils + plugin provider), lint clean on touched files, `payouts/vendor/*` 8/10 → racing subscriber removed
+ (re-run pending), new `payouts/admin/payout-pipeline.spec.ts` (fixes in progress). Gotchas: integration tests need
+ `packages/plugins/magento2-connector` built (test config loads its provider); `bun run test:unit` can't resolve
+ `@swc/jest` locally, use `bun test <dirs>`; declaration emit needs an explicit `ReturnWorkflow<>` annotation on
+ workflows that return `when()` results (TS2742).
+- Open: Stripe test-mode run by hand (assert.md § I); PR to `main`.
## Session — Medusa 2.22.0 upgrade (2026-10-22), branch `chore/medusa-2-22`
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 544f1ed9a..74cdbd588 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -61,7 +61,7 @@ The Medusa plugin that holds all marketplace business logic. Wired into the API
- **Modules** (`src/modules/`): `seller` (registration, profiles, members, order groups), `commission` (rates, rules, calculation), `offer` (seller listings against master products), `payout` (accounts, onboarding, payouts), `product-attribute` (typed attribute catalog), `product-edit` (product change-request pipeline), `order-group`, `media`, `custom-fields`, `inventory-item`, `stock-location`, `shipping-profile`, `shipping-option`, `price-list`, `promotion`, `campaign`.
- **Workflows** (`src/workflows/`): 22+ workflow groups for seller lifecycle (create / approve / suspend), member invites, commissions, payouts, multi-vendor cart and order split, offers, product change-requests, fulfilment. Workflows support compensation (automatic rollback on failure) and expose hooks as extension points; steps return `StepResponse` and compose into a `WorkflowResponse`.
- **Modules never reference each other directly** — cross-module communication happens only through **links** and **workflows**. Links are relationships defined separately (e.g. `product-seller-link`, `offer-product-link`, `offer-variant-link`, `order-group-order-link`); dozens of them wire the marketplace layer into the commerce layer.
-- **Scheduled jobs + subscribers**: jobs run on intervals (e.g. payout capture-check every 15 min, daily payouts at 1 AM UTC) and emit events; subscribers listen and fire async side effects (notifications, webhook calls, payout transfers).
+- **Subscribers** (`src/subscribers/`): react to Medusa and Mercur events (order split, payment capture split, payout webhooks). Core ships no scheduled jobs; integrations such as the Stripe connector plugin bring their own.
- **API routes** (`src/api/`): `admin/*` (marketplace operator), `vendor/*` (seller-scoped), plus hooks, middlewares, query configs, and validators.
- **Auth/RBAC**: `withMercur()` auto-registers a roles module so vendor scoping works out of the box.
@@ -99,8 +99,8 @@ React primitives shared by Admin and Vendor: `TabbedForm`, `DataTable`, `Form`,
### `packages/registry` — blocks registry
Private workspace holding the canonical block catalogue (team management, reviews, notifications, search integrations, chat, etc.). Backs `mercurjs search` / `mercurjs view` / `mercurjs add`.
-### `packages/providers/payout-stripe-connect`
-Stripe Connect implementation for the `payout` module: creates connected accounts per seller and transfers payout balances.
+### `packages/plugins/stripe-connector`
+`@mercurjs/stripe-connector-plugin`: a Medusa payment provider (`pp_stripe-connector_*`, manual capture on the platform account) and a Mercur payout provider (`pop_stripe-connect_*`: Express accounts, onboarding and login links, payouts as Connect transfers, reversals, Connect webhooks). On top of core's payout module it owns the payout operations: the scheduled jobs (onboarding sync, capture validation, payouts, reversals, settlements, failed-operation alerts, KYC monitoring), its own `stripe-connector` module (job runs, checkpoints, notification log, settlements with their bank payout, operator adjustments), the `/admin/stripe/*` and `/vendor/stripe/*` routes, the admin Integrations → Stripe area (Settlements, with Adjustments, Captures and Jobs nested under it), Settings → Stripe (webhooks, notifications, account mapping), widgets on the seller, order and payout-account pages, and the vendor Settings → Stripe page.
## Apps (starters wired to the packages)
@@ -124,7 +124,7 @@ Stripe Connect implementation for the `payout` module: creates connected account
- **Product Change** — an immutable record in the product change-request pipeline (`product-edit` module). Captures every product edit as typed actions (`UPDATE`, `VARIANT_*`, `ATTRIBUTE_*`, `STATUS_CHANGE`, `PRODUCT_ADD/DELETE`); status `pending` → `confirmed` / `declined` / `canceled` / `requires_action`. Low-risk edits auto-confirm.
- **Order-Group** — wrapper that lets a single customer cart contain items from multiple sellers. On placement, the cart is split into per-seller orders linked to a parent group. Has a serial `display_id`, read-only `cart_id`, and query-time computed `seller_count` / `total`.
- **Commission** — fee structure applied during order placement, deducted from payouts. Rules match across `product` / `product_type` / `product_collection` / `product_category` / `seller`; most-specific wins (AND across dimensions, OR within), ties to oldest. Fixed rates support per-currency amounts; only the global rate may include shipping. Arithmetic uses BigNumber.
-- **Payout** — settlement to a seller's connected account (default provider: Stripe Connect). Account lifecycle `PENDING` → `ACTIVE` ↔ `RESTRICTED` / → `REJECTED`, driven by provider webhooks; each account has an onboarding record with provider `data`. Payout transfer is automated via a daily job (1 AM UTC) emitting `payout.requested` + a subscriber running `createPayoutWorkflow`.
+- **Payout** — one provider per marketplace (the system provider when none is configured), shaped like Medusa's payment module. A `payout_account` mirrors the provider account (`external_id`, flags, `kyc_status`, a rotating onboarding token with a TTL) and owns an `onboarding` link record; a `payout` is the seller's share of one order (total − commission, net of earlier refunds) with one status machine (`pending`, `on_hold`, `processing`, `paid`, `failed`, `aborted`) and a stable `status_reason` code; a `payout_reversal` takes a later refund's share back, like `Refund` on `Payment`. Steps and subscribers resolve the module as `IPayoutModuleService` from `@mercurjs/types`. Scheduling, settlements and operator adjustments belong to the integration (the Stripe connector plugin), not core.
- **Product Attributes** — an operator-managed, typed attribute catalog (`multi_select`, `single_select`, `text`, `unit`, `toggle`). A `multi_select` axis attribute (`is_variant_axis`) maps to a native Medusa `ProductOption` and generates variants; `is_filterable` exposes it as a storefront filter.
- **Blocks** — feature packages distributed as **source code** (not npm packages): the CLI copies files into the project so you own them. Discovered via `blocks.json`, added with `mercurjs add`, updated via `mercurjs diff` + `--overwrite`.
@@ -161,8 +161,11 @@ Storefront cart contains offers from sellers A and B
-> split items by seller -> create Order per seller
-> calculate commission lines per seller (rule matching + specificity)
-> split payment proportionally across seller orders
- -> credit each seller order to its payout account (after commission)
- -> later: daily job emits payout.requested -> subscriber transfers via provider
+ -> createOrderPayoutsWorkflow pays each fulfilled, captured order's seller
+ total − commission (core; called by the integration's schedule)
+ -> createPayoutReversalsWorkflow takes refunded shares back
+ -> Stripe connector plugin jobs: validate captures, run the two workflows
+ above, net settlements and pay them out to the seller's bank
```
## Extension Points
diff --git a/docs/PRODUCT.md b/docs/PRODUCT.md
index 051a88e9a..458d175cf 100644
--- a/docs/PRODUCT.md
+++ b/docs/PRODUCT.md
@@ -29,10 +29,11 @@ The product has three audiences:
- Commission visibility for both marketplace operators and individual vendors.
### Vendor Payouts
-- Pluggable payout provider interface; **Stripe Connect** ships out of the box.
-- Payout account creation and onboarding flows (`create-payout-account`, `create-onboarding`). Each account carries an onboarding record holding provider-specific data (e.g. Stripe Connect links).
+- Single payout provider per marketplace, modelled on Medusa's payment providers: configure exactly one provider on the payout module (the built-in system provider is used when none is configured). Webhooks arrive at `/hooks/payout`. **Stripe Connect** ships in `@mercurjs/stripe-connector-plugin`; any other provider implements `IPayoutProvider` (`createAccount`, `retrieveAccount`, `createOnboarding`, `createPayout`, `reversePayout`, `getWebhookActionAndData`).
+- Payout account creation and onboarding flows (`create-payout-account`, `create-onboarding`, `create-or-refresh-seller-payout-account`). Each account carries an onboarding record holding provider-specific data (e.g. Stripe Connect links).
- Payout account lifecycle: `PENDING` → `ACTIVE`, then `ACTIVE` ↔ `RESTRICTED` (provider flagged, e.g. missing KYC) or `ACTIVE` → `REJECTED`, driven by provider webhooks.
-- **Automated payout pipeline**: a capture-check job (every 15 min) finds orders ready for capture; a subscriber captures authorized payments; a daily job (1 AM UTC) emits `payout.requested` for eligible orders; a subscriber runs `createPayoutWorkflow` to transfer funds. Tunable in `medusa-config.ts` via `authorizationWindowMs` (7d), `sellerActionWindowMs` (72h), `captureSafetyBufferMs` (24h), `requiredFulfillmentStatus` (`"fulfilled"`).
+- One `payout` per seller order (order total minus commission, net of refunds that landed before it) and one `payout_reversal` per later refund (net of its commission share), mirroring Medusa's `Payment` → `Refund`. Status: `pending`, `on_hold`, `processing`, `paid`, `failed`, `aborted`. `create-order-payouts` puts an order that is not ready (no active account, not fulfilled, payment not captured) on hold and re-decides it on the next call; `create-payout-reversals` takes the refunded share back; `retry-payout` retries a failed or held payout.
+- Core ships no payout schedule. When payouts run is the integration's call: the Stripe connector plugin brings the scheduled jobs (onboarding sync, capture validation, payouts, reversals, settlements, failed-operation alerts, KYC monitoring), settlements, operator adjustments and their admin screens.
- Webhook processing for provider events (`process-payout-for-webhook`).
- Vendor-side onboarding status and payout history in the Vendor Portal.
@@ -175,7 +176,7 @@ The product has three audiences:
- **Framework lock**: peer-pinned to `@medusajs/framework` `>=2.22.0` across core and providers (the workspace resolves 2.22.0).
- **Languages**: TypeScript end-to-end; React 18 for the dashboards.
- **License**: MIT, open-core. No transaction fees, no commercial lock-in, no hosted vendor required.
-- **Payout providers**: only Stripe Connect ships out of the box; others must be implemented against the provider interface.
+- **Payout providers**: only Stripe Connect ships out of the box (in the Stripe connector plugin); others implement `IPayoutProvider` from `@mercurjs/types`.
## Distribution Surface
@@ -186,5 +187,5 @@ The product has three audiences:
- `@mercurjs/dashboard-shared` — shared dashboard primitives.
- `@mercurjs/admin` — admin panel UI package.
- `@mercurjs/vendor` — vendor portal UI package.
-- `@mercurjs/payout-stripe-connect` — Stripe Connect payout provider.
+- `@mercurjs/stripe-connector-plugin` — Stripe payment provider, Stripe Connect payout provider and the Stripe admin/vendor screens.
- Templates (`basic`, `plugin`) — starter scaffolds.
diff --git a/integration-tests/http/auth/vendor/panel-auth.spec.ts b/integration-tests/http/auth/vendor/panel-auth.spec.ts
index 5a5e6af79..11e917f53 100644
--- a/integration-tests/http/auth/vendor/panel-auth.spec.ts
+++ b/integration-tests/http/auth/vendor/panel-auth.spec.ts
@@ -78,7 +78,22 @@ medusaIntegrationTestRunner({
.post(`/vendor/sellers/select`, { seller_id: otherSellerId }, member)
.catch((e) => e.response)
- expect(response.status).toEqual(400)
+ expect(response.status).toEqual(403)
+ expect(response.data.message).toEqual(
+ "You are not a member of this seller account"
+ )
+ })
+
+ it("forbids a vendor route for a seller the member does not belong to", async () => {
+ const member = await login("member", "[email protected]")
+
+ const response = await api
+ .get(`/vendor/members/me`, {
+ headers: { ...member.headers, "x-seller-id": otherSellerId },
+ })
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(403)
expect(response.data.message).toEqual(
"You are not a member of this seller account"
)
diff --git a/integration-tests/http/commission-rates/admin/commission-calculation.spec.ts b/integration-tests/http/commission-rates/admin/commission-calculation.spec.ts
index 6410eb3d3..cf5263c4b 100644
--- a/integration-tests/http/commission-rates/admin/commission-calculation.spec.ts
+++ b/integration-tests/http/commission-rates/admin/commission-calculation.spec.ts
@@ -313,7 +313,7 @@ medusaIntegrationTestRunner({
input: { order_ids: [order.id] },
})
- // Same query createPayoutWorkflow uses to total commission for the
+ // Same query createOrderPayoutsWorkflow uses to total commission for the
// payout: read the order's item + shipping commission lines.
const { data: lines } = await query.graph({
entity: "commission_line",
diff --git a/integration-tests/http/magento2-connector/external-payment.spec.ts b/integration-tests/http/magento2-connector/external-payment.spec.ts
index f5ca04778..b05e725b7 100644
--- a/integration-tests/http/magento2-connector/external-payment.spec.ts
+++ b/integration-tests/http/magento2-connector/external-payment.spec.ts
@@ -83,7 +83,7 @@ medusaIntegrationTestRunner({
})
})
- const checkout = (reference = "MIR$000001", captured = false) =>
+ const checkout = (reference = "MIR$000001") =>
completeExternalCheckout({
container: appContainer,
api,
@@ -93,29 +93,8 @@ medusaIntegrationTestRunner({
offerIds: [seedA.offer.id, seedB.offer.id],
email: customerEmail,
reference,
- captured,
})
- const getOrder = async (orderId: string, fields = "id,payment_status") =>
- (await api.get(`/admin/orders/${orderId}?fields=${fields}`, adminHeaders)).data.order
-
- // The order reports the cart payment as captured before the split hands it
- // a payment collection of its own, which refunds need.
- const waitForSplitCapture = (orderId: string) =>
- waitFor(async () => {
- const order = await getOrder(orderId, "id,payment_status,*payment_collections")
- return (
- order.payment_status === "captured" &&
- !!order.payment_collections?.[0]?.metadata?.cart_payment_collection_id
- )
- })
-
- const captureGroup = (orderGroupId: string, body: Record<string, unknown> = {}) =>
- api.post(`/admin/magento/order-groups/${orderGroupId}/payments/capture`, body, adminHeaders)
-
- const cancelGroup = (orderGroupId: string, body: Record<string, unknown> = {}) =>
- api.post(`/admin/magento/order-groups/${orderGroupId}/payments/cancel`, body, adminHeaders)
-
it("completes a two-seller cart on the external provider and carries the channel onto the order group", async () => {
const { completed, orderGroup } = await checkout()
@@ -133,158 +112,33 @@ medusaIntegrationTestRunner({
expect(data.order_group.metadata).toEqual({ channel: "magento" })
})
- it("leaves each child order authorized until the storefront reports the capture", async () => {
+ it("records the external capture so each child order is paid and commission lines exist", async () => {
const { orderGroup } = await checkout("MIR$000002")
for (const order of orderGroup.orders) {
- const data = await getOrder(
- order.id,
- "id,payment_status,*payment_collections,*payment_collections.payments"
- )
- expect(data.payment_status).toEqual("authorized")
+ await waitFor(async () => {
+ const { data } = await api.get(
+ `/admin/orders/${order.id}?fields=id,payment_status,*payment_collections,*payment_collections.payments`,
+ adminHeaders
+ )
+ return data.order.payment_status === "captured"
+ })
- const payments = data.payment_collections.flatMap((pc: any) => pc.payments)
- expect(payments).toHaveLength(1)
+ const { data } = await api.get(
+ `/admin/orders/${order.id}?fields=id,payment_status,total,*payment_collections,*payment_collections.payments`,
+ adminHeaders
+ )
+ const payments = data.order.payment_collections.flatMap((pc: any) => pc.payments)
+ expect(payments.length).toBeGreaterThan(0)
expect(payments[0].provider_id).toEqual("pp_external_external")
- expect(payments[0].captured_at).toBeNull()
+ expect(payments[0].captured_at).toBeTruthy()
expect(payments[0].data).toEqual(
expect.objectContaining({ reference: "MIR$000002", channel: "magento" })
)
- expect(payments[0].data.authorized_at).toBeTruthy()
- }
- })
-
- it("captures the group payment so each child order is paid and commission lines exist", async () => {
- const receiver: WebhookReceiver = await startWebhookReceiver()
- try {
- await api.post(
- `/admin/magento/webhooks`,
- { url: receiver.url, events: ["order.payment_captured"] },
- adminHeaders
- )
-
- const { orderGroup } = await checkout("MIR$000012")
-
- const captured = await captureGroup(orderGroup.id, { reference: "INV-1" })
- expect(captured.status).toEqual(200)
- expect(captured.data.payment.provider_id).toEqual("pp_external_external")
- expect(captured.data.payment.captured_at).toBeTruthy()
-
- for (const order of orderGroup.orders) {
- await waitForSplitCapture(order.id)
-
- const data = await getOrder(
- order.id,
- "id,payment_status,total,*payment_collections,*payment_collections.payments"
- )
- const payments = data.payment_collections.flatMap((pc: any) => pc.payments)
- expect(payments.length).toBeGreaterThan(0)
- expect(payments[0].provider_id).toEqual("pp_external_external")
- expect(payments[0].captured_at).toBeTruthy()
- expect(payments[0].data).toEqual(
- expect.objectContaining({ reference: "MIR$000012", channel: "magento" })
- )
- const lines = await api.get(`/admin/orders/${order.id}/commission-lines`, adminHeaders)
- expect(lines.status).toEqual(200)
- expect(Array.isArray(lines.data.commission_lines)).toBe(true)
- }
-
- await waitFor(() => receiver.received.length > 0)
- const body = JSON.parse(receiver.received[0].body)
- expect(body.event).toEqual("order.payment_captured")
- expect(body.data).toEqual(
- expect.objectContaining({
- id: orderGroup.id,
- payment_id: captured.data.payment.id,
- reference: "INV-1",
- })
- )
- } finally {
- await receiver.close()
- }
- })
-
- it("captures the group payment only once", async () => {
- const { orderGroup } = await checkout("MIR$000013")
-
- const first = await captureGroup(orderGroup.id)
- expect(first.status).toEqual(200)
-
- const second = await captureGroup(orderGroup.id)
- expect(second.status).toEqual(200)
- expect(second.data.payment.id).toEqual(first.data.payment.id)
- expect(second.data.payment.captured_at).toEqual(first.data.payment.captured_at)
-
- for (const order of orderGroup.orders) {
- await waitForSplitCapture(order.id)
- }
- await new Promise((resolve) => setTimeout(resolve, 1000))
-
- for (const order of orderGroup.orders) {
- const data = await getOrder(
- order.id,
- "id,payment_status,*payment_collections,*payment_collections.payments,*payment_collections.payments.captures"
- )
- expect(data.payment_status).toEqual("captured")
- const payments = data.payment_collections.flatMap((pc: any) => pc.payments)
- expect(payments).toHaveLength(1)
- expect(payments[0].captures).toHaveLength(1)
- }
- })
-
- it("refuses an external refund before the group payment is captured", async () => {
- const { orderGroup } = await checkout("MIR$000014")
-
- const res = await api
- .post(
- `/admin/magento/orders/${orderGroup.orders[0].id}/refunds/external`,
- { amount: 100 },
- adminHeaders
- )
- .catch((e: any) => e.response)
- expect(res.status).toEqual(400)
- expect(res.data.message).toMatch(/not yet captured/)
- })
-
- it("cancels the child orders and voids the authorization when the storefront cancels before capture", async () => {
- const { orderGroup } = await checkout("MIR$000015")
-
- const res = await cancelGroup(orderGroup.id, { reference: "CANCEL-1" })
- expect(res.status).toEqual(200)
- expect(res.data.payment.captured_at).toBeNull()
- expect(res.data.payment.canceled_at).toBeTruthy()
-
- for (const order of orderGroup.orders) {
- const data = await getOrder(order.id, "id,status,payment_status")
- expect(data.status).toEqual("canceled")
- expect(data.payment_status).toEqual("canceled")
- }
-
- const capture = await captureGroup(orderGroup.id).catch((e: any) => e.response)
- expect(capture.status).toEqual(400)
- })
-
- it("refuses to cancel a captured group payment", async () => {
- const { orderGroup } = await checkout("MIR$000016")
- await captureGroup(orderGroup.id)
-
- const res = await cancelGroup(orderGroup.id).catch((e: any) => e.response)
- expect(res.status).toEqual(400)
- expect(res.data.message).toMatch(/already captured/)
- })
-
- it("still accepts a session that reports captured_at up front", async () => {
- const { orderGroup } = await checkout("MIR$000017", true)
-
- for (const order of orderGroup.orders) {
- await waitForSplitCapture(order.id)
- const data = await getOrder(
- order.id,
- "id,payment_status,*payment_collections,*payment_collections.payments"
- )
- const payments = data.payment_collections.flatMap((pc: any) => pc.payments)
- expect(payments[0].captured_at).toBeTruthy()
+ const lines = await api.get(`/admin/orders/${order.id}/commission-lines`, adminHeaders)
+ expect(lines.status).toEqual(200)
+ expect(Array.isArray(lines.data.commission_lines)).toBe(true)
}
})
@@ -300,8 +154,13 @@ medusaIntegrationTestRunner({
const { orderGroup } = await checkout("MIR$000003")
const order = orderGroup.orders[0]
- await captureGroup(orderGroup.id)
- await waitForSplitCapture(order.id)
+ await waitFor(async () => {
+ const { data } = await api.get(
+ `/admin/orders/${order.id}?fields=id,payment_status`,
+ adminHeaders
+ )
+ return data.order.payment_status === "captured"
+ })
const refund = await api.post(
`/admin/magento/orders/${order.id}/refunds/external`,
@@ -335,8 +194,13 @@ medusaIntegrationTestRunner({
const { orderGroup } = await checkout("MIR$000004")
const order = orderGroup.orders[0]
- await captureGroup(orderGroup.id)
- await waitForSplitCapture(order.id)
+ await waitFor(async () => {
+ const { data } = await api.get(
+ `/admin/orders/${order.id}?fields=id,payment_status`,
+ adminHeaders
+ )
+ return data.order.payment_status === "captured"
+ })
await api.post(
`/admin/magento/orders/${order.id}/refunds/external`,
diff --git a/integration-tests/http/magento2-connector/helpers.ts b/integration-tests/http/magento2-connector/helpers.ts
index d4eb01b4c..e2b2d8a94 100644
--- a/integration-tests/http/magento2-connector/helpers.ts
+++ b/integration-tests/http/magento2-connector/helpers.ts
@@ -76,7 +76,6 @@ export const completeExternalCheckout = async (opts: {
email: string
reference: string
channel?: string
- captured?: boolean
}) => {
const { api, storeHeaders } = opts
@@ -128,8 +127,8 @@ export const completeExternalCheckout = async (opts: {
provider_id: "pp_external_external",
data: {
reference: opts.reference,
+ captured_at: new Date().toISOString(),
channel: opts.channel ?? "magento",
- ...(opts.captured ? { captured_at: new Date().toISOString() } : {}),
},
},
storeHeaders
diff --git a/integration-tests/http/payment/payment-webhook-cart-completion.spec.ts b/integration-tests/http/payment/payment-webhook-cart-completion.spec.ts
index 5a1683a2a..b042965f4 100644
--- a/integration-tests/http/payment/payment-webhook-cart-completion.spec.ts
+++ b/integration-tests/http/payment/payment-webhook-cart-completion.spec.ts
@@ -391,6 +391,47 @@ medusaIntegrationTestRunner({
})
expect(orderCarts).toHaveLength(1)
})
+
+ it("does not record a capture the payment already has when the provider confirms it", async () => {
+ const { cart, sessionId } = await seedReadyCart(
+ sellerSeed.offer.id
+ )
+ const query = appContainer.resolve(
+ ContainerRegistrationKeys.QUERY
+ )
+ const paymentModule = appContainer.resolve(Modules.PAYMENT)
+ const { processPaymentWorkflow } = await import(
+ "@mercurjs/core/workflows/payment/workflows/process-payment"
+ )
+
+ await api.post(`/store/carts/${cart.id}/complete`, {}, storeHeaders)
+
+ const {
+ data: [payment],
+ } = await query.graph({
+ entity: "payment",
+ fields: ["id", "amount"],
+ filters: { payment_session_id: sessionId },
+ })
+ const partial = Number(payment.amount) / 2
+ await paymentModule.capturePayment({ payment_id: payment.id, amount: partial })
+
+ await processPaymentWorkflow(appContainer).run({
+ input: {
+ action: "captured",
+ data: { session_id: sessionId, amount: partial },
+ },
+ })
+
+ const {
+ data: [after],
+ } = await query.graph({
+ entity: "payment",
+ fields: ["captures.amount"],
+ filters: { id: payment.id },
+ })
+ expect((after as { captures?: unknown[] }).captures).toHaveLength(1)
+ })
})
},
})
diff --git a/integration-tests/http/payouts/admin/payouts.spec.ts b/integration-tests/http/payouts/admin/payouts.spec.ts
new file mode 100644
index 000000000..cc7199502
--- /dev/null
+++ b/integration-tests/http/payouts/admin/payouts.spec.ts
@@ -0,0 +1,328 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import { MedusaContainer } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import {
+ WorkflowResponse,
+ createStep,
+ createWorkflow,
+ transform,
+} from "@medusajs/framework/workflows-sdk"
+import { MercurModules, PayoutStatus, PayoutStatusReason } from "@mercurjs/types"
+import {
+ createOrRefreshSellerPayoutAccountWorkflow,
+ createPayoutsStep,
+ processPayoutForWebhookWorkflow,
+ processPayoutsStep,
+ updatePayoutsStep,
+} from "@mercurjs/core/workflows"
+
+import { adminHeaders, createAdminUser } from "../../../helpers/create-admin-user"
+import { createSellerUser } from "../../../helpers/create-seller-user"
+
+jest.setTimeout(180000)
+
+const failAfterSendStep = createStep("test-fail-after-send", async () => {
+ throw new Error("fails after the payout was sent")
+})
+
+const createSendThenFailWorkflow = createWorkflow(
+ "test-create-send-then-fail",
+ function (input: { account_id: string }) {
+ const created = createPayoutsStep(
+ transform({ input }, ({ input }) => [{ account_id: input.account_id, amount: 100, currency_code: "usd" }])
+ )
+ processPayoutsStep(transform({ created }, ({ created }) => ({ ids: created.map((payout) => payout.id) })))
+ failAfterSendStep()
+
+ return new WorkflowResponse(created)
+ }
+)
+
+const updateSendThenFailWorkflow = createWorkflow(
+ "test-update-send-then-fail",
+ function (input: { id: string }) {
+ const updated = updatePayoutsStep(
+ transform({ input }, ({ input }) => [{ id: input.id, status: PayoutStatus.PENDING }])
+ )
+ processPayoutsStep(transform({ input }, ({ input }) => ({ ids: [input.id] })))
+ failAfterSendStep()
+
+ return new WorkflowResponse(updated)
+ }
+)
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api, dbConnection }) => {
+ describe("Admin - Payouts", () => {
+ let container: MedusaContainer
+ let payoutService: any
+ let seller: any
+ let sellerHeaders: any
+
+ beforeAll(async () => {
+ container = getContainer()
+ payoutService = container.resolve(MercurModules.PAYOUT)
+ })
+
+ beforeEach(async () => {
+ await createAdminUser(dbConnection, adminHeaders, container)
+ const result = await createSellerUser(container, {
+ email: "[email protected]",
+ name: "Admin Payouts Seller",
+ })
+ seller = result.seller
+ sellerHeaders = result.headers
+ })
+
+ const createSellerPayout = async (accountId: string, input: Record<string, unknown> = {}) => {
+ const payout = await payoutService.createPayouts({
+ account_id: accountId,
+ amount: 100,
+ currency_code: "usd",
+ ...input,
+ })
+ await container.resolve(ContainerRegistrationKeys.LINK).create({
+ [MercurModules.PAYOUT]: { payout_id: payout.id },
+ [MercurModules.SELLER]: { seller_id: seller.id },
+ })
+ return payout
+ }
+
+ it("creates one account per seller and exposes it to the vendor", async () => {
+ const first = await createOrRefreshSellerPayoutAccountWorkflow(container).run({ input: { seller_id: seller.id } })
+ const again = await createOrRefreshSellerPayoutAccountWorkflow(container).run({ input: { seller_id: seller.id } })
+ expect(again.result.account_id).toEqual(first.result.account_id)
+
+ const accounts = await api.get(`/admin/payout-accounts?seller_id=${seller.id}`, adminHeaders)
+ expect(accounts.status).toEqual(200)
+ expect(accounts.data.count).toEqual(1)
+ const account = accounts.data.payout_accounts[0]
+ expect(account.provider_id).toBeUndefined()
+ expect(account.status).toEqual("active")
+ expect(account.payouts_enabled).toBe(true)
+ expect(account.seller.id).toEqual(seller.id)
+
+ const me = await api.get("/vendor/payout-accounts/me", sellerHeaders)
+ expect(me.status).toEqual(200)
+ expect(me.data.payout_account.id).toEqual(account.id)
+ })
+
+ it("refuses a second mapping for a seller that already has an account", async () => {
+ await createOrRefreshSellerPayoutAccountWorkflow(container).run({ input: { seller_id: seller.id } })
+
+ const response = await api
+ .post("/admin/payout-accounts", { seller_id: seller.id, external_id: "acct_x" }, adminHeaders)
+ .catch((e: any) => e.response)
+ expect(response.status).toEqual(409)
+ })
+
+ it("syncs an account from the provider", async () => {
+ const {
+ result: { account_id },
+ } = await createOrRefreshSellerPayoutAccountWorkflow(container).run({ input: { seller_id: seller.id } })
+
+ const synced = await api.post(`/admin/payout-accounts/${account_id}/sync`, {}, adminHeaders)
+ expect(synced.data.payout_account.kyc_status).toEqual("approved")
+ expect(synced.data.payout_account.last_synced_at).toBeTruthy()
+ })
+
+ it("filters payouts by seller, order and status", async () => {
+ const {
+ result: { account_id },
+ } = await createOrRefreshSellerPayoutAccountWorkflow(container).run({ input: { seller_id: seller.id } })
+ const paid = await createSellerPayout(account_id, { order_id: "order_a", status: PayoutStatus.PAID })
+ await createSellerPayout(account_id, { order_id: "order_b", status: PayoutStatus.ON_HOLD })
+
+ const bySeller = await api.get(`/admin/payouts?seller_id=${seller.id}`, adminHeaders)
+ expect(bySeller.data.count).toEqual(2)
+
+ const byOrder = await api.get(`/admin/payouts?order_id=order_a`, adminHeaders)
+ expect(byOrder.data.payouts.map((p: any) => p.id)).toEqual([paid.id])
+ expect(byOrder.data.payouts[0].seller.id).toEqual(seller.id)
+
+ const byStatus = await api.get(`/admin/payouts?seller_id=${seller.id}&status=paid`, adminHeaders)
+ expect(byStatus.data.payouts.map((p: any) => p.id)).toEqual([paid.id])
+
+ const byOther = await api.get(`/admin/payouts?seller_id=sel_none`, adminHeaders)
+ expect(byOther.data.payouts).toEqual([])
+ })
+
+ it("retries a failed payout", async () => {
+ const {
+ result: { account_id },
+ } = await createOrRefreshSellerPayoutAccountWorkflow(container).run({ input: { seller_id: seller.id } })
+ const failed = await createSellerPayout(account_id, {
+ status: PayoutStatus.FAILED,
+ status_reason: PayoutStatusReason.PROVIDER_ERROR,
+ data: { status_detail: "provider down" },
+ })
+
+ const response = await api.post(`/admin/payouts/${failed.id}/retry`, {}, adminHeaders)
+ expect(response.status).toEqual(200)
+ expect(response.data.payout.status).toEqual(PayoutStatus.PAID)
+ expect(response.data.payout.status_reason).toBeNull()
+ expect(response.data.payout.data.provider.id).toBeTruthy()
+ expect(response.data.payout.data.status_detail).toBeNull()
+ })
+
+ it("sends a pending order payout on retry", async () => {
+ const {
+ result: { account_id },
+ } = await createOrRefreshSellerPayoutAccountWorkflow(container).run({ input: { seller_id: seller.id } })
+ const pending = await createSellerPayout(account_id, { order_id: "order_pending", status: PayoutStatus.PENDING })
+
+ const response = await api.post(`/admin/payouts/${pending.id}/retry`, {}, adminHeaders)
+ expect(response.status).toEqual(200)
+ expect(response.data.payout.status).toEqual(PayoutStatus.PAID)
+ expect(response.data.payout.data.provider.id).toBeTruthy()
+ })
+
+ it("refuses to retry a paid payout", async () => {
+ const {
+ result: { account_id },
+ } = await createOrRefreshSellerPayoutAccountWorkflow(container).run({ input: { seller_id: seller.id } })
+ const paid = await createSellerPayout(account_id, { status: PayoutStatus.PAID })
+
+ const response = await api
+ .post(`/admin/payouts/${paid.id}/retry`, {}, adminHeaders)
+ .catch((e: any) => e.response)
+ expect(response.status).toEqual(400)
+ })
+
+ describe("payout webhooks", () => {
+ it("stores the provider's payout id when a webhook marks the payout paid", async () => {
+ const {
+ result: { account_id },
+ } = await createOrRefreshSellerPayoutAccountWorkflow(container).run({ input: { seller_id: seller.id } })
+ const processing = await createSellerPayout(account_id, {
+ status: PayoutStatus.PROCESSING,
+ data: { attempts: 1, idempotency_key: "key_1" },
+ })
+
+ await processPayoutForWebhookWorkflow(container).run({
+ input: { action: "payout.paid", data: { id: "tr_webhook", payout_id: processing.id } },
+ })
+
+ const paid = await payoutService.retrievePayout(processing.id)
+ expect(paid.status).toEqual(PayoutStatus.PAID)
+ expect(paid.data).toEqual(
+ expect.objectContaining({ attempts: 1, idempotency_key: "key_1", provider: { id: "tr_webhook" } })
+ )
+ })
+
+ it("clears the idempotency key when a webhook fails the payout", async () => {
+ const {
+ result: { account_id },
+ } = await createOrRefreshSellerPayoutAccountWorkflow(container).run({ input: { seller_id: seller.id } })
+ const processing = await createSellerPayout(account_id, {
+ status: PayoutStatus.PROCESSING,
+ data: { attempts: 1, idempotency_key: "key_1" },
+ })
+
+ await processPayoutForWebhookWorkflow(container).run({
+ input: {
+ action: "payout.failed",
+ data: { id: "tr_webhook", payout_id: processing.id, status_reason: "bank account closed" },
+ },
+ })
+
+ const failed = await payoutService.retrievePayout(processing.id)
+ expect(failed.status).toEqual(PayoutStatus.FAILED)
+ expect(failed.status_reason).toEqual(PayoutStatusReason.PROVIDER_ERROR)
+ expect(failed.data.status_detail).toEqual("bank account closed")
+ expect(failed.data.idempotency_key).toBeNull()
+ })
+ })
+
+ describe("rollback", () => {
+ it("keeps a created payout that was already sent", async () => {
+ const {
+ result: { account_id },
+ } = await createOrRefreshSellerPayoutAccountWorkflow(container).run({ input: { seller_id: seller.id } })
+
+ const { errors } = await createSendThenFailWorkflow(container).run({
+ input: { account_id },
+ throwOnError: false,
+ })
+ expect(errors).toHaveLength(1)
+
+ const payouts = await payoutService.listPayouts({ account_id })
+ expect(payouts).toHaveLength(1)
+ expect(payouts[0].status).toEqual(PayoutStatus.PAID)
+ })
+
+ it("does not restore an updated payout that was already sent", async () => {
+ const {
+ result: { account_id },
+ } = await createOrRefreshSellerPayoutAccountWorkflow(container).run({ input: { seller_id: seller.id } })
+ const failed = await createSellerPayout(account_id, { status: PayoutStatus.FAILED })
+
+ const { errors } = await updateSendThenFailWorkflow(container).run({
+ input: { id: failed.id },
+ throwOnError: false,
+ })
+ expect(errors).toHaveLength(1)
+
+ const payout = await payoutService.retrievePayout(failed.id)
+ expect(payout.status).toEqual(PayoutStatus.PAID)
+ expect(payout.data.provider.id).toBeTruthy()
+ })
+ })
+
+ describe("GET /payout/onboarding/refresh", () => {
+ const createOnboardingAccount = async () => {
+ const account = await payoutService.createPayoutAccounts({ external_id: "acct_onboarding", data: {} })
+ await payoutService.createOnboarding({ account_id: account.id })
+ return payoutService.retrievePayoutAccount(account.id)
+ }
+
+ const refresh = (token: string) =>
+ api.get(`/payout/onboarding/refresh?token=${token}`, { maxRedirects: 0, validateStatus: () => true })
+
+ it("rotates the token on every refresh", async () => {
+ const account = await createOnboardingAccount()
+ expect(account.onboarding_token).toBeTruthy()
+ expect(account.onboarding_token_issued_at).toBeTruthy()
+
+ const first = await refresh(account.onboarding_token)
+ expect(first.status).toEqual(302)
+
+ const rotated = await payoutService.retrievePayoutAccount(account.id)
+ expect(rotated.onboarding_token).toBeTruthy()
+ expect(rotated.onboarding_token).not.toEqual(account.onboarding_token)
+
+ const reused = await refresh(account.onboarding_token)
+ expect(reused.status).toEqual(404)
+
+ const next = await refresh(rotated.onboarding_token)
+ expect(next.status).toEqual(302)
+ })
+
+ it("rejects a token older than the TTL", async () => {
+ const account = await createOnboardingAccount()
+ await payoutService.updatePayoutAccounts({
+ id: account.id,
+ onboarding_token_issued_at: new Date(Date.now() - 25 * 60 * 60 * 1000),
+ })
+
+ const response = await refresh(account.onboarding_token)
+ expect(response.status).toEqual(400)
+ })
+
+ it("issues a new token for a new link once the old one expired", async () => {
+ const account = await createOnboardingAccount()
+ await payoutService.updatePayoutAccounts({
+ id: account.id,
+ onboarding_token_issued_at: new Date(Date.now() - 25 * 60 * 60 * 1000),
+ })
+
+ await payoutService.createOnboarding({ account_id: account.id })
+
+ const renewed = await payoutService.retrievePayoutAccount(account.id)
+ expect(renewed.onboarding_token).not.toEqual(account.onboarding_token)
+ expect((await refresh(renewed.onboarding_token)).status).toEqual(302)
+ })
+ })
+ })
+ },
+})
diff --git a/integration-tests/http/payouts/vendor/payout-accounts.spec.ts b/integration-tests/http/payouts/vendor/payout-accounts.spec.ts
index 9917a74b3..caa07f859 100644
--- a/integration-tests/http/payouts/vendor/payout-accounts.spec.ts
+++ b/integration-tests/http/payouts/vendor/payout-accounts.spec.ts
@@ -52,6 +52,23 @@ medusaIntegrationTestRunner({
expect(response.data.payout_account.id).toEqual(expect.any(String))
})
})
+
+ describe("GET /vendor/payout-accounts/me", () => {
+ it("ignores fields outside the vendor defaults", async () => {
+ await api.post("/vendor/payout-accounts", {}, sellerHeaders)
+
+ const response = await api.get(
+ "/vendor/payout-accounts/me?fields=+onboarding_token,+payouts.id,+context",
+ sellerHeaders
+ )
+
+ expect(response.status).toEqual(200)
+ expect(response.data.payout_account.id).toEqual(expect.any(String))
+ expect(response.data.payout_account.onboarding_token).toBeUndefined()
+ expect(response.data.payout_account.payouts).toBeUndefined()
+ expect(response.data.payout_account.context).toBeUndefined()
+ })
+ })
})
},
})
diff --git a/integration-tests/http/payouts/vendor/payout-module-service.spec.ts b/integration-tests/http/payouts/vendor/payout-module-service.spec.ts
index 5bf0fe3b6..aaf7a1c45 100644
--- a/integration-tests/http/payouts/vendor/payout-module-service.spec.ts
+++ b/integration-tests/http/payouts/vendor/payout-module-service.spec.ts
@@ -1,6 +1,14 @@
import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
import { MedusaContainer } from "@medusajs/framework/types"
-import { MercurModules, PayoutStatus } from "@mercurjs/types"
+import {
+ MercurModules,
+ PayoutAccountStatus,
+ PayoutKycStatus,
+ PayoutProviderError,
+ PayoutProviderErrorCode,
+ PayoutStatus,
+ PayoutStatusReason,
+} from "@mercurjs/types"
import { createSellerUser } from "../../../helpers/create-seller-user"
import { createPayoutAccountWorkflow } from "@mercurjs/core/workflows"
@@ -8,7 +16,7 @@ jest.setTimeout(120000)
medusaIntegrationTestRunner({
testSuite: ({ getContainer }) => {
- describe("Payout module - createPayouts", () => {
+ describe("Payout module - processPayout", () => {
let appContainer: MedusaContainer
let payoutService: any
let providerService: any
@@ -35,91 +43,187 @@ medusaIntegrationTestRunner({
jest.restoreAllMocks()
})
- it("inserts the row before calling the provider and passes its id as idempotency_key", async () => {
- let visibleDuringProviderCall: any[] = []
- let receivedInput: any
-
- jest
- .spyOn(providerService, "createPayout")
- .mockImplementation(async (input: any) => {
- receivedInput = input
- visibleDuringProviderCall = await payoutService.listPayouts({
- account_id: accountId,
- })
- return { status: PayoutStatus.PAID, data: { transfer_id: "tr_1" } }
- })
-
- const payout = await payoutService.createPayouts({
+ const createPending = () =>
+ payoutService.createPayouts({
account_id: accountId,
+ order_id: "order_1",
amount: 1000,
currency_code: "usd",
- data: { order_id: "order_1" },
+ data: { source_payment: { id: "pay_1", data: { id: "pi_1" } } },
})
- expect(visibleDuringProviderCall).toHaveLength(1)
- expect(visibleDuringProviderCall[0].id).toEqual(payout.id)
- expect(visibleDuringProviderCall[0].status).toEqual(PayoutStatus.PENDING)
+ it("sends the payout with its id as idempotency key and the source payment", async () => {
+ let receivedInput: any
+ jest.spyOn(providerService, "createPayout").mockImplementation(async (input: any) => {
+ receivedInput = input
+ return { id: "tr_1", status: PayoutStatus.PAID, data: { id: "tr_1" } }
+ })
+
+ const pending = await createPending()
+ const payout = await payoutService.processPayout(pending.id)
- expect(receivedInput.context).toEqual({ idempotency_key: payout.id })
- expect(receivedInput.data).toMatchObject({ order_id: "order_1" })
+ expect(receivedInput.context).toEqual({ idempotency_key: pending.id })
+ expect(receivedInput.source_payment).toEqual({ id: "pay_1", data: { id: "pi_1" } })
+ expect(receivedInput.group).toEqual("order_1")
+ expect(receivedInput.metadata).toEqual({ payout_id: pending.id, order_id: "order_1" })
expect(payout.status).toEqual(PayoutStatus.PAID)
- expect(payout.data).toEqual({ transfer_id: "tr_1" })
+ expect(payout.data).toMatchObject({ attempts: 1, provider: { id: "tr_1" } })
})
- it("keeps the caller's idempotency_key when one is passed", async () => {
- let receivedInput: any
- jest
+ it("keeps the idempotency key after an error with an unknown outcome", async () => {
+ const spy = jest
.spyOn(providerService, "createPayout")
- .mockImplementation(async (input: any) => {
- receivedInput = input
- return { status: PayoutStatus.PAID, data: {} }
- })
+ .mockRejectedValueOnce(new Error("socket hang up"))
+ .mockResolvedValueOnce({ id: "tr_2", status: PayoutStatus.PAID, data: {} })
- await payoutService.createPayouts({
- account_id: accountId,
- amount: 1000,
- currency_code: "usd",
- context: { idempotency_key: "order_abc" },
- })
+ const pending = await createPending()
+
+ const failed = await payoutService.processPayout(pending.id)
+ expect(failed.status).toEqual(PayoutStatus.FAILED)
+ expect(failed.status_reason).toEqual(PayoutStatusReason.PROVIDER_ERROR)
+ expect(failed.data.status_detail).toEqual("socket hang up")
+
+ const paid = await payoutService.processPayout(pending.id)
+ expect(paid.status).toEqual(PayoutStatus.PAID)
+ expect(paid.status_reason).toBeNull()
+ expect(paid.data.status_detail).toBeNull()
+ expect(spy.mock.calls[1][0].context).toEqual({ idempotency_key: pending.id })
+ })
- expect(receivedInput.context.idempotency_key).toEqual("order_abc")
+ it("retries with a fresh key after the provider refused the payout", async () => {
+ const spy = jest
+ .spyOn(providerService, "createPayout")
+ .mockRejectedValueOnce(
+ new PayoutProviderError("insufficient funds", { code: PayoutProviderErrorCode.REFUSED })
+ )
+ .mockRejectedValueOnce(new Error("timeout"))
+ .mockResolvedValueOnce({ id: "tr_2", status: PayoutStatus.PAID, data: {} })
+
+ const pending = await createPending()
+
+ const refused = await payoutService.processPayout(pending.id)
+ expect(refused.status).toEqual(PayoutStatus.FAILED)
+ expect(refused.data.status_detail).toEqual("insufficient funds")
+
+ await payoutService.processPayout(pending.id)
+ await payoutService.processPayout(pending.id)
+
+ expect(spy.mock.calls.map((call) => call[0].context.idempotency_key)).toEqual([
+ pending.id,
+ `${pending.id}:2`,
+ `${pending.id}:2`,
+ ])
})
- it("leaves no payout row and rethrows when the provider fails", async () => {
+ it("aborts the payout on a final provider error", async () => {
jest
.spyOn(providerService, "createPayout")
- .mockRejectedValue(new Error("provider down"))
+ .mockRejectedValue(new PayoutProviderError("account closed", { final: true }))
- await expect(
- payoutService.createPayouts({
- account_id: accountId,
- amount: 1000,
- currency_code: "usd",
- })
- ).rejects.toThrow("provider down")
+ const pending = await createPending()
+ const payout = await payoutService.processPayout(pending.id)
- const payouts = await payoutService.listPayouts(
- { account_id: accountId },
- { withDeleted: true }
- )
- expect(payouts).toHaveLength(0)
+ expect(payout.status).toEqual(PayoutStatus.ABORTED)
+ expect(payout.status_reason).toEqual(PayoutStatusReason.PROVIDER_ERROR)
+ expect(payout.data.status_detail).toEqual("account closed")
})
- it("persists the processing status", async () => {
- const payout = await payoutService.createPayouts({
- account_id: accountId,
- amount: 1000,
- currency_code: "usd",
+ it("leaves a paid payout alone", async () => {
+ const spy = jest.spyOn(providerService, "createPayout")
+
+ const pending = await createPending()
+ await payoutService.updatePayouts({ id: pending.id, status: PayoutStatus.PAID })
+ const payout = await payoutService.processPayout(pending.id)
+
+ expect(payout.status).toEqual(PayoutStatus.PAID)
+ expect(spy).not.toHaveBeenCalled()
+ })
+
+ it("reverses against the provider payout", async () => {
+ let receivedInput: any
+ jest.spyOn(providerService, "createPayout").mockResolvedValue({
+ id: "tr_1",
+ status: PayoutStatus.PAID,
+ data: { id: "tr_1" },
+ })
+ jest.spyOn(providerService, "reversePayout").mockImplementation(async (input: any) => {
+ receivedInput = input
+ return { id: "trr_1", status: PayoutStatus.PAID, data: {} }
+ })
+
+ const payout = await payoutService.processPayout((await createPending()).id)
+ const pendingReversal = await payoutService.createPayoutReversals({
+ payout_id: payout.id,
+ refund_id: "ref_1",
+ amount: 400,
+ })
+ const reversal = await payoutService.processPayoutReversal(pendingReversal.id)
+
+ expect(receivedInput.payout).toEqual({ id: "tr_1", data: { id: "tr_1" } })
+ expect(Number(receivedInput.amount)).toEqual(400)
+ expect(receivedInput.currency_code).toEqual("usd")
+ expect(receivedInput.context).toEqual({ idempotency_key: pendingReversal.id })
+ expect(reversal.status).toEqual(PayoutStatus.PAID)
+ expect(reversal.data.provider.id).toEqual("trr_1")
+ })
+
+ describe("deletePayoutAccount", () => {
+ it("deletes the account at the provider before the stored row", async () => {
+ const deleteAccount = jest.spyOn(providerService, "deleteAccount").mockResolvedValue(undefined)
+ const account = await payoutService.retrievePayoutAccount(accountId)
+
+ await payoutService.deletePayoutAccount(accountId)
+
+ expect(deleteAccount).toHaveBeenCalledWith({
+ account: { id: account.external_id, data: account.data },
+ })
+ expect(await payoutService.listPayoutAccounts({ id: accountId })).toHaveLength(0)
+ })
+ })
+
+ describe("syncPayoutAccount", () => {
+ const providerAccount = (overrides: Record<string, unknown> = {}) => ({
+ id: "acct_1",
+ status: PayoutAccountStatus.ACTIVE,
+ payouts_enabled: true,
+ charges_enabled: true,
+ details_submitted: true,
+ disabled_reason: null,
+ requirements: { currently_due: [], past_due: [], pending_verification: [] },
+ data: { id: "acct_1" },
+ ...overrides,
})
- await payoutService.updatePayouts({
- id: payout.id,
- status: PayoutStatus.PROCESSING,
+ it.each([
+ [{ requirements: { currently_due: ["individual.id_number"], past_due: [], pending_verification: [] } }, PayoutKycStatus.PENDING_SUBMISSION],
+ [{ requirements: { currently_due: [], past_due: [], pending_verification: ["individual.verification.document"] } }, PayoutKycStatus.PENDING_APPROVAL],
+ [{ disabled_reason: "rejected.fraud" }, PayoutKycStatus.REFUSED],
+ [{ disabled_reason: "under_review" }, PayoutKycStatus.PENDING_APPROVAL],
+ [{}, PayoutKycStatus.APPROVED],
+ ])("derives the KYC status from the provider account (%o)", async (overrides, kycStatus) => {
+ jest.spyOn(providerService, "retrieveAccount").mockResolvedValue(providerAccount(overrides))
+
+ const account = await payoutService.syncPayoutAccount(accountId)
+
+ expect(account.kyc_status).toEqual(kycStatus)
})
- const updated = await payoutService.retrievePayout(payout.id)
- expect(updated.status).toEqual(PayoutStatus.PROCESSING)
+ it("derives the account status from the provider flags", async () => {
+ const retrieve = jest.spyOn(providerService, "retrieveAccount")
+
+ retrieve.mockResolvedValueOnce(providerAccount({ details_submitted: false }))
+ expect((await payoutService.syncPayoutAccount(accountId)).status).toEqual(PayoutAccountStatus.PENDING)
+
+ retrieve.mockResolvedValueOnce(providerAccount({ payouts_enabled: false }))
+ expect((await payoutService.syncPayoutAccount(accountId)).status).toEqual(PayoutAccountStatus.RESTRICTED)
+
+ retrieve.mockResolvedValueOnce(providerAccount({ disabled_reason: "rejected.terms_of_service" }))
+ expect((await payoutService.syncPayoutAccount(accountId)).status).toEqual(PayoutAccountStatus.REJECTED)
+
+ retrieve.mockResolvedValueOnce(providerAccount())
+ expect((await payoutService.syncPayoutAccount(accountId)).status).toEqual(PayoutAccountStatus.ACTIVE)
+ })
})
})
},
diff --git a/integration-tests/http/payouts/vendor/payouts.spec.ts b/integration-tests/http/payouts/vendor/payouts.spec.ts
index 4b7a19610..a96450af7 100644
--- a/integration-tests/http/payouts/vendor/payouts.spec.ts
+++ b/integration-tests/http/payouts/vendor/payouts.spec.ts
@@ -8,20 +8,32 @@ import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
import {
CommissionRateType,
MercurModules,
+ PayoutStatus,
+ PayoutStatusReason,
} from "@mercurjs/types"
import { createSellerUser } from "../../../helpers/create-seller-user"
import { createShippingProfile } from "../../../helpers/create-shipping-profile"
-import { generatePublishableKey, generateStoreHeaders } from "../../../helpers/create-admin-user"
+import {
+ adminHeaders,
+ createAdminUser,
+ generatePublishableKey,
+ generateStoreHeaders,
+} from "../../../helpers/create-admin-user"
import { createVendorProduct } from "../../../helpers/create-product"
-import { createPayoutAccountWorkflow, createPayoutWorkflow } from '@mercurjs/core/workflows'
+import {
+ createOrderPayoutsWorkflow,
+ createPayoutAccountWorkflow,
+ createPayoutReversalsWorkflow,
+} from "@mercurjs/core/workflows"
jest.setTimeout(120000)
medusaIntegrationTestRunner({
- testSuite: ({ getContainer, api }) => {
+ testSuite: ({ getContainer, api, dbConnection }) => {
describe("Vendor - Payouts", () => {
let appContainer: MedusaContainer
let commissionService: any
+ let payoutService: any
let query: any
let seller: any
let sellerHeaders: any
@@ -35,10 +47,13 @@ medusaIntegrationTestRunner({
beforeAll(async () => {
appContainer = getContainer()
commissionService = appContainer.resolve(MercurModules.COMMISSION)
+ payoutService = appContainer.resolve(MercurModules.PAYOUT)
query = appContainer.resolve(ContainerRegistrationKeys.QUERY)
})
beforeEach(async () => {
+ await createAdminUser(dbConnection, adminHeaders, appContainer)
+
// Create seller
const sellerResult = await createSellerUser(appContainer, {
@@ -298,38 +313,48 @@ medusaIntegrationTestRunner({
}
describe("Payout Flow", () => {
- const getOrderFromGroup = async (orderGroupId: string) => {
- const { data: [orderGroup] } = await query.graph({
- entity: "order_group",
- fields: ["id", "orders.*", "orders.items.*"],
- filters: { id: orderGroupId },
+ const getOrder = async (orderId: string) => {
+ const {
+ data: [order],
+ } = await query.graph({
+ entity: "order",
+ fields: [
+ "id",
+ "total",
+ "currency_code",
+ "items.id",
+ "payment_collections.payments.id",
+ "payment_collections.payments.captured_at",
+ "cart.payment_collection.payments.id",
+ ],
+ filters: { id: orderId },
})
- const order = orderGroup.orders[0]
-
- const itemIds = (order.items ?? [])
- .map((item: any) => item.id)
- .filter(Boolean)
- if (itemIds.length) {
- const { data: commissionLines } = await query.graph({
- entity: "commission_line",
- fields: [
- "id",
- "item_id",
- "shipping_method_id",
- "code",
- "rate",
- "amount",
- ],
- filters: { item_id: itemIds },
- })
- for (const item of order.items) {
- item.commission_lines = commissionLines.filter(
- (line: any) => line.item_id === item.id
- )
+ return order
+ }
+
+ const commissionOf = async (order: any) => {
+ const { data: lines } = await query.graph({
+ entity: "commission_line",
+ fields: ["amount"],
+ filters: { item_id: order.items.map((item: any) => item.id) },
+ })
+ return lines.reduce((acc: number, line: any) => acc + Number(line.amount), 0)
+ }
+
+ // The cart payment is split onto the orders by a subscriber, after
+ // the capture request returns.
+ const eventually = async (assertion: () => Promise<void>) => {
+ const deadline = Date.now() + 15000
+ for (;;) {
+ try {
+ return await assertion()
+ } catch (error) {
+ if (Date.now() > deadline) {
+ throw error
+ }
+ await new Promise((r) => setTimeout(r, 250))
}
}
-
- return order
}
const placeOrder = async (quantity: number) => {
@@ -341,50 +366,132 @@ medusaIntegrationTestRunner({
const completeResult = await completeCart(cart.id)
expect(completeResult.type).toEqual("order_group")
- return getOrderFromGroup(completeResult.order_group.id)
+ const {
+ data: [orderGroup],
+ } = await query.graph({
+ entity: "order_group",
+ fields: ["orders.id"],
+ filters: { id: completeResult.order_group.id },
+ })
+ return getOrder(orderGroup.orders[0].id)
}
- it("should create a payout for an order and expose it via /vendor/payouts", async () => {
- const order = await placeOrder(1) // $100 item + $10 shipping
+ const capture = async (order: any) => {
+ await api.post(
+ `/admin/payments/${order.cart.payment_collection.payments[0].id}/capture`,
+ {},
+ adminHeaders
+ )
+ await eventually(async () => {
+ const current = await getOrder(order.id)
+ expect(current.payment_collections[0]?.payments[0]?.captured_at).toBeTruthy()
+ })
+ return getOrder(order.id)
+ }
- expect(order).toBeDefined()
- expect(order.items).toHaveLength(1)
+ const payOut = (orderIds: string[]) =>
+ createOrderPayoutsWorkflow(appContainer).run({
+ input: { order_ids: orderIds, required_fulfillment_status: "not_fulfilled" },
+ })
- // Commission (10% of the $100 item) is recorded on the order item.
- const commissionLine = order.items[0].commission_lines?.[0]
- expect(commissionLine).toBeDefined()
- expect(commissionLine.amount).toEqual(1000) // $10 in cents
+ it("pays the seller the order total minus commission and exposes it via /vendor/payouts", async () => {
+ const order = await capture(await placeOrder(1))
+ const commission = await commissionOf(order)
+ expect(commission).toEqual(1000)
- // Create the payout directly from the order.
- const payoutResult = await createPayoutWorkflow(appContainer).run({
- input: { order_id: order.id },
- })
+ const { result } = await payOut([order.id])
+ expect(result.payouts).toHaveLength(1)
- const payout = payoutResult.result
- expect(payout).toBeDefined()
- expect(payout.id).toBeDefined()
- expect(Number(payout.amount)).toBeGreaterThan(0)
- expect(payout.currency_code).toEqual("usd")
+ const payout = result.payouts[0]
+ expect(payout.order_id).toEqual(order.id)
+ expect(payout.status).toEqual(PayoutStatus.PAID)
+ expect(Number(payout.amount)).toEqual(Number(order.total) - commission)
+ expect(payout.data.provider.id).toBeTruthy()
- // The seller can see the payout on their payouts endpoint.
const payoutsResponse = await api.get(`/vendor/payouts`, sellerHeaders)
-
expect(payoutsResponse.status).toEqual(200)
- const listed = payoutsResponse.data.payouts.find(
- (p: any) => p.id === payout.id
- )
+ const listed = payoutsResponse.data.payouts.find((p: any) => p.id === payout.id)
expect(listed).toBeDefined()
+ expect(listed.order_id).toEqual(order.id)
expect(Number(listed.amount)).toEqual(Number(payout.amount))
- expect(listed.currency_code).toEqual("usd")
})
- it("should not expose a payout to another seller", async () => {
+ it("holds the payout until the payment is captured, then pays the same row", async () => {
const order = await placeOrder(1)
- const payout = (
- await createPayoutWorkflow(appContainer).run({
- input: { order_id: order.id },
- })
- ).result
+
+ await payOut([order.id])
+ const [held] = await payoutService.listPayouts({ order_id: order.id })
+ expect(held.status).toEqual(PayoutStatus.ON_HOLD)
+ expect(held.status_reason).toEqual(PayoutStatusReason.PAYMENT_NOT_READY)
+ expect(held.data.status_detail).toContain("is not ready yet")
+
+ await capture(order)
+ await payOut([order.id])
+
+ const payouts = await payoutService.listPayouts({ order_id: order.id })
+ expect(payouts).toHaveLength(1)
+ expect(payouts[0].id).toEqual(held.id)
+ expect(payouts[0].status).toEqual(PayoutStatus.PAID)
+ })
+
+ it("holds the payout until the order reaches the required fulfillment status", async () => {
+ const order = await capture(await placeOrder(1))
+
+ await createOrderPayoutsWorkflow(appContainer).run({
+ input: { order_ids: [order.id] },
+ })
+
+ const [held] = await payoutService.listPayouts({ order_id: order.id })
+ expect(held.status).toEqual(PayoutStatus.ON_HOLD)
+ expect(held.status_reason).toEqual(PayoutStatusReason.ORDER_NOT_READY)
+ expect(held.data.status_detail).toEqual("Order is not ready yet, status is not_fulfilled")
+ })
+
+ it("does not pay an order out twice", async () => {
+ const order = await capture(await placeOrder(1))
+
+ await payOut([order.id])
+ const { result } = await payOut([order.id])
+
+ expect(result.payouts).toHaveLength(0)
+ expect(await payoutService.listPayouts({ order_id: order.id })).toHaveLength(1)
+ })
+
+ it("reverses the refunded share net of its commission", async () => {
+ const order = await capture(await placeOrder(1))
+ const commission = await commissionOf(order)
+ const { result } = await payOut([order.id])
+ const payout = result.payouts[0]
+
+ await api.post(
+ `/admin/payments/${order.payment_collections[0].payments[0].id}/refund`,
+ { amount: 5500 },
+ adminHeaders
+ )
+
+ const reversals = await createPayoutReversalsWorkflow(appContainer).run({
+ input: { order_ids: [order.id] },
+ })
+ expect(reversals.result.reversals).toHaveLength(1)
+
+ const reversal = reversals.result.reversals[0]
+ expect(reversal.payout_id).toEqual(payout.id)
+ expect(reversal.status).toEqual(PayoutStatus.PAID)
+ expect(reversal.refund_id).toBeTruthy()
+ expect(Number(reversal.amount)).toEqual(5500 - (commission * 5500) / Number(order.total))
+
+ const again = await createPayoutReversalsWorkflow(appContainer).run({
+ input: { order_ids: [order.id] },
+ })
+ expect(again.result.reversals).toHaveLength(0)
+
+ const detail = await api.get(`/vendor/payouts/${payout.id}`, sellerHeaders)
+ expect(detail.data.payout.reversals).toHaveLength(1)
+ })
+
+ it("should not expose a payout to another seller", async () => {
+ const order = await capture(await placeOrder(1))
+ const payout = (await payOut([order.id])).result.payouts[0]
const other = await createSellerUser(appContainer, {
@@ -401,35 +508,21 @@ medusaIntegrationTestRunner({
expect(asOwner.data.count).toEqual(1)
})
- it("should reject creating a payout for a non-existent order", async () => {
- const { errors } = await createPayoutWorkflow(appContainer).run({
- input: { order_id: "order_does_not_exist" },
- throwOnError: false,
- })
-
- expect(errors.length).toBeGreaterThan(0)
+ it("creates nothing for an order that does not exist", async () => {
+ const { result } = await payOut(["order_does_not_exist"])
+ expect(result.payouts).toHaveLength(0)
+ expect(await payoutService.listPayouts({ order_id: "order_does_not_exist" })).toHaveLength(0)
})
it("should create separate payouts for multiple orders", async () => {
- const order1 = await placeOrder(2) // 2 x $100
- const payout1 = (
- await createPayoutWorkflow(appContainer).run({
- input: { order_id: order1.id },
- })
- ).result
-
- const order2 = await placeOrder(1) // 1 x $100
- const payout2 = (
- await createPayoutWorkflow(appContainer).run({
- input: { order_id: order2.id },
- })
- ).result
+ const order1 = await capture(await placeOrder(2))
+ const order2 = await capture(await placeOrder(1))
- expect(payout1.id).not.toEqual(payout2.id)
- expect(Number(payout1.amount)).toBeGreaterThan(0)
- expect(Number(payout2.amount)).toBeGreaterThan(0)
+ const { result } = await payOut([order1.id, order2.id])
+ const payout1 = result.payouts.find((p: any) => p.order_id === order1.id)
+ const payout2 = result.payouts.find((p: any) => p.order_id === order2.id)
- // The larger order should yield the larger payout.
+ expect(payout1.id).not.toEqual(payout2.id)
expect(Number(payout1.amount)).toBeGreaterThan(Number(payout2.amount))
const payoutsResponse = await api.get(`/vendor/payouts`, sellerHeaders)
diff --git a/package.json b/package.json
index 33d2d68b7..6762e6a4e 100644
--- a/package.json
+++ b/package.json
@@ -29,7 +29,6 @@
"workspaces": [
"apps/*",
"packages/*",
- "packages/providers/*",
"packages/plugins/*",
"integration-tests",
"e2e-tests",
diff --git a/packages/admin/src/components/layout/main-layout/main-layout.tsx b/packages/admin/src/components/layout/main-layout/main-layout.tsx
index 60c903ae4..950b33078 100644
--- a/packages/admin/src/components/layout/main-layout/main-layout.tsx
+++ b/packages/admin/src/components/layout/main-layout/main-layout.tsx
@@ -144,6 +144,7 @@ const useSidebarRoutes = () => {
icon: item.icon ? <item.icon /> : undefined,
translationNs: item.translationNs,
group: item.group,
+ type: "extension" as const,
items: addNestedItems(item.path, visibleMenuItems),
}));
@@ -505,6 +506,12 @@ const useCoreRoutes = (): Omit<INavItem, "pathname">[] => {
icon: <CreditCardRefresh />,
label: t("payouts.domain"),
to: "/payouts",
+ items: [
+ {
+ label: t("payoutAccounts.domain"),
+ to: "/payout-accounts",
+ },
+ ],
},
];
};
diff --git a/packages/admin/src/components/layout/nav-item/nav-item.tsx b/packages/admin/src/components/layout/nav-item/nav-item.tsx
index d2a967243..32f81b42c 100644
--- a/packages/admin/src/components/layout/nav-item/nav-item.tsx
+++ b/packages/admin/src/components/layout/nav-item/nav-item.tsx
@@ -150,16 +150,14 @@ export const NavItem = ({
isNested?: boolean;
isSetting?: boolean;
}) => {
- if (["core", "setting"].includes(type)) {
- isActive = pathname.startsWith(to);
+ isActive = pathname.startsWith(to);
- if (isActive && !isNested && items?.length) {
- const nestedIsActive = items.some((item) =>
- pathname.startsWith(item.to),
- );
- if (nestedIsActive) {
- isActive = false;
- }
+ if (isActive && !isNested && items?.length) {
+ const nestedIsActive = items.some((item) =>
+ pathname.startsWith(item.to),
+ );
+ if (nestedIsActive) {
+ isActive = false;
}
}
@@ -169,7 +167,7 @@ export const NavItem = ({
[SETTING_NAV_LINK_CLASSES]: isSetting,
});
},
- [type, pathname, items],
+ [pathname, items],
);
const isSetting = type === "setting";
diff --git a/packages/admin/src/extension-targets.d.ts b/packages/admin/src/extension-targets.d.ts
index c93af0455..ac35ebd62 100644
--- a/packages/admin/src/extension-targets.d.ts
+++ b/packages/admin/src/extension-targets.d.ts
@@ -78,8 +78,16 @@ declare module "@mercurjs/dashboard-sdk" {
"orders.detail.side.before": true
"orders.list.after": true
"orders.list.before": true
+ "payout_accounts.detail.main.after": true
+ "payout_accounts.detail.main.before": true
+ "payout_accounts.detail.side.after": true
+ "payout_accounts.detail.side.before": true
+ "payout_accounts.list.after": true
+ "payout_accounts.list.before": true
"payouts.detail.main.after": true
"payouts.detail.main.before": true
+ "payouts.detail.side.after": true
+ "payouts.detail.side.before": true
"payouts.list.after": true
"payouts.list.before": true
"price-lists.detail.main.after": true
@@ -186,6 +194,7 @@ declare module "@mercurjs/dashboard-sdk" {
"inventory": true
"offers": true
"orders": true
+ "payout-accounts": true
"payouts": true
"price-lists": true
"products": true
diff --git a/packages/admin/src/get-route-map.tsx b/packages/admin/src/get-route-map.tsx
index fd21d8cf3..53df19a1a 100644
--- a/packages/admin/src/get-route-map.tsx
+++ b/packages/admin/src/get-route-map.tsx
@@ -1060,6 +1060,43 @@ export function getRouteMap({
},
],
},
+ {
+ path: "/payout-accounts",
+ errorElement: <ErrorBoundary />,
+ handle: {
+ breadcrumb: () => t("payoutAccounts.domain"),
+ permissions: "payouts:view",
+ },
+ children: [
+ {
+ path: "",
+ lazy: () => import("./pages/payout-accounts/payout-account-list"),
+ },
+ {
+ path: ":id",
+ lazy: async () => {
+ const { Breadcrumb, loader } =
+ await import("./pages/payout-accounts/payout-account-detail");
+
+ return {
+ Component: Outlet,
+ loader: withPermission(loader, "payouts:view"),
+ handle: {
+ breadcrumb: (match: UIMatch) => (
+ <Breadcrumb {...match} />
+ ),
+ },
+ };
+ },
+ children: [
+ {
+ path: "",
+ lazy: () => import("./pages/payout-accounts/payout-account-detail").then(withLoaderPermission("payouts:view")),
+ },
+ ],
+ },
+ ],
+ },
{
path: "/reservations",
errorElement: <ErrorBoundary />,
diff --git a/packages/admin/src/hooks/api/payout-accounts.tsx b/packages/admin/src/hooks/api/payout-accounts.tsx
new file mode 100644
index 000000000..01aff52f7
--- /dev/null
+++ b/packages/admin/src/hooks/api/payout-accounts.tsx
@@ -0,0 +1,129 @@
+import {
+ ClientError,
+ InferClientInput,
+} from "@mercurjs/client";
+import {
+ QueryKey,
+ UseMutationOptions,
+ UseQueryOptions,
+ useMutation,
+ useQuery,
+} from "@tanstack/react-query";
+import { AdminPayoutAccount } from "../../lib/payouts";
+import { sdk } from "../../lib/client";
+import { queryClient } from "../../lib/query-client";
+import { queryKeysFactory } from "../../lib/query-key-factory";
+
+export type { AdminPayoutAccount };
+
+const PAYOUT_ACCOUNTS_QUERY_KEY = "payout_accounts" as const;
+export const payoutAccountsQueryKeys = queryKeysFactory(
+ PAYOUT_ACCOUNTS_QUERY_KEY,
+);
+
+
+type PayoutAccountResponse = { payout_account: AdminPayoutAccount };
+
+export const usePayoutAccount = (
+ id: string,
+ query?: Omit<
+ InferClientInput<typeof sdk.admin.payoutAccounts.$id.query>,
+ "$id"
+ >,
+ options?: Omit<
+ UseQueryOptions<
+ PayoutAccountResponse,
+ ClientError,
+ PayoutAccountResponse,
+ QueryKey
+ >,
+ "queryKey" | "queryFn"
+ >,
+) => {
+ const { data, ...rest } = useQuery({
+ queryFn: () =>
+ sdk.admin.payoutAccounts.$id.query({
+ $id: id,
+ ...query,
+ }) as Promise<PayoutAccountResponse>,
+ queryKey: payoutAccountsQueryKeys.detail(id),
+ ...options,
+ });
+
+ return { ...data, ...rest };
+};
+
+type PayoutAccountListResponse = {
+ payout_accounts: AdminPayoutAccount[];
+ count: number;
+ offset: number;
+ limit: number;
+};
+
+export const usePayoutAccounts = (
+ query?: InferClientInput<typeof sdk.admin.payoutAccounts.query>,
+ options?: Omit<
+ UseQueryOptions<
+ PayoutAccountListResponse,
+ ClientError,
+ PayoutAccountListResponse,
+ QueryKey
+ >,
+ "queryKey" | "queryFn"
+ >,
+) => {
+ const { data, ...rest } = useQuery({
+ queryFn: () =>
+ sdk.admin.payoutAccounts.query({
+ ...query,
+ }) as Promise<PayoutAccountListResponse>,
+ queryKey: payoutAccountsQueryKeys.list(query),
+ ...options,
+ });
+
+ return { ...data, ...rest };
+};
+
+const invalidate = (id: string) =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: payoutAccountsQueryKeys.lists(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: payoutAccountsQueryKeys.detail(id),
+ }),
+ ]);
+
+export const useSyncPayoutAccount = (
+ id: string,
+ options?: UseMutationOptions<PayoutAccountResponse, ClientError, void>,
+) => {
+ return useMutation({
+ mutationFn: () =>
+ sdk.admin.payoutAccounts.$id.sync.mutate({
+ $id: id,
+ }) as Promise<PayoutAccountResponse>,
+ onSuccess: async (data, variables, context) => {
+ await invalidate(id);
+ options?.onSuccess?.(data, variables, context);
+ },
+ ...options,
+ });
+};
+
+export const useRefreshPayoutAccountLink = (
+ id: string,
+ options?: UseMutationOptions<PayoutAccountResponse, ClientError, void>,
+) => {
+ return useMutation({
+ mutationFn: () =>
+ sdk.admin.payoutAccounts.$id.refreshLink.mutate({
+ $id: id,
+ }) as Promise<PayoutAccountResponse>,
+ onSuccess: async (data, variables, context) => {
+ await invalidate(id);
+ options?.onSuccess?.(data, variables, context);
+ },
+ ...options,
+ });
+};
diff --git a/packages/admin/src/hooks/api/payouts.tsx b/packages/admin/src/hooks/api/payouts.tsx
index 31b785c73..31fd98e61 100644
--- a/packages/admin/src/hooks/api/payouts.tsx
+++ b/packages/admin/src/hooks/api/payouts.tsx
@@ -1,31 +1,48 @@
import {
ClientError,
InferClientInput,
- InferClientOutput,
} from "@mercurjs/client";
-import { QueryKey, UseQueryOptions, useQuery } from "@tanstack/react-query";
+import {
+ QueryKey,
+ UseMutationOptions,
+ UseQueryOptions,
+ useMutation,
+ useQuery,
+} from "@tanstack/react-query";
+import { AdminPayout } from "../../lib/payouts";
import { sdk } from "../../lib/client";
+import { queryClient } from "../../lib/query-client";
import { queryKeysFactory } from "../../lib/query-key-factory";
-import { PayoutDTO } from "@mercurjs/types";
+
+export type { AdminPayout };
const PAYOUTS_QUERY_KEY = "payouts" as const;
export const payoutsQueryKeys = queryKeysFactory(PAYOUTS_QUERY_KEY);
+
+type PayoutResponse = { payout: AdminPayout };
+
+type PayoutListResponse = {
+ payouts: AdminPayout[];
+ count: number;
+ offset: number;
+ limit: number;
+};
+
export const usePayout = (
id: string,
query?: Omit<InferClientInput<typeof sdk.admin.payouts.$id.query>, "$id">,
options?: Omit<
- UseQueryOptions<
- { payout: PayoutDTO },
- ClientError,
- { payout: PayoutDTO },
- QueryKey
- >,
+ UseQueryOptions<PayoutResponse, ClientError, PayoutResponse, QueryKey>,
"queryKey" | "queryFn"
>,
) => {
const { data, ...rest } = useQuery({
- queryFn: () => sdk.admin.payouts.$id.query({ $id: id, ...query }),
+ queryFn: () =>
+ sdk.admin.payouts.$id.query({
+ $id: id,
+ ...query,
+ }) as Promise<PayoutResponse>,
queryKey: payoutsQueryKeys.detail(id),
...options,
});
@@ -37,19 +54,42 @@ export const usePayouts = (
query?: InferClientInput<typeof sdk.admin.payouts.query>,
options?: Omit<
UseQueryOptions<
- InferClientOutput<typeof sdk.admin.payouts.query>,
+ PayoutListResponse,
ClientError,
- InferClientOutput<typeof sdk.admin.payouts.query>,
+ PayoutListResponse,
QueryKey
>,
"queryKey" | "queryFn"
>,
) => {
const { data, ...rest } = useQuery({
- queryFn: () => sdk.admin.payouts.query({ ...query }),
+ queryFn: () =>
+ sdk.admin.payouts.query({ ...query }) as Promise<PayoutListResponse>,
queryKey: payoutsQueryKeys.list(query),
...options,
});
return { ...data, ...rest };
};
+
+export const useRetryPayout = (
+ id: string,
+ options?: UseMutationOptions<PayoutResponse, ClientError, void>,
+) => {
+ return useMutation({
+ mutationFn: () =>
+ sdk.admin.payouts.$id.retry.mutate({
+ $id: id,
+ }) as Promise<PayoutResponse>,
+ onSuccess: async (data, variables, context) => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: payoutsQueryKeys.lists() }),
+ queryClient.invalidateQueries({
+ queryKey: payoutsQueryKeys.detail(id),
+ }),
+ ]);
+ options?.onSuccess?.(data, variables, context);
+ },
+ ...options,
+ });
+};
diff --git a/packages/admin/src/hooks/table/columns/use-payout-account-table-columns.tsx b/packages/admin/src/hooks/table/columns/use-payout-account-table-columns.tsx
new file mode 100644
index 000000000..062a496ab
--- /dev/null
+++ b/packages/admin/src/hooks/table/columns/use-payout-account-table-columns.tsx
@@ -0,0 +1,59 @@
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+
+import { DateCell } from "../../../components/table/table-cells/common/date-cell"
+import { StatusCell } from "../../../components/table/table-cells/common/status-cell"
+import {
+ TextCell,
+ TextHeader,
+} from "../../../components/table/table-cells/common/text-cell"
+import { AdminPayoutAccount } from "../../api/payout-accounts"
+import {
+ getPayoutAccountKycProps,
+ getPayoutAccountStatusProps,
+} from "../../../pages/payout-accounts/common/utils"
+
+const columnHelper = createColumnHelper<AdminPayoutAccount>()
+
+export const usePayoutAccountTableColumns = () => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "store",
+ header: () => <TextHeader text={t("payoutAccounts.fields.store")} />,
+ cell: ({ row }) => <TextCell text={row.original.seller?.name} />,
+ }),
+ columnHelper.accessor("status", {
+ header: () => <TextHeader text={t("fields.status")} />,
+ cell: ({ getValue }) => {
+ const { color, label } = getPayoutAccountStatusProps(getValue(), t)
+ return <StatusCell color={color}>{label}</StatusCell>
+ },
+ }),
+ columnHelper.accessor("kyc_status", {
+ header: () => (
+ <TextHeader text={t("payoutAccounts.fields.kycStatus")} />
+ ),
+ cell: ({ getValue }) => {
+ const props = getPayoutAccountKycProps(getValue(), t)
+ if (!props) {
+ return <TextCell />
+ }
+ return <StatusCell color={props.color}>{props.label}</StatusCell>
+ },
+ }),
+ columnHelper.accessor("created_at", {
+ header: () => <TextHeader text={t("fields.createdAt")} />,
+ cell: ({ getValue }) => <DateCell date={getValue()} />,
+ }),
+ columnHelper.accessor("updated_at", {
+ header: () => <TextHeader text={t("fields.updatedAt")} />,
+ cell: ({ getValue }) => <DateCell date={getValue()} />,
+ }),
+ ],
+ [t],
+ )
+}
diff --git a/packages/admin/src/hooks/table/columns/use-payout-table-columns.tsx b/packages/admin/src/hooks/table/columns/use-payout-table-columns.tsx
index 333fd36e1..364389300 100644
--- a/packages/admin/src/hooks/table/columns/use-payout-table-columns.tsx
+++ b/packages/admin/src/hooks/table/columns/use-payout-table-columns.tsx
@@ -1,29 +1,18 @@
-import { StatusBadge } from "@medusajs/ui"
import { createColumnHelper } from "@tanstack/react-table"
import { useMemo } from "react"
import { useTranslation } from "react-i18next"
import { DateCell } from "../../../components/table/table-cells/common/date-cell"
-import { getStylizedAmount } from "../../../lib/money-amount-helpers"
-import { PayoutDTO } from "@mercurjs/types"
+import { MoneyAmountCell } from "../../../components/table/table-cells/common/money-amount-cell"
+import { StatusCell } from "../../../components/table/table-cells/common/status-cell"
+import {
+ TextCell,
+ TextHeader,
+} from "../../../components/table/table-cells/common/text-cell"
+import { getPayoutStatusProps } from "../../../pages/payouts/common/utils"
+import { AdminPayout } from "../../api/payouts"
-const columnHelper = createColumnHelper<PayoutDTO>()
-
-const payoutStatusColor = (status: string) => {
- switch (status) {
- case "paid":
- return "green"
- case "processing":
- return "orange"
- case "pending":
- return "grey"
- case "failed":
- case "canceled":
- return "red"
- default:
- return "grey"
- }
-}
+const columnHelper = createColumnHelper<AdminPayout>()
export const usePayoutTableColumns = () => {
const { t } = useTranslation()
@@ -31,28 +20,52 @@ export const usePayoutTableColumns = () => {
return useMemo(
() => [
columnHelper.accessor("display_id", {
- header: t("fields.id"),
- cell: ({ getValue }) => `#${getValue()}`,
+ header: () => <TextHeader text={t("fields.id")} />,
+ cell: ({ getValue }) => <TextCell text={`#${getValue()}`} />,
+ }),
+ columnHelper.display({
+ id: "store",
+ header: () => <TextHeader text={t("payoutAccounts.fields.store")} />,
+ cell: ({ row }) => (
+ <TextCell
+ text={
+ row.original.seller?.name ??
+ row.original.account?.seller?.name ??
+ undefined
+ }
+ />
+ ),
+ }),
+ columnHelper.accessor("order_id", {
+ header: () => <TextHeader text={t("payouts.fields.order")} />,
+ cell: ({ getValue, row }) => (
+ <TextCell
+ text={
+ row.original.order?.display_id
+ ? `#${row.original.order.display_id}`
+ : getValue() ?? undefined
+ }
+ />
+ ),
+ }),
+ columnHelper.accessor("amount", {
+ header: () => <TextHeader text={t("fields.amount")} />,
+ cell: ({ getValue, row }) => (
+ <MoneyAmountCell
+ amount={Number(getValue())}
+ currencyCode={row.original.currency_code}
+ />
+ ),
}),
columnHelper.accessor("status", {
- header: t("fields.status"),
+ header: () => <TextHeader text={t("fields.status")} />,
cell: ({ getValue }) => {
- const status = getValue()
- const label = status.charAt(0).toUpperCase() + status.slice(1)
- return (
- <StatusBadge color={payoutStatusColor(status)}>
- {label}
- </StatusBadge>
- )
+ const { color, label } = getPayoutStatusProps(getValue(), t)
+ return <StatusCell color={color}>{label}</StatusCell>
},
}),
- columnHelper.accessor("amount", {
- header: t("fields.amount"),
- cell: ({ getValue, row }) =>
- getStylizedAmount(getValue() as number, row.original.currency_code),
- }),
columnHelper.accessor("created_at", {
- header: t("fields.createdAt"),
+ header: () => <TextHeader text={t("fields.createdAt")} />,
cell: ({ getValue }) => <DateCell date={getValue()} />,
}),
],
diff --git a/packages/admin/src/hooks/table/filters/use-payout-account-table-filters.tsx b/packages/admin/src/hooks/table/filters/use-payout-account-table-filters.tsx
new file mode 100644
index 000000000..538bef170
--- /dev/null
+++ b/packages/admin/src/hooks/table/filters/use-payout-account-table-filters.tsx
@@ -0,0 +1,58 @@
+import { useTranslation } from "react-i18next"
+
+import { Filter } from "../../../components/table/data-table"
+import { useSellers } from "../../api/sellers"
+
+export const usePayoutAccountTableFilters = () => {
+ const { t } = useTranslation()
+
+ const { sellers } = useSellers({ limit: 1000, fields: "id,name" })
+
+ const statusFilter: Filter = {
+ key: "status",
+ label: t("fields.status"),
+ type: "select",
+ multiple: true,
+ options: ["pending", "active", "restricted", "rejected"].map((value) => ({
+ label: t(`payoutAccounts.status.${value}`),
+ value,
+ })),
+ }
+
+ const kycFilter: Filter = {
+ key: "kyc_status",
+ label: t("payoutAccounts.fields.kycStatus"),
+ type: "select",
+ multiple: true,
+ options: [
+ "pending_submission",
+ "pending_approval",
+ "approved",
+ "refused",
+ ].map((value) => ({
+ label: t(`payoutAccounts.kycStatus.${value}`),
+ value,
+ })),
+ }
+
+ const sellerFilter: Filter[] = sellers?.length
+ ? [
+ {
+ key: "seller_id",
+ label: t("payoutAccounts.fields.store"),
+ type: "select",
+ multiple: true,
+ options: sellers
+ .filter((seller) => seller.name)
+ .map((seller) => ({ label: seller.name, value: seller.id })),
+ },
+ ]
+ : []
+
+ const dateFilters: Filter[] = [
+ { label: t("fields.createdAt"), key: "created_at" },
+ { label: t("fields.updatedAt"), key: "updated_at" },
+ ].map((f) => ({ key: f.key, label: f.label, type: "date" }))
+
+ return [statusFilter, kycFilter, ...sellerFilter, ...dateFilters]
+}
diff --git a/packages/admin/src/hooks/table/filters/use-payout-table-filters.tsx b/packages/admin/src/hooks/table/filters/use-payout-table-filters.tsx
new file mode 100644
index 000000000..652233b5b
--- /dev/null
+++ b/packages/admin/src/hooks/table/filters/use-payout-table-filters.tsx
@@ -0,0 +1,43 @@
+import { useTranslation } from "react-i18next"
+
+import { Filter } from "../../../components/table/data-table"
+import { PAYOUT_STATUSES } from "../../../pages/payouts/common/utils"
+import { useSellers } from "../../api/sellers"
+
+export const usePayoutTableFilters = () => {
+ const { t } = useTranslation()
+
+ const { sellers } = useSellers({ limit: 1000, fields: "id,name" })
+
+ const statusFilter: Filter = {
+ key: "status",
+ label: t("fields.status"),
+ type: "select",
+ multiple: true,
+ options: PAYOUT_STATUSES.map((value) => ({
+ label: t(`payouts.status.${value}`),
+ value,
+ })),
+ }
+
+ const sellerFilter: Filter[] = sellers?.length
+ ? [
+ {
+ key: "seller_id",
+ label: t("payoutAccounts.fields.store"),
+ type: "select",
+ multiple: true,
+ options: sellers
+ .filter((seller) => seller.name)
+ .map((seller) => ({ label: seller.name, value: seller.id })),
+ },
+ ]
+ : []
+
+ const dateFilters: Filter[] = [
+ { label: t("fields.createdAt"), key: "created_at" },
+ { label: t("fields.updatedAt"), key: "updated_at" },
+ ].map((f) => ({ key: f.key, label: f.label, type: "date" }))
+
+ return [statusFilter, ...sellerFilter, ...dateFilters]
+}
diff --git a/packages/admin/src/hooks/table/query/use-payout-account-table-query.tsx b/packages/admin/src/hooks/table/query/use-payout-account-table-query.tsx
new file mode 100644
index 000000000..bdf8fb0dd
--- /dev/null
+++ b/packages/admin/src/hooks/table/query/use-payout-account-table-query.tsx
@@ -0,0 +1,45 @@
+import { useQueryParams } from "../../use-query-params"
+
+type UsePayoutAccountTableQueryProps = {
+ prefix?: string
+ pageSize?: number
+}
+
+export const usePayoutAccountTableQuery = ({
+ prefix,
+ pageSize = 20,
+}: UsePayoutAccountTableQueryProps) => {
+ const queryObject = useQueryParams(
+ [
+ "offset",
+ "q",
+ "order",
+ "status",
+ "kyc_status",
+ "seller_id",
+ "created_at",
+ "updated_at",
+ ],
+ prefix,
+ )
+
+ const { offset, q, order, status, kyc_status, seller_id, created_at, updated_at } =
+ queryObject
+
+ const searchParams = {
+ limit: pageSize,
+ offset: offset ? Number(offset) : 0,
+ order: order ?? "-created_at",
+ status: status?.split(","),
+ kyc_status: kyc_status?.split(","),
+ seller_id: seller_id?.split(","),
+ created_at: created_at ? JSON.parse(created_at) : undefined,
+ updated_at: updated_at ? JSON.parse(updated_at) : undefined,
+ ...(q ? { q } : {}),
+ }
+
+ return {
+ searchParams,
+ raw: queryObject,
+ }
+}
diff --git a/packages/admin/src/hooks/table/query/use-payout-table-query.tsx b/packages/admin/src/hooks/table/query/use-payout-table-query.tsx
index 6bdbbc02a..30a22ecb4 100644
--- a/packages/admin/src/hooks/table/query/use-payout-table-query.tsx
+++ b/packages/admin/src/hooks/table/query/use-payout-table-query.tsx
@@ -10,20 +10,32 @@ export const usePayoutTableQuery = ({
pageSize = 20,
}: UsePayoutTableQueryProps) => {
const queryObject = useQueryParams(
- ["offset", "q", "order", "created_at", "updated_at", "status"],
+ [
+ "offset",
+ "q",
+ "order",
+ "created_at",
+ "updated_at",
+ "status",
+ "seller_id",
+ "order_id",
+ ],
prefix,
)
- const { offset, q, order, created_at, updated_at, status } = queryObject
+ const { offset, q, order, created_at, updated_at, status, seller_id, order_id } =
+ queryObject
const searchParams: Record<string, string | number | string[] | undefined> = {
limit: pageSize,
offset: offset ? Number(offset) : 0,
- q,
order: order ?? "-created_at",
created_at: created_at ? JSON.parse(created_at) : undefined,
updated_at: updated_at ? JSON.parse(updated_at) : undefined,
status: status?.split(","),
+ seller_id: seller_id?.split(","),
+ order_id: order_id?.split(","),
+ ...(q ? { q } : {}),
}
return {
diff --git a/packages/admin/src/i18n/translations/$schema.json b/packages/admin/src/i18n/translations/$schema.json
index 5086e8877..bd793b418 100644
--- a/packages/admin/src/i18n/translations/$schema.json
+++ b/packages/admin/src/i18n/translations/$schema.json
@@ -7587,28 +7587,188 @@
"status": {
"type": "object",
"properties": {
- "paid": {
+ "pending": {
+ "type": "string"
+ },
+ "on_hold": {
"type": "string"
},
"processing": {
"type": "string"
},
- "pending": {
+ "paid": {
"type": "string"
},
"failed": {
"type": "string"
},
- "canceled": {
+ "aborted": {
"type": "string"
}
},
"required": [
- "paid",
- "processing",
"pending",
+ "on_hold",
+ "processing",
+ "paid",
"failed",
- "canceled"
+ "aborted"
+ ],
+ "additionalProperties": false
+ },
+ "fields": {
+ "type": "object",
+ "properties": {
+ "order": {
+ "type": "string"
+ },
+ "payoutAccount": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "order",
+ "payoutAccount"
+ ],
+ "additionalProperties": false
+ },
+ "actions": {
+ "type": "object",
+ "properties": {
+ "retry": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "retry"
+ ],
+ "additionalProperties": false
+ },
+ "retry": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "successToast": {
+ "type": "string"
+ },
+ "disabledTooltip": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "title",
+ "description",
+ "successToast",
+ "disabledTooltip"
+ ],
+ "additionalProperties": false
+ },
+ "reversals": {
+ "type": "object",
+ "properties": {
+ "header": {
+ "type": "string"
+ },
+ "refund": {
+ "type": "string"
+ },
+ "noRecordsTitle": {
+ "type": "string"
+ },
+ "noRecordsMessage": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "header",
+ "refund",
+ "noRecordsTitle",
+ "noRecordsMessage"
+ ],
+ "additionalProperties": false
+ },
+ "references": {
+ "type": "object",
+ "properties": {
+ "header": {
+ "type": "string"
+ },
+ "empty": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "header",
+ "empty"
+ ],
+ "additionalProperties": false
+ },
+ "statusReasons": {
+ "type": "object",
+ "properties": {
+ "account_not_ready": {
+ "type": "string"
+ },
+ "account_payouts_disabled": {
+ "type": "string"
+ },
+ "order_not_ready": {
+ "type": "string"
+ },
+ "order_aborted": {
+ "type": "string"
+ },
+ "payment_not_ready": {
+ "type": "string"
+ },
+ "payment_failed": {
+ "type": "string"
+ },
+ "payment_canceled": {
+ "type": "string"
+ },
+ "payment_refunded": {
+ "type": "string"
+ },
+ "payout_not_ready": {
+ "type": "string"
+ },
+ "refund_aborted": {
+ "type": "string"
+ },
+ "refund_absorbed": {
+ "type": "string"
+ },
+ "invalid_amount": {
+ "type": "string"
+ },
+ "provider_error": {
+ "type": "string"
+ },
+ "other": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "account_not_ready",
+ "account_payouts_disabled",
+ "order_not_ready",
+ "order_aborted",
+ "payment_not_ready",
+ "payment_failed",
+ "payment_canceled",
+ "payment_refunded",
+ "payout_not_ready",
+ "refund_aborted",
+ "refund_absorbed",
+ "invalid_amount",
+ "provider_error",
+ "other"
],
"additionalProperties": false
}
@@ -7616,7 +7776,251 @@
"required": [
"domain",
"list",
- "status"
+ "status",
+ "fields",
+ "actions",
+ "retry",
+ "reversals",
+ "references",
+ "statusReasons"
+ ],
+ "additionalProperties": false
+ },
+ "payoutAccounts": {
+ "type": "object",
+ "properties": {
+ "domain": {
+ "type": "string"
+ },
+ "subtitle": {
+ "type": "string"
+ },
+ "noStore": {
+ "type": "string"
+ },
+ "enabled": {
+ "type": "string"
+ },
+ "disabled": {
+ "type": "string"
+ },
+ "list": {
+ "type": "object",
+ "properties": {
+ "noRecordsMessage": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "noRecordsMessage"
+ ],
+ "additionalProperties": false
+ },
+ "fields": {
+ "type": "object",
+ "properties": {
+ "store": {
+ "type": "string"
+ },
+ "kycStatus": {
+ "type": "string"
+ },
+ "payoutsEnabled": {
+ "type": "string"
+ },
+ "chargesEnabled": {
+ "type": "string"
+ },
+ "detailsSubmitted": {
+ "type": "string"
+ },
+ "lastSyncedAt": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "store",
+ "kycStatus",
+ "payoutsEnabled",
+ "chargesEnabled",
+ "detailsSubmitted",
+ "lastSyncedAt"
+ ],
+ "additionalProperties": false
+ },
+ "status": {
+ "type": "object",
+ "properties": {
+ "pending": {
+ "type": "string"
+ },
+ "active": {
+ "type": "string"
+ },
+ "restricted": {
+ "type": "string"
+ },
+ "rejected": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "pending",
+ "active",
+ "restricted",
+ "rejected"
+ ],
+ "additionalProperties": false
+ },
+ "kycStatus": {
+ "type": "object",
+ "properties": {
+ "pending_submission": {
+ "type": "string"
+ },
+ "pending_approval": {
+ "type": "string"
+ },
+ "approved": {
+ "type": "string"
+ },
+ "refused": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "pending_submission",
+ "pending_approval",
+ "approved",
+ "refused"
+ ],
+ "additionalProperties": false
+ },
+ "actions": {
+ "type": "object",
+ "properties": {
+ "sync": {
+ "type": "string"
+ },
+ "refreshLink": {
+ "type": "string"
+ },
+ "openLink": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "sync",
+ "refreshLink",
+ "openLink"
+ ],
+ "additionalProperties": false
+ },
+ "sync": {
+ "type": "object",
+ "properties": {
+ "successToast": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "successToast"
+ ],
+ "additionalProperties": false
+ },
+ "refreshLink": {
+ "type": "object",
+ "properties": {
+ "successToast": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "successToast"
+ ],
+ "additionalProperties": false
+ },
+ "capabilities": {
+ "type": "object",
+ "properties": {
+ "header": {
+ "type": "string"
+ },
+ "kycUnknown": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "header",
+ "kycUnknown"
+ ],
+ "additionalProperties": false
+ },
+ "storeSection": {
+ "type": "object",
+ "properties": {
+ "header": {
+ "type": "string"
+ },
+ "empty": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "header",
+ "empty"
+ ],
+ "additionalProperties": false
+ },
+ "disabledReason": {
+ "type": "object",
+ "properties": {
+ "pastDue": {
+ "type": "string"
+ },
+ "pendingVerification": {
+ "type": "string"
+ },
+ "requirements": {
+ "type": "string"
+ },
+ "rejected": {
+ "type": "string"
+ },
+ "underReview": {
+ "type": "string"
+ },
+ "other": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "pastDue",
+ "pendingVerification",
+ "requirements",
+ "rejected",
+ "underReview",
+ "other"
+ ],
+ "additionalProperties": false
+ }
+ },
+ "required": [
+ "domain",
+ "subtitle",
+ "noStore",
+ "enabled",
+ "disabled",
+ "list",
+ "fields",
+ "status",
+ "kycStatus",
+ "actions",
+ "sync",
+ "refreshLink",
+ "capabilities",
+ "storeSection",
+ "disabledReason"
],
"additionalProperties": false
},
@@ -17103,6 +17507,7 @@
"customerGroups",
"orders",
"payouts",
+ "payoutAccounts",
"draftOrders",
"stockLocations",
"shippingProfile",
diff --git a/packages/admin/src/i18n/translations/ar.json b/packages/admin/src/i18n/translations/ar.json
index ac004686b..6f2666641 100644
--- a/packages/admin/src/i18n/translations/ar.json
+++ b/packages/admin/src/i18n/translations/ar.json
@@ -3617,8 +3617,7 @@
"paid": "مدفوع",
"processing": "قيد المعالجة",
"pending": "قيد الانتظار",
- "failed": "فشل",
- "canceled": "ملغى"
+ "failed": "فشل"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/bg.json b/packages/admin/src/i18n/translations/bg.json
index 8f5820e1c..b9e3c2b4b 100644
--- a/packages/admin/src/i18n/translations/bg.json
+++ b/packages/admin/src/i18n/translations/bg.json
@@ -3617,8 +3617,7 @@
"paid": "Изплатено",
"processing": "В обработка",
"pending": "В изчакване",
- "failed": "Неуспешно",
- "canceled": "Анулирана"
+ "failed": "Неуспешно"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/bs.json b/packages/admin/src/i18n/translations/bs.json
index c38c48042..8cc2065e3 100644
--- a/packages/admin/src/i18n/translations/bs.json
+++ b/packages/admin/src/i18n/translations/bs.json
@@ -3615,8 +3615,7 @@
"paid": "Isplaćeno",
"processing": "U obradi",
"pending": "Na čekanju",
- "failed": "Neuspješno",
- "canceled": "Otkazano"
+ "failed": "Neuspješno"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/cs.json b/packages/admin/src/i18n/translations/cs.json
index f93d0c727..68b2cec77 100644
--- a/packages/admin/src/i18n/translations/cs.json
+++ b/packages/admin/src/i18n/translations/cs.json
@@ -3613,8 +3613,7 @@
"paid": "Vyplaceno",
"processing": "Zpracovává se",
"pending": "Čeká se",
- "failed": "Selhalo",
- "canceled": "Zrušeno"
+ "failed": "Selhalo"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/de.json b/packages/admin/src/i18n/translations/de.json
index b4f003a74..24083277f 100644
--- a/packages/admin/src/i18n/translations/de.json
+++ b/packages/admin/src/i18n/translations/de.json
@@ -3618,8 +3618,7 @@
"paid": "Bezahlt",
"processing": "In Bearbeitung",
"pending": "Ausstehend",
- "failed": "Fehlgeschlagen",
- "canceled": "Abgebrochen"
+ "failed": "Fehlgeschlagen"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/el.json b/packages/admin/src/i18n/translations/el.json
index 3713a91c9..fbff0b55f 100644
--- a/packages/admin/src/i18n/translations/el.json
+++ b/packages/admin/src/i18n/translations/el.json
@@ -3617,8 +3617,7 @@
"paid": "Πληρώθηκε",
"processing": "Σε επεξεργασία",
"pending": "Σε εκκρεμότητα",
- "failed": "Απέτυχε",
- "canceled": "Ακυρώθηκε"
+ "failed": "Απέτυχε"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/en.json b/packages/admin/src/i18n/translations/en.json
index 6857899b1..8fa1d06df 100644
--- a/packages/admin/src/i18n/translations/en.json
+++ b/packages/admin/src/i18n/translations/en.json
@@ -1856,14 +1856,111 @@
"payouts": {
"domain": "Payouts",
"list": {
- "empty": "No payouts found"
+ "empty": "Payouts appear once a fulfilled and paid order is processed."
},
"status": {
- "paid": "Paid",
- "processing": "Processing",
"pending": "Pending",
+ "on_hold": "On hold",
+ "processing": "Processing",
+ "paid": "Paid",
"failed": "Failed",
- "canceled": "Canceled"
+ "aborted": "Aborted"
+ },
+ "fields": {
+ "order": "Order",
+ "payoutAccount": "Payout account"
+ },
+ "actions": {
+ "retry": "Retry payout"
+ },
+ "retry": {
+ "title": "Retry payout",
+ "description": "The payout is evaluated again and sent to the payout provider once the order is ready.",
+ "successToast": "Payout retried.",
+ "disabledTooltip": "Only pending, failed or on-hold payouts can be retried."
+ },
+ "reversals": {
+ "header": "Reversals",
+ "refund": "Refund",
+ "noRecordsTitle": "No reversals",
+ "noRecordsMessage": "Refunds on this order have not taken anything back from the store."
+ },
+ "references": {
+ "header": "References",
+ "empty": "This payout has no linked records."
+ },
+ "statusReasons": {
+ "account_not_ready": "The store's payout account cannot receive payouts yet.",
+ "account_payouts_disabled": "Payouts are disabled on the store's payout account.",
+ "order_not_ready": "The order is not fulfilled yet.",
+ "order_aborted": "The order was canceled.",
+ "payment_not_ready": "The order's payment is not captured yet.",
+ "payment_failed": "The order's payment failed.",
+ "payment_canceled": "The order's payment was canceled.",
+ "payment_refunded": "The order's payment was refunded in full.",
+ "payout_not_ready": "The payout for this order has not been sent yet.",
+ "refund_aborted": "The refund was canceled.",
+ "refund_absorbed": "The refund was deducted before the payout was sent.",
+ "invalid_amount": "The amount to pay out is not valid.",
+ "provider_error": "The payout provider returned an error.",
+ "other": "This payout needs attention."
+ }
+ },
+ "payoutAccounts": {
+ "domain": "Payout accounts",
+ "subtitle": "Every store's payout account, mirrored from its payout provider.",
+ "noStore": "This account is not linked to a store.",
+ "enabled": "Enabled",
+ "disabled": "Disabled",
+ "list": {
+ "noRecordsMessage": "Payout accounts appear once a store starts onboarding with a payout provider."
+ },
+ "fields": {
+ "store": "Store",
+ "kycStatus": "KYC status",
+ "payoutsEnabled": "Payouts",
+ "chargesEnabled": "Charges",
+ "detailsSubmitted": "Details submitted",
+ "lastSyncedAt": "Last synced"
+ },
+ "status": {
+ "pending": "Pending",
+ "active": "Active",
+ "restricted": "Restricted",
+ "rejected": "Rejected"
+ },
+ "kycStatus": {
+ "pending_submission": "Pending submission",
+ "pending_approval": "Pending approval",
+ "approved": "Approved",
+ "refused": "Refused"
+ },
+ "actions": {
+ "sync": "Sync from provider",
+ "refreshLink": "Refresh onboarding link",
+ "openLink": "Open onboarding link"
+ },
+ "sync": {
+ "successToast": "Account synced from the payout provider."
+ },
+ "refreshLink": {
+ "successToast": "A new onboarding link was created."
+ },
+ "capabilities": {
+ "header": "Capabilities",
+ "kycUnknown": "Not reported"
+ },
+ "storeSection": {
+ "header": "Payout account",
+ "empty": "This store has no payout account yet."
+ },
+ "disabledReason": {
+ "pastDue": "Payouts are paused: the payout provider is waiting for overdue information from this store.",
+ "pendingVerification": "Payouts are paused while the payout provider verifies this store's information.",
+ "requirements": "Payouts are paused until this store completes onboarding with the payout provider.",
+ "rejected": "The payout provider rejected this account. Payouts to this store are not possible.",
+ "underReview": "The payout provider is reviewing this account. Payouts are paused until the review ends.",
+ "other": "The payout provider has disabled payouts for this account."
}
},
"draftOrders": {
diff --git a/packages/admin/src/i18n/translations/es.json b/packages/admin/src/i18n/translations/es.json
index 0e94840e7..d9b0b7344 100644
--- a/packages/admin/src/i18n/translations/es.json
+++ b/packages/admin/src/i18n/translations/es.json
@@ -3633,8 +3633,7 @@
"paid": "Pagado",
"processing": "Procesando",
"pending": "Pendiente",
- "failed": "Fallido",
- "canceled": "Cancelado"
+ "failed": "Fallido"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/fa.json b/packages/admin/src/i18n/translations/fa.json
index ba5ef3091..3fe809edc 100644
--- a/packages/admin/src/i18n/translations/fa.json
+++ b/packages/admin/src/i18n/translations/fa.json
@@ -3617,8 +3617,7 @@
"paid": "پرداخت‌شده",
"processing": "در حال پردازش",
"pending": "در انتظار",
- "failed": "ناموفق",
- "canceled": "لغو شده"
+ "failed": "ناموفق"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/fr.json b/packages/admin/src/i18n/translations/fr.json
index 450e7c33e..655274c6f 100644
--- a/packages/admin/src/i18n/translations/fr.json
+++ b/packages/admin/src/i18n/translations/fr.json
@@ -3618,8 +3618,7 @@
"paid": "Payé",
"processing": "En cours de traitement",
"pending": "En attente",
- "failed": "Échec",
- "canceled": "Annulé"
+ "failed": "Échec"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/he.json b/packages/admin/src/i18n/translations/he.json
index df9a2d216..197d1dfe3 100644
--- a/packages/admin/src/i18n/translations/he.json
+++ b/packages/admin/src/i18n/translations/he.json
@@ -3613,8 +3613,7 @@
"paid": "שולם",
"processing": "בעיבוד",
"pending": "ממתין",
- "failed": "נכשל",
- "canceled": "בוטל"
+ "failed": "נכשל"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/hu.json b/packages/admin/src/i18n/translations/hu.json
index b9cad6b39..2e976c383 100644
--- a/packages/admin/src/i18n/translations/hu.json
+++ b/packages/admin/src/i18n/translations/hu.json
@@ -3616,8 +3616,7 @@
"paid": "Kifizetve",
"processing": "Feldolgozás alatt",
"pending": "Függőben",
- "failed": "Sikertelen",
- "canceled": "Törölt"
+ "failed": "Sikertelen"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/id.json b/packages/admin/src/i18n/translations/id.json
index 48d7cb709..41c75e2d3 100644
--- a/packages/admin/src/i18n/translations/id.json
+++ b/packages/admin/src/i18n/translations/id.json
@@ -3613,8 +3613,7 @@
"paid": "Dibayar",
"processing": "Sedang diproses",
"pending": "Tertunda",
- "failed": "Gagal",
- "canceled": "Dibatalkan"
+ "failed": "Gagal"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/it.json b/packages/admin/src/i18n/translations/it.json
index 0a1f7ec7e..9cdc4c260 100644
--- a/packages/admin/src/i18n/translations/it.json
+++ b/packages/admin/src/i18n/translations/it.json
@@ -3618,8 +3618,7 @@
"paid": "Pagato",
"processing": "In elaborazione",
"pending": "In attesa",
- "failed": "Fallito",
- "canceled": "Annullato"
+ "failed": "Fallito"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/ja.json b/packages/admin/src/i18n/translations/ja.json
index 39b582262..f5d51d6f0 100644
--- a/packages/admin/src/i18n/translations/ja.json
+++ b/packages/admin/src/i18n/translations/ja.json
@@ -3618,8 +3618,7 @@
"paid": "支払い済み",
"processing": "処理中",
"pending": "保留中",
- "failed": "失敗",
- "canceled": "キャンセル済み"
+ "failed": "失敗"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/ko.json b/packages/admin/src/i18n/translations/ko.json
index 50af83851..b8cf4ef22 100644
--- a/packages/admin/src/i18n/translations/ko.json
+++ b/packages/admin/src/i18n/translations/ko.json
@@ -3613,8 +3613,7 @@
"paid": "지급 완료",
"processing": "처리 중",
"pending": "대기 중",
- "failed": "실패",
- "canceled": "취소됨"
+ "failed": "실패"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/lt.json b/packages/admin/src/i18n/translations/lt.json
index accdd935a..18c5981e8 100644
--- a/packages/admin/src/i18n/translations/lt.json
+++ b/packages/admin/src/i18n/translations/lt.json
@@ -3617,8 +3617,7 @@
"paid": "Apmokėta",
"processing": "Apdorojama",
"pending": "Laukia",
- "failed": "Nepavyko",
- "canceled": "Atšauktas"
+ "failed": "Nepavyko"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/mk.json b/packages/admin/src/i18n/translations/mk.json
index b2872139f..542d9442e 100644
--- a/packages/admin/src/i18n/translations/mk.json
+++ b/packages/admin/src/i18n/translations/mk.json
@@ -3617,8 +3617,7 @@
"paid": "Платено",
"processing": "Во обработка",
"pending": "Во очекување",
- "failed": "Не успеа",
- "canceled": "Откажано"
+ "failed": "Не успеа"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/mn.json b/packages/admin/src/i18n/translations/mn.json
index bd47f5fdd..cd5816e95 100644
--- a/packages/admin/src/i18n/translations/mn.json
+++ b/packages/admin/src/i18n/translations/mn.json
@@ -3617,8 +3617,7 @@
"paid": "Төлөгдсөн",
"processing": "Боловсруулж байна",
"pending": "Хүлээгдэж буй",
- "failed": "Амжилтгүй",
- "canceled": "Цуцлагдсан"
+ "failed": "Амжилтгүй"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/nl.json b/packages/admin/src/i18n/translations/nl.json
index 81db99ec1..cd9dd4a8d 100644
--- a/packages/admin/src/i18n/translations/nl.json
+++ b/packages/admin/src/i18n/translations/nl.json
@@ -3616,8 +3616,7 @@
"paid": "Betaald",
"processing": "Wordt verwerkt",
"pending": "In behandeling",
- "failed": "Mislukt",
- "canceled": "Geannuleerd"
+ "failed": "Mislukt"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/pl.json b/packages/admin/src/i18n/translations/pl.json
index ebf244ec6..36534d024 100644
--- a/packages/admin/src/i18n/translations/pl.json
+++ b/packages/admin/src/i18n/translations/pl.json
@@ -1866,8 +1866,7 @@
"paid": "Opłacone",
"processing": "Przetwarzane",
"pending": "Oczekujące",
- "failed": "Nieudane",
- "canceled": "Anulowane"
+ "failed": "Nieudane"
}
},
"draftOrders": {
diff --git a/packages/admin/src/i18n/translations/ptBR.json b/packages/admin/src/i18n/translations/ptBR.json
index 29a22c612..9518de561 100644
--- a/packages/admin/src/i18n/translations/ptBR.json
+++ b/packages/admin/src/i18n/translations/ptBR.json
@@ -3618,8 +3618,7 @@
"paid": "Pago",
"processing": "Processando",
"pending": "Pendente",
- "failed": "Falhou",
- "canceled": "Cancelado"
+ "failed": "Falhou"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/ro.json b/packages/admin/src/i18n/translations/ro.json
index 29ee6a64b..2e104143b 100644
--- a/packages/admin/src/i18n/translations/ro.json
+++ b/packages/admin/src/i18n/translations/ro.json
@@ -3617,8 +3617,7 @@
"paid": "Plătit",
"processing": "În procesare",
"pending": "În așteptare",
- "failed": "A eșuat",
- "canceled": "Anulat"
+ "failed": "A eșuat"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/ru.json b/packages/admin/src/i18n/translations/ru.json
index faddf567b..c1b7766ab 100644
--- a/packages/admin/src/i18n/translations/ru.json
+++ b/packages/admin/src/i18n/translations/ru.json
@@ -3617,8 +3617,7 @@
"paid": "Выплачено",
"processing": "В обработке",
"pending": "В обработке",
- "failed": "Неудача",
- "canceled": "Отменен"
+ "failed": "Неудача"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/th.json b/packages/admin/src/i18n/translations/th.json
index 238f3727b..53536c694 100644
--- a/packages/admin/src/i18n/translations/th.json
+++ b/packages/admin/src/i18n/translations/th.json
@@ -3618,8 +3618,7 @@
"paid": "จ่ายแล้ว",
"processing": "กำลังดำเนินการ",
"pending": "รอดำเนินการ",
- "failed": "ล้มเหลว",
- "canceled": "ยกเลิก"
+ "failed": "ล้มเหลว"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/tr.json b/packages/admin/src/i18n/translations/tr.json
index 0b35bd7f8..5b2c63580 100644
--- a/packages/admin/src/i18n/translations/tr.json
+++ b/packages/admin/src/i18n/translations/tr.json
@@ -3617,8 +3617,7 @@
"paid": "Ödendi",
"processing": "İşleniyor",
"pending": "Beklemede",
- "failed": "Başarısız",
- "canceled": "İptal edildi"
+ "failed": "Başarısız"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/uk.json b/packages/admin/src/i18n/translations/uk.json
index 3bea35395..7475594f3 100644
--- a/packages/admin/src/i18n/translations/uk.json
+++ b/packages/admin/src/i18n/translations/uk.json
@@ -3618,8 +3618,7 @@
"paid": "Виплачено",
"processing": "Обробляється",
"pending": "Очікує",
- "failed": "Не вдалося",
- "canceled": "Скасовано"
+ "failed": "Не вдалося"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/vi.json b/packages/admin/src/i18n/translations/vi.json
index 802c554e5..1468ca5fb 100644
--- a/packages/admin/src/i18n/translations/vi.json
+++ b/packages/admin/src/i18n/translations/vi.json
@@ -3613,8 +3613,7 @@
"paid": "Đã thanh toán",
"processing": "Đang xử lý",
"pending": "Đang chờ xử lý",
- "failed": "Thất bại",
- "canceled": "Đã hủy"
+ "failed": "Thất bại"
}
},
"marketplace": {
diff --git a/packages/admin/src/i18n/translations/zhCN.json b/packages/admin/src/i18n/translations/zhCN.json
index eb352b1aa..857f15087 100644
--- a/packages/admin/src/i18n/translations/zhCN.json
+++ b/packages/admin/src/i18n/translations/zhCN.json
@@ -3613,8 +3613,7 @@
"paid": "已支付",
"processing": "处理中",
"pending": "处理中",
- "failed": "失败",
- "canceled": "已取消"
+ "failed": "失败"
}
},
"marketplace": {
diff --git a/packages/admin/src/lib/payouts.ts b/packages/admin/src/lib/payouts.ts
new file mode 100644
index 000000000..b37e9c4c5
--- /dev/null
+++ b/packages/admin/src/lib/payouts.ts
@@ -0,0 +1,19 @@
+import { PayoutAccountDTO, PayoutDTO, PayoutReversalDTO } from "@mercurjs/types"
+
+type PayoutSeller = { id: string; name: string | null; handle: string | null }
+
+export type AdminPayout = PayoutDTO & {
+ reversals?: PayoutReversalDTO[]
+ order?: { id: string; display_id: number } | null
+ seller?: PayoutSeller | null
+ account?: {
+ id: string
+ status: string
+ seller?: PayoutSeller | null
+ } | null
+}
+
+export type AdminPayoutAccount = PayoutAccountDTO & {
+ seller?: { id: string; name: string; handle: string } | null
+ onboarding?: { id: string; data: Record<string, unknown> | null } | null
+}
diff --git a/packages/admin/src/pages/payout-accounts/common/utils.ts b/packages/admin/src/pages/payout-accounts/common/utils.ts
new file mode 100644
index 000000000..0f3446c3a
--- /dev/null
+++ b/packages/admin/src/pages/payout-accounts/common/utils.ts
@@ -0,0 +1,41 @@
+import { TFunction } from "i18next"
+
+type BadgeColor = "green" | "red" | "blue" | "orange" | "grey" | "purple"
+
+export const getPayoutAccountStatusProps = (
+ status: string,
+ t: TFunction,
+): { color: BadgeColor; label: string } => {
+ const colors: Record<string, BadgeColor> = {
+ pending: "orange",
+ active: "green",
+ restricted: "red",
+ rejected: "red",
+ }
+
+ return {
+ color: colors[status] ?? "grey",
+ label: t(`payoutAccounts.status.${status}`, { defaultValue: status }),
+ }
+}
+
+export const getPayoutAccountKycProps = (
+ status: string | null,
+ t: TFunction,
+): { color: BadgeColor; label: string } | null => {
+ if (!status) {
+ return null
+ }
+
+ const colors: Record<string, BadgeColor> = {
+ pending_submission: "orange",
+ pending_approval: "blue",
+ approved: "green",
+ refused: "red",
+ }
+
+ return {
+ color: colors[status] ?? "grey",
+ label: t(`payoutAccounts.kycStatus.${status}`, { defaultValue: status }),
+ }
+}
diff --git a/packages/admin/src/pages/payout-accounts/index.ts b/packages/admin/src/pages/payout-accounts/index.ts
new file mode 100644
index 000000000..c289d0b2d
--- /dev/null
+++ b/packages/admin/src/pages/payout-accounts/index.ts
@@ -0,0 +1,2 @@
+export { PayoutAccountListPage } from "./payout-account-list/payout-account-list"
+export { PayoutAccountDetailPage } from "./payout-account-detail/payout-account-detail"
diff --git a/packages/admin/src/pages/payout-accounts/payout-account-detail/breadcrumb.tsx b/packages/admin/src/pages/payout-accounts/payout-account-detail/breadcrumb.tsx
new file mode 100644
index 000000000..1491dabf9
--- /dev/null
+++ b/packages/admin/src/pages/payout-accounts/payout-account-detail/breadcrumb.tsx
@@ -0,0 +1,21 @@
+import { UIMatch } from "react-router-dom"
+
+import { usePayoutAccount } from "../../../hooks/api/payout-accounts"
+
+export const PayoutAccountDetailBreadcrumb = (props: UIMatch) => {
+ const { id } = props.params || {}
+
+ const { payout_account } = usePayoutAccount(id!, undefined, {
+ enabled: Boolean(id),
+ })
+
+ if (!payout_account) {
+ return null
+ }
+
+ return (
+ <span>
+ {payout_account.seller?.name ?? payout_account.id}
+ </span>
+ )
+}
diff --git a/packages/admin/src/pages/payout-accounts/payout-account-detail/components/payout-account-capabilities-section.tsx b/packages/admin/src/pages/payout-accounts/payout-account-detail/components/payout-account-capabilities-section.tsx
new file mode 100644
index 000000000..3a00bb0d3
--- /dev/null
+++ b/packages/admin/src/pages/payout-accounts/payout-account-detail/components/payout-account-capabilities-section.tsx
@@ -0,0 +1,90 @@
+import { Container, Heading, Text, clx } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { AdminPayoutAccount } from "../../../../lib/payouts"
+import { getPayoutAccountKycProps } from "../../common/utils"
+
+type Tone = "green" | "orange" | "red" | "blue" | "grey" | "purple"
+
+const barColor: Record<Tone, string> = {
+ green: "bg-ui-tag-green-icon",
+ orange: "bg-ui-tag-orange-icon",
+ red: "bg-ui-tag-red-icon",
+ blue: "bg-ui-tag-blue-icon",
+ grey: "bg-ui-tag-neutral-icon",
+ purple: "bg-ui-tag-purple-icon",
+}
+
+const CapabilityCard = ({
+ label,
+ value,
+ tone,
+ testId,
+}: {
+ label: string
+ value: string
+ tone: Tone
+ testId: string
+}) => (
+ <div
+ className="shadow-elevation-card-rest bg-ui-bg-component text-ui-fg-subtle flex items-center gap-x-3 rounded-md px-3 py-1.5"
+ data-testid={testId}
+ >
+ <div className={clx("h-8 w-1 rounded-full", barColor[tone])} />
+ <div>
+ <Text weight="plus" size="small">
+ {label}
+ </Text>
+ <Text size="small">{value}</Text>
+ </div>
+ </div>
+)
+
+export const PayoutAccountCapabilitiesSection = ({
+ account,
+}: {
+ account: AdminPayoutAccount
+}) => {
+ const { t } = useTranslation()
+
+ const kyc = getPayoutAccountKycProps(account.kyc_status, t)
+ const enabled = (flag: boolean) =>
+ flag ? t("payoutAccounts.enabled") : t("payoutAccounts.disabled")
+
+ return (
+ <Container
+ className="flex flex-col gap-y-4"
+ data-testid="payout-account-capabilities-section"
+ >
+ <div className="flex items-center justify-between">
+ <Heading level="h2">{t("payoutAccounts.capabilities.header")}</Heading>
+ </div>
+ <div className="grid grid-cols-2 gap-3">
+ <CapabilityCard
+ label={t("payoutAccounts.fields.payoutsEnabled")}
+ value={enabled(account.payouts_enabled)}
+ tone={account.payouts_enabled ? "green" : "orange"}
+ testId="payout-account-capabilities-payouts"
+ />
+ <CapabilityCard
+ label={t("payoutAccounts.fields.chargesEnabled")}
+ value={enabled(account.charges_enabled)}
+ tone={account.charges_enabled ? "green" : "orange"}
+ testId="payout-account-capabilities-charges"
+ />
+ <CapabilityCard
+ label={t("payoutAccounts.fields.kycStatus")}
+ value={kyc?.label ?? t("payoutAccounts.capabilities.kycUnknown")}
+ tone={kyc?.color ?? "grey"}
+ testId="payout-account-capabilities-kyc"
+ />
+ <CapabilityCard
+ label={t("payoutAccounts.fields.detailsSubmitted")}
+ value={account.details_submitted ? t("general.yes") : t("general.no")}
+ tone={account.details_submitted ? "green" : "orange"}
+ testId="payout-account-capabilities-details"
+ />
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/admin/src/pages/payout-accounts/payout-account-detail/components/payout-account-general-section.tsx b/packages/admin/src/pages/payout-accounts/payout-account-detail/components/payout-account-general-section.tsx
new file mode 100644
index 000000000..cba03c612
--- /dev/null
+++ b/packages/admin/src/pages/payout-accounts/payout-account-detail/components/payout-account-general-section.tsx
@@ -0,0 +1,106 @@
+import { ArrowPath, ArrowUpRightOnBox, Link as LinkIcon } from "@medusajs/icons"
+import { Container, Heading, StatusBadge, toast } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { ActionMenu } from "../../../../components/common/action-menu"
+import { SectionRow } from "../../../../components/common/section"
+import { useRefreshPayoutAccountLink, useSyncPayoutAccount } from "../../../../hooks/api/payout-accounts"
+import { AdminPayoutAccount } from "../../../../lib/payouts"
+import { useDate } from "../../../../hooks/use-date"
+import { getPayoutAccountStatusProps } from "../../common/utils"
+
+export const PayoutAccountGeneralSection = ({
+ account,
+}: {
+ account: AdminPayoutAccount
+}) => {
+ const { t } = useTranslation()
+ const { getFullDate } = useDate()
+
+ const sync = useSyncPayoutAccount(account.id)
+ const refreshLink = useRefreshPayoutAccountLink(account.id)
+
+ const status = getPayoutAccountStatusProps(account.status, t)
+ const onboardingUrl =
+ typeof account.onboarding?.data?.url === "string"
+ ? account.onboarding.data.url
+ : null
+
+ const handleSync = () => {
+ sync.mutate(undefined, {
+ onSuccess: () => toast.success(t("payoutAccounts.sync.successToast")),
+ onError: (error) => toast.error(error.message),
+ })
+ }
+
+ const handleRefreshLink = () => {
+ refreshLink.mutate(undefined, {
+ onSuccess: () =>
+ toast.success(t("payoutAccounts.refreshLink.successToast")),
+ onError: (error) => toast.error(error.message),
+ })
+ }
+
+ const formatDate = (value: Date | string | null | undefined) =>
+ value ? getFullDate({ date: value, includeTime: true }) : "-"
+
+ return (
+ <Container className="divide-y p-0" data-testid="payout-account-general-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading data-testid="payout-account-general-section-heading">
+ {account.seller?.name ?? account.id}
+ </Heading>
+ <div className="flex items-center gap-x-2">
+ <StatusBadge
+ color={status.color}
+ data-testid="payout-account-general-section-status-badge"
+ >
+ {status.label}
+ </StatusBadge>
+ <ActionMenu
+ data-testid="payout-account-general-section-action-menu"
+ groups={[
+ {
+ actions: [
+ {
+ label: t("payoutAccounts.actions.sync"),
+ icon: <ArrowPath />,
+ onClick: handleSync,
+ permission: "payouts:edit",
+ },
+ {
+ label: t("payoutAccounts.actions.refreshLink"),
+ icon: <LinkIcon />,
+ onClick: handleRefreshLink,
+ permission: "payouts:edit",
+ },
+ ...(onboardingUrl
+ ? [
+ {
+ label: t("payoutAccounts.actions.openLink"),
+ icon: <ArrowUpRightOnBox />,
+ onClick: () => window.open(onboardingUrl, "_blank"),
+ },
+ ]
+ : []),
+ ],
+ },
+ ]}
+ />
+ </div>
+ </div>
+ <SectionRow
+ title={t("payoutAccounts.fields.lastSyncedAt")}
+ value={formatDate(account.last_synced_at)}
+ />
+ <SectionRow
+ title={t("fields.createdAt")}
+ value={formatDate(account.created_at)}
+ />
+ <SectionRow
+ title={t("fields.updatedAt")}
+ value={formatDate(account.updated_at)}
+ />
+ </Container>
+ )
+}
diff --git a/packages/admin/src/pages/payout-accounts/payout-account-detail/components/payout-account-status-alert.tsx b/packages/admin/src/pages/payout-accounts/payout-account-detail/components/payout-account-status-alert.tsx
new file mode 100644
index 000000000..15b99f3c2
--- /dev/null
+++ b/packages/admin/src/pages/payout-accounts/payout-account-detail/components/payout-account-status-alert.tsx
@@ -0,0 +1,47 @@
+import { Alert } from "@medusajs/ui"
+import { TFunction } from "i18next"
+import { useTranslation } from "react-i18next"
+
+import { AdminPayoutAccount } from "../../../../lib/payouts"
+
+// Providers report why an account cannot be paid out as a dotted code
+// (`requirements.past_due`, `rejected.fraud`, ...); only its family matters here.
+const disabledReasonMessage = (reason: string, t: TFunction) => {
+ if (reason === "requirements.past_due") {
+ return t("payoutAccounts.disabledReason.pastDue")
+ }
+ if (reason === "requirements.pending_verification") {
+ return t("payoutAccounts.disabledReason.pendingVerification")
+ }
+ if (reason.startsWith("requirements.")) {
+ return t("payoutAccounts.disabledReason.requirements")
+ }
+ if (reason.startsWith("rejected.")) {
+ return t("payoutAccounts.disabledReason.rejected")
+ }
+ if (reason === "under_review" || reason === "listed") {
+ return t("payoutAccounts.disabledReason.underReview")
+ }
+ return t("payoutAccounts.disabledReason.other")
+}
+
+export const PayoutAccountStatusAlert = ({
+ account,
+}: {
+ account: AdminPayoutAccount
+}) => {
+ const { t } = useTranslation()
+
+ if (!account.disabled_reason) {
+ return null
+ }
+
+ return (
+ <Alert
+ variant={account.disabled_reason.startsWith("rejected.") ? "error" : "warning"}
+ data-testid="payout-account-status-alert"
+ >
+ {disabledReasonMessage(account.disabled_reason, t)}
+ </Alert>
+ )
+}
diff --git a/packages/admin/src/pages/payout-accounts/payout-account-detail/components/payout-account-store-section.tsx b/packages/admin/src/pages/payout-accounts/payout-account-detail/components/payout-account-store-section.tsx
new file mode 100644
index 000000000..80ce0b006
--- /dev/null
+++ b/packages/admin/src/pages/payout-accounts/payout-account-detail/components/payout-account-store-section.tsx
@@ -0,0 +1,67 @@
+import { TriangleRightMini } from "@medusajs/icons"
+import { Avatar, Container, Heading, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+import { AdminPayoutAccount } from "../../../../lib/payouts"
+
+export const PayoutAccountStoreSection = ({
+ account,
+}: {
+ account: AdminPayoutAccount
+}) => {
+ const { t } = useTranslation()
+ const seller = account.seller
+
+ return (
+ <Container className="p-0" data-testid="payout-account-store-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("payoutAccounts.fields.store")}</Heading>
+ </div>
+ {seller?.id ? (
+ <div className="txt-small flex flex-col gap-2 px-2 pb-2">
+ <Link
+ to={`/stores/${seller.id}`}
+ className="outline-none focus-within:shadow-borders-interactive-with-focus rounded-md [&:hover>div]:bg-ui-bg-component-hover"
+ data-testid="payout-account-store-link"
+ >
+ <div className="shadow-elevation-card-rest bg-ui-bg-component rounded-md px-4 py-2 transition-colors">
+ <div className="flex items-center gap-3">
+ <Avatar
+ size="small"
+ fallback={(seller.name?.[0] ?? "?").toUpperCase()}
+ data-testid="payout-account-store-avatar"
+ />
+ <div className="flex flex-1 flex-col">
+ <span
+ className="text-ui-fg-base font-medium"
+ data-testid="payout-account-store-name"
+ >
+ {seller.name ?? seller.id}
+ </span>
+ {seller.handle && (
+ <span
+ className="text-ui-fg-subtle"
+ data-testid="payout-account-store-handle"
+ >
+ {seller.handle}
+ </span>
+ )}
+ </div>
+ <div className="flex size-7 items-center justify-center">
+ <TriangleRightMini className="text-ui-fg-muted rtl:rotate-180" />
+ </div>
+ </div>
+ </div>
+ </Link>
+ </div>
+ ) : (
+ <div className="border-t px-6 py-4">
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ {t("payoutAccounts.noStore")}
+ </Text>
+ </div>
+ )}
+ </Container>
+ )
+}
diff --git a/packages/admin/src/pages/payout-accounts/payout-account-detail/index.ts b/packages/admin/src/pages/payout-accounts/payout-account-detail/index.ts
new file mode 100644
index 000000000..15e902b70
--- /dev/null
+++ b/packages/admin/src/pages/payout-accounts/payout-account-detail/index.ts
@@ -0,0 +1,3 @@
+export { PayoutAccountDetailPage as Component } from "./payout-account-detail"
+export { PayoutAccountDetailBreadcrumb as Breadcrumb } from "./breadcrumb"
+export { payoutAccountLoader as loader } from "./loader"
diff --git a/packages/admin/src/pages/payout-accounts/payout-account-detail/loader.ts b/packages/admin/src/pages/payout-accounts/payout-account-detail/loader.ts
new file mode 100644
index 000000000..260f6aa16
--- /dev/null
+++ b/packages/admin/src/pages/payout-accounts/payout-account-detail/loader.ts
@@ -0,0 +1,17 @@
+import { LoaderFunctionArgs } from "react-router-dom"
+
+import { payoutAccountsQueryKeys } from "../../../hooks/api/payout-accounts"
+import { sdk } from "../../../lib/client"
+import { queryClient } from "../../../lib/query-client"
+
+const payoutAccountDetailQuery = (id: string) => ({
+ queryKey: payoutAccountsQueryKeys.detail(id),
+ queryFn: async () => sdk.admin.payoutAccounts.$id.query({ $id: id }),
+})
+
+export const payoutAccountLoader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = payoutAccountDetailQuery(id!)
+
+ return queryClient.ensureQueryData(query)
+}
diff --git a/packages/admin/src/pages/payout-accounts/payout-account-detail/payout-account-detail.tsx b/packages/admin/src/pages/payout-accounts/payout-account-detail/payout-account-detail.tsx
new file mode 100644
index 000000000..bf15e6085
--- /dev/null
+++ b/packages/admin/src/pages/payout-accounts/payout-account-detail/payout-account-detail.tsx
@@ -0,0 +1,73 @@
+import { Children, ReactNode } from "react"
+import { useLoaderData, useParams } from "react-router-dom"
+
+import { WidgetZone } from "@mercurjs/dashboard-shared"
+import { TwoColumnPageSkeleton } from "../../../components/common/skeleton"
+import { TwoColumnPage } from "../../../components/layout/pages"
+import { usePayoutAccount } from "../../../hooks/api/payout-accounts"
+import { PayoutAccountCapabilitiesSection } from "./components/payout-account-capabilities-section"
+import { PayoutAccountGeneralSection } from "./components/payout-account-general-section"
+import { PayoutsSection } from "../../payouts/common/components/payouts-section"
+import { PayoutAccountStatusAlert } from "./components/payout-account-status-alert"
+import { PayoutAccountStoreSection } from "./components/payout-account-store-section"
+import { payoutAccountLoader } from "./loader"
+
+const Root = ({ children }: { children?: ReactNode }) => {
+ const { id } = useParams()
+
+ const initialData = useLoaderData() as Awaited<
+ ReturnType<typeof payoutAccountLoader>
+ >
+
+ const { payout_account, isLoading, isError, error } = usePayoutAccount(
+ id!,
+ undefined,
+ { initialData },
+ )
+
+ if (isLoading || !payout_account) {
+ return (
+ <TwoColumnPageSkeleton mainSections={2} sidebarSections={2} showJSON />
+ )
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return Children.count(children) > 0 ? (
+ <TwoColumnPage data={payout_account} showJSON>
+ {children}
+ </TwoColumnPage>
+ ) : (
+ <TwoColumnPage data={payout_account} showJSON>
+ <TwoColumnPage.Main>
+ <WidgetZone id="payout_accounts.detail.main" data={payout_account}>
+ <PayoutAccountStatusAlert account={payout_account} />
+ <PayoutAccountGeneralSection account={payout_account} />
+ <PayoutsSection
+ scope={{ account_id: payout_account.id }}
+ prefix="pacpay"
+ data-testid="payout-account-payouts-section"
+ />
+ </WidgetZone>
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <WidgetZone id="payout_accounts.detail.side" data={payout_account}>
+ <PayoutAccountStoreSection account={payout_account} />
+ <PayoutAccountCapabilitiesSection account={payout_account} />
+ </WidgetZone>
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
+ )
+}
+
+export const PayoutAccountDetailPage = Object.assign(Root, {
+ Main: TwoColumnPage.Main,
+ Sidebar: TwoColumnPage.Sidebar,
+ MainStatusAlert: PayoutAccountStatusAlert,
+ MainGeneralSection: PayoutAccountGeneralSection,
+ MainPayoutsSection: PayoutsSection,
+ SidebarStoreSection: PayoutAccountStoreSection,
+ SidebarCapabilitiesSection: PayoutAccountCapabilitiesSection,
+})
diff --git a/packages/admin/src/pages/payout-accounts/payout-account-list/index.ts b/packages/admin/src/pages/payout-accounts/payout-account-list/index.ts
new file mode 100644
index 000000000..35255f3f1
--- /dev/null
+++ b/packages/admin/src/pages/payout-accounts/payout-account-list/index.ts
@@ -0,0 +1 @@
+export { PayoutAccountListPage as Component } from "./payout-account-list"
diff --git a/packages/admin/src/pages/payout-accounts/payout-account-list/payout-account-list.tsx b/packages/admin/src/pages/payout-accounts/payout-account-list/payout-account-list.tsx
new file mode 100644
index 000000000..90fff99d5
--- /dev/null
+++ b/packages/admin/src/pages/payout-accounts/payout-account-list/payout-account-list.tsx
@@ -0,0 +1,158 @@
+import { Children, ReactNode } from "react"
+import { Container, Heading, Text } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { useTranslation } from "react-i18next"
+
+import { WidgetZone } from "@mercurjs/dashboard-shared"
+
+import { SingleColumnPage } from "../../../components/layout/pages"
+import { _DataTable } from "../../../components/table/data-table"
+import { usePayoutAccounts } from "../../../hooks/api/payout-accounts"
+import { usePayoutAccountTableColumns } from "../../../hooks/table/columns/use-payout-account-table-columns"
+import { usePayoutAccountTableFilters } from "../../../hooks/table/filters/use-payout-account-table-filters"
+import { usePayoutAccountTableQuery } from "../../../hooks/table/query/use-payout-account-table-query"
+import { useDataTable } from "../../../hooks/use-data-table"
+
+const PAGE_SIZE = 20
+
+export const PayoutAccountListTitle = () => {
+ const { t } = useTranslation()
+
+ return (
+ <div>
+ <Heading data-testid="payout-account-list-heading">
+ {t("payoutAccounts.domain")}
+ </Heading>
+ <Text className="text-ui-fg-subtle" size="small">
+ {t("payoutAccounts.subtitle")}
+ </Text>
+ </div>
+ )
+}
+
+export const PayoutAccountListActions = ({
+ children,
+}: {
+ children?: ReactNode
+}) => {
+ return (
+ <div className="flex items-center gap-x-2">
+ {Children.count(children) > 0 ? children : null}
+ </div>
+ )
+}
+
+export const PayoutAccountListHeader = ({
+ children,
+}: {
+ children?: ReactNode
+}) => {
+ return (
+ <div
+ className="flex items-center justify-between px-6 py-4"
+ data-testid="payout-account-list-header"
+ >
+ {Children.count(children) > 0 ? (
+ children
+ ) : (
+ <>
+ <PayoutAccountListTitle />
+ <PayoutAccountListActions />
+ </>
+ )}
+ </div>
+ )
+}
+
+export const PayoutAccountListDataTable = () => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = usePayoutAccountTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const { payout_accounts, count, isError, error, isLoading } =
+ usePayoutAccounts(searchParams, {
+ placeholderData: keepPreviousData,
+ })
+
+ const columns = usePayoutAccountTableColumns()
+ const filters = usePayoutAccountTableFilters()
+
+ const { table } = useDataTable({
+ data: payout_accounts ?? [],
+ columns,
+ enablePagination: true,
+ count: count ?? 0,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <_DataTable
+ columns={columns}
+ table={table}
+ pagination
+ navigateTo={(row) => row.original.id}
+ count={count ?? 0}
+ filters={filters}
+ isLoading={isLoading}
+ pageSize={PAGE_SIZE}
+ orderBy={[
+ { key: "status", label: t("fields.status") },
+ { key: "kyc_status", label: t("payoutAccounts.fields.kycStatus") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ defaultOrder="-created_at"
+ queryObject={raw}
+ noRecords={{
+ message: t("payoutAccounts.list.noRecordsMessage"),
+ }}
+ />
+ )
+}
+
+export const PayoutAccountListTable = ({
+ children,
+}: {
+ children?: ReactNode
+}) => {
+ return (
+ <Container
+ className="divide-y p-0"
+ data-testid="payout-account-list-container"
+ >
+ {Children.count(children) > 0 ? (
+ children
+ ) : (
+ <>
+ <PayoutAccountListHeader />
+ <PayoutAccountListDataTable />
+ </>
+ )}
+ </Container>
+ )
+}
+
+const Root = ({ children }: { children?: ReactNode }) => {
+ return (
+ <SingleColumnPage>
+ <WidgetZone id="payout_accounts.list">
+ {Children.count(children) > 0 ? children : <PayoutAccountListTable />}
+ </WidgetZone>
+ </SingleColumnPage>
+ )
+}
+
+export const PayoutAccountListPage = Object.assign(Root, {
+ Table: PayoutAccountListTable,
+ Header: PayoutAccountListHeader,
+ HeaderTitle: PayoutAccountListTitle,
+ HeaderActions: PayoutAccountListActions,
+ DataTable: PayoutAccountListDataTable,
+})
diff --git a/packages/admin/src/pages/payouts/common/components/payouts-section.tsx b/packages/admin/src/pages/payouts/common/components/payouts-section.tsx
new file mode 100644
index 000000000..b26864d63
--- /dev/null
+++ b/packages/admin/src/pages/payouts/common/components/payouts-section.tsx
@@ -0,0 +1,94 @@
+import { CurrencyDollar } from "@medusajs/icons"
+import { Container, Heading } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+
+import { _DataTable } from "../../../../components/table/data-table"
+import { usePayouts } from "../../../../hooks/api/payouts"
+import { usePayoutTableColumns } from "../../../../hooks/table/columns/use-payout-table-columns"
+import { usePayoutTableFilters } from "../../../../hooks/table/filters/use-payout-table-filters"
+import { usePayoutTableQuery } from "../../../../hooks/table/query/use-payout-table-query"
+import { useDataTable } from "../../../../hooks/use-data-table"
+
+const PAGE_SIZE = 10
+
+type PayoutsSectionProps = {
+ /** Narrows the payouts to one payout account or one store; the Store column and filter drop out. */
+ scope: { account_id: string } | { seller_id: string }
+ prefix: string
+ "data-testid"?: string
+}
+
+export const PayoutsSection = ({
+ scope,
+ prefix,
+ "data-testid": testId = "payouts-section",
+}: PayoutsSectionProps) => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = usePayoutTableQuery({
+ prefix,
+ pageSize: PAGE_SIZE,
+ })
+
+ const { payouts, count, isError, error, isLoading } = usePayouts(
+ { ...searchParams, ...scope },
+ { placeholderData: keepPreviousData }
+ )
+
+ const base = usePayoutTableColumns()
+ const columns = useMemo(
+ () => base.filter((column) => column.id !== "store"),
+ [base]
+ )
+ const filters = usePayoutTableFilters().filter(
+ (filter) => filter.key !== "seller_id"
+ )
+
+ const { table } = useDataTable({
+ data: payouts ?? [],
+ columns,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ count: count ?? 0,
+ pageSize: PAGE_SIZE,
+ prefix,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0" data-testid={testId}>
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2" data-testid={`${testId}-heading`}>
+ {t("payouts.domain")}
+ </Heading>
+ </div>
+ <_DataTable
+ columns={columns}
+ table={table}
+ pagination
+ navigateTo={(row) => `/payouts/${row.original.id}`}
+ count={count ?? 0}
+ filters={filters}
+ isLoading={isLoading}
+ pageSize={PAGE_SIZE}
+ orderBy={[
+ { key: "status", label: t("fields.status") },
+ { key: "amount", label: t("fields.amount") },
+ { key: "created_at", label: t("fields.createdAt") },
+ ]}
+ defaultOrder="-created_at"
+ queryObject={raw}
+ prefix={prefix}
+ noRecords={{
+ message: t("payouts.list.empty"),
+ icon: <CurrencyDollar className="text-ui-fg-subtle" />,
+ }}
+ />
+ </Container>
+ )
+}
diff --git a/packages/admin/src/pages/payouts/common/hooks/use-retry-payout-action.tsx b/packages/admin/src/pages/payouts/common/hooks/use-retry-payout-action.tsx
new file mode 100644
index 000000000..97ad674fe
--- /dev/null
+++ b/packages/admin/src/pages/payouts/common/hooks/use-retry-payout-action.tsx
@@ -0,0 +1,34 @@
+import { toast, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { useRetryPayout } from "../../../../hooks/api/payouts"
+import { AdminPayout } from "../../../../lib/payouts"
+import { RETRYABLE_PAYOUT_STATUSES } from "../utils"
+
+export const useRetryPayoutAction = (payout: AdminPayout) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const { mutateAsync } = useRetryPayout(payout.id)
+
+ const canRetry = RETRYABLE_PAYOUT_STATUSES.includes(payout.status)
+
+ const handleRetry = async () => {
+ const confirmed = await prompt({
+ title: t("payouts.retry.title"),
+ description: t("payouts.retry.description"),
+ confirmText: t("actions.confirm"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!confirmed) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => toast.success(t("payouts.retry.successToast")),
+ onError: (error) => toast.error(error.message),
+ })
+ }
+
+ return { handleRetry, canRetry }
+}
diff --git a/packages/admin/src/pages/payouts/common/utils.ts b/packages/admin/src/pages/payouts/common/utils.ts
new file mode 100644
index 000000000..86b62937c
--- /dev/null
+++ b/packages/admin/src/pages/payouts/common/utils.ts
@@ -0,0 +1,64 @@
+import { TFunction } from "i18next"
+
+type BadgeColor = "green" | "red" | "blue" | "orange" | "grey" | "purple"
+
+export const PAYOUT_STATUSES = [
+ "pending",
+ "on_hold",
+ "processing",
+ "paid",
+ "failed",
+ "aborted",
+] as const
+
+export const RETRYABLE_PAYOUT_STATUSES = ["failed", "on_hold", "pending"]
+
+const STATUS_COLORS: Record<string, BadgeColor> = {
+ pending: "grey",
+ on_hold: "orange",
+ processing: "blue",
+ paid: "green",
+ failed: "red",
+ aborted: "red",
+}
+
+export const getPayoutStatusProps = (
+ status: string,
+ t: TFunction,
+): { color: BadgeColor; label: string } => ({
+ color: STATUS_COLORS[status] ?? "grey",
+ label: t(`payouts.status.${status}`, { defaultValue: status }),
+})
+
+export const PAYOUT_STATUS_REASONS = [
+ "account_not_ready",
+ "account_payouts_disabled",
+ "order_not_ready",
+ "order_aborted",
+ "payment_not_ready",
+ "payment_failed",
+ "payment_canceled",
+ "payment_refunded",
+ "payout_not_ready",
+ "refund_aborted",
+ "refund_absorbed",
+ "invalid_amount",
+ "provider_error",
+] as const
+
+type PayoutStatusReason = (typeof PAYOUT_STATUS_REASONS)[number]
+
+const isPayoutStatusReason = (reason: string): reason is PayoutStatusReason =>
+ (PAYOUT_STATUS_REASONS as readonly string[]).includes(reason)
+
+export const getPayoutStatusReasonLabel = (reason: string, t: TFunction) =>
+ isPayoutStatusReason(reason)
+ ? t(`payouts.statusReasons.${reason}`)
+ : t("payouts.statusReasons.other")
+
+export const getPayoutStatusDetail = (
+ data: Record<string, unknown> | null | undefined
+) => {
+ const detail = data?.status_detail
+ return typeof detail === "string" && detail.length > 0 ? detail : null
+}
diff --git a/packages/admin/src/pages/payouts/payout-detail/components/payout-general-section.tsx b/packages/admin/src/pages/payouts/payout-detail/components/payout-general-section.tsx
index 9ceaac582..0a1634e6b 100644
--- a/packages/admin/src/pages/payouts/payout-detail/components/payout-general-section.tsx
+++ b/packages/admin/src/pages/payouts/payout-detail/components/payout-general-section.tsx
@@ -1,77 +1,66 @@
-import { Container, Heading, StatusBadge, Text } from "@medusajs/ui"
-import { PayoutDTO } from "@mercurjs/types"
+import { ArrowPath } from "@medusajs/icons"
+import { Container, Heading, StatusBadge } from "@medusajs/ui"
import { useTranslation } from "react-i18next"
-import { getStylizedAmount } from "../../../../lib/money-amount-helpers"
-const payoutStatusColor = (status: string) => {
- switch (status) {
- case "paid":
- return "green"
- case "processing":
- return "orange"
- case "pending":
- return "grey"
- case "failed":
- case "canceled":
- return "red"
- default:
- return "grey"
- }
-}
+import { ActionMenu } from "../../../../components/common/action-menu"
+import { SectionRow } from "../../../../components/common/section"
+import { AdminPayout } from "../../../../lib/payouts"
+import { useDate } from "../../../../hooks/use-date"
+import { getStylizedAmount } from "../../../../lib/money-amount-helpers"
+import { useRetryPayoutAction } from "../../common/hooks/use-retry-payout-action"
+import { getPayoutStatusProps } from "../../common/utils"
-export const PayoutGeneralSection = ({ payout }: { payout: PayoutDTO }) => {
+export const PayoutGeneralSection = ({ payout }: { payout: AdminPayout }) => {
const { t } = useTranslation()
+ const { getFullDate } = useDate()
+ const { handleRetry, canRetry } = useRetryPayoutAction(payout)
+
+ const status = getPayoutStatusProps(payout.status, t)
- const statusText = t(`payouts.status.${payout.status}`, {
- defaultValue: payout.status.charAt(0).toUpperCase() + payout.status.slice(1),
- })
+ const formatDate = (value: Date | string | null | undefined) =>
+ value ? getFullDate({ date: value, includeTime: true }) : "-"
return (
- <Container className="divide-y p-0">
+ <Container className="divide-y p-0" data-testid="payout-general-section">
<div className="flex items-center justify-between px-6 py-4">
- <Heading>#{payout.display_id}</Heading>
+ <Heading data-testid="payout-general-section-heading">
+ {getStylizedAmount(Number(payout.amount), payout.currency_code)}
+ </Heading>
<div className="flex items-center gap-x-2">
- <StatusBadge color={payoutStatusColor(payout.status)}>
- {statusText}
+ <StatusBadge
+ color={status.color}
+ data-testid="payout-general-section-status-badge"
+ >
+ {status.label}
</StatusBadge>
+ <ActionMenu
+ data-testid="payout-general-section-action-menu"
+ groups={[
+ {
+ actions: [
+ {
+ label: t("payouts.actions.retry"),
+ icon: <ArrowPath />,
+ onClick: handleRetry,
+ permission: "payouts:edit",
+ disabled: !canRetry,
+ disabledTooltip: t("payouts.retry.disabledTooltip"),
+ },
+ ],
+ },
+ ]}
+ />
</div>
</div>
- <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
- <Text size="small" leading="compact" weight="plus">
- {t("fields.amount")}
- </Text>
- <Text size="small" leading="compact">
- {getStylizedAmount(payout.amount as number, payout.currency_code)}
- </Text>
- </div>
- <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
- <Text size="small" leading="compact" weight="plus">
- {t("fields.createdAt")}
- </Text>
- <Text size="small" leading="compact">
- {new Date(payout.created_at).toLocaleDateString(undefined, {
- year: "numeric",
- month: "long",
- day: "numeric",
- hour: "2-digit",
- minute: "2-digit",
- })}
- </Text>
- </div>
- <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
- <Text size="small" leading="compact" weight="plus">
- {t("fields.updatedAt")}
- </Text>
- <Text size="small" leading="compact">
- {new Date(payout.updated_at).toLocaleDateString(undefined, {
- year: "numeric",
- month: "long",
- day: "numeric",
- hour: "2-digit",
- minute: "2-digit",
- })}
- </Text>
- </div>
+ <SectionRow title={t("fields.id")} value={`#${payout.display_id}`} />
+ <SectionRow
+ title={t("fields.createdAt")}
+ value={formatDate(payout.created_at)}
+ />
+ <SectionRow
+ title={t("fields.updatedAt")}
+ value={formatDate(payout.updated_at)}
+ />
</Container>
)
}
diff --git a/packages/admin/src/pages/payouts/payout-detail/components/payout-references-section.tsx b/packages/admin/src/pages/payouts/payout-detail/components/payout-references-section.tsx
new file mode 100644
index 000000000..0cd31571f
--- /dev/null
+++ b/packages/admin/src/pages/payouts/payout-detail/components/payout-references-section.tsx
@@ -0,0 +1,57 @@
+import { BuildingStorefront, CurrencyDollar, ShoppingCart } from "@medusajs/icons"
+import { Container, Heading, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { SidebarLink } from "../../../../components/common/sidebar-link/sidebar-link"
+import { AdminPayout } from "../../../../lib/payouts"
+
+export const PayoutReferencesSection = ({ payout }: { payout: AdminPayout }) => {
+ const { t } = useTranslation()
+ const seller = payout.seller ?? payout.account?.seller
+
+ const hasReferences = !!seller?.id || !!payout.account_id || !!payout.order_id
+
+ return (
+ <Container className="p-0" data-testid="payout-references-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("payouts.references.header")}</Heading>
+ </div>
+ {!hasReferences && (
+ <div className="border-t px-6 py-4">
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ {t("payouts.references.empty")}
+ </Text>
+ </div>
+ )}
+ {payout.order_id && (
+ <SidebarLink
+ to={`/orders/${payout.order_id}`}
+ labelKey={t("payouts.fields.order")}
+ descriptionKey={
+ payout.order?.display_id ? `#${payout.order.display_id}` : payout.order_id
+ }
+ icon={<ShoppingCart />}
+ dataTestid="payout-reference-order"
+ />
+ )}
+ {seller?.id && (
+ <SidebarLink
+ to={`/stores/${seller.id}`}
+ labelKey={seller.name ?? seller.id}
+ descriptionKey={seller.handle ?? seller.id}
+ icon={<BuildingStorefront />}
+ dataTestid="payout-reference-store"
+ />
+ )}
+ {payout.account_id && (
+ <SidebarLink
+ to={`/payout-accounts/${payout.account_id}`}
+ labelKey={t("payouts.fields.payoutAccount")}
+ descriptionKey={payout.account_id}
+ icon={<CurrencyDollar />}
+ dataTestid="payout-reference-payout-account"
+ />
+ )}
+ </Container>
+ )
+}
diff --git a/packages/admin/src/pages/payouts/payout-detail/components/payout-reversals-section.tsx b/packages/admin/src/pages/payouts/payout-detail/components/payout-reversals-section.tsx
new file mode 100644
index 000000000..d086771e4
--- /dev/null
+++ b/packages/admin/src/pages/payouts/payout-detail/components/payout-reversals-section.tsx
@@ -0,0 +1,108 @@
+import { ExclamationCircle } from "@medusajs/icons"
+import { Container, Heading, Tooltip } from "@medusajs/ui"
+import { PayoutReversalDTO } from "@mercurjs/types"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+
+import { NoRecords } from "../../../../components/common/empty-table-content"
+import { _DataTable } from "../../../../components/table/data-table"
+import { DateCell } from "../../../../components/table/table-cells/common/date-cell"
+import { MoneyAmountCell } from "../../../../components/table/table-cells/common/money-amount-cell"
+import { StatusCell } from "../../../../components/table/table-cells/common/status-cell"
+import { TextCell } from "../../../../components/table/table-cells/common/text-cell"
+import { useDataTable } from "../../../../hooks/use-data-table"
+import { AdminPayout } from "../../../../lib/payouts"
+import {
+ getPayoutStatusDetail,
+ getPayoutStatusProps,
+ getPayoutStatusReasonLabel,
+} from "../../common/utils"
+
+const columnHelper = createColumnHelper<PayoutReversalDTO>()
+
+export const PayoutReversalsSection = ({ payout }: { payout: AdminPayout }) => {
+ const { t } = useTranslation()
+
+ const reversals = useMemo(() => payout.reversals ?? [], [payout.reversals])
+
+ const columns = useMemo(
+ () => [
+ columnHelper.accessor("created_at", {
+ header: () => t("fields.date"),
+ cell: ({ getValue }) => <DateCell date={getValue()} />,
+ }),
+ columnHelper.accessor("refund_id", {
+ header: () => t("payouts.reversals.refund"),
+ cell: ({ getValue }) => <TextCell text={getValue() ?? "-"} />,
+ }),
+ columnHelper.accessor("amount", {
+ header: () => t("fields.amount"),
+ cell: ({ getValue }) => (
+ <MoneyAmountCell
+ currencyCode={payout.currency_code}
+ amount={Number(getValue())}
+ />
+ ),
+ }),
+ columnHelper.accessor("status", {
+ header: () => t("fields.status"),
+ cell: ({ getValue, row }) => {
+ const status = getPayoutStatusProps(getValue(), t)
+ const reason = row.original.status_reason
+ const detail = getPayoutStatusDetail(row.original.data)
+ return (
+ <div className="flex h-full w-full items-center gap-x-2">
+ <StatusCell color={status.color}>{status.label}</StatusCell>
+ {reason && (
+ <Tooltip
+ content={
+ detail
+ ? `${getPayoutStatusReasonLabel(reason, t)} ${detail}`
+ : getPayoutStatusReasonLabel(reason, t)
+ }
+ >
+ <ExclamationCircle
+ className="text-ui-tag-orange-icon shrink-0"
+ data-testid={`payout-reversal-reason-${row.original.id}`}
+ />
+ </Tooltip>
+ )}
+ </div>
+ )
+ },
+ }),
+ ],
+ [t, payout.currency_code]
+ )
+
+ const { table } = useDataTable({
+ data: reversals,
+ count: reversals.length,
+ columns,
+ getRowId: (row) => row.id,
+ pageSize: Math.max(reversals.length, 1),
+ })
+
+ return (
+ <Container className="divide-y p-0" data-testid="payout-reversals-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("payouts.reversals.header")}</Heading>
+ </div>
+ {reversals.length > 0 ? (
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={Math.max(reversals.length, 1)}
+ count={reversals.length}
+ />
+ ) : (
+ <NoRecords
+ className="border-t"
+ title={t("payouts.reversals.noRecordsTitle")}
+ message={t("payouts.reversals.noRecordsMessage")}
+ />
+ )}
+ </Container>
+ )
+}
diff --git a/packages/admin/src/pages/payouts/payout-detail/components/payout-status-alert.tsx b/packages/admin/src/pages/payouts/payout-detail/components/payout-status-alert.tsx
new file mode 100644
index 000000000..ecc0695e1
--- /dev/null
+++ b/packages/admin/src/pages/payouts/payout-detail/components/payout-status-alert.tsx
@@ -0,0 +1,50 @@
+import { Alert, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { AdminPayout } from "../../../../lib/payouts"
+import {
+ getPayoutStatusDetail,
+ getPayoutStatusReasonLabel,
+} from "../../common/utils"
+
+const variantForStatus = (status: string) => {
+ switch (status) {
+ case "failed":
+ case "aborted":
+ return "error"
+ case "on_hold":
+ return "warning"
+ default:
+ return "info"
+ }
+}
+
+export const PayoutStatusAlert = ({ payout }: { payout: AdminPayout }) => {
+ const { t } = useTranslation()
+
+ if (!payout.status_reason) {
+ return null
+ }
+
+ const detail = getPayoutStatusDetail(payout.data)
+
+ return (
+ <Alert
+ variant={variantForStatus(payout.status)}
+ data-testid="payout-status-alert"
+ >
+ <div className="flex flex-col gap-y-1">
+ <span>{getPayoutStatusReasonLabel(payout.status_reason, t)}</span>
+ {detail && (
+ <Text
+ size="small"
+ className="text-ui-fg-subtle"
+ data-testid="payout-status-alert-detail"
+ >
+ {detail}
+ </Text>
+ )}
+ </div>
+ </Alert>
+ )
+}
diff --git a/packages/admin/src/pages/payouts/payout-detail/loader.ts b/packages/admin/src/pages/payouts/payout-detail/loader.ts
index 1147986bc..c9b3cb1a2 100644
--- a/packages/admin/src/pages/payouts/payout-detail/loader.ts
+++ b/packages/admin/src/pages/payouts/payout-detail/loader.ts
@@ -1,12 +1,14 @@
import { LoaderFunctionArgs } from "react-router-dom"
import { payoutsQueryKeys } from "../../../hooks/api/payouts"
+import { AdminPayout } from "../../../lib/payouts"
import { sdk } from "../../../lib/client"
import { queryClient } from "../../../lib/query-client"
const payoutDetailQuery = (id: string) => ({
queryKey: payoutsQueryKeys.detail(id),
- queryFn: async () => sdk.admin.payouts.$id.query({ $id: id }),
+ queryFn: async () =>
+ sdk.admin.payouts.$id.query({ $id: id }) as Promise<{ payout: AdminPayout }>,
})
export const payoutLoader = async ({ params }: LoaderFunctionArgs) => {
diff --git a/packages/admin/src/pages/payouts/payout-detail/payout-detail.tsx b/packages/admin/src/pages/payouts/payout-detail/payout-detail.tsx
index 68c746883..8ae2bce56 100644
--- a/packages/admin/src/pages/payouts/payout-detail/payout-detail.tsx
+++ b/packages/admin/src/pages/payouts/payout-detail/payout-detail.tsx
@@ -1,19 +1,29 @@
-import { ReactNode, Children } from "react"
-import { useParams } from "react-router-dom"
+import { Children, ReactNode } from "react"
+import { useLoaderData, useParams } from "react-router-dom"
import { WidgetZone } from "@mercurjs/dashboard-shared"
-import { SingleColumnPageSkeleton } from "../../../components/common/skeleton"
-import { SingleColumnPage } from "../../../components/layout/pages"
+import { TwoColumnPageSkeleton } from "../../../components/common/skeleton"
+import { TwoColumnPage } from "../../../components/layout/pages"
import { usePayout } from "../../../hooks/api/payouts"
import { PayoutGeneralSection } from "./components/payout-general-section"
+import { PayoutReferencesSection } from "./components/payout-references-section"
+import { PayoutReversalsSection } from "./components/payout-reversals-section"
+import { PayoutStatusAlert } from "./components/payout-status-alert"
+import { payoutLoader } from "./loader"
const Root = ({ children }: { children?: ReactNode }) => {
const { id } = useParams()
- const { payout, isLoading, isError, error } = usePayout(id!)
+ const initialData = useLoaderData() as Awaited<ReturnType<typeof payoutLoader>>
+
+ const { payout, isLoading, isError, error } = usePayout(id!, undefined, {
+ initialData,
+ })
if (isLoading || !payout) {
- return <SingleColumnPageSkeleton sections={1} />
+ return (
+ <TwoColumnPageSkeleton mainSections={2} sidebarSections={1} showJSON />
+ )
}
if (isError) {
@@ -21,18 +31,32 @@ const Root = ({ children }: { children?: ReactNode }) => {
}
return Children.count(children) > 0 ? (
- <SingleColumnPage data={payout} showJSON showMetadata>
+ <TwoColumnPage data={payout} showJSON showMetadata>
{children}
- </SingleColumnPage>
+ </TwoColumnPage>
) : (
- <SingleColumnPage data={payout} showJSON showMetadata>
- <WidgetZone id="payouts.detail.main" data={payout}>
- <PayoutGeneralSection payout={payout} />
- </WidgetZone>
- </SingleColumnPage>
+ <TwoColumnPage data={payout} showJSON showMetadata>
+ <TwoColumnPage.Main>
+ <WidgetZone id="payouts.detail.main" data={payout}>
+ <PayoutStatusAlert payout={payout} />
+ <PayoutGeneralSection payout={payout} />
+ <PayoutReversalsSection payout={payout} />
+ </WidgetZone>
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <WidgetZone id="payouts.detail.side" data={payout}>
+ <PayoutReferencesSection payout={payout} />
+ </WidgetZone>
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
)
}
export const PayoutDetailPage = Object.assign(Root, {
- GeneralSection: PayoutGeneralSection,
+ Main: TwoColumnPage.Main,
+ Sidebar: TwoColumnPage.Sidebar,
+ MainStatusAlert: PayoutStatusAlert,
+ MainGeneralSection: PayoutGeneralSection,
+ MainReversalsSection: PayoutReversalsSection,
+ SidebarReferencesSection: PayoutReferencesSection,
})
diff --git a/packages/admin/src/pages/payouts/payout-list/payout-list.tsx b/packages/admin/src/pages/payouts/payout-list/payout-list.tsx
index 772912be4..d3a9a3204 100644
--- a/packages/admin/src/pages/payouts/payout-list/payout-list.tsx
+++ b/packages/admin/src/pages/payouts/payout-list/payout-list.tsx
@@ -1,25 +1,74 @@
-import { Children, ReactNode } from "react"
+import { Children, ReactNode, useMemo } from "react"
+import { ArrowPath } from "@medusajs/icons"
import { Container, Heading } from "@medusajs/ui"
import { keepPreviousData } from "@tanstack/react-query"
+import { createColumnHelper } from "@tanstack/react-table"
import { useTranslation } from "react-i18next"
import { WidgetZone } from "@mercurjs/dashboard-shared"
+import { ActionMenu } from "../../../components/common/action-menu"
import { SingleColumnPage } from "../../../components/layout/pages"
import { _DataTable } from "../../../components/table/data-table"
import { usePayouts } from "../../../hooks/api/payouts"
+import { AdminPayout } from "../../../lib/payouts"
import { usePayoutTableColumns } from "../../../hooks/table/columns/use-payout-table-columns"
+import { usePayoutTableFilters } from "../../../hooks/table/filters/use-payout-table-filters"
import { usePayoutTableQuery } from "../../../hooks/table/query/use-payout-table-query"
import { useDataTable } from "../../../hooks/use-data-table"
-import { PayoutDTO } from "@mercurjs/types"
+import { useRetryPayoutAction } from "../common/hooks/use-retry-payout-action"
-const PAGE_SIZE = 10
+const PAGE_SIZE = 20
+
+const PayoutRowActions = ({ payout }: { payout: AdminPayout }) => {
+ const { t } = useTranslation()
+ const { handleRetry, canRetry } = useRetryPayoutAction(payout)
+
+ return (
+ <ActionMenu
+ data-testid={`payout-list-row-actions-${payout.id}`}
+ groups={[
+ {
+ actions: [
+ {
+ icon: <ArrowPath />,
+ label: t("payouts.actions.retry"),
+ onClick: handleRetry,
+ permission: "payouts:edit",
+ disabled: !canRetry,
+ disabledTooltip: t("payouts.retry.disabledTooltip"),
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<AdminPayout>()
+
+const useColumns = () => {
+ const base = usePayoutTableColumns()
+
+ return useMemo(
+ () => [
+ ...base,
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => <PayoutRowActions payout={row.original} />,
+ }),
+ ],
+ [base],
+ )
+}
export const PayoutListTitle = () => {
const { t } = useTranslation()
return (
- <Heading level="h2">{t("payouts.domain")}</Heading>
+ <Heading level="h2" data-testid="payout-list-heading">
+ {t("payouts.domain")}
+ </Heading>
)
}
@@ -60,10 +109,11 @@ export const PayoutListDataTable = () => {
},
)
- const columns = usePayoutTableColumns()
+ const columns = useColumns()
+ const filters = usePayoutTableFilters()
const { table } = useDataTable({
- data: (payouts as PayoutDTO[]) ?? [],
+ data: payouts ?? [],
columns,
enablePagination: true,
count: count ?? 0,
@@ -81,13 +131,17 @@ export const PayoutListDataTable = () => {
pagination
navigateTo={(row) => `/payouts/${row.original.id}`}
count={count ?? 0}
+ filters={filters}
search
isLoading={isLoading}
pageSize={PAGE_SIZE}
orderBy={[
+ { key: "status", label: t("fields.status") },
+ { key: "amount", label: t("fields.amount") },
{ key: "created_at", label: t("fields.createdAt") },
{ key: "updated_at", label: t("fields.updatedAt") },
]}
+ defaultOrder="-created_at"
queryObject={raw}
noRecords={{
message: t("payouts.list.empty"),
diff --git a/packages/admin/src/pages/stores/store-details/components/store-details.tsx b/packages/admin/src/pages/stores/store-details/components/store-details.tsx
index 1608fb7b2..d5106804f 100644
--- a/packages/admin/src/pages/stores/store-details/components/store-details.tsx
+++ b/packages/admin/src/pages/stores/store-details/components/store-details.tsx
@@ -21,11 +21,13 @@ import { StorePaymentDetailsSection } from "./store-payment-details-section";
import { StoreCompanyDetailsSection } from "./store-company-details-section";
import { StoreConfigurationSection } from "./store-configuration-section";
import { StoreAddressSection } from "./store-address-section";
+import { StorePayoutAccountSection } from "./store-payout-account-section";
import { StoreRegionsSection } from "./store-regions-section";
import { StoreMembersSection } from "./store-members-section";
import { StoreRequestSection } from "./store-request-section";
import { StoreOrdersSection } from "./store-orders-section";
import { StoreOffersSection } from "./store-offers-section";
+import { PayoutsSection } from "../../../payouts/common/components/payouts-section";
import {
StoreDetailHeader,
StoreDetailTitle,
@@ -136,6 +138,21 @@ const Root = ({ children }: { children?: ReactNode }) => {
},
]
: []),
+ ...(can("payouts")
+ ? [
+ {
+ id: "payouts",
+ label: t("payouts.domain"),
+ content: (
+ <PayoutsSection
+ scope={{ seller_id: seller.id }}
+ prefix="store-payouts"
+ data-testid="store-payouts-section"
+ />
+ ),
+ },
+ ]
+ : []),
...(can("members")
? [
{
@@ -181,6 +198,7 @@ const Root = ({ children }: { children?: ReactNode }) => {
<StoreRegionsSection seller={seller} />
<StoreCompanyDetailsSection seller={seller} />
<StorePaymentDetailsSection seller={seller} />
+ <StorePayoutAccountSection sellerId={seller.id} />
</WidgetZone>
</TwoColumnPage.Sidebar>
</TwoColumnPage>
@@ -195,6 +213,7 @@ export const StoreDetailPage = Object.assign(Root, {
MainPaymentDetailsSection: StorePaymentDetailsSection,
MainCompanyDetailsSection: StoreCompanyDetailsSection,
SidebarAddressSection: StoreAddressSection,
+ SidebarPayoutAccountSection: StorePayoutAccountSection,
SidebarRegionsSection: StoreRegionsSection,
SidebarMembersSection: StoreMembersSection,
Header: StoreDetailHeader,
diff --git a/packages/admin/src/pages/stores/store-details/components/store-payout-account-section.tsx b/packages/admin/src/pages/stores/store-details/components/store-payout-account-section.tsx
new file mode 100644
index 000000000..31d8df9d9
--- /dev/null
+++ b/packages/admin/src/pages/stores/store-details/components/store-payout-account-section.tsx
@@ -0,0 +1,50 @@
+import { CurrencyDollar } from "@medusajs/icons"
+import { Container, Heading, StatusBadge, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { SidebarLink } from "../../../../components/common/sidebar-link/sidebar-link"
+import { usePayoutAccounts } from "../../../../hooks/api/payout-accounts"
+import { getPayoutAccountStatusProps } from "../../../payout-accounts/common/utils"
+
+export const StorePayoutAccountSection = ({ sellerId }: { sellerId: string }) => {
+ const { t } = useTranslation()
+ const { payout_accounts, isPending } = usePayoutAccounts({
+ seller_id: sellerId,
+ limit: 1,
+ })
+
+ if (isPending) {
+ return null
+ }
+
+ const account = payout_accounts?.[0]
+ const status = account ? getPayoutAccountStatusProps(account.status, t) : null
+
+ return (
+ <Container className="p-0" data-testid="store-payout-account-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("payoutAccounts.storeSection.header")}</Heading>
+ {status && (
+ <StatusBadge color={status.color} data-testid="store-payout-account-status">
+ {status.label}
+ </StatusBadge>
+ )}
+ </div>
+ {account ? (
+ <SidebarLink
+ to={`/payout-accounts/${account.id}`}
+ labelKey={t("payouts.fields.payoutAccount")}
+ descriptionKey={account.external_id ?? account.id}
+ icon={<CurrencyDollar />}
+ dataTestid="store-payout-account-link"
+ />
+ ) : (
+ <div className="border-t px-6 py-4">
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ {t("payoutAccounts.storeSection.empty")}
+ </Text>
+ </div>
+ )}
+ </Container>
+ )
+}
diff --git a/packages/cli/routes-manifest.json b/packages/cli/routes-manifest.json
index 782480526..d5ba7db5d 100644
--- a/packages/cli/routes-manifest.json
+++ b/packages/cli/routes-manifest.json
@@ -139,8 +139,13 @@
"/admin/payments/:id/capture": "typeof import(\"@medusajs/medusa/api/admin/payments/[id]/capture/route\")",
"/admin/payments/:id/refund": "typeof import(\"@medusajs/medusa/api/admin/payments/[id]/refund/route\")",
"/admin/payments/payment-providers": "typeof import(\"@medusajs/medusa/api/admin/payments/payment-providers/route\")",
+ "/admin/payout-accounts": "typeof import(\"@mercurjs/core/api/admin/payout-accounts/route\")",
+ "/admin/payout-accounts/:id": "typeof import(\"@mercurjs/core/api/admin/payout-accounts/[id]/route\")",
+ "/admin/payout-accounts/:id/refresh-link": "typeof import(\"@mercurjs/core/api/admin/payout-accounts/[id]/refresh-link/route\")",
+ "/admin/payout-accounts/:id/sync": "typeof import(\"@mercurjs/core/api/admin/payout-accounts/[id]/sync/route\")",
"/admin/payouts": "typeof import(\"@mercurjs/core/api/admin/payouts/route\")",
"/admin/payouts/:id": "typeof import(\"@mercurjs/core/api/admin/payouts/[id]/route\")",
+ "/admin/payouts/:id/retry": "typeof import(\"@mercurjs/core/api/admin/payouts/[id]/retry/route\")",
"/admin/plugins": "typeof import(\"@medusajs/medusa/api/admin/plugins/route\")",
"/admin/price-lists": "typeof import(\"@medusajs/medusa/api/admin/price-lists/route\")",
"/admin/price-lists/:id": "typeof import(\"@medusajs/medusa/api/admin/price-lists/[id]/route\")",
@@ -337,6 +342,7 @@
"/cloud/auth/users": "typeof import(\"@medusajs/medusa/api/cloud/auth/users/route\")",
"/hooks/payment/:provider": "typeof import(\"@mercurjs/core/api/hooks/payment/[provider]/route\")",
"/hooks/payout": "typeof import(\"@mercurjs/core/api/hooks/payout/route\")",
+ "/payout/onboarding/refresh": "typeof import(\"@mercurjs/core/api/payout/onboarding/refresh/route\")",
"/store/carts": "typeof import(\"@medusajs/medusa/api/store/carts/route\")",
"/store/carts/:id": "typeof import(\"@medusajs/medusa/api/store/carts/[id]/route\")",
"/store/carts/:id/complete": "typeof import(\"@mercurjs/core/api/store/carts/[id]/complete/route\")",
@@ -480,6 +486,7 @@
"/vendor/payout-accounts": "typeof import(\"@mercurjs/core/api/vendor/payout-accounts/route\")",
"/vendor/payout-accounts/:id": "typeof import(\"@mercurjs/core/api/vendor/payout-accounts/[id]/route\")",
"/vendor/payout-accounts/:id/onboarding": "typeof import(\"@mercurjs/core/api/vendor/payout-accounts/[id]/onboarding/route\")",
+ "/vendor/payout-accounts/me": "typeof import(\"@mercurjs/core/api/vendor/payout-accounts/me/route\")",
"/vendor/payouts": "typeof import(\"@mercurjs/core/api/vendor/payouts/route\")",
"/vendor/payouts/:id": "typeof import(\"@mercurjs/core/api/vendor/payouts/[id]/route\")",
"/vendor/price-lists": "typeof import(\"@mercurjs/core/api/vendor/price-lists/route\")",
diff --git a/packages/core/.mercur/routes.d.ts b/packages/core/.mercur/routes.d.ts
index 78cd99e4b..3f687fb63 100644
--- a/packages/core/.mercur/routes.d.ts
+++ b/packages/core/.mercur/routes.d.ts
@@ -230,7 +230,9 @@ export type Routes = {
paymentProviders: typeof import("@medusajs/medusa/api/admin/payments/payment-providers/route");
};
payouts: typeof import("../src/api/admin/payouts/route") & {
- $id: typeof import("../src/api/admin/payouts/[id]/route");
+ $id: typeof import("../src/api/admin/payouts/[id]/route") & {
+ retry: typeof import("../src/api/admin/payouts/[id]/retry/route");
+ };
};
plugins: typeof import("@medusajs/medusa/api/admin/plugins/route");
priceLists: typeof import("@medusajs/medusa/api/admin/price-lists/route") & {
@@ -517,6 +519,12 @@ export type Routes = {
offerConditions: typeof import("../src/api/admin/offer-conditions/route") & {
$id: typeof import("../src/api/admin/offer-conditions/[id]/route");
};
+ payoutAccounts: typeof import("../src/api/admin/payout-accounts/route") & {
+ $id: typeof import("../src/api/admin/payout-accounts/[id]/route") & {
+ refreshLink: typeof import("../src/api/admin/payout-accounts/[id]/refresh-link/route");
+ sync: typeof import("../src/api/admin/payout-accounts/[id]/sync/route");
+ };
+ };
reviews: typeof import("../src/api/admin/reviews/route") & {
$id: typeof import("../src/api/admin/reviews/[id]/route") & {
respond: typeof import("../src/api/admin/reviews/[id]/respond/route");
@@ -801,6 +809,7 @@ export type Routes = {
$id: typeof import("../src/api/vendor/payout-accounts/[id]/route") & {
onboarding: typeof import("../src/api/vendor/payout-accounts/[id]/onboarding/route");
};
+ me: typeof import("../src/api/vendor/payout-accounts/me/route");
};
payouts: typeof import("../src/api/vendor/payouts/route") & {
$id: typeof import("../src/api/vendor/payouts/[id]/route");
@@ -947,4 +956,9 @@ export type Routes = {
$id: typeof import("../src/api/vendor/reviews/[id]/route");
};
};
+ payout: {
+ onboarding: {
+ refresh: typeof import("../src/api/payout/onboarding/refresh/route");
+ };
+ };
};
diff --git a/packages/core/src/api/admin/middlewares.ts b/packages/core/src/api/admin/middlewares.ts
index 94698e220..1fccf31f8 100644
--- a/packages/core/src/api/admin/middlewares.ts
+++ b/packages/core/src/api/admin/middlewares.ts
@@ -11,6 +11,7 @@ import { adminCustomerGroupsMiddlewares } from "./customer-groups/middlewares"
import { adminOffersMiddlewares } from "./offers/middlewares"
import { adminOfferConditionsMiddlewares } from "./offer-conditions/middlewares"
import { adminPayoutsMiddlewares } from "./payouts/middlewares"
+import { adminPayoutAccountsMiddlewares } from "./payout-accounts/middlewares"
import { adminSellersMiddlewares } from "./sellers/middlewares"
import { adminRegionsMiddlewares } from "./regions/middlewares"
import { adminMembersMiddlewares } from "./members/middlewares"
@@ -56,6 +57,7 @@ export const adminMiddlewares: MiddlewareRoute[] = [
...adminOffersMiddlewares,
...adminOfferConditionsMiddlewares,
...adminPayoutsMiddlewares,
+ ...adminPayoutAccountsMiddlewares,
...adminSellersMiddlewares,
...adminRegionsMiddlewares,
...adminMembersMiddlewares,
diff --git a/packages/core/src/api/admin/payout-accounts/[id]/refresh-link/route.ts b/packages/core/src/api/admin/payout-accounts/[id]/refresh-link/route.ts
new file mode 100644
index 000000000..99e5d2931
--- /dev/null
+++ b/packages/core/src/api/admin/payout-accounts/[id]/refresh-link/route.ts
@@ -0,0 +1,18 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { HttpTypes } from "@mercurjs/types"
+
+import { refreshPayoutAccountLinkWorkflow } from "../../../../../workflows/payout"
+import { refetchPayoutAccount } from "../../helpers"
+
+export const POST = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse<HttpTypes.AdminPayoutAccountResponse>
+) => {
+ await refreshPayoutAccountLinkWorkflow(req.scope).run({
+ input: { id: req.params.id },
+ })
+
+ const payout_account = await refetchPayoutAccount(req.params.id, req.scope, req.queryConfig.fields)
+
+ res.json({ payout_account })
+}
diff --git a/packages/core/src/api/admin/payout-accounts/[id]/route.ts b/packages/core/src/api/admin/payout-accounts/[id]/route.ts
new file mode 100644
index 000000000..50d13012a
--- /dev/null
+++ b/packages/core/src/api/admin/payout-accounts/[id]/route.ts
@@ -0,0 +1,24 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { ContainerRegistrationKeys, MedusaError } from "@medusajs/framework/utils"
+import { HttpTypes } from "@mercurjs/types"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse<HttpTypes.AdminPayoutAccountResponse>
+) => {
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const {
+ data: [payout_account],
+ } = await query.graph({
+ entity: "payout_account",
+ fields: req.queryConfig.fields,
+ filters: { id: req.params.id },
+ })
+
+ if (!payout_account) {
+ throw new MedusaError(MedusaError.Types.NOT_FOUND, `Payout account ${req.params.id} was not found`)
+ }
+
+ res.json({ payout_account })
+}
diff --git a/packages/core/src/api/admin/payout-accounts/[id]/sync/route.ts b/packages/core/src/api/admin/payout-accounts/[id]/sync/route.ts
new file mode 100644
index 000000000..2337e5515
--- /dev/null
+++ b/packages/core/src/api/admin/payout-accounts/[id]/sync/route.ts
@@ -0,0 +1,18 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { HttpTypes } from "@mercurjs/types"
+
+import { syncPayoutAccountWorkflow } from "../../../../../workflows/payout"
+import { refetchPayoutAccount } from "../../helpers"
+
+export const POST = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse<HttpTypes.AdminPayoutAccountResponse>
+) => {
+ await syncPayoutAccountWorkflow(req.scope).run({
+ input: { id: req.params.id },
+ })
+
+ const payout_account = await refetchPayoutAccount(req.params.id, req.scope, req.queryConfig.fields)
+
+ res.json({ payout_account })
+}
diff --git a/packages/core/src/api/admin/payout-accounts/helpers.ts b/packages/core/src/api/admin/payout-accounts/helpers.ts
new file mode 100644
index 000000000..2413f0222
--- /dev/null
+++ b/packages/core/src/api/admin/payout-accounts/helpers.ts
@@ -0,0 +1,5 @@
+import { MedusaContainer } from "@medusajs/framework"
+import { refetchEntity } from "@medusajs/framework/http"
+
+export const refetchPayoutAccount = async (id: string, scope: MedusaContainer, fields: string[]) =>
+ await refetchEntity({ entity: "payout_account", idOrFilter: id, scope, fields })
diff --git a/packages/core/src/api/admin/payout-accounts/middlewares.ts b/packages/core/src/api/admin/payout-accounts/middlewares.ts
new file mode 100644
index 000000000..da4e4af99
--- /dev/null
+++ b/packages/core/src/api/admin/payout-accounts/middlewares.ts
@@ -0,0 +1,48 @@
+import { validateAndTransformBody, validateAndTransformQuery } from "@medusajs/framework"
+import { MiddlewareRoute, maybeApplyLinkFilter } from "@medusajs/framework/http"
+
+import { requirePermission } from "../../utils"
+import { adminPayoutAccountQueryConfig } from "./query-config"
+import {
+ AdminCreatePayoutAccount,
+ AdminGetPayoutAccountParams,
+ AdminGetPayoutAccountsParams,
+} from "./validators"
+
+const retrieve = validateAndTransformQuery(AdminGetPayoutAccountParams, adminPayoutAccountQueryConfig.retrieve)
+
+export const adminPayoutAccountsMiddlewares: MiddlewareRoute[] = [
+ {
+ method: ["GET"],
+ matcher: "/admin/payout-accounts",
+ middlewares: [
+ requirePermission("payouts", "view"),
+ validateAndTransformQuery(AdminGetPayoutAccountsParams, adminPayoutAccountQueryConfig.list),
+ maybeApplyLinkFilter({
+ entryPoint: "seller_payout_account",
+ resourceId: "payout_account_id",
+ filterableField: "seller_id",
+ }),
+ ],
+ },
+ {
+ method: ["POST"],
+ matcher: "/admin/payout-accounts",
+ middlewares: [requirePermission("payouts", "edit"), validateAndTransformBody(AdminCreatePayoutAccount), retrieve],
+ },
+ {
+ method: ["GET"],
+ matcher: "/admin/payout-accounts/:id",
+ middlewares: [requirePermission("payouts", "view"), retrieve],
+ },
+ {
+ method: ["POST"],
+ matcher: "/admin/payout-accounts/:id/refresh-link",
+ middlewares: [requirePermission("payouts", "edit"), retrieve],
+ },
+ {
+ method: ["POST"],
+ matcher: "/admin/payout-accounts/:id/sync",
+ middlewares: [requirePermission("payouts", "edit"), retrieve],
+ },
+]
diff --git a/packages/core/src/api/admin/payout-accounts/query-config.ts b/packages/core/src/api/admin/payout-accounts/query-config.ts
new file mode 100644
index 000000000..1c7ab1804
--- /dev/null
+++ b/packages/core/src/api/admin/payout-accounts/query-config.ts
@@ -0,0 +1,23 @@
+export const adminPayoutAccountFields = [
+ "id",
+ "external_id",
+ "status",
+ "kyc_status",
+ "payouts_enabled",
+ "charges_enabled",
+ "details_submitted",
+ "disabled_reason",
+ "last_synced_at",
+ "created_at",
+ "updated_at",
+ "onboarding.id",
+ "onboarding.data",
+ "seller.id",
+ "seller.name",
+ "seller.handle",
+]
+
+export const adminPayoutAccountQueryConfig = {
+ list: { defaults: adminPayoutAccountFields, isList: true },
+ retrieve: { defaults: adminPayoutAccountFields, isList: false },
+}
diff --git a/packages/core/src/api/admin/payout-accounts/route.ts b/packages/core/src/api/admin/payout-accounts/route.ts
new file mode 100644
index 000000000..43bd97e65
--- /dev/null
+++ b/packages/core/src/api/admin/payout-accounts/route.ts
@@ -0,0 +1,41 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { HttpTypes } from "@mercurjs/types"
+
+import { linkPayoutAccountWorkflow } from "../../../workflows/payout"
+import { refetchPayoutAccount } from "./helpers"
+import { AdminCreatePayoutAccountType } from "./validators"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse<HttpTypes.AdminPayoutAccountListResponse>
+) => {
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const { data: payout_accounts, metadata } = await query.graph({
+ entity: "payout_account",
+ fields: req.queryConfig.fields,
+ filters: req.filterableFields,
+ pagination: req.queryConfig.pagination,
+ })
+
+ res.json({
+ payout_accounts,
+ count: metadata?.count ?? 0,
+ offset: metadata?.skip ?? 0,
+ limit: metadata?.take ?? 0,
+ })
+}
+
+export const POST = async (
+ req: AuthenticatedMedusaRequest<AdminCreatePayoutAccountType>,
+ res: MedusaResponse<HttpTypes.AdminPayoutAccountResponse>
+) => {
+ const { result } = await linkPayoutAccountWorkflow(req.scope).run({
+ input: req.validatedBody,
+ })
+
+ const payout_account = await refetchPayoutAccount(result.id, req.scope, req.queryConfig.fields)
+
+ res.status(201).json({ payout_account })
+}
diff --git a/packages/core/src/api/admin/payout-accounts/validators.ts b/packages/core/src/api/admin/payout-accounts/validators.ts
new file mode 100644
index 000000000..cd813863a
--- /dev/null
+++ b/packages/core/src/api/admin/payout-accounts/validators.ts
@@ -0,0 +1,30 @@
+import { z } from "zod"
+import {
+ createFindParams,
+ createOperatorMap,
+ createSelectParams,
+} from "@medusajs/medusa/api/utils/validators"
+
+export type AdminGetPayoutAccountParamsType = z.infer<typeof AdminGetPayoutAccountParams>
+export const AdminGetPayoutAccountParams = createSelectParams()
+
+export type AdminGetPayoutAccountsParamsType = z.infer<typeof AdminGetPayoutAccountsParams>
+export const AdminGetPayoutAccountsParams = createFindParams({ offset: 0, limit: 20 }).merge(
+ z.object({
+ id: z.union([z.string(), z.array(z.string())]).optional(),
+ seller_id: z.union([z.string(), z.array(z.string())]).optional(),
+ status: z.union([z.string(), z.array(z.string())]).optional(),
+ kyc_status: z.union([z.string(), z.array(z.string())]).optional(),
+ payouts_enabled: z.coerce.boolean().optional(),
+ created_at: createOperatorMap().optional(),
+ updated_at: createOperatorMap().optional(),
+ })
+)
+
+export type AdminCreatePayoutAccountType = z.infer<typeof AdminCreatePayoutAccount>
+export const AdminCreatePayoutAccount = z
+ .object({
+ seller_id: z.string(),
+ external_id: z.string(),
+ })
+ .strict()
diff --git a/packages/core/src/api/admin/payouts/[id]/retry/route.ts b/packages/core/src/api/admin/payouts/[id]/retry/route.ts
new file mode 100644
index 000000000..09f9375eb
--- /dev/null
+++ b/packages/core/src/api/admin/payouts/[id]/retry/route.ts
@@ -0,0 +1,18 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { HttpTypes } from "@mercurjs/types"
+
+import { retryPayoutWorkflow } from "../../../../../workflows/payout"
+import { refetchPayout } from "../../helpers"
+
+export const POST = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse<HttpTypes.AdminPayoutResponse>
+) => {
+ await retryPayoutWorkflow(req.scope).run({
+ input: { id: req.params.id },
+ })
+
+ const payout = await refetchPayout(req.params.id, req.scope, req.queryConfig.fields)
+
+ res.json({ payout })
+}
diff --git a/packages/core/src/api/admin/payouts/helpers.ts b/packages/core/src/api/admin/payouts/helpers.ts
new file mode 100644
index 000000000..86bc06aa4
--- /dev/null
+++ b/packages/core/src/api/admin/payouts/helpers.ts
@@ -0,0 +1,5 @@
+import { MedusaContainer } from "@medusajs/framework"
+import { refetchEntity } from "@medusajs/framework/http"
+
+export const refetchPayout = async (id: string, scope: MedusaContainer, fields: string[]) =>
+ await refetchEntity({ entity: "payout", idOrFilter: id, scope, fields })
diff --git a/packages/core/src/api/admin/payouts/middlewares.ts b/packages/core/src/api/admin/payouts/middlewares.ts
index b7f80fdd2..9fff89a6b 100644
--- a/packages/core/src/api/admin/payouts/middlewares.ts
+++ b/packages/core/src/api/admin/payouts/middlewares.ts
@@ -1,11 +1,19 @@
import { requirePermission } from "../../utils"
-import { MiddlewareRoute } from "@medusajs/framework/http"
+import { MiddlewareRoute, maybeApplyLinkFilter } from "@medusajs/framework/http"
import { validateAndTransformQuery } from "@medusajs/framework"
import { adminPayoutQueryConfig } from "./query-config"
import { AdminGetPayoutParams, AdminGetPayoutsParams } from "./validators"
export const adminPayoutsMiddlewares: MiddlewareRoute[] = [
+ {
+ method: ["POST"],
+ matcher: "/admin/payouts/:id/retry",
+ middlewares: [
+ requirePermission("payouts", "edit"),
+ validateAndTransformQuery(AdminGetPayoutParams, adminPayoutQueryConfig.retrieve),
+ ],
+ },
{
method: ["GET"],
matcher: "/admin/payouts",
@@ -15,6 +23,12 @@ export const adminPayoutsMiddlewares: MiddlewareRoute[] = [
AdminGetPayoutsParams,
adminPayoutQueryConfig.list
),
+ maybeApplyLinkFilter({
+ entryPoint: "seller_payout_account",
+ resourceId: "payout_account_id",
+ filterableField: "seller_id",
+ filterByField: "account_id",
+ }),
],
},
{
diff --git a/packages/core/src/api/admin/payouts/query-config.ts b/packages/core/src/api/admin/payouts/query-config.ts
index e25063d4e..dd8bb5d94 100644
--- a/packages/core/src/api/admin/payouts/query-config.ts
+++ b/packages/core/src/api/admin/payouts/query-config.ts
@@ -12,6 +12,15 @@ export const adminPayoutFields = [
"seller.name",
"seller.handle",
"display_id",
+ "status_reason",
+ "order_id",
+ "order.id",
+ "order.display_id",
+ "metadata",
+ "reversals.*",
+ "account.seller.id",
+ "account.seller.name",
+ "account.seller.handle",
]
export const adminPayoutQueryConfig = {
diff --git a/packages/core/src/api/admin/payouts/validators.ts b/packages/core/src/api/admin/payouts/validators.ts
index 5fc3f197c..43c77c5e5 100644
--- a/packages/core/src/api/admin/payouts/validators.ts
+++ b/packages/core/src/api/admin/payouts/validators.ts
@@ -17,6 +17,8 @@ export const AdminGetPayoutsParams = createFindParams({
id: z.union([z.string(), z.array(z.string())]).optional(),
status: z.union([z.string(), z.array(z.string())]).optional(),
account_id: z.union([z.string(), z.array(z.string())]).optional(),
+ seller_id: z.union([z.string(), z.array(z.string())]).optional(),
+ order_id: z.union([z.string(), z.array(z.string())]).optional(),
created_at: createOperatorMap().optional(),
updated_at: createOperatorMap().optional(),
})
diff --git a/packages/core/src/api/hooks/payout/route.ts b/packages/core/src/api/hooks/payout/route.ts
index 4640fddc9..d54e11d8b 100644
--- a/packages/core/src/api/hooks/payout/route.ts
+++ b/packages/core/src/api/hooks/payout/route.ts
@@ -1,26 +1,23 @@
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { Modules } from "@medusajs/framework/utils"
+import { PayoutModuleEvents } from "@mercurjs/types"
export const POST = async (req: MedusaRequest, res: MedusaResponse) => {
try {
- const event = {
- data: req.body, rawData: req.rawBody, headers: req.headers
- }
-
const eventBus = req.scope.resolve(Modules.EVENT_BUS)
await eventBus.emit(
{
- name: "payout.webhook_received",
- data: event,
+ name: PayoutModuleEvents.WEBHOOK_RECEIVED,
+ data: { data: req.body, rawData: req.rawBody, headers: req.headers },
},
{
delay: 5000,
attempts: 3,
}
)
- } catch (err: any) {
- res.status(400).send(`Webhook Error: ${err.message}`)
+ } catch (err) {
+ res.status(400).send(`Webhook Error: ${(err as Error).message}`)
return
}
diff --git a/packages/core/src/api/payout/onboarding/refresh/route.ts b/packages/core/src/api/payout/onboarding/refresh/route.ts
new file mode 100644
index 000000000..8ef3fba0a
--- /dev/null
+++ b/packages/core/src/api/payout/onboarding/refresh/route.ts
@@ -0,0 +1,21 @@
+import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { MedusaError } from "@medusajs/framework/utils"
+
+import { refreshOnboardingWorkflow } from "../../../../workflows/payout"
+
+/**
+ * Public refresh URL handed to the provider with every onboarding link: a
+ * seller whose link expired lands here and is sent to a fresh one.
+ */
+export const GET = async (req: MedusaRequest, res: MedusaResponse) => {
+ const token = req.query.token
+ if (typeof token !== "string" || !token) {
+ throw new MedusaError(MedusaError.Types.INVALID_DATA, "token is required")
+ }
+
+ const { result } = await refreshOnboardingWorkflow(req.scope).run({
+ input: { token },
+ })
+
+ res.redirect(302, result.url)
+}
diff --git a/packages/core/src/api/utils/ensure-seller-middleware.ts b/packages/core/src/api/utils/ensure-seller-middleware.ts
index 6933ea49a..32cbde2d9 100644
--- a/packages/core/src/api/utils/ensure-seller-middleware.ts
+++ b/packages/core/src/api/utils/ensure-seller-middleware.ts
@@ -45,7 +45,7 @@ export async function ensureSellerMiddleware(
if (!sellerMembers.length) {
return next(
new MedusaError(
- MedusaError.Types.NOT_ALLOWED,
+ MedusaError.Types.FORBIDDEN,
"You are not a member of this seller account"
)
)
diff --git a/packages/core/src/api/vendor/payout-accounts/[id]/onboarding/route.ts b/packages/core/src/api/vendor/payout-accounts/[id]/onboarding/route.ts
index ea085ce55..0a5e25e25 100644
--- a/packages/core/src/api/vendor/payout-accounts/[id]/onboarding/route.ts
+++ b/packages/core/src/api/vendor/payout-accounts/[id]/onboarding/route.ts
@@ -2,18 +2,16 @@ import {
AuthenticatedMedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
import { HttpTypes } from "@mercurjs/types"
import { createOnboardingWorkflow } from "../../../../../workflows/payout"
-import { validateSellerPayoutAccount } from "../../helpers"
+import { refetchOnboarding, validateSellerPayoutAccount } from "../../helpers"
import { VendorCreateOnboardingType } from "../../validators"
export const POST = async (
req: AuthenticatedMedusaRequest<VendorCreateOnboardingType>,
res: MedusaResponse<HttpTypes.VendorOnboardingResponse>
) => {
- const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
const sellerId = req.seller_context!.seller_id
await validateSellerPayoutAccount(req.scope, sellerId, req.params.id)
@@ -26,13 +24,7 @@ export const POST = async (
},
})
- const {
- data: [onboarding],
- } = await query.graph({
- entity: "onboarding",
- fields: req.queryConfig.fields,
- filters: { id: result.id },
- })
+ const onboarding = await refetchOnboarding(result.id, req.scope, req.queryConfig.fields)
res.status(201).json({ onboarding })
}
diff --git a/packages/core/src/api/vendor/payout-accounts/__tests__/validators.unit.spec.ts b/packages/core/src/api/vendor/payout-accounts/__tests__/validators.unit.spec.ts
new file mode 100644
index 000000000..9442a4c64
--- /dev/null
+++ b/packages/core/src/api/vendor/payout-accounts/__tests__/validators.unit.spec.ts
@@ -0,0 +1,11 @@
+import { VendorCreateOnboarding } from "../validators"
+
+describe("VendorCreateOnboarding", () => {
+ it("drops redirect urls so sellers can't point onboarding at their own domain", () => {
+ const parsed = VendorCreateOnboarding.parse({
+ data: { refresh_url: "https://evil.test", return_url: "https://evil.test", country: "DE" },
+ })
+
+ expect(parsed.data).toEqual({ country: "DE" })
+ })
+})
diff --git a/packages/core/src/api/vendor/payout-accounts/helpers.ts b/packages/core/src/api/vendor/payout-accounts/helpers.ts
index 017d3650a..579eec885 100644
--- a/packages/core/src/api/vendor/payout-accounts/helpers.ts
+++ b/packages/core/src/api/vendor/payout-accounts/helpers.ts
@@ -1,4 +1,5 @@
import { MedusaContainer } from "@medusajs/framework"
+import { refetchEntity } from "@medusajs/framework/http"
import {
ContainerRegistrationKeys,
MedusaError,
@@ -29,3 +30,9 @@ export const validateSellerPayoutAccount = async (
)
}
}
+
+export const refetchPayoutAccount = async (id: string, scope: MedusaContainer, fields: string[]) =>
+ await refetchEntity({ entity: "payout_account", idOrFilter: id, scope, fields })
+
+export const refetchOnboarding = async (id: string, scope: MedusaContainer, fields: string[]) =>
+ await refetchEntity({ entity: "onboarding", idOrFilter: id, scope, fields })
diff --git a/packages/core/src/api/vendor/payout-accounts/me/route.ts b/packages/core/src/api/vendor/payout-accounts/me/route.ts
new file mode 100644
index 000000000..78e4dc3ed
--- /dev/null
+++ b/packages/core/src/api/vendor/payout-accounts/me/route.ts
@@ -0,0 +1,20 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { HttpTypes } from "@mercurjs/types"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse<HttpTypes.VendorPayoutAccountMeResponse>
+) => {
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const {
+ data: [payout_account],
+ } = await query.graph({
+ entity: "payout_account",
+ fields: req.queryConfig.fields,
+ filters: { seller: { id: req.seller_context!.seller_id } },
+ })
+
+ res.json({ payout_account: payout_account ?? null })
+}
diff --git a/packages/core/src/api/vendor/payout-accounts/middlewares.ts b/packages/core/src/api/vendor/payout-accounts/middlewares.ts
index f22dbbea9..d8d1a82a7 100644
--- a/packages/core/src/api/vendor/payout-accounts/middlewares.ts
+++ b/packages/core/src/api/vendor/payout-accounts/middlewares.ts
@@ -8,6 +8,7 @@ import {
} from "@medusajs/framework"
import {
+ vendorMyPayoutAccountQueryConfig,
vendorPayoutAccountQueryConfig,
vendorOnboardingQueryConfig,
} from "./query-config"
@@ -21,6 +22,17 @@ import {
const applySellerPayoutAccountLinkFilter = applySellerLinkFilter()
export const vendorPayoutAccountsMiddlewares: MiddlewareRoute[] = [
+ {
+ method: ["GET"],
+ matcher: "/vendor/payout-accounts/me",
+ middlewares: [
+ requirePermission("payout_accounts", "view"),
+ validateAndTransformQuery(
+ VendorGetPayoutAccountParams,
+ vendorMyPayoutAccountQueryConfig.retrieve
+ ),
+ ],
+ },
{
method: ["GET"],
matcher: "/vendor/payout-accounts",
diff --git a/packages/core/src/api/vendor/payout-accounts/query-config.ts b/packages/core/src/api/vendor/payout-accounts/query-config.ts
index 395501057..10f993747 100644
--- a/packages/core/src/api/vendor/payout-accounts/query-config.ts
+++ b/packages/core/src/api/vendor/payout-accounts/query-config.ts
@@ -15,10 +15,39 @@ export const vendorPayoutAccountFields = [
export const vendorPayoutAccountQueryConfig = {
list: {
defaults: vendorPayoutAccountFields,
+ allowed: vendorPayoutAccountFields,
isList: true,
},
retrieve: {
defaults: vendorPayoutAccountFields,
+ allowed: vendorPayoutAccountFields,
+ isList: false,
+ },
+}
+
+export const vendorMyPayoutAccountFields = [
+ "id",
+ "external_id",
+ "status",
+ "kyc_status",
+ "payouts_enabled",
+ "charges_enabled",
+ "details_submitted",
+ "disabled_reason",
+ "last_synced_at",
+ "created_at",
+ "updated_at",
+ "onboarding.id",
+ "onboarding.account_id",
+ "onboarding.data",
+ "onboarding.created_at",
+ "onboarding.updated_at",
+]
+
+export const vendorMyPayoutAccountQueryConfig = {
+ retrieve: {
+ defaults: vendorMyPayoutAccountFields,
+ allowed: vendorMyPayoutAccountFields,
isList: false,
},
}
@@ -34,6 +63,7 @@ export const vendorOnboardingFields = [
export const vendorOnboardingQueryConfig = {
retrieve: {
defaults: vendorOnboardingFields,
+ allowed: vendorOnboardingFields,
isList: false,
},
}
diff --git a/packages/core/src/api/vendor/payout-accounts/route.ts b/packages/core/src/api/vendor/payout-accounts/route.ts
index 40a0bf9ac..b2be4deee 100644
--- a/packages/core/src/api/vendor/payout-accounts/route.ts
+++ b/packages/core/src/api/vendor/payout-accounts/route.ts
@@ -6,6 +6,7 @@ import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
import { HttpTypes } from "@mercurjs/types"
import { createPayoutAccountWorkflow } from "../../../workflows/payout"
+import { refetchPayoutAccount } from "./helpers"
import { VendorCreatePayoutAccountType } from "./validators"
export const GET = async (
@@ -33,24 +34,15 @@ export const POST = async (
req: AuthenticatedMedusaRequest<VendorCreatePayoutAccountType>,
res: MedusaResponse<HttpTypes.VendorPayoutAccountResponse>
) => {
- const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
- const sellerId = req.seller_context!.seller_id
-
const { result } = await createPayoutAccountWorkflow(req.scope).run({
input: {
- seller_id: sellerId,
+ seller_id: req.seller_context!.seller_id,
data: req.validatedBody.data,
context: req.validatedBody.context,
},
})
- const {
- data: [payout_account],
- } = await query.graph({
- entity: "payout_account",
- fields: req.queryConfig.fields,
- filters: { id: result.id },
- })
+ const payout_account = await refetchPayoutAccount(result.id, req.scope, req.queryConfig.fields)
res.status(201).json({ payout_account })
}
diff --git a/packages/core/src/api/vendor/payout-accounts/validators.ts b/packages/core/src/api/vendor/payout-accounts/validators.ts
index fc912ada8..6eb4c0519 100644
--- a/packages/core/src/api/vendor/payout-accounts/validators.ts
+++ b/packages/core/src/api/vendor/payout-accounts/validators.ts
@@ -24,7 +24,10 @@ export const VendorCreatePayoutAccount = z
export type VendorCreateOnboardingType = z.infer<typeof VendorCreateOnboarding>
export const VendorCreateOnboarding = z
.object({
- data: z.record(z.string(), z.unknown()).optional(),
+ data: z
+ .record(z.string(), z.unknown())
+ .transform(({ refresh_url: _refreshUrl, return_url: _returnUrl, ...data }) => data)
+ .optional(),
context: z.record(z.string(), z.unknown()).optional(),
})
.strict()
diff --git a/packages/core/src/api/vendor/payouts/query-config.ts b/packages/core/src/api/vendor/payouts/query-config.ts
index 59aeff170..911ef32be 100644
--- a/packages/core/src/api/vendor/payouts/query-config.ts
+++ b/packages/core/src/api/vendor/payouts/query-config.ts
@@ -3,19 +3,29 @@ export const vendorPayoutFields = [
"amount",
"currency_code",
"status",
- "data",
"created_at",
"updated_at",
"display_id",
+ "order_id",
+ "order.id",
+ "order.display_id",
+ "status_reason",
+ "reversals.id",
+ "reversals.amount",
+ "reversals.status",
+ "reversals.refund_id",
+ "reversals.created_at",
]
export const vendorPayoutQueryConfig = {
list: {
defaults: vendorPayoutFields,
+ allowed: vendorPayoutFields,
isList: true,
},
retrieve: {
defaults: vendorPayoutFields,
+ allowed: vendorPayoutFields,
isList: false,
},
}
diff --git a/packages/core/src/api/vendor/payouts/validators.ts b/packages/core/src/api/vendor/payouts/validators.ts
index e33155b86..e56e9353c 100644
--- a/packages/core/src/api/vendor/payouts/validators.ts
+++ b/packages/core/src/api/vendor/payouts/validators.ts
@@ -15,6 +15,7 @@ export const VendorGetPayoutsParams = createFindParams({
}).merge(
z.object({
status: z.union([z.string(), z.array(z.string())]).optional(),
+ order_id: z.union([z.string(), z.array(z.string())]).optional(),
created_at: createOperatorMap().optional(),
updated_at: createOperatorMap().optional(),
})
diff --git a/packages/core/src/api/vendor/sellers/select/route.ts b/packages/core/src/api/vendor/sellers/select/route.ts
index 76c109399..3618a309b 100644
--- a/packages/core/src/api/vendor/sellers/select/route.ts
+++ b/packages/core/src/api/vendor/sellers/select/route.ts
@@ -32,7 +32,7 @@ export const POST = async (
if (!sellerMembers.length) {
throw new MedusaError(
- MedusaError.Types.NOT_ALLOWED,
+ MedusaError.Types.FORBIDDEN,
"You are not a member of this seller account"
)
}
diff --git a/packages/core/src/modules/payout/loaders/provider.ts b/packages/core/src/modules/payout/loaders/provider.ts
index c7479f3c5..e378c2c65 100644
--- a/packages/core/src/modules/payout/loaders/provider.ts
+++ b/packages/core/src/modules/payout/loaders/provider.ts
@@ -5,14 +5,22 @@ import {
ModuleProvider,
ModulesSdkTypes,
} from "@medusajs/framework/types"
+import { MedusaError } from "@medusajs/framework/utils"
-import {
- PayoutProviderRegistrationPrefix,
-} from "../services/provider-service"
+import { PayoutProviderRegistrationPrefix } from "../services/provider-service"
import { SystemPayoutProvider } from "../providers"
const registrationFn = async (klass, container, pluginOptions) => {
- const key = `${PayoutProviderRegistrationPrefix}${klass.identifier}_${pluginOptions.id}`
+ if (!klass?.identifier) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_ARGUMENT,
+ `Trying to register a payout provider without a provider identifier.`
+ )
+ }
+
+ const key = `${PayoutProviderRegistrationPrefix}${klass.identifier}${
+ pluginOptions.id ? `_${pluginOptions.id}` : ""
+ }`
container.register({
[key]: asFunction(
@@ -42,7 +50,7 @@ export default async ({
await moduleProviderLoader({
container,
- providers: options?.providers || [],
+ providers,
registerServiceFn: registrationFn,
})
}
diff --git a/packages/core/src/modules/payout/migrations/.snapshot-medusa-payout.json b/packages/core/src/modules/payout/migrations/.snapshot-medusa-payout.json
index 9a966d09f..bdbe437e1 100644
--- a/packages/core/src/modules/payout/migrations/.snapshot-medusa-payout.json
+++ b/packages/core/src/modules/payout/migrations/.snapshot-medusa-payout.json
@@ -11,8 +11,31 @@
"type": "text",
"unsigned": false,
"autoincrement": false,
- "primary": false,
+ "primary": true,
"nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "text"
+ },
+ "external_id": {
+ "name": "external_id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "text"
},
"status": {
@@ -22,7 +45,12 @@
"autoincrement": false,
"primary": false,
"nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
"default": "'pending'",
+ "comment": null,
"enumItems": [
"pending",
"active",
@@ -31,6 +59,139 @@
],
"mappedType": "enum"
},
+ "kyc_status": {
+ "name": "kyc_status",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [
+ "pending_submission",
+ "pending_approval",
+ "approved",
+ "refused"
+ ],
+ "mappedType": "enum"
+ },
+ "payouts_enabled": {
+ "name": "payouts_enabled",
+ "type": "boolean",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": "false",
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "boolean"
+ },
+ "charges_enabled": {
+ "name": "charges_enabled",
+ "type": "boolean",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": "false",
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "boolean"
+ },
+ "details_submitted": {
+ "name": "details_submitted",
+ "type": "boolean",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": "false",
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "boolean"
+ },
+ "disabled_reason": {
+ "name": "disabled_reason",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "text"
+ },
+ "onboarding_token": {
+ "name": "onboarding_token",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "text"
+ },
+ "onboarding_token_issued_at": {
+ "name": "onboarding_token_issued_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "unique": false,
+ "length": 6,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "datetime"
+ },
+ "last_synced_at": {
+ "name": "last_synced_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "unique": false,
+ "length": 6,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "datetime"
+ },
"data": {
"name": "data",
"type": "jsonb",
@@ -38,7 +199,13 @@
"autoincrement": false,
"primary": false,
"nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
"default": "'{}'",
+ "comment": null,
+ "enumItems": [],
"mappedType": "json"
},
"context": {
@@ -48,6 +215,13 @@
"autoincrement": false,
"primary": false,
"nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "json"
},
"created_at": {
@@ -57,8 +231,13 @@
"autoincrement": false,
"primary": false,
"nullable": false,
+ "unique": false,
"length": 6,
+ "precision": null,
+ "scale": null,
"default": "now()",
+ "comment": null,
+ "enumItems": [],
"mappedType": "datetime"
},
"updated_at": {
@@ -68,8 +247,13 @@
"autoincrement": false,
"primary": false,
"nullable": false,
+ "unique": false,
"length": 6,
+ "precision": null,
+ "scale": null,
"default": "now()",
+ "comment": null,
+ "enumItems": [],
"mappedType": "datetime"
},
"deleted_at": {
@@ -79,7 +263,13 @@
"autoincrement": false,
"primary": false,
"nullable": true,
+ "unique": false,
"length": 6,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "datetime"
}
},
@@ -95,6 +285,24 @@
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_payout_account_deleted_at\" ON \"payout_account\" (\"deleted_at\") WHERE deleted_at IS NULL"
},
+ {
+ "keyName": "IDX_payout_account_external_id",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_payout_account_external_id\" ON \"payout_account\" (\"external_id\") WHERE deleted_at IS NULL AND external_id IS NOT NULL"
+ },
+ {
+ "keyName": "IDX_payout_account_onboarding_token",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_payout_account_onboarding_token\" ON \"payout_account\" (\"onboarding_token\") WHERE deleted_at IS NULL AND onboarding_token IS NOT NULL"
+ },
{
"keyName": "payout_account_pkey",
"columnNames": [
@@ -117,8 +325,15 @@
"type": "text",
"unsigned": false,
"autoincrement": false,
- "primary": false,
+ "primary": true,
"nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "text"
},
"display_id": {
@@ -128,8 +343,31 @@
"autoincrement": true,
"primary": false,
"nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "integer"
},
+ "order_id": {
+ "name": "order_id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "text"
+ },
"currency_code": {
"name": "currency_code",
"type": "text",
@@ -137,6 +375,13 @@
"autoincrement": false,
"primary": false,
"nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "text"
},
"amount": {
@@ -146,8 +391,54 @@
"autoincrement": false,
"primary": false,
"nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "decimal"
},
+ "status": {
+ "name": "status",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": "'pending'",
+ "comment": null,
+ "enumItems": [
+ "pending",
+ "on_hold",
+ "processing",
+ "paid",
+ "failed",
+ "aborted"
+ ],
+ "mappedType": "enum"
+ },
+ "status_reason": {
+ "name": "status_reason",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "text"
+ },
"data": {
"name": "data",
"type": "jsonb",
@@ -155,33 +446,46 @@
"autoincrement": false,
"primary": false,
"nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "json"
},
- "account_id": {
- "name": "account_id",
- "type": "text",
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
"unsigned": false,
"autoincrement": false,
"primary": false,
- "nullable": false,
- "mappedType": "text"
+ "nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "json"
},
- "status": {
- "name": "status",
+ "account_id": {
+ "name": "account_id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
- "default": "'pending'",
- "enumItems": [
- "pending",
- "processing",
- "paid",
- "failed",
- "canceled"
- ],
- "mappedType": "enum"
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "text"
},
"raw_amount": {
"name": "raw_amount",
@@ -190,6 +494,13 @@
"autoincrement": false,
"primary": false,
"nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "json"
},
"created_at": {
@@ -199,8 +510,13 @@
"autoincrement": false,
"primary": false,
"nullable": false,
+ "unique": false,
"length": 6,
+ "precision": null,
+ "scale": null,
"default": "now()",
+ "comment": null,
+ "enumItems": [],
"mappedType": "datetime"
},
"updated_at": {
@@ -210,8 +526,13 @@
"autoincrement": false,
"primary": false,
"nullable": false,
+ "unique": false,
"length": 6,
+ "precision": null,
+ "scale": null,
"default": "now()",
+ "comment": null,
+ "enumItems": [],
"mappedType": "datetime"
},
"deleted_at": {
@@ -221,7 +542,13 @@
"autoincrement": false,
"primary": false,
"nullable": true,
+ "unique": false,
"length": 6,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "datetime"
}
},
@@ -246,6 +573,33 @@
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_payout_deleted_at\" ON \"payout\" (\"deleted_at\") WHERE deleted_at IS NULL"
},
+ {
+ "keyName": "IDX_payout_account_id_created_at",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payout_account_id_created_at\" ON \"payout\" (\"account_id\", \"created_at\") WHERE deleted_at IS NULL"
+ },
+ {
+ "keyName": "IDX_payout_status_created_at",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payout_status_created_at\" ON \"payout\" (\"status\", \"created_at\") WHERE deleted_at IS NULL"
+ },
+ {
+ "keyName": "IDX_payout_order_id",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_payout_order_id\" ON \"payout\" (\"order_id\") WHERE deleted_at IS NULL AND order_id IS NOT NULL"
+ },
{
"keyName": "payout_pkey",
"columnNames": [
@@ -281,8 +635,15 @@
"type": "text",
"unsigned": false,
"autoincrement": false,
- "primary": false,
+ "primary": true,
"nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "text"
},
"data": {
@@ -292,6 +653,13 @@
"autoincrement": false,
"primary": false,
"nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "json"
},
"context": {
@@ -301,6 +669,13 @@
"autoincrement": false,
"primary": false,
"nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "json"
},
"account_id": {
@@ -310,6 +685,13 @@
"autoincrement": false,
"primary": false,
"nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "text"
},
"created_at": {
@@ -319,8 +701,13 @@
"autoincrement": false,
"primary": false,
"nullable": false,
+ "unique": false,
"length": 6,
+ "precision": null,
+ "scale": null,
"default": "now()",
+ "comment": null,
+ "enumItems": [],
"mappedType": "datetime"
},
"updated_at": {
@@ -330,8 +717,13 @@
"autoincrement": false,
"primary": false,
"nullable": false,
+ "unique": false,
"length": 6,
+ "precision": null,
+ "scale": null,
"default": "now()",
+ "comment": null,
+ "enumItems": [],
"mappedType": "datetime"
},
"deleted_at": {
@@ -341,7 +733,13 @@
"autoincrement": false,
"primary": false,
"nullable": true,
+ "unique": false,
"length": 6,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
"mappedType": "datetime"
}
},
@@ -393,6 +791,260 @@
}
},
"nativeEnums": {}
+ },
+ {
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": true,
+ "nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "text"
+ },
+ "refund_id": {
+ "name": "refund_id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "text"
+ },
+ "amount": {
+ "name": "amount",
+ "type": "numeric",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "decimal"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": "'pending'",
+ "comment": null,
+ "enumItems": [
+ "pending",
+ "on_hold",
+ "processing",
+ "paid",
+ "failed",
+ "aborted"
+ ],
+ "mappedType": "enum"
+ },
+ "status_reason": {
+ "name": "status_reason",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "text"
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "json"
+ },
+ "payout_id": {
+ "name": "payout_id",
+ "type": "text",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "text"
+ },
+ "raw_amount": {
+ "name": "raw_amount",
+ "type": "jsonb",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "unique": false,
+ "length": null,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "json"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "unique": false,
+ "length": 6,
+ "precision": null,
+ "scale": null,
+ "default": "now()",
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "datetime"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": false,
+ "unique": false,
+ "length": 6,
+ "precision": null,
+ "scale": null,
+ "default": "now()",
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "datetime"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "timestamptz",
+ "unsigned": false,
+ "autoincrement": false,
+ "primary": false,
+ "nullable": true,
+ "unique": false,
+ "length": 6,
+ "precision": null,
+ "scale": null,
+ "default": null,
+ "comment": null,
+ "enumItems": [],
+ "mappedType": "datetime"
+ }
+ },
+ "name": "payout_reversal",
+ "schema": "public",
+ "indexes": [
+ {
+ "keyName": "IDX_payout_reversal_payout_id",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payout_reversal_payout_id\" ON \"payout_reversal\" (\"payout_id\") WHERE deleted_at IS NULL"
+ },
+ {
+ "keyName": "IDX_payout_reversal_deleted_at",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payout_reversal_deleted_at\" ON \"payout_reversal\" (\"deleted_at\") WHERE deleted_at IS NULL"
+ },
+ {
+ "keyName": "IDX_payout_reversal_refund_id",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_payout_reversal_refund_id\" ON \"payout_reversal\" (\"refund_id\") WHERE deleted_at IS NULL AND refund_id IS NOT NULL"
+ },
+ {
+ "keyName": "IDX_payout_reversal_status_created_at",
+ "columnNames": [],
+ "composite": false,
+ "constraint": false,
+ "primary": false,
+ "unique": false,
+ "expression": "CREATE INDEX IF NOT EXISTS \"IDX_payout_reversal_status_created_at\" ON \"payout_reversal\" (\"status\", \"created_at\") WHERE deleted_at IS NULL"
+ },
+ {
+ "keyName": "payout_reversal_pkey",
+ "columnNames": [
+ "id"
+ ],
+ "composite": false,
+ "constraint": true,
+ "primary": true,
+ "unique": true
+ }
+ ],
+ "checks": [],
+ "foreignKeys": {
+ "payout_reversal_payout_id_foreign": {
+ "constraintName": "payout_reversal_payout_id_foreign",
+ "columnNames": [
+ "payout_id"
+ ],
+ "localTableName": "public.payout_reversal",
+ "referencedColumnNames": [
+ "id"
+ ],
+ "referencedTableName": "public.payout",
+ "deleteRule": "cascade",
+ "updateRule": "cascade"
+ }
+ },
+ "nativeEnums": {}
}
],
"nativeEnums": {}
diff --git a/packages/core/src/modules/payout/migrations/Migration20261028120000.ts b/packages/core/src/modules/payout/migrations/Migration20261028120000.ts
new file mode 100644
index 000000000..347a5bb9b
--- /dev/null
+++ b/packages/core/src/modules/payout/migrations/Migration20261028120000.ts
@@ -0,0 +1,99 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations"
+
+export class Migration20261028120000 extends Migration {
+ override async up(): Promise<void> {
+ this.addSql(`alter table if exists "payout" drop constraint if exists "payout_settlement_id_foreign";`)
+ this.addSql(`DROP INDEX IF EXISTS "IDX_payout_settlement_id";`)
+ this.addSql(`alter table if exists "payout" drop column if exists "settlement_id";`)
+ this.addSql(`alter table if exists "payout_account" drop column if exists "provider_id", drop column if exists "ignored", drop column if exists "requirements";`)
+
+ this.addSql(`DROP INDEX IF EXISTS "IDX_payout_account_provider_account_id";`)
+ this.addSql(`
+ DO $$
+ BEGIN
+ IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = 'payout_account' AND column_name = 'provider_account_id') THEN
+ IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = 'payout_account' AND column_name = 'external_id') THEN
+ UPDATE "payout_account" SET "external_id" = "provider_account_id" WHERE "external_id" IS NULL;
+ ALTER TABLE "payout_account" DROP COLUMN "provider_account_id";
+ ELSE
+ ALTER TABLE "payout_account" RENAME COLUMN "provider_account_id" TO "external_id";
+ END IF;
+ END IF;
+ END $$;
+ `)
+ this.addSql(`alter table if exists "payout_account" add column if not exists "external_id" text null, add column if not exists "kyc_status" text check ("kyc_status" in ('pending_submission', 'pending_approval', 'approved', 'refused')) null, add column if not exists "payouts_enabled" boolean not null default false, add column if not exists "charges_enabled" boolean not null default false, add column if not exists "details_submitted" boolean not null default false, add column if not exists "disabled_reason" text null, add column if not exists "onboarding_token" text null, add column if not exists "onboarding_token_issued_at" timestamptz null, add column if not exists "last_synced_at" timestamptz null;`)
+ this.addSql(`update "payout_account" set "external_id" = "data"->>'id' where "external_id" is null and "data"->>'id' is not null;`)
+ this.addSql(`update "payout_account" set "payouts_enabled" = true, "charges_enabled" = true, "details_submitted" = true where "status" = 'active' and "last_synced_at" is null;`)
+ this.addSql(`update "payout_account" set "onboarding_token_issued_at" = now() where "onboarding_token" is not null and "onboarding_token_issued_at" is null;`)
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_payout_account_external_id" ON "payout_account" ("external_id") WHERE deleted_at IS NULL AND external_id IS NOT NULL;`)
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_payout_account_onboarding_token" ON "payout_account" ("onboarding_token") WHERE deleted_at IS NULL AND onboarding_token IS NOT NULL;`)
+
+ this.addSql(`alter table if exists "payout" add column if not exists "order_id" text null, add column if not exists "status_reason" text null, add column if not exists "metadata" jsonb null;`)
+ // Payouts created before order_id existed kept the Stripe transfer as data,
+ // with the order id as its transfer_group. Several rows could carry the same
+ // transfer for one order, so only the oldest gets the order id.
+ this.addSql(`
+ with derived as (
+ select "id", coalesce("data"->>'order_id', "data"->>'transfer_group', "data"->'metadata'->>'order_id') as "derived_order_id",
+ row_number() over (partition by coalesce("data"->>'order_id', "data"->>'transfer_group', "data"->'metadata'->>'order_id') order by "created_at") as "position"
+ from "payout"
+ where "order_id" is null and "deleted_at" is null
+ )
+ update "payout" set "order_id" = derived."derived_order_id"
+ from derived
+ where "payout"."id" = derived."id"
+ and derived."derived_order_id" is not null
+ and derived."position" = 1
+ and not exists (select 1 from "payout" taken where taken."order_id" = derived."derived_order_id" and taken."deleted_at" is null);
+ `)
+ this.addSql(`
+ DO $$
+ BEGIN
+ IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = 'payout' AND column_name = 'provider_payout_id') THEN
+ EXECUTE 'UPDATE "payout" SET "data" = coalesce("data", ''{}''::jsonb) || jsonb_build_object(''provider'', coalesce("data"->''provider'', ''{}''::jsonb) || jsonb_build_object(''id'', "provider_payout_id")) WHERE "provider_payout_id" IS NOT NULL';
+ END IF;
+ END $$;
+ `)
+ this.addSql(`update "payout" set "data" = "data" || jsonb_build_object('provider', jsonb_build_object('id', "data"->>'id')) where "data"->'provider' is null and "data"->>'id' is not null;`)
+ this.addSql(`DROP INDEX IF EXISTS "IDX_payout_provider_payout_id";`)
+ this.addSql(`alter table if exists "payout" drop column if exists "provider_payout_id";`)
+ this.addSql(`alter table if exists "payout" drop constraint if exists "payout_status_check";`)
+ this.addSql(`update "payout" set "status" = 'aborted' where "status" = 'canceled';`)
+ this.addSql(`alter table if exists "payout" add constraint "payout_status_check" check ("status" in ('pending', 'on_hold', 'processing', 'paid', 'failed', 'aborted'));`)
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_payout_order_id" ON "payout" ("order_id") WHERE deleted_at IS NULL AND order_id IS NOT NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_payout_account_id_created_at" ON "payout" ("account_id", "created_at") WHERE deleted_at IS NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_payout_status_created_at" ON "payout" ("status", "created_at") WHERE deleted_at IS NULL;`)
+
+ this.addSql(`create table if not exists "payout_reversal" ("id" text not null, "refund_id" text null, "amount" numeric not null, "raw_amount" jsonb not null, "status" text check ("status" in ('pending', 'on_hold', 'processing', 'paid', 'failed', 'aborted')) not null default 'pending', "status_reason" text null, "data" jsonb null, "payout_id" text not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "payout_reversal_pkey" primary key ("id"));`)
+ this.addSql(`
+ DO $$
+ BEGIN
+ IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = 'payout_reversal' AND column_name = 'provider_reversal_id') THEN
+ EXECUTE 'UPDATE "payout_reversal" SET "data" = coalesce("data", ''{}''::jsonb) || jsonb_build_object(''provider'', coalesce("data"->''provider'', ''{}''::jsonb) || jsonb_build_object(''id'', "provider_reversal_id")) WHERE "provider_reversal_id" IS NOT NULL';
+ END IF;
+ END $$;
+ `)
+ this.addSql(`alter table if exists "payout_reversal" drop column if exists "provider_reversal_id";`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_payout_reversal_deleted_at" ON "payout_reversal" ("deleted_at") WHERE deleted_at IS NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_payout_reversal_payout_id" ON "payout_reversal" ("payout_id") WHERE deleted_at IS NULL;`)
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_payout_reversal_refund_id" ON "payout_reversal" ("refund_id") WHERE deleted_at IS NULL AND refund_id IS NOT NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_payout_reversal_status_created_at" ON "payout_reversal" ("status", "created_at") WHERE deleted_at IS NULL;`)
+ this.addSql(`alter table if exists "payout_reversal" drop constraint if exists "payout_reversal_payout_id_foreign";`)
+ this.addSql(`alter table if exists "payout_reversal" add constraint "payout_reversal_payout_id_foreign" foreign key ("payout_id") references "payout" ("id") on update cascade on delete cascade;`)
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(`drop table if exists "payout_reversal" cascade;`)
+
+ this.addSql(`DROP INDEX IF EXISTS "IDX_payout_order_id";`)
+ this.addSql(`alter table if exists "payout" drop constraint if exists "payout_status_check";`)
+ this.addSql(`update "payout" set "status" = 'canceled' where "status" = 'aborted';`)
+ this.addSql(`update "payout" set "status" = 'pending' where "status" = 'on_hold';`)
+ this.addSql(`alter table if exists "payout" add constraint "payout_status_check" check ("status" in ('pending', 'processing', 'paid', 'failed', 'canceled'));`)
+ this.addSql(`alter table if exists "payout" drop column if exists "order_id", drop column if exists "status_reason", drop column if exists "metadata";`)
+
+ this.addSql(`DROP INDEX IF EXISTS "IDX_payout_account_external_id";`)
+ this.addSql(`DROP INDEX IF EXISTS "IDX_payout_account_onboarding_token";`)
+ this.addSql(`alter table if exists "payout_account" drop column if exists "external_id", drop column if exists "kyc_status", drop column if exists "payouts_enabled", drop column if exists "charges_enabled", drop column if exists "details_submitted", drop column if exists "disabled_reason", drop column if exists "onboarding_token", drop column if exists "onboarding_token_issued_at", drop column if exists "last_synced_at";`)
+ }
+}
diff --git a/packages/core/src/modules/payout/models/index.ts b/packages/core/src/modules/payout/models/index.ts
index 9d7b04c8c..75305c0bb 100644
--- a/packages/core/src/modules/payout/models/index.ts
+++ b/packages/core/src/modules/payout/models/index.ts
@@ -1,3 +1,4 @@
export { Onboarding } from './onboarding'
export { Payout } from './payout'
export { PayoutAccount } from './payout-account'
+export { PayoutReversal } from './payout-reversal'
diff --git a/packages/core/src/modules/payout/models/payout-account.ts b/packages/core/src/modules/payout/models/payout-account.ts
index 1e70e3f06..17ec4b057 100644
--- a/packages/core/src/modules/payout/models/payout-account.ts
+++ b/packages/core/src/modules/payout/models/payout-account.ts
@@ -1,18 +1,44 @@
import { model } from "@medusajs/framework/utils";
-import { PayoutAccountStatus } from "@mercurjs/types";
+import { PayoutAccountStatus, PayoutKycStatus } from "@mercurjs/types";
import { Onboarding } from "./onboarding";
import { Payout } from "./payout";
-export const PayoutAccount = model.define("payout_account", {
- id: model.id({ prefix: "pacc" }).primaryKey(),
- status: model.enum(PayoutAccountStatus).default(PayoutAccountStatus.PENDING),
- data: model.json().default({}),
- context: model.json().nullable(),
- onboarding: model.hasOne(() => Onboarding, {
- mappedBy: 'account'
- }).nullable(),
- payouts: model.hasMany(() => Payout, {
- mappedBy: 'account'
- }),
-});
+export const PayoutAccount = model
+ .define("payout_account", {
+ id: model.id({ prefix: "pacc" }).primaryKey(),
+ external_id: model.text().nullable(),
+ status: model.enum(PayoutAccountStatus).default(PayoutAccountStatus.PENDING),
+ kyc_status: model.enum(PayoutKycStatus).nullable(),
+ payouts_enabled: model.boolean().default(false),
+ charges_enabled: model.boolean().default(false),
+ details_submitted: model.boolean().default(false),
+ disabled_reason: model.text().nullable(),
+ onboarding_token: model.text().nullable(),
+ onboarding_token_issued_at: model.dateTime().nullable(),
+ last_synced_at: model.dateTime().nullable(),
+ data: model.json().default({}),
+ context: model.json().nullable(),
+ onboarding: model
+ .hasOne(() => Onboarding, {
+ mappedBy: "account",
+ })
+ .nullable(),
+ payouts: model.hasMany(() => Payout, {
+ mappedBy: "account",
+ }),
+ })
+ .indexes([
+ {
+ name: "IDX_payout_account_external_id",
+ on: ["external_id"],
+ unique: true,
+ where: "deleted_at IS NULL AND external_id IS NOT NULL",
+ },
+ {
+ name: "IDX_payout_account_onboarding_token",
+ on: ["onboarding_token"],
+ unique: true,
+ where: "deleted_at IS NULL AND onboarding_token IS NOT NULL",
+ },
+ ]);
diff --git a/packages/core/src/modules/payout/models/payout-reversal.ts b/packages/core/src/modules/payout/models/payout-reversal.ts
new file mode 100644
index 000000000..395cc9312
--- /dev/null
+++ b/packages/core/src/modules/payout/models/payout-reversal.ts
@@ -0,0 +1,35 @@
+import { model } from '@medusajs/framework/utils'
+
+import { Payout } from './payout'
+import { PayoutStatus } from '@mercurjs/types'
+
+export const PayoutReversal = model
+ .define('payout_reversal', {
+ id: model.id({ prefix: 'pourev' }).primaryKey(),
+ refund_id: model.text().nullable(),
+ amount: model.bigNumber(),
+ status: model.enum(PayoutStatus).default(PayoutStatus.PENDING),
+ status_reason: model.text().nullable(),
+ data: model.json().nullable(),
+ payout: model.belongsTo(() => Payout, {
+ mappedBy: 'reversals'
+ })
+ })
+ .indexes([
+ {
+ name: 'IDX_payout_reversal_payout_id',
+ on: ['payout_id'],
+ where: 'deleted_at IS NULL'
+ },
+ {
+ name: 'IDX_payout_reversal_refund_id',
+ on: ['refund_id'],
+ unique: true,
+ where: 'deleted_at IS NULL AND refund_id IS NOT NULL'
+ },
+ {
+ name: 'IDX_payout_reversal_status_created_at',
+ on: ['status', 'created_at'],
+ where: 'deleted_at IS NULL'
+ }
+ ])
diff --git a/packages/core/src/modules/payout/models/payout.ts b/packages/core/src/modules/payout/models/payout.ts
index 427b5f373..ff2bb283c 100644
--- a/packages/core/src/modules/payout/models/payout.ts
+++ b/packages/core/src/modules/payout/models/payout.ts
@@ -1,19 +1,29 @@
import { model } from '@medusajs/framework/utils'
import { PayoutAccount } from './payout-account'
+import { PayoutReversal } from './payout-reversal'
import { PayoutStatus } from '@mercurjs/types'
export const Payout = model
.define('payout', {
id: model.id({ prefix: 'pout' }).primaryKey(),
display_id: model.autoincrement(),
+ order_id: model.text().nullable(),
currency_code: model.text(),
amount: model.bigNumber(),
+ status: model.enum(PayoutStatus).default(PayoutStatus.PENDING),
+ status_reason: model.text().nullable(),
data: model.json().nullable(),
+ metadata: model.json().nullable(),
account: model.belongsTo(() => PayoutAccount, {
mappedBy: 'payouts'
}),
- status: model.enum(PayoutStatus).default(PayoutStatus.PENDING)
+ reversals: model.hasMany(() => PayoutReversal, {
+ mappedBy: 'payout'
+ })
+ })
+ .cascades({
+ delete: ['reversals']
})
.indexes([
{
@@ -25,5 +35,11 @@ export const Payout = model
name: 'IDX_payout_status_created_at',
on: ['status', 'created_at'],
where: 'deleted_at IS NULL'
+ },
+ {
+ name: 'IDX_payout_order_id',
+ on: ['order_id'],
+ unique: true,
+ where: 'deleted_at IS NULL AND order_id IS NOT NULL'
}
])
diff --git a/packages/core/src/modules/payout/providers/system.ts b/packages/core/src/modules/payout/providers/system.ts
index 16cf164a0..83a9b41f2 100644
--- a/packages/core/src/modules/payout/providers/system.ts
+++ b/packages/core/src/modules/payout/providers/system.ts
@@ -1,43 +1,69 @@
import crypto from "crypto"
import {
- CreatePayoutAccountInput,
- CreatePayoutAccountResponse,
- CreatePayoutInput,
- CreatePayoutResponse,
+ AccountOutput,
+ CreateAccountInput,
+ CreateLoginLinkInput,
CreateOnboardingInput,
- CreateOnboardingResponse,
- PayoutWebhookActionInput,
- PayoutWebhookResult,
- IPayoutProvider,
+ CreatePayoutInput,
+ LinkOutput,
+ ListAccountsInput,
+ ListAccountsOutput,
PayoutAccountStatus,
+ PayoutOutput,
PayoutStatus,
+ PayoutWebhookActionInput,
+ PayoutWebhookResult,
+ RetrieveAccountInput,
+ ReversePayoutInput,
} from "@mercurjs/types"
-export class SystemPayoutProvider implements IPayoutProvider {
+import { AbstractPayoutProvider } from "../utils/abstract-payout-provider"
+
+const activeAccount = (id: string, data: Record<string, unknown> = {}): AccountOutput => ({
+ id,
+ status: PayoutAccountStatus.ACTIVE,
+ payouts_enabled: true,
+ charges_enabled: true,
+ details_submitted: true,
+ disabled_reason: null,
+ requirements: { currently_due: [], past_due: [], pending_verification: [] },
+ data,
+})
+
+export class SystemPayoutProvider extends AbstractPayoutProvider {
static identifier = "system"
- async createPayoutAccount(
- _input: CreatePayoutAccountInput
- ): Promise<CreatePayoutAccountResponse> {
- return {
- id: crypto.randomUUID(),
- status: PayoutAccountStatus.ACTIVE,
- data: {},
- }
+ constructor(container: Record<string, unknown>, options: Record<string, unknown>) {
+ super(container, options)
+ }
+
+ async createAccount(_input: CreateAccountInput): Promise<AccountOutput> {
+ return activeAccount(crypto.randomUUID())
}
- async createPayout(_input: CreatePayoutInput): Promise<CreatePayoutResponse> {
- return {
- status: PayoutStatus.PAID,
- data: {},
- }
+ async retrieveAccount(input: RetrieveAccountInput): Promise<AccountOutput> {
+ return activeAccount(input.account.id, input.account.data)
}
- async createOnboarding(
- _input: CreateOnboardingInput
- ): Promise<CreateOnboardingResponse> {
- return { data: {} }
+ async listAccounts(_input: ListAccountsInput): Promise<ListAccountsOutput> {
+ return { accounts: [], has_more: false }
+ }
+
+ async createOnboarding(input: CreateOnboardingInput): Promise<LinkOutput> {
+ return { url: input.return_url, data: {} }
+ }
+
+ async createLoginLink(input: CreateLoginLinkInput): Promise<LinkOutput> {
+ return { url: `system://account/${input.account.id}`, data: {} }
+ }
+
+ async createPayout(_input: CreatePayoutInput): Promise<PayoutOutput> {
+ return { id: crypto.randomUUID(), status: PayoutStatus.PAID, data: {} }
+ }
+
+ async reversePayout(_input: ReversePayoutInput): Promise<PayoutOutput> {
+ return { id: crypto.randomUUID(), status: PayoutStatus.PAID, data: {} }
}
async getWebhookActionAndData(
@@ -46,4 +72,3 @@ export class SystemPayoutProvider implements IPayoutProvider {
return { action: "not_supported" }
}
}
-
diff --git a/packages/core/src/modules/payout/services/payout-module-service.ts b/packages/core/src/modules/payout/services/payout-module-service.ts
index b8c53d69d..6c1a799a6 100644
--- a/packages/core/src/modules/payout/services/payout-module-service.ts
+++ b/packages/core/src/modules/payout/services/payout-module-service.ts
@@ -7,233 +7,521 @@ import {
MedusaService,
} from "@medusajs/framework/utils"
import {
+ AccountOutput,
+ CreateAccountInput,
CreatePayoutAccountDTO,
- CreatePayoutAccountResponse,
- CreatePayoutDTO,
CreateOnboardingDTO,
+ IPayoutModuleService,
OnboardingDTO,
PayoutAccountDTO,
+ PayoutAccountRequirements,
PayoutAccountStatus,
PayoutDTO,
- PayoutWebhookActionInput,
- PayoutWebhookResult,
+ PayoutKycStatus,
PayoutModuleOptions,
+ PayoutOutput,
+ PayoutProviderErrorCode,
+ PayoutReversalDTO,
PayoutStatus,
- PAYOUT_MODULE_OPTION_DEFAULTS,
+ PayoutStatusReason,
+ PayoutWebhookActionInput,
+ PayoutWebhookResult,
+ ResolvedPayoutModuleOptions,
+ resolvePayoutModuleOptions,
} from "@mercurjs/types"
import PayoutProviderService from "./provider-service"
-import { Onboarding, Payout, PayoutAccount } from "../models"
-import { Context, DAL, InferEntityType } from "@medusajs/framework/types"
-import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
+import {
+ Onboarding,
+ Payout,
+ PayoutAccount,
+ PayoutReversal,
+} from "../models"
+import { Context, DAL } from "@medusajs/framework/types"
+import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"
type InjectedDependencies = {
payoutProviderService: PayoutProviderService
baseRepository: DAL.RepositoryService
}
-export default class PayoutModuleService extends MedusaService({
- Onboarding,
- Payout,
- PayoutAccount,
-}) {
+type ProviderAccount = { external_id?: string | null; data?: Record<string, unknown> | null }
+
+type ProviderResult = {
+ status: PayoutStatus
+ status_reason: string | null
+ data: Record<string, unknown>
+}
+
+export default class PayoutModuleService
+ extends MedusaService<{
+ Onboarding: { dto: OnboardingDTO }
+ Payout: { dto: PayoutDTO }
+ PayoutAccount: { dto: PayoutAccountDTO }
+ PayoutReversal: { dto: PayoutReversalDTO }
+ }>({
+ Onboarding,
+ Payout,
+ PayoutAccount,
+ PayoutReversal,
+ })
+ implements IPayoutModuleService
+{
+ protected static readonly PROCESSABLE_STATUSES = [PayoutStatus.PENDING, PayoutStatus.FAILED]
+ protected static readonly STATUS_DETAIL_MAX_LENGTH = 1024
+
protected readonly payoutProviderService_: PayoutProviderService
protected readonly baseRepository_: DAL.RepositoryService
- protected readonly options_: PayoutModuleOptions
+ protected readonly options_: ResolvedPayoutModuleOptions
constructor({ payoutProviderService, baseRepository }: InjectedDependencies, options: PayoutModuleOptions) {
// @ts-ignore
super(...arguments)
this.payoutProviderService_ = payoutProviderService
this.baseRepository_ = baseRepository
- this.options_ = {
- ...PAYOUT_MODULE_OPTION_DEFAULTS,
- ...(options ?? {}),
- }
+ this.options_ = resolvePayoutModuleOptions(options)
}
- getOptions() {
- return {
- ...PAYOUT_MODULE_OPTION_DEFAULTS,
- ...(this.options_ ?? {}),
- }
+ getOptions(): ResolvedPayoutModuleOptions {
+ return this.options_
}
@InjectManager()
@EmitEvents()
async createPayoutAccount(
input: CreatePayoutAccountDTO,
- @MedusaContext() sharedContext?: Context<EntityManager>
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
): Promise<PayoutAccountDTO> {
- let payoutAccount: InferEntityType<typeof PayoutAccount> | null = null
- let providerAccount: CreatePayoutAccountResponse | null = null
+ const payoutAccount = await this.createPayoutAccounts(
+ { data: input.data ?? {}, context: (input.context ?? null) as Record<string, unknown> | null },
+ sharedContext
+ )
+ let providerAccount: AccountOutput
try {
- payoutAccount = await this.createPayoutAccounts(
- { data: input.data, context: input.context as Record<string, unknown> },
- sharedContext
- )
-
- providerAccount = await this.payoutProviderService_.createPayoutAccount({
- context: {
- idempotency_key: payoutAccount.id,
- ...input.context
- },
- data: {
- ...input.data,
- account_id: payoutAccount.id,
- }
- })
-
- payoutAccount = await this.updatePayoutAccounts(
- {
- id: payoutAccount.id,
- data: providerAccount.data,
- status: providerAccount.status
- },
- sharedContext
+ providerAccount = await this.payoutProviderService_.createAccount(
+ this.providerAccountInput_(payoutAccount.id, input)
)
} catch (error) {
- if (providerAccount && payoutAccount?.id) {
- await this.updatePayoutAccounts(
- {
- id: payoutAccount.id,
- data: providerAccount.data,
- status: providerAccount.status,
- },
- sharedContext
- ).catch(() => null)
- } else if (payoutAccount?.id) {
- await this.deletePayoutAccounts(payoutAccount.id, sharedContext)
- }
+ await this.deletePayoutAccounts(payoutAccount.id, sharedContext)
throw error
}
- return await this.baseRepository_.serialize<PayoutAccountDTO>(payoutAccount)
+ const updated = await this.updatePayoutAccounts(
+ { id: payoutAccount.id, ...this.accountFieldsFromProvider_(providerAccount) },
+ sharedContext
+ )
+
+ return await this.baseRepository_.serialize<PayoutAccountDTO>(updated)
}
- @InjectTransactionManager()
+ @InjectManager()
+ @EmitEvents()
+ async syncPayoutAccount(
+ accountId: string,
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
+ ): Promise<PayoutAccountDTO> {
+ const account = await this.retrievePayoutAccount(accountId, {}, sharedContext)
+
+ const providerAccount = await this.payoutProviderService_.retrieveAccount({
+ account: this.providerAccountRef_(account),
+ })
+
+ const updated = await this.updatePayoutAccounts(
+ {
+ id: accountId,
+ ...this.accountFieldsFromProvider_(providerAccount),
+ ...(providerAccount.details_submitted
+ ? { onboarding_token: null, onboarding_token_issued_at: null }
+ : {}),
+ },
+ sharedContext
+ )
+
+ return await this.baseRepository_.serialize<PayoutAccountDTO>(updated)
+ }
+
+ @InjectManager()
+ @EmitEvents()
+ async deletePayoutAccount(
+ accountId: string,
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
+ ): Promise<void> {
+ const account = await this.retrievePayoutAccount(accountId, { relations: ["onboarding"] }, sharedContext)
+
+ if (account.external_id) {
+ await this.payoutProviderService_.deleteAccount({ account: this.providerAccountRef_(account) })
+ }
+
+ if (account.onboarding) {
+ await this.deleteOnboardings(account.onboarding.id, sharedContext)
+ }
+ await this.deletePayoutAccounts(accountId, sharedContext)
+ }
+
+ @InjectManager()
@EmitEvents()
async createOnboarding(
input: CreateOnboardingDTO,
- @MedusaContext() sharedContext?: Context<EntityManager>
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
): Promise<OnboardingDTO> {
- const payoutAccount = await this.retrievePayoutAccount(input.account_id, {
- select: ['data'],
- relations: ['onboarding']
- }, sharedContext)
+ const account = await this.retrievePayoutAccount(
+ input.account_id,
+ { relations: ["onboarding"] },
+ sharedContext
+ )
- const providerData = await this.payoutProviderService_.createOnboarding(
- {
- context: {
- idempotency_key: input.account_id,
- ...input.context
- },
- data: {
- ...payoutAccount.data,
- ...input.data
- }
+ const loginLink = account.details_submitted
+ ? await this.payoutProviderService_.createLoginLink({ account: this.providerAccountRef_(account) })
+ : null
+
+ let data: Record<string, unknown>
+ if (loginLink) {
+ data = { ...loginLink.data, url: loginLink.url, kind: "login", expires_at: loginLink.expires_at ?? null }
+ } else {
+ const token =
+ input.rotate_token || !this.isOnboardingTokenValid_(account)
+ ? this.generateOnboardingToken_()
+ : (account.onboarding_token as string)
+ if (token !== account.onboarding_token) {
+ await this.updatePayoutAccounts(
+ { id: account.id, onboarding_token: token, onboarding_token_issued_at: new Date() },
+ sharedContext
+ )
}
- )
- const upsertOnboardingData = {
- ...(payoutAccount.onboarding ? { id: payoutAccount.onboarding.id } : {}),
- account: input.account_id,
- data: providerData.data,
- context: input.context as Record<string, unknown>
+ const link = await this.payoutProviderService_.createOnboarding({
+ context: { ...input.context, idempotency_key: input.account_id },
+ data: { ...account.data, ...input.data },
+ account: this.providerAccountRef_(account),
+ refresh_url:
+ (input.data?.refresh_url as string | undefined) ??
+ `${this.options_.onboarding.refreshBaseUrl}/payout/onboarding/refresh?token=${token}`,
+ return_url: (input.data?.return_url as string | undefined) ?? this.options_.onboarding.returnUrl,
+ })
+ data = { ...link.data, url: link.url, kind: "onboarding", expires_at: link.expires_at ?? null }
}
- let onboarding: InferEntityType<typeof Onboarding>
- if (!payoutAccount.onboarding) {
- onboarding = await this.createOnboardings(
- upsertOnboardingData,
- sharedContext
- )
- } else {
- onboarding = await this.updateOnboardings(
- upsertOnboardingData,
+ const onboarding = account.onboarding
+ ? await this.updateOnboardings({ id: account.onboarding.id, data }, sharedContext)
+ : await this.createOnboardings(
+ {
+ account_id: input.account_id,
+ data,
+ context: (input.context ?? null) as Record<string, unknown> | null,
+ },
+ sharedContext
+ )
+
+ return await this.baseRepository_.serialize<OnboardingDTO>(onboarding)
+ }
+
+ @InjectManager()
+ @EmitEvents()
+ async processPayout(
+ payoutId: string,
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
+ ): Promise<PayoutDTO> {
+ const { payout, attempt } = await this.processPayout_(payoutId, sharedContext)
+
+ if (attempt) {
+ const result = await this.processPayoutFromProvider_(payout, attempt)
+ await this.updatePayouts(
+ { id: payout.id, ...result, data: { ...(payout.data ?? {}), ...attempt, ...result.data } },
sharedContext
)
}
- return await this.baseRepository_.serialize<OnboardingDTO>(onboarding)
+ const updated = await this.retrievePayout(payoutId, {}, sharedContext)
+ return await this.baseRepository_.serialize<PayoutDTO>(updated)
}
@InjectManager()
@EmitEvents()
- // @ts-ignore
- async createPayouts(
- input: CreatePayoutDTO,
- @MedusaContext() sharedContext?: Context<EntityManager>
- ): Promise<PayoutDTO> {
- const { payout, payoutAccount } = await this.createPayouts_(input, sharedContext)
+ async processPayoutReversal(
+ reversalId: string,
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
+ ): Promise<PayoutReversalDTO> {
+ const { reversal, attempt } = await this.processPayoutReversal_(reversalId, sharedContext)
+
+ if (attempt) {
+ const result = await this.processPayoutReversalFromProvider_(reversal, attempt)
+ await this.updatePayoutReversals(
+ { id: reversal.id, ...result, data: { ...(reversal.data ?? {}), ...attempt, ...result.data } },
+ sharedContext
+ )
+ }
+
+ const updated = await this.retrievePayoutReversal(reversalId, {}, sharedContext)
+ return await this.baseRepository_.serialize<PayoutReversalDTO>(updated)
+ }
+
+ async getWebhookActionAndData(input: PayoutWebhookActionInput): Promise<PayoutWebhookResult> {
+ return await this.payoutProviderService_.getWebhookActionAndData(input)
+ }
+
+ @InjectTransactionManager()
+ protected async processPayout_(
+ payoutId: string,
+ @MedusaContext() sharedContext: Context<SqlEntityManager> = {}
+ ): Promise<{ payout: PayoutDTO; attempt: { attempts: number; idempotency_key: string } | null }> {
+ await this.lockRow_("payout", payoutId, sharedContext)
+
+ const payout = await this.retrievePayout(payoutId, { relations: ["account"] }, sharedContext)
+ if (!PayoutModuleService.PROCESSABLE_STATUSES.includes(payout.status)) {
+ return { payout, attempt: null }
+ }
+
+ const attempt = this.nextAttempt_(payout.id, payout.data)
+ await this.updatePayouts(
+ { id: payout.id, status: PayoutStatus.PROCESSING, data: { ...(payout.data ?? {}), ...attempt } },
+ sharedContext
+ )
+
+ return { payout, attempt }
+ }
+
+ @InjectTransactionManager()
+ protected async processPayoutReversal_(
+ reversalId: string,
+ @MedusaContext() sharedContext: Context<SqlEntityManager> = {}
+ ): Promise<{ reversal: PayoutReversalDTO; attempt: { attempts: number; idempotency_key: string } | null }> {
+ await this.lockRow_("payout_reversal", reversalId, sharedContext)
+
+ const reversal = await this.retrievePayoutReversal(reversalId, { relations: ["payout"] }, sharedContext)
+ if (!PayoutModuleService.PROCESSABLE_STATUSES.includes(reversal.status)) {
+ return { reversal, attempt: null }
+ }
+
+ const attempt = this.nextAttempt_(reversal.id, reversal.data)
+ await this.updatePayoutReversals(
+ {
+ id: reversal.id,
+ status: PayoutStatus.PROCESSING,
+ data: { ...(reversal.data ?? {}), ...attempt },
+ },
+ sharedContext
+ )
+
+ return { reversal, attempt }
+ }
+
+ // Runs outside the transaction so the row lock is never held across the provider call.
+ protected async processPayoutFromProvider_(
+ payout: PayoutDTO,
+ attempt: { idempotency_key: string }
+ ): Promise<ProviderResult> {
+ const source = (payout.data?.source_payment ?? null) as { id: string; data: Record<string, unknown> } | null
- let updated: InferEntityType<typeof Payout>
try {
- const providerResponse = await this.payoutProviderService_.createPayout({
- account_id: input.account_id,
- amount: input.amount,
- currency_code: input.currency_code,
- context: {
- idempotency_key: payout.id,
- ...input.context
+ const response = await this.payoutProviderService_.createPayout({
+ account: this.providerAccountRef_(payout.account ?? {}),
+ amount: payout.amount,
+ currency_code: payout.currency_code,
+ source_payment: source,
+ group: payout.order_id,
+ metadata: {
+ payout_id: payout.id,
+ ...(payout.order_id ? { order_id: payout.order_id } : {}),
},
- data: {
- ...payoutAccount.data,
- ...input.data
- }
+ context: { idempotency_key: attempt.idempotency_key },
})
- updated = await this.updatePayouts(
- {
- id: payout.id,
- data: providerResponse.data,
- status: providerResponse.status,
- },
- sharedContext
- )
+ return this.statusFromProvider_(response)
} catch (error) {
- await this.deletePayouts(payout.id, sharedContext).catch(() => null)
- throw error
+ return this.statusFromError_(error)
}
+ }
- return await this.baseRepository_.serialize<PayoutDTO>(updated)
+ protected async processPayoutReversalFromProvider_(
+ reversal: PayoutReversalDTO,
+ attempt: { idempotency_key: string }
+ ): Promise<ProviderResult> {
+ const payout = reversal.payout as PayoutDTO
+ const provider = (payout.data?.provider ?? {}) as Record<string, unknown>
+
+ try {
+ const response = await this.payoutProviderService_.reversePayout({
+ payout: { id: provider.id as string, data: provider },
+ amount: reversal.amount,
+ currency_code: payout.currency_code,
+ metadata: {
+ payout_id: payout.id,
+ payout_reversal_id: reversal.id,
+ ...(reversal.refund_id ? { refund_id: reversal.refund_id } : {}),
+ },
+ context: { idempotency_key: attempt.idempotency_key },
+ })
+
+ return this.statusFromProvider_(response)
+ } catch (error) {
+ return this.statusFromError_(error)
+ }
}
- @InjectTransactionManager()
- protected async createPayouts_(
- input: CreatePayoutDTO,
- @MedusaContext() sharedContext?: Context<EntityManager>
- ): Promise<{
- payout: InferEntityType<typeof Payout>
- payoutAccount: InferEntityType<typeof PayoutAccount>
- }> {
- const payoutAccount = await this.retrievePayoutAccount(input.account_id, {
- select: ['id', 'status', 'data']
- }, sharedContext)
-
- if (payoutAccount.status !== PayoutAccountStatus.ACTIVE) {
+ protected async lockRow_(table: string, id: string, sharedContext: Context<SqlEntityManager>) {
+ // A FOR UPDATE on a pooled (autocommit) connection would release the lock
+ // immediately, so require the transaction context.
+ const knex = sharedContext.transactionManager?.getTransactionContext()
+ if (!knex) {
throw new MedusaError(
- MedusaError.Types.NOT_ALLOWED,
- `Account '${input.account_id}' is not active`
+ MedusaError.Types.UNEXPECTED_STATE,
+ `Processing ${table} ${id} must run inside a transaction.`
)
}
- const payout = await super.createPayouts(
- {
- amount: input.amount,
- currency_code: input.currency_code,
- account_id: payoutAccount.id,
- status: PayoutStatus.PENDING,
+ await knex.raw("SET LOCAL lock_timeout = '3s'")
+ await knex(table).where("id", id).forUpdate().select("id")
+ }
+
+ /**
+ * The key of a request whose outcome is unknown is kept, so a retry after a
+ * timeout returns the payout the provider may already have made. Only a
+ * provider refusal clears it, and the next attempt gets a fresh key.
+ */
+ protected nextAttempt_(id: string, data: Record<string, unknown> | null) {
+ const attempts = Number(data?.attempts ?? 0) + 1
+ const kept = data?.idempotency_key as string | null | undefined
+
+ return {
+ attempts,
+ idempotency_key: kept ?? (attempts === 1 ? id : `${id}:${attempts}`),
+ }
+ }
+
+ protected statusFromProvider_(response: PayoutOutput): ProviderResult {
+ return {
+ status: response.status,
+ status_reason: null,
+ data: { provider: { ...response.data, id: response.id }, status_detail: null },
+ }
+ }
+
+ protected statusFromError_(error: unknown): ProviderResult {
+ const code = this.providerErrorCode_(error)
+ const message = error instanceof Error ? error.message : String(error)
+
+ return {
+ status: code === PayoutProviderErrorCode.FINAL ? PayoutStatus.ABORTED : PayoutStatus.FAILED,
+ status_reason: PayoutStatusReason.PROVIDER_ERROR,
+ data: {
+ status_detail: message.slice(0, PayoutModuleService.STATUS_DETAIL_MAX_LENGTH),
+ ...(code === PayoutProviderErrorCode.REFUSED ? { idempotency_key: null } : {}),
},
- sharedContext
- )
+ }
+ }
+
+ // Read structurally: the error may come from another copy of @mercurjs/types.
+ protected providerErrorCode_(error: unknown): PayoutProviderErrorCode {
+ const { code, final } = (error ?? {}) as { code?: unknown; final?: unknown }
+ if (final === true || code === PayoutProviderErrorCode.FINAL) {
+ return PayoutProviderErrorCode.FINAL
+ }
- return { payout, payoutAccount }
+ return code === PayoutProviderErrorCode.REFUSED ? PayoutProviderErrorCode.REFUSED : PayoutProviderErrorCode.UNKNOWN
}
- async getWebhookActionAndData(
- input: PayoutWebhookActionInput
- ): Promise<PayoutWebhookResult> {
- return await this.payoutProviderService_.getWebhookActionAndData(input)
+ protected isOnboardingTokenValid_(account: PayoutAccountDTO) {
+ if (!account.onboarding_token || !account.onboarding_token_issued_at) {
+ return false
+ }
+
+ const issuedAt = new Date(account.onboarding_token_issued_at).getTime()
+ return Date.now() - issuedAt < this.options_.onboarding.tokenTtlSeconds * 1000
+ }
+
+ protected generateOnboardingToken_() {
+ return Array.from(crypto.getRandomValues(new Uint8Array(16)))
+ .map((byte) => byte.toString(16).padStart(2, "0"))
+ .join("")
+ }
+
+ protected providerAccountRef_(account: ProviderAccount) {
+ return {
+ id: account.external_id ?? ((account.data?.id as string | undefined) ?? ""),
+ data: (account.data ?? {}) as Record<string, unknown>,
+ }
+ }
+
+ protected providerAccountInput_(accountId: string, input: CreatePayoutAccountDTO): CreateAccountInput {
+ const seller = input.seller
+ const prefill = this.options_.onboarding.prefill && seller
+
+ return {
+ context: { idempotency_key: accountId, ...input.context },
+ data: { ...input.data, account_id: accountId },
+ country:
+ (input.data?.country as string | undefined) ??
+ seller?.country_code ??
+ this.options_.onboarding.defaultCountry ??
+ undefined,
+ business_type:
+ (input.data?.business_type as "individual" | "company" | undefined) ??
+ (prefill ? (seller?.is_company ? "company" : "individual") : undefined),
+ business_profile: prefill
+ ? {
+ name: (input.data?.business_name as string | undefined) ?? seller?.name ?? null,
+ url: (input.data?.website as string | undefined) ?? seller?.website_url ?? null,
+ support_email: (input.data?.support_email as string | undefined) ?? seller?.email ?? null,
+ support_phone: (input.data?.support_phone as string | undefined) ?? seller?.phone ?? null,
+ }
+ : undefined,
+ metadata: {
+ account_id: accountId,
+ ...(seller?.id ? { seller_id: seller.id } : {}),
+ },
+ }
+ }
+
+ protected accountFieldsFromProvider_(account: AccountOutput) {
+ return {
+ external_id: account.id,
+ status: this.deriveAccountStatus_(account),
+ kyc_status: this.deriveKycStatus_(account.requirements, account.disabled_reason),
+ payouts_enabled: account.payouts_enabled,
+ charges_enabled: account.charges_enabled,
+ details_submitted: account.details_submitted,
+ disabled_reason: account.disabled_reason,
+ data: account.data,
+ last_synced_at: new Date(),
+ }
+ }
+
+ /**
+ * Outstanding requirements beat pending verification, a `rejected.*`
+ * disabled reason is final, any other disabled reason is still under review.
+ */
+ protected deriveKycStatus_(
+ requirements: PayoutAccountRequirements | null | undefined,
+ disabledReason: string | null | undefined
+ ): PayoutKycStatus {
+ if (requirements?.currently_due?.length || requirements?.past_due?.length) {
+ return PayoutKycStatus.PENDING_SUBMISSION
+ }
+
+ if (requirements?.pending_verification?.length) {
+ return PayoutKycStatus.PENDING_APPROVAL
+ }
+
+ if (disabledReason?.startsWith("rejected")) {
+ return PayoutKycStatus.REFUSED
+ }
+
+ return disabledReason ? PayoutKycStatus.PENDING_APPROVAL : PayoutKycStatus.APPROVED
+ }
+
+ protected deriveAccountStatus_(account: AccountOutput): PayoutAccountStatus {
+ if (account.status === PayoutAccountStatus.REJECTED || account.disabled_reason?.startsWith("rejected")) {
+ return PayoutAccountStatus.REJECTED
+ }
+
+ if (!account.details_submitted) {
+ return PayoutAccountStatus.PENDING
+ }
+
+ if (account.payouts_enabled && account.charges_enabled && !account.disabled_reason) {
+ return PayoutAccountStatus.ACTIVE
+ }
+
+ return PayoutAccountStatus.RESTRICTED
}
}
diff --git a/packages/core/src/modules/payout/services/provider-service.ts b/packages/core/src/modules/payout/services/provider-service.ts
index 811c5d444..1ff90acd6 100644
--- a/packages/core/src/modules/payout/services/provider-service.ts
+++ b/packages/core/src/modules/payout/services/provider-service.ts
@@ -1,21 +1,24 @@
import { MedusaError } from "@medusajs/framework/utils"
import { Constructor } from "@medusajs/framework/types"
import {
- IPayoutProvider,
- CreatePayoutAccountInput,
- CreatePayoutAccountResponse,
- CreatePayoutInput,
- CreatePayoutResponse,
+ AccountOutput,
+ CreateAccountInput,
+ CreateLoginLinkInput,
CreateOnboardingInput,
- CreateOnboardingResponse,
+ CreatePayoutInput,
+ DeleteAccountInput,
+ IPayoutProvider,
+ LinkOutput,
+ ListAccountsInput,
+ ListAccountsOutput,
+ PayoutOutput,
PayoutWebhookActionInput,
PayoutWebhookResult,
+ RetrieveAccountInput,
+ ReversePayoutInput,
} from "@mercurjs/types"
-export const PayoutProviderIdentifierRegistrationName =
- "payout_providers_identifier"
-
-export const PayoutProviderRegistrationPrefix = "payout_"
+export const PayoutProviderRegistrationPrefix = "pop_"
type InjectedDependencies = {
[key: `${typeof PayoutProviderRegistrationPrefix}${string}`]: IPayoutProvider
@@ -25,46 +28,68 @@ export default class PayoutProviderService {
protected readonly payoutProvider_: IPayoutProvider
constructor(container: InjectedDependencies) {
- const payoutProviderKeys = Object.keys(container).filter((k) =>
- k.startsWith(PayoutProviderRegistrationPrefix)
+ const keys = Object.keys(container).filter((key) =>
+ key.startsWith(PayoutProviderRegistrationPrefix)
)
- if (payoutProviderKeys.length !== 1) {
+ if (keys.length !== 1) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Payout module should be initialized with exactly one provider`
)
}
- this.payoutProvider_ = container[payoutProviderKeys[0]]
+ this.payoutProvider_ = container[keys[0]]
}
static getRegistrationIdentifier(
providerClass: Constructor<IPayoutProvider>,
optionName?: string
) {
- return `${(providerClass as any).identifier}_${optionName}`
+ return `${(providerClass as unknown as { identifier: string }).identifier}_${optionName}`
+ }
+
+ async createAccount(input: CreateAccountInput): Promise<AccountOutput> {
+ return await this.payoutProvider_.createAccount(input)
+ }
+
+ async retrieveAccount(input: RetrieveAccountInput): Promise<AccountOutput> {
+ return await this.payoutProvider_.retrieveAccount(input)
}
- async createPayoutAccount(
- data: CreatePayoutAccountInput
- ): Promise<CreatePayoutAccountResponse> {
- return await this.payoutProvider_.createPayoutAccount(data)
+ async deleteAccount(input: DeleteAccountInput): Promise<void> {
+ if (this.payoutProvider_.deleteAccount) {
+ await this.payoutProvider_.deleteAccount(input)
+ }
}
- async createPayout(data: CreatePayoutInput): Promise<CreatePayoutResponse> {
- return await this.payoutProvider_.createPayout(data)
+ async listAccounts(input: ListAccountsInput): Promise<ListAccountsOutput | null> {
+ return this.payoutProvider_.listAccounts
+ ? await this.payoutProvider_.listAccounts(input)
+ : null
}
- async createOnboarding(
- input: CreateOnboardingInput
- ): Promise<CreateOnboardingResponse> {
+ async createOnboarding(input: CreateOnboardingInput): Promise<LinkOutput> {
return await this.payoutProvider_.createOnboarding(input)
}
+ async createLoginLink(input: CreateLoginLinkInput): Promise<LinkOutput | null> {
+ return this.payoutProvider_.createLoginLink
+ ? await this.payoutProvider_.createLoginLink(input)
+ : null
+ }
+
+ async createPayout(input: CreatePayoutInput): Promise<PayoutOutput> {
+ return await this.payoutProvider_.createPayout(input)
+ }
+
+ async reversePayout(input: ReversePayoutInput): Promise<PayoutOutput> {
+ return await this.payoutProvider_.reversePayout(input)
+ }
+
async getWebhookActionAndData(
- payload: PayoutWebhookActionInput
+ input: PayoutWebhookActionInput
): Promise<PayoutWebhookResult> {
- return await this.payoutProvider_.getWebhookActionAndData(payload)
+ return await this.payoutProvider_.getWebhookActionAndData(input)
}
}
diff --git a/packages/core/src/modules/payout/utils/abstract-payout-provider.ts b/packages/core/src/modules/payout/utils/abstract-payout-provider.ts
new file mode 100644
index 000000000..ba73b197b
--- /dev/null
+++ b/packages/core/src/modules/payout/utils/abstract-payout-provider.ts
@@ -0,0 +1,54 @@
+import {
+ AccountOutput,
+ CreateAccountInput,
+ CreateLoginLinkInput,
+ CreateOnboardingInput,
+ CreatePayoutInput,
+ DeleteAccountInput,
+ IPayoutProvider,
+ LinkOutput,
+ ListAccountsInput,
+ ListAccountsOutput,
+ PayoutOutput,
+ PayoutWebhookActionInput,
+ PayoutWebhookResult,
+ RetrieveAccountInput,
+ ReversePayoutInput,
+} from "@mercurjs/types"
+
+export abstract class AbstractPayoutProvider<TConfig = Record<string, unknown>>
+ implements IPayoutProvider
+{
+ static identifier: string
+ static _isPayoutProvider = true
+
+ protected readonly config: TConfig
+ protected readonly container: Record<string, unknown>
+
+ static validateOptions(_options: Record<string, unknown>): void | never {}
+
+ static isPayoutProvider(object: unknown): boolean {
+ return !!(object as { _isPayoutProvider?: boolean })?._isPayoutProvider
+ }
+
+ protected constructor(container: Record<string, unknown>, config: TConfig) {
+ this.container = container
+ this.config = config
+ }
+
+ get identifier(): string {
+ return (this.constructor as typeof AbstractPayoutProvider).identifier
+ }
+
+ abstract createAccount(input: CreateAccountInput): Promise<AccountOutput>
+ abstract retrieveAccount(input: RetrieveAccountInput): Promise<AccountOutput>
+ deleteAccount?(input: DeleteAccountInput): Promise<void>
+ listAccounts?(input: ListAccountsInput): Promise<ListAccountsOutput>
+ abstract createOnboarding(input: CreateOnboardingInput): Promise<LinkOutput>
+ createLoginLink?(input: CreateLoginLinkInput): Promise<LinkOutput>
+ abstract createPayout(input: CreatePayoutInput): Promise<PayoutOutput>
+ abstract reversePayout(input: ReversePayoutInput): Promise<PayoutOutput>
+ abstract getWebhookActionAndData(
+ payload: PayoutWebhookActionInput
+ ): Promise<PayoutWebhookResult>
+}
diff --git a/packages/core/src/modules/payout/utils/index.ts b/packages/core/src/modules/payout/utils/index.ts
new file mode 100644
index 000000000..00d6e5e79
--- /dev/null
+++ b/packages/core/src/modules/payout/utils/index.ts
@@ -0,0 +1 @@
+export * from "./abstract-payout-provider"
diff --git a/packages/core/src/subscribers/payout-webhook.ts b/packages/core/src/subscribers/payout-webhook.ts
index 673c77c2d..b3812441f 100644
--- a/packages/core/src/subscribers/payout-webhook.ts
+++ b/packages/core/src/subscribers/payout-webhook.ts
@@ -1,9 +1,8 @@
-import { MercurModules } from "@mercurjs/types"
+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
+import { ProviderWebhookPayload } from "@medusajs/framework/types"
import { Modules } from "@medusajs/framework/utils"
+import { IPayoutModuleService, MercurModules, PayoutModuleEvents } from "@mercurjs/types"
-import PayoutModuleService from "../modules/payout/services/payout-module-service"
-import { ProviderWebhookPayload } from "@medusajs/framework/types"
-import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
import { processPayoutForWebhookWorkflowId } from "../workflows/payout"
type SerializedBuffer = {
@@ -14,24 +13,22 @@ type SerializedBuffer = {
export default async function payoutWebhookHandler({
event,
container,
-}: SubscriberArgs<ProviderWebhookPayload['payload']>) {
- const payoutService = container.resolve<PayoutModuleService>(MercurModules.PAYOUT)
+}: SubscriberArgs<ProviderWebhookPayload["payload"]>) {
+ const payoutService = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
const input = event.data
- if (
- (input?.rawData as unknown as SerializedBuffer)?.type === "Buffer"
- ) {
- input.rawData = Buffer.from(
- (input.rawData as unknown as SerializedBuffer).data
- )
+ if ((input?.rawData as unknown as SerializedBuffer)?.type === "Buffer") {
+ input.rawData = Buffer.from((input.rawData as unknown as SerializedBuffer).data)
}
- const processedEvent = await payoutService.getWebhookActionAndData(
- input
- )
+ const processedEvent = await payoutService.getWebhookActionAndData({
+ data: input.data as Record<string, unknown>,
+ rawData: input.rawData,
+ headers: input.headers as Record<string, unknown>,
+ })
- if (!processedEvent.data) {
+ if (!processedEvent.data || processedEvent.action === "not_supported") {
return
}
@@ -40,7 +37,7 @@ export default async function payoutWebhookHandler({
}
export const config: SubscriberConfig = {
- event: "payout.webhook_received",
+ event: PayoutModuleEvents.WEBHOOK_RECEIVED,
context: {
subscriberId: "payout-webhook-handler",
},
diff --git a/packages/core/src/workflows/payment/utils/__tests__/split-order-payment.unit.spec.ts b/packages/core/src/workflows/payment/utils/__tests__/split-order-payment.unit.spec.ts
index bc34cdd32..af85d1be3 100644
--- a/packages/core/src/workflows/payment/utils/__tests__/split-order-payment.unit.spec.ts
+++ b/packages/core/src/workflows/payment/utils/__tests__/split-order-payment.unit.spec.ts
@@ -231,6 +231,35 @@ describe("planCartPaymentSplit", () => {
expect(amountsOf(plan.refunds)).toEqual([98])
})
+ it("gives a capture that left out a canceled order to the open orders only", () => {
+ const plan = planCartPaymentSplit(cartCollection([102]), [
+ order("order_a", 98, { status: "canceled" }),
+ order("order_b", 102),
+ ])
+
+ expect(plan.captures.map((c) => c.order_id)).toEqual(["order_b"])
+ expect(amountsOf(plan.captures)).toEqual([102])
+ expect(plan.refunds).toEqual([])
+ })
+
+ it("keeps a capture above the order totals with the orders when nothing is canceled", () => {
+ const plan = planCartPaymentSplit(cartCollection([200.01]), [order("order_a", 100), order("order_b", 100)])
+
+ expect(plan.refunds).toEqual([])
+ expect(amountsOf(plan.captures).reduce((a, b) => a + b, 0)).toBeCloseTo(200.01, 6)
+ })
+
+ it("gives a later capture to the open orders only, not what a canceled order already held", () => {
+ const plan = planCartPaymentSplit(
+ cartCollection([100, 10], { metadata: { split_order_collections: true } }),
+ [splitOrder("order_a", 98, 49), { ...splitOrder("order_b", 102, 51), status: "canceled" }]
+ )
+
+ expect(plan.captures.map((c) => c.payment_id)).toEqual(["pay_order_a"])
+ expect(amountsOf(plan.captures)).toEqual([10])
+ expect(plan.refunds).toEqual([])
+ })
+
it("reuses a collection left without a payment", () => {
const plan = planCartPaymentSplit(cartCollection([200]), [
order("order_a", 98, {
diff --git a/packages/core/src/workflows/payment/utils/split-order-payment-group.ts b/packages/core/src/workflows/payment/utils/split-order-payment-group.ts
index a872921b6..16720fc7d 100644
--- a/packages/core/src/workflows/payment/utils/split-order-payment-group.ts
+++ b/packages/core/src/workflows/payment/utils/split-order-payment-group.ts
@@ -293,9 +293,20 @@ export const planCartPaymentSplit = (
weights,
decimalDigits,
})
+ // Capture can leave canceled orders out; anything above the open total is refunded.
+ // What a canceled order held was refunded on its own payment, so it is not available.
+ const hasCanceled = orders.some(isOrderCanceled)
+ const openWeights = orders.map((order) => (isOrderCanceled(order) ? 0 : order.total))
+ const openTotal = openWeights.reduce<BigNumberInput>((acc, weight) => MathBN.add(acc, weight), 0)
+ const heldByCanceled = orders
+ .filter(isOrderCanceled)
+ .reduce<BigNumberInput>(
+ (acc, order) => MathBN.add(acc, sum(getOrderCollection(order, cartCollection.id)?.payments?.[0]?.captures)),
+ 0
+ )
const targets = allocateProportionally({
- amount: captured,
- weights,
+ amount: hasCanceled ? MathBN.min(MathBN.sub(captured, heldByCanceled), openTotal) : captured,
+ weights: hasCanceled ? openWeights : weights,
decimalDigits,
})
diff --git a/packages/core/src/workflows/payment/workflows/process-payment.ts b/packages/core/src/workflows/payment/workflows/process-payment.ts
index 744b80db3..eeb34d0c4 100644
--- a/packages/core/src/workflows/payment/workflows/process-payment.ts
+++ b/packages/core/src/workflows/payment/workflows/process-payment.ts
@@ -1,5 +1,5 @@
import { BigNumberInput } from "@medusajs/framework/types"
-import { PaymentActions } from "@medusajs/framework/utils"
+import { MathBN, PaymentActions } from "@medusajs/framework/utils"
import {
createWorkflow,
transform,
@@ -40,7 +40,7 @@ export const processPaymentWorkflow = createWorkflow(
(input: ProcessPaymentWorkflowInput) => {
const paymentData = useQueryGraphStep({
entity: "payment",
- fields: ["id"],
+ fields: ["id", "amount", "captures.amount", "captures.raw_amount"],
filters: { payment_session_id: input.data?.session_id },
}).config({ name: "payment-query" })
@@ -88,12 +88,19 @@ export const processPaymentWorkflow = createWorkflow(
})
})
+ // A partial capture leaves Medusa's payment without captured_at, so the
+ // provider's confirmation of it would otherwise be recorded again.
when({ input, paymentData }, ({ input, paymentData }) => {
- return (
- !!input.data?.session_id &&
- input.action === PaymentActions.SUCCESSFUL &&
- !!paymentData.data.length
+ const payment = paymentData.data[0]
+ if (!input.data?.session_id || input.action !== PaymentActions.SUCCESSFUL || !payment) {
+ return false
+ }
+ const captured = (payment.captures ?? []).reduce(
+ (sum: BigNumberInput, capture) =>
+ MathBN.add(sum, capture?.raw_amount ?? capture?.amount ?? 0),
+ 0
)
+ return MathBN.lt(captured, input.data.amount ?? payment.amount)
}).then(() => {
capturePaymentWorkflow
.runAsStep({
diff --git a/packages/core/src/workflows/payout/steps/create-onboarding.ts b/packages/core/src/workflows/payout/steps/create-onboarding.ts
index d3b3858ae..0d3d02ba3 100644
--- a/packages/core/src/workflows/payout/steps/create-onboarding.ts
+++ b/packages/core/src/workflows/payout/steps/create-onboarding.ts
@@ -1,15 +1,19 @@
import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
-import { CreateOnboardingDTO, MercurModules, OnboardingDTO } from "@mercurjs/types"
+import { CreateOnboardingDTO, IPayoutModuleService, MercurModules } from "@mercurjs/types"
-import PayoutModuleService from "../../../modules/payout/services/payout-module-service"
+export const createOnboardingStepId = "create-onboarding"
+/**
+ * Publishes the onboarding link, or the dashboard login link once the seller
+ * submitted their details. A published link cannot be revoked, so there is
+ * no compensation.
+ */
export const createOnboardingStep = createStep(
- "create-onboarding",
+ createOnboardingStepId,
async (input: CreateOnboardingDTO, { container }) => {
- const service = container.resolve<PayoutModuleService>(MercurModules.PAYOUT)
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+ const onboarding = await service.createOnboarding(input)
- const onboarding: OnboardingDTO = await service.createOnboarding(input)
-
- return new StepResponse(onboarding, onboarding.id)
+ return new StepResponse(onboarding)
}
)
diff --git a/packages/core/src/workflows/payout/steps/create-payout-account.ts b/packages/core/src/workflows/payout/steps/create-payout-account.ts
index 954ce8e6d..a1661ddf2 100644
--- a/packages/core/src/workflows/payout/steps/create-payout-account.ts
+++ b/packages/core/src/workflows/payout/steps/create-payout-account.ts
@@ -1,15 +1,21 @@
import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
-import { CreatePayoutAccountDTO, MercurModules, PayoutAccountDTO } from "@mercurjs/types"
+import { CreatePayoutAccountDTO, IPayoutModuleService, MercurModules } from "@mercurjs/types"
-import PayoutModuleService from "../../../modules/payout/services/payout-module-service"
+export const createPayoutAccountStepId = "create-payout-account"
export const createPayoutAccountStep = createStep(
- "create-payout-account",
+ createPayoutAccountStepId,
async (input: CreatePayoutAccountDTO, { container }) => {
- const service = container.resolve<PayoutModuleService>(MercurModules.PAYOUT)
-
- const payoutAccount: PayoutAccountDTO = await service.createPayoutAccount(input)
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+ const payoutAccount = await service.createPayoutAccount(input)
return new StepResponse(payoutAccount, payoutAccount.id)
+ },
+ async (id, { container }) => {
+ if (!id) {
+ return
+ }
+
+ await container.resolve<IPayoutModuleService>(MercurModules.PAYOUT).deletePayoutAccount(id)
}
)
diff --git a/packages/core/src/workflows/payout/steps/create-payout-accounts.ts b/packages/core/src/workflows/payout/steps/create-payout-accounts.ts
new file mode 100644
index 000000000..d2db4d5a1
--- /dev/null
+++ b/packages/core/src/workflows/payout/steps/create-payout-accounts.ts
@@ -0,0 +1,34 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { IPayoutModuleService, MercurModules } from "@mercurjs/types"
+
+export type CreatePayoutAccountsStepInput = {
+ external_id: string
+ data?: Record<string, unknown>
+}[]
+
+export const createPayoutAccountsStepId = "create-payout-accounts"
+
+/**
+ * Stores accounts that already exist at the provider, without calling it.
+ * Compensation only removes the stored rows: the provider accounts predate
+ * the workflow.
+ */
+export const createPayoutAccountsStep = createStep(
+ createPayoutAccountsStepId,
+ async (input: CreatePayoutAccountsStepInput, { container }) => {
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+ const accounts = input.length ? await service.createPayoutAccounts(input) : []
+
+ return new StepResponse(
+ accounts,
+ accounts.map((account) => account.id)
+ )
+ },
+ async (ids, { container }) => {
+ if (!ids?.length) {
+ return
+ }
+
+ await container.resolve<IPayoutModuleService>(MercurModules.PAYOUT).deletePayoutAccounts(ids)
+ }
+)
diff --git a/packages/core/src/workflows/payout/steps/create-payout-reversals.ts b/packages/core/src/workflows/payout/steps/create-payout-reversals.ts
new file mode 100644
index 000000000..d3e5198a6
--- /dev/null
+++ b/packages/core/src/workflows/payout/steps/create-payout-reversals.ts
@@ -0,0 +1,34 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { CreatePayoutReversalDTO, IPayoutModuleService, MercurModules } from "@mercurjs/types"
+
+import { sentToProvider } from "../utils/sent-to-provider"
+
+export type CreatePayoutReversalsStepInput = CreatePayoutReversalDTO[]
+
+export const createPayoutReversalsStepId = "create-payout-reversals-step"
+
+export const createPayoutReversalsStep = createStep(
+ createPayoutReversalsStepId,
+ async (input: CreatePayoutReversalsStepInput, { container }) => {
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+ const reversals = input.length ? await service.createPayoutReversals(input) : []
+
+ return new StepResponse(
+ reversals,
+ reversals.map((reversal) => reversal.id)
+ )
+ },
+ async (ids, { container }) => {
+ if (!ids?.length) {
+ return
+ }
+
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+ const current = await service.listPayoutReversals({ id: ids }, { select: ["id", "status", "data"], take: null })
+ const unsent = current.filter((reversal) => !sentToProvider(reversal)).map((reversal) => reversal.id)
+
+ if (unsent.length) {
+ await service.deletePayoutReversals(unsent)
+ }
+ }
+)
diff --git a/packages/core/src/workflows/payout/steps/create-payout.ts b/packages/core/src/workflows/payout/steps/create-payout.ts
deleted file mode 100644
index 3aaa3bff8..000000000
--- a/packages/core/src/workflows/payout/steps/create-payout.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
-import { CreatePayoutDTO, MercurModules } from "@mercurjs/types"
-
-import PayoutModuleService from "../../../modules/payout/services/payout-module-service"
-
-export const createPayoutStepId = "create-payout-step"
-
-export const createPayoutStep = createStep(
- createPayoutStepId,
- async (input: CreatePayoutDTO, { container }) => {
- const payoutService = container.resolve<PayoutModuleService>(MercurModules.PAYOUT)
-
- const payout = await payoutService.createPayouts(input)
-
- return new StepResponse(payout, payout.id)
- }
-)
diff --git a/packages/core/src/workflows/payout/steps/create-payouts.ts b/packages/core/src/workflows/payout/steps/create-payouts.ts
new file mode 100644
index 000000000..fecf798a8
--- /dev/null
+++ b/packages/core/src/workflows/payout/steps/create-payouts.ts
@@ -0,0 +1,34 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { CreatePayoutDTO, IPayoutModuleService, MercurModules } from "@mercurjs/types"
+
+import { sentToProvider } from "../utils/sent-to-provider"
+
+export type CreatePayoutsStepInput = CreatePayoutDTO[]
+
+export const createPayoutsStepId = "create-payouts"
+
+export const createPayoutsStep = createStep(
+ createPayoutsStepId,
+ async (input: CreatePayoutsStepInput, { container }) => {
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+ const payouts = input.length ? await service.createPayouts(input) : []
+
+ return new StepResponse(
+ payouts,
+ payouts.map((payout) => payout.id)
+ )
+ },
+ async (ids, { container }) => {
+ if (!ids?.length) {
+ return
+ }
+
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+ const current = await service.listPayouts({ id: ids }, { select: ["id", "status", "data"], take: null })
+ const unsent = current.filter((payout) => !sentToProvider(payout)).map((payout) => payout.id)
+
+ if (unsent.length) {
+ await service.deletePayouts(unsent)
+ }
+ }
+)
diff --git a/packages/core/src/workflows/payout/steps/index.ts b/packages/core/src/workflows/payout/steps/index.ts
index c382ea1eb..89749502c 100644
--- a/packages/core/src/workflows/payout/steps/index.ts
+++ b/packages/core/src/workflows/payout/steps/index.ts
@@ -1,6 +1,13 @@
-export * from "./create-payout-account"
export * from "./create-onboarding"
-export * from "./create-payout"
-export * from "./update-payout-account"
-export * from "./update-payout"
-export * from "./validate-seller-payout-account"
+export * from "./create-payout-account"
+export * from "./create-payout-accounts"
+export * from "./create-payout-reversals"
+export * from "./create-payouts"
+export * from "./process-payout-reversals"
+export * from "./process-payouts"
+export * from "./sync-payout-account"
+export * from "./update-payout-reversals"
+export * from "./update-payouts"
+export * from "./validate-onboarding-token"
+export * from "./validate-payout-retry"
+export * from "./validate-seller-without-payout-account"
diff --git a/packages/core/src/workflows/payout/steps/process-payout-reversals.ts b/packages/core/src/workflows/payout/steps/process-payout-reversals.ts
new file mode 100644
index 000000000..e3589505b
--- /dev/null
+++ b/packages/core/src/workflows/payout/steps/process-payout-reversals.ts
@@ -0,0 +1,23 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { IPayoutModuleService, MercurModules, PayoutReversalDTO } from "@mercurjs/types"
+
+export type ProcessPayoutReversalsStepInput = {
+ ids: string[]
+}
+
+export const processPayoutReversalsStepId = "process-payout-reversals"
+
+export const processPayoutReversalsStep = createStep(
+ processPayoutReversalsStepId,
+ async (input: ProcessPayoutReversalsStepInput, { container }) => {
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+
+ const reversals: PayoutReversalDTO[] = []
+ for (const id of input.ids) {
+ reversals.push(await service.processPayoutReversal(id))
+ }
+
+ return new StepResponse(reversals)
+ }
+ // Not compensated: money that reached the provider cannot be pulled back by a rollback.
+)
diff --git a/packages/core/src/workflows/payout/steps/process-payouts.ts b/packages/core/src/workflows/payout/steps/process-payouts.ts
new file mode 100644
index 000000000..328a1a66a
--- /dev/null
+++ b/packages/core/src/workflows/payout/steps/process-payouts.ts
@@ -0,0 +1,23 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { IPayoutModuleService, MercurModules, PayoutDTO } from "@mercurjs/types"
+
+export type ProcessPayoutsStepInput = {
+ ids: string[]
+}
+
+export const processPayoutsStepId = "process-payouts"
+
+export const processPayoutsStep = createStep(
+ processPayoutsStepId,
+ async (input: ProcessPayoutsStepInput, { container }) => {
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+
+ const payouts: PayoutDTO[] = []
+ for (const id of input.ids) {
+ payouts.push(await service.processPayout(id))
+ }
+
+ return new StepResponse(payouts)
+ }
+ // Not compensated: money that reached the provider cannot be pulled back by a rollback.
+)
diff --git a/packages/core/src/workflows/payout/steps/sync-payout-account.ts b/packages/core/src/workflows/payout/steps/sync-payout-account.ts
new file mode 100644
index 000000000..2ca0cce7c
--- /dev/null
+++ b/packages/core/src/workflows/payout/steps/sync-payout-account.ts
@@ -0,0 +1,42 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { IPayoutModuleService, MercurModules } from "@mercurjs/types"
+
+export type SyncPayoutAccountStepInput = {
+ id: string
+}
+
+export const syncPayoutAccountStepId = "sync-payout-account-step"
+
+/**
+ * Pulls the account from the provider and stores its state.
+ */
+export const syncPayoutAccountStep = createStep(
+ syncPayoutAccountStepId,
+ async (input: SyncPayoutAccountStepInput, { container }) => {
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+
+ const previous = await service.retrievePayoutAccount(input.id)
+ const account = await service.syncPayoutAccount(input.id)
+
+ return new StepResponse(account, {
+ id: previous.id,
+ status: previous.status,
+ kyc_status: previous.kyc_status,
+ payouts_enabled: previous.payouts_enabled,
+ charges_enabled: previous.charges_enabled,
+ details_submitted: previous.details_submitted,
+ disabled_reason: previous.disabled_reason,
+ onboarding_token: previous.onboarding_token,
+ onboarding_token_issued_at: previous.onboarding_token_issued_at,
+ last_synced_at: previous.last_synced_at,
+ data: previous.data,
+ })
+ },
+ async (previous, { container }) => {
+ if (!previous) {
+ return
+ }
+
+ await container.resolve<IPayoutModuleService>(MercurModules.PAYOUT).updatePayoutAccounts(previous)
+ }
+)
diff --git a/packages/core/src/workflows/payout/steps/update-payout-account.ts b/packages/core/src/workflows/payout/steps/update-payout-account.ts
deleted file mode 100644
index 06b5df2bc..000000000
--- a/packages/core/src/workflows/payout/steps/update-payout-account.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
-import { MercurModules, UpdatePayoutAccountDTO } from "@mercurjs/types"
-
-import PayoutModuleService from "../../../modules/payout/services/payout-module-service"
-
-export const updatePayoutAccountStepId = "update-payout-account-step"
-
-export const updatePayoutAccountStep = createStep(
- updatePayoutAccountStepId,
- async (input: UpdatePayoutAccountDTO, { container }) => {
- const payoutService = container.resolve<PayoutModuleService>(MercurModules.PAYOUT)
-
- const previousAccount = await payoutService.retrievePayoutAccount(input.id)
-
- const updatedAccount = await payoutService.updatePayoutAccounts({
- id: input.id,
- status: input.status,
- })
-
- return new StepResponse(updatedAccount, {
- id: input.id,
- previousStatus: previousAccount.status,
- })
- },
- async (rollbackData, { container }) => {
- if (!rollbackData) return
-
- const payoutService = container.resolve<PayoutModuleService>(MercurModules.PAYOUT)
-
- await payoutService.updatePayoutAccounts({
- id: rollbackData.id,
- status: rollbackData.previousStatus,
- })
- }
-)
diff --git a/packages/core/src/workflows/payout/steps/update-payout-reversals.ts b/packages/core/src/workflows/payout/steps/update-payout-reversals.ts
new file mode 100644
index 000000000..8b6d99a12
--- /dev/null
+++ b/packages/core/src/workflows/payout/steps/update-payout-reversals.ts
@@ -0,0 +1,47 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { IPayoutModuleService, MercurModules, UpdatePayoutReversalDTO } from "@mercurjs/types"
+
+import { sentToProvider } from "../utils/sent-to-provider"
+
+export type UpdatePayoutReversalsStepInput = UpdatePayoutReversalDTO[]
+
+export const updatePayoutReversalsStepId = "update-payout-reversals"
+
+export const updatePayoutReversalsStep = createStep(
+ updatePayoutReversalsStepId,
+ async (input: UpdatePayoutReversalsStepInput, { container }) => {
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+ const previous = input.length
+ ? await service.listPayoutReversals({ id: input.map((reversal) => reversal.id) }, { take: null })
+ : []
+ const reversals = input.length ? await service.updatePayoutReversals(input) : []
+
+ return new StepResponse(
+ reversals,
+ previous.map(({ id, amount, status, status_reason, data }) => ({ id, amount, status, status_reason, data }))
+ )
+ },
+ async (previous, { container }) => {
+ if (!previous?.length) {
+ return
+ }
+
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+ const current = new Map(
+ (
+ await service.listPayoutReversals(
+ { id: previous.map((reversal) => reversal.id) },
+ { select: ["id", "status", "data"], take: null }
+ )
+ ).map((reversal) => [reversal.id, reversal])
+ )
+ const restorable = previous.filter((reversal) => {
+ const now = current.get(reversal.id)
+ return now && !sentToProvider(now, reversal)
+ })
+
+ if (restorable.length) {
+ await service.updatePayoutReversals(restorable)
+ }
+ }
+)
diff --git a/packages/core/src/workflows/payout/steps/update-payout.ts b/packages/core/src/workflows/payout/steps/update-payout.ts
deleted file mode 100644
index 7e6637ff6..000000000
--- a/packages/core/src/workflows/payout/steps/update-payout.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
-import { MercurModules, UpdatePayoutDTO } from "@mercurjs/types"
-
-import PayoutModuleService from "../../../modules/payout/services/payout-module-service"
-
-export const updatePayoutStepId = "update-payout-step"
-
-export const updatePayoutStep = createStep(
- updatePayoutStepId,
- async (input: UpdatePayoutDTO, { container }) => {
- const payoutService = container.resolve<PayoutModuleService>(MercurModules.PAYOUT)
-
- const previousPayout = await payoutService.retrievePayout(input.id)
-
- const updatedPayout = await payoutService.updatePayouts({
- id: input.id,
- status: input.status,
- })
-
- return new StepResponse(updatedPayout, {
- id: input.id,
- previousStatus: previousPayout.status,
- })
- },
- async (rollbackData, { container }) => {
- if (!rollbackData) return
-
- const payoutService = container.resolve<PayoutModuleService>(MercurModules.PAYOUT)
-
- await payoutService.updatePayouts({
- id: rollbackData.id,
- status: rollbackData.previousStatus,
- })
- }
-)
diff --git a/packages/core/src/workflows/payout/steps/update-payouts.ts b/packages/core/src/workflows/payout/steps/update-payouts.ts
new file mode 100644
index 000000000..0664be273
--- /dev/null
+++ b/packages/core/src/workflows/payout/steps/update-payouts.ts
@@ -0,0 +1,49 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { IPayoutModuleService, MercurModules, UpdatePayoutDTO } from "@mercurjs/types"
+
+import { sentToProvider } from "../utils/sent-to-provider"
+
+export type UpdatePayoutsStepInput = UpdatePayoutDTO[]
+
+export const updatePayoutsStepId = "update-payouts"
+
+export const updatePayoutsStep = createStep(
+ updatePayoutsStepId,
+ async (input: UpdatePayoutsStepInput, { container }) => {
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+ const previous = input.length ? await service.listPayouts({ id: input.map((payout) => payout.id) }, { take: null }) : []
+ const payouts = input.length ? await service.updatePayouts(input) : []
+
+ return new StepResponse(
+ payouts,
+ previous.map(({ id, account_id, amount, status, status_reason, data }) => ({
+ id,
+ account_id,
+ amount,
+ status,
+ status_reason,
+ data,
+ }))
+ )
+ },
+ async (previous, { container }) => {
+ if (!previous?.length) {
+ return
+ }
+
+ const service = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+ const current = new Map(
+ (
+ await service.listPayouts({ id: previous.map((payout) => payout.id) }, { select: ["id", "status", "data"], take: null })
+ ).map((payout) => [payout.id, payout])
+ )
+ const restorable = previous.filter((payout) => {
+ const now = current.get(payout.id)
+ return now && !sentToProvider(now, payout)
+ })
+
+ if (restorable.length) {
+ await service.updatePayouts(restorable)
+ }
+ }
+)
diff --git a/packages/core/src/workflows/payout/steps/validate-onboarding-token.ts b/packages/core/src/workflows/payout/steps/validate-onboarding-token.ts
new file mode 100644
index 000000000..5b43d4c86
--- /dev/null
+++ b/packages/core/src/workflows/payout/steps/validate-onboarding-token.ts
@@ -0,0 +1,31 @@
+import { MedusaError } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { IPayoutModuleService, MercurModules } from "@mercurjs/types"
+
+export type ValidateOnboardingTokenStepInput = {
+ account: { id: string; onboarding_token_issued_at: Date | string | null } | null | undefined
+}
+
+export const validateOnboardingTokenStepId = "validate-onboarding-token"
+
+/**
+ * Rejects an unknown token and one older than the module's
+ * `onboarding.tokenTtlSeconds`.
+ */
+export const validateOnboardingTokenStep = createStep(
+ validateOnboardingTokenStepId,
+ async ({ account }: ValidateOnboardingTokenStepInput, { container }) => {
+ if (!account) {
+ throw new MedusaError(MedusaError.Types.NOT_FOUND, "Unknown onboarding token")
+ }
+
+ const { tokenTtlSeconds } = container.resolve<IPayoutModuleService>(MercurModules.PAYOUT).getOptions().onboarding
+ const issuedAt = account.onboarding_token_issued_at ? new Date(account.onboarding_token_issued_at).getTime() : 0
+
+ if (Date.now() - issuedAt >= tokenTtlSeconds * 1000) {
+ throw new MedusaError(MedusaError.Types.NOT_ALLOWED, "The onboarding token has expired")
+ }
+
+ return new StepResponse(void 0)
+ }
+)
diff --git a/packages/core/src/workflows/payout/steps/validate-payout-retry.ts b/packages/core/src/workflows/payout/steps/validate-payout-retry.ts
new file mode 100644
index 000000000..8e938bf63
--- /dev/null
+++ b/packages/core/src/workflows/payout/steps/validate-payout-retry.ts
@@ -0,0 +1,25 @@
+import { MedusaError } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { PayoutStatus } from "@mercurjs/types"
+
+export type ValidatePayoutRetryStepInput = {
+ payout: { id: string; status: PayoutStatus }
+}
+
+export const RETRYABLE_PAYOUT_STATUSES = [PayoutStatus.FAILED, PayoutStatus.ON_HOLD, PayoutStatus.PENDING]
+
+export const validatePayoutRetryStepId = "validate-payout-retry"
+
+export const validatePayoutRetryStep = createStep(
+ validatePayoutRetryStepId,
+ async ({ payout }: ValidatePayoutRetryStepInput) => {
+ if (!RETRYABLE_PAYOUT_STATUSES.includes(payout.status)) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_ALLOWED,
+ `Payout ${payout.id} is ${payout.status} and cannot be retried`
+ )
+ }
+
+ return new StepResponse(void 0)
+ }
+)
diff --git a/packages/core/src/workflows/payout/steps/validate-seller-payout-account.ts b/packages/core/src/workflows/payout/steps/validate-seller-payout-account.ts
deleted file mode 100644
index 6fec98e93..000000000
--- a/packages/core/src/workflows/payout/steps/validate-seller-payout-account.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { Query } from "@medusajs/framework"
-import { MedusaError } from "@medusajs/framework/utils"
-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
-import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
-
-interface ValidateSellerPayoutAccountInput {
- seller_id: string
-}
-
-export const validateSellerPayoutAccountStep = createStep(
- "validate-seller-payout-account",
- async (input: ValidateSellerPayoutAccountInput, { container }) => {
- const query = container.resolve<Query>(ContainerRegistrationKeys.QUERY)
-
- const { data } = await query.graph({
- entity: "seller_payout_account",
- filters: {
- seller_id: input.seller_id,
- },
- fields: ["seller_id", "payout_account_id"],
- })
-
- if (data.length > 0) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- `Seller already has a payout account`
- )
- }
-
- return new StepResponse(void 0)
- }
-)
diff --git a/packages/core/src/workflows/payout/steps/validate-seller-without-payout-account.ts b/packages/core/src/workflows/payout/steps/validate-seller-without-payout-account.ts
new file mode 100644
index 000000000..6956eb1f1
--- /dev/null
+++ b/packages/core/src/workflows/payout/steps/validate-seller-without-payout-account.ts
@@ -0,0 +1,19 @@
+import { MedusaError } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+export type ValidateSellerWithoutPayoutAccountStepInput = {
+ seller: { id: string; payout_account?: { id: string } | null }
+}
+
+export const validateSellerWithoutPayoutAccountStepId = "validate-seller-without-payout-account"
+
+export const validateSellerWithoutPayoutAccountStep = createStep(
+ validateSellerWithoutPayoutAccountStepId,
+ async ({ seller }: ValidateSellerWithoutPayoutAccountStepInput) => {
+ if (seller.payout_account) {
+ throw new MedusaError(MedusaError.Types.CONFLICT, `Seller ${seller.id} already has a payout account`)
+ }
+
+ return new StepResponse(void 0)
+ }
+)
diff --git a/packages/core/src/workflows/payout/utils/__tests__/payout-amounts.unit.spec.ts b/packages/core/src/workflows/payout/utils/__tests__/payout-amounts.unit.spec.ts
new file mode 100644
index 000000000..b7eeecbc4
--- /dev/null
+++ b/packages/core/src/workflows/payout/utils/__tests__/payout-amounts.unit.spec.ts
@@ -0,0 +1,190 @@
+import { PayoutStatus, PayoutStatusReason } from "@mercurjs/types"
+
+import { fulfillmentReached } from "../fulfillment-status"
+import { decideOrderPayout, decideReversal } from "../payout-amounts"
+import { sentToProvider } from "../sent-to-provider"
+
+const order = (overrides: Partial<Parameters<typeof decideOrderPayout>[0]["order"]> = {}) => ({
+ id: "order_1",
+ seller_id: "sel_1",
+ status: "pending",
+ canceled_at: null,
+ fulfillment_status: "fulfilled",
+ total: 180,
+ currency_code: "eur",
+ created_at: new Date("2026-10-21T14:12:00Z"),
+ ...overrides,
+})
+
+const account = { id: "pacc_1", payouts_enabled: true }
+const payment = {
+ id: "pay_1",
+ captured: true,
+ canceled: false,
+ fully_refunded: false,
+ data: { id: "pi_1", latest_charge: "ch_1" },
+}
+
+const base = {
+ order: order(),
+ account,
+ payment,
+ commission_total: 18,
+ required_fulfillment_status: "fulfilled" as const,
+}
+
+describe("decideOrderPayout", () => {
+ it("holds when the seller has no account", () => {
+ const decision = decideOrderPayout({ ...base, account: null })
+ expect(decision.status).toBe(PayoutStatus.ON_HOLD)
+ expect(decision.status_reason).toBe(PayoutStatusReason.ACCOUNT_NOT_READY)
+ expect(decision.status_detail).toBe("Cannot find payout account for seller sel_1")
+ })
+
+ it("holds when payouts are disabled on the account", () => {
+ const decision = decideOrderPayout({ ...base, account: { ...account, payouts_enabled: false } })
+ expect(decision.status).toBe(PayoutStatus.ON_HOLD)
+ expect(decision.status_reason).toBe(PayoutStatusReason.ACCOUNT_PAYOUTS_DISABLED)
+ })
+
+ it("aborts a canceled order", () => {
+ const decision = decideOrderPayout({ ...base, order: order({ status: "canceled" }) })
+ expect(decision.status).toBe(PayoutStatus.ABORTED)
+ expect(decision.status_reason).toBe(PayoutStatusReason.ORDER_ABORTED)
+ expect(decision.status_detail).toBe("Order cannot be processed, status is canceled")
+ })
+
+ it("aborts a canceled order even when the seller has no usable account", () => {
+ expect(decideOrderPayout({ ...base, account: null, order: order({ status: "canceled" }) }).status).toBe(
+ PayoutStatus.ABORTED
+ )
+ expect(
+ decideOrderPayout({
+ ...base,
+ account: { ...account, payouts_enabled: false },
+ order: order({ canceled_at: new Date() }),
+ }).status
+ ).toBe(PayoutStatus.ABORTED)
+ })
+
+ it("holds an order below the required fulfillment status", () => {
+ const decision = decideOrderPayout({ ...base, order: order({ fulfillment_status: "partially_fulfilled" }) })
+ expect(decision.status).toBe(PayoutStatus.ON_HOLD)
+ expect(decision.status_reason).toBe(PayoutStatusReason.ORDER_NOT_READY)
+ expect(decision.status_detail).toBe("Order is not ready yet, status is partially_fulfilled")
+ })
+
+ it("holds an authorized but uncaptured payment", () => {
+ const decision = decideOrderPayout({ ...base, payment: { ...payment, captured: false } })
+ expect(decision.status).toBe(PayoutStatus.ON_HOLD)
+ expect(decision.status_reason).toBe(PayoutStatusReason.PAYMENT_NOT_READY)
+ expect(decision.status_detail).toBe("Payment pay_1 is not ready yet, status is authorized")
+ })
+
+ it("aborts a canceled or fully refunded payment", () => {
+ expect(decideOrderPayout({ ...base, payment: { ...payment, canceled: true } }).status).toBe(PayoutStatus.ABORTED)
+ expect(decideOrderPayout({ ...base, payment: { ...payment, fully_refunded: true } }).status).toBe(PayoutStatus.ABORTED)
+ })
+
+ it("aborts when total minus commission is not positive", () => {
+ const decision = decideOrderPayout({ ...base, commission_total: 180 })
+ expect(decision.status).toBe(PayoutStatus.ABORTED)
+ expect(decision.status_reason).toBe(PayoutStatusReason.INVALID_AMOUNT)
+ expect(decision.status_detail).toBe("Amount must be positive, input was: 0")
+ })
+
+ it("rounds the payout to the currency precision", () => {
+ const decision = decideOrderPayout({ ...base, order: order({ total: 265.5 }), commission_total: 18.375 })
+ expect(Number(decision.amount)).toBe(247.13)
+ })
+
+ it("is pending for total minus commission", () => {
+ const decision = decideOrderPayout(base)
+ expect(decision.status).toBe(PayoutStatus.PENDING)
+ expect(decision.status_reason).toBeNull()
+ expect(Number(decision.amount)).toBe(162)
+ })
+
+})
+
+describe("fulfillmentReached", () => {
+ it("walks the ordered scale and never counts canceled", () => {
+ expect(fulfillmentReached("shipped", "fulfilled")).toBe(true)
+ expect(fulfillmentReached("not_fulfilled", "fulfilled")).toBe(false)
+ expect(fulfillmentReached("canceled", "not_fulfilled")).toBe(false)
+ })
+})
+
+describe("decideReversal", () => {
+ const payout = { id: "pout_1", status: PayoutStatus.PAID, provider_payout_id: "tr_1" }
+
+ it("reverses the refund net of its commission share", () => {
+ const decision = decideReversal({
+ refund_id: "ref_1",
+ refund_amount: 60,
+ refund_canceled: false,
+ order_total: 180,
+ commission_total: 18,
+ payout,
+ })
+ expect(decision.status).toBe(PayoutStatus.PENDING)
+ expect(Number(decision.amount)).toBe(54)
+ })
+
+ it("rounds the reversal to the currency precision", () => {
+ const decision = decideReversal({
+ refund_id: "ref_1",
+ refund_amount: 60.05,
+ refund_canceled: false,
+ order_total: 180,
+ commission_total: 18,
+ currency_code: "eur",
+ payout,
+ })
+ expect(Number(decision.amount)).toBe(54.05)
+ })
+
+ it("holds until the order payout is paid", () => {
+ const decision = decideReversal({
+ refund_id: "ref_1",
+ refund_amount: 60,
+ refund_canceled: false,
+ order_total: 180,
+ commission_total: 18,
+ payout: { ...payout, status: PayoutStatus.ON_HOLD, provider_payout_id: null },
+ })
+ expect(decision.status).toBe(PayoutStatus.ON_HOLD)
+ expect(decision.status_reason).toBe(PayoutStatusReason.PAYOUT_NOT_READY)
+ })
+
+ it("aborts when the order payout was aborted", () => {
+ const decision = decideReversal({
+ refund_id: "ref_1",
+ refund_amount: 60,
+ refund_canceled: false,
+ order_total: 180,
+ commission_total: 18,
+ payout: { ...payout, status: PayoutStatus.ABORTED },
+ })
+ expect(decision.status).toBe(PayoutStatus.ABORTED)
+ expect(decision.status_reason).toBe(PayoutStatusReason.REFUND_ABORTED)
+ expect(decision.status_detail).toBe("Refund ref_1 has been aborted")
+ })
+})
+
+describe("sentToProvider", () => {
+ it("counts a processing or paid row as sent", () => {
+ expect(sentToProvider({ status: PayoutStatus.PROCESSING })).toBe(true)
+ expect(sentToProvider({ status: PayoutStatus.PAID })).toBe(true)
+ })
+
+ it("counts a failed row as sent when it was attempted after the snapshot", () => {
+ expect(sentToProvider({ status: PayoutStatus.FAILED, data: { attempts: 1 } })).toBe(true)
+ expect(sentToProvider({ status: PayoutStatus.FAILED, data: { attempts: 2 } }, { data: { attempts: 1 } })).toBe(true)
+ })
+
+ it("leaves a row that never reached the provider restorable", () => {
+ expect(sentToProvider({ status: PayoutStatus.PENDING, data: {} })).toBe(false)
+ expect(sentToProvider({ status: PayoutStatus.ON_HOLD, data: { attempts: 1 } }, { data: { attempts: 1 } })).toBe(false)
+ })
+})
diff --git a/packages/core/src/workflows/payout/utils/fulfillment-status.ts b/packages/core/src/workflows/payout/utils/fulfillment-status.ts
new file mode 100644
index 000000000..28840dd78
--- /dev/null
+++ b/packages/core/src/workflows/payout/utils/fulfillment-status.ts
@@ -0,0 +1,73 @@
+import { BigNumberInput, FulfillmentStatus } from "@medusajs/framework/types"
+import { MathBN } from "@medusajs/framework/utils"
+
+export type FulfillmentRow = {
+ canceled_at?: Date | string | null
+ shipped_at?: Date | string | null
+ delivered_at?: Date | string | null
+ items?: { line_item_id?: string | null; quantity: BigNumberInput }[] | null
+}
+
+export type FulfillableOrder = {
+ items?: { id: string; quantity: BigNumberInput }[] | null
+ fulfillments?: FulfillmentRow[] | null
+}
+
+export const ORDER_FULFILLMENT_FIELDS = [
+ "items.id",
+ "items.quantity",
+ "fulfillments.canceled_at",
+ "fulfillments.shipped_at",
+ "fulfillments.delivered_at",
+ "fulfillments.items.line_item_id",
+ "fulfillments.items.quantity",
+]
+
+const FULFILLMENT_SCALE: FulfillmentStatus[] = [
+ "not_fulfilled",
+ "partially_fulfilled",
+ "fulfilled",
+ "partially_shipped",
+ "shipped",
+ "partially_delivered",
+ "delivered",
+]
+
+export function fulfillmentReached(status: string | null | undefined, required: FulfillmentStatus): boolean {
+ if (status === "canceled") {
+ return false
+ }
+ return FULFILLMENT_SCALE.indexOf((status ?? "not_fulfilled") as FulfillmentStatus) >= FULFILLMENT_SCALE.indexOf(required)
+}
+
+/**
+ * The order module derives `fulfillment_status` only on its own read path,
+ * not through query.graph, so the pipeline rebuilds it from the fulfillments
+ * the same way: a status is reached when every ordered unit is in a
+ * fulfillment that reached it, partial when some are.
+ */
+export function deriveFulfillmentStatus(order: FulfillableOrder): FulfillmentStatus {
+ const ordered = (order.items ?? []).reduce<BigNumberInput>((acc, item) => MathBN.add(acc, item.quantity), 0)
+ if (MathBN.lte(ordered, 0)) {
+ return "not_fulfilled"
+ }
+
+ const active = (order.fulfillments ?? []).filter((f) => !f.canceled_at)
+ const count = (predicate: (f: FulfillmentRow) => boolean) =>
+ active
+ .filter(predicate)
+ .flatMap((f) => f.items ?? [])
+ .reduce<BigNumberInput>((acc, item) => MathBN.add(acc, item.quantity), 0)
+
+ const fulfilled = count(() => true)
+ const shipped = count((f) => !!f.shipped_at)
+ const delivered = count((f) => !!f.delivered_at)
+
+ if (MathBN.gte(delivered, ordered)) return "delivered"
+ if (MathBN.gt(delivered, 0)) return "partially_delivered"
+ if (MathBN.gte(shipped, ordered)) return "shipped"
+ if (MathBN.gt(shipped, 0)) return "partially_shipped"
+ if (MathBN.gte(fulfilled, ordered)) return "fulfilled"
+ if (MathBN.gt(fulfilled, 0)) return "partially_fulfilled"
+ return "not_fulfilled"
+}
diff --git a/packages/core/src/workflows/payout/utils/index.ts b/packages/core/src/workflows/payout/utils/index.ts
new file mode 100644
index 000000000..5439b22a3
--- /dev/null
+++ b/packages/core/src/workflows/payout/utils/index.ts
@@ -0,0 +1,3 @@
+export * from "./fulfillment-status"
+export * from "./payout-amounts"
+export * from "./sent-to-provider"
diff --git a/packages/core/src/workflows/payout/utils/payout-amounts.ts b/packages/core/src/workflows/payout/utils/payout-amounts.ts
new file mode 100644
index 000000000..b272f8c08
--- /dev/null
+++ b/packages/core/src/workflows/payout/utils/payout-amounts.ts
@@ -0,0 +1,473 @@
+import { BigNumberInput, FulfillmentStatus } from "@medusajs/framework/types"
+import { MathBN } from "@medusajs/framework/utils"
+import {
+ PayoutDTO,
+ PayoutReversalDTO,
+ PayoutStatus,
+ PayoutStatusReason,
+ PayoutStatusReasonCode,
+} from "@mercurjs/types"
+
+import { getCurrencyDecimalDigits } from "../../payment/utils/split-order-payment"
+import {
+ FulfillableOrder,
+ ORDER_FULFILLMENT_FIELDS,
+ deriveFulfillmentStatus,
+ fulfillmentReached,
+} from "./fulfillment-status"
+
+type AmountRow = { amount: BigNumberInput; raw_amount?: BigNumberInput | null }
+type RefundRow = AmountRow & { id: string }
+type PaymentRow = AmountRow & {
+ id: string
+ captured_at: Date | string | null
+ canceled_at: Date | string | null
+ data: Record<string, unknown> | null
+ captures?: AmountRow[] | null
+ refunds?: RefundRow[] | null
+}
+
+export type PayoutOrder = FulfillableOrder & {
+ id: string
+ status: string
+ canceled_at: Date | string | null
+ total: BigNumberInput
+ currency_code: string
+ credit_lines?: { amount: BigNumberInput }[] | null
+ shipping_methods?: { id: string }[] | null
+ seller?: {
+ id: string
+ payout_account?: { id: string; payouts_enabled: boolean } | null
+ } | null
+ payment_collections?: { payments?: PaymentRow[] | null }[] | null
+}
+
+export type CommissionLine = {
+ amount: BigNumberInput
+ item_id?: string | null
+ shipping_method_id?: string | null
+}
+
+export type PaymentState = {
+ id: string
+ captured: boolean
+ canceled: boolean
+ fully_refunded: boolean
+ data: Record<string, unknown>
+} | null
+
+export type PayoutDecision = {
+ status: PayoutStatus
+ status_reason: PayoutStatusReasonCode | null
+ status_detail: string | null
+ amount: BigNumberInput
+}
+
+export const PAYOUT_ORDER_FIELDS = [
+ "id",
+ "status",
+ "canceled_at",
+ "total",
+ "currency_code",
+ ...ORDER_FULFILLMENT_FIELDS,
+ "credit_lines.amount",
+ "shipping_methods.id",
+ "seller.id",
+ "seller.payout_account.id",
+ "seller.payout_account.payouts_enabled",
+ "payment_collections.payments.id",
+ "payment_collections.payments.amount",
+ "payment_collections.payments.raw_amount",
+ "payment_collections.payments.captured_at",
+ "payment_collections.payments.canceled_at",
+ "payment_collections.payments.data",
+ "payment_collections.payments.captures.amount",
+ "payment_collections.payments.captures.raw_amount",
+ "payment_collections.payments.refunds.id",
+ "payment_collections.payments.refunds.amount",
+ "payment_collections.payments.refunds.raw_amount",
+]
+
+export const REVERSAL_ORDER_FIELDS = [
+ "id",
+ "total",
+ "currency_code",
+ "credit_lines.amount",
+ "items.id",
+ "shipping_methods.id",
+ "payment_collections.payments.refunds.id",
+ "payment_collections.payments.refunds.amount",
+ "payment_collections.payments.refunds.raw_amount",
+]
+
+const RETRIABLE = [PayoutStatus.FAILED, PayoutStatus.ON_HOLD]
+
+const sum = (rows: AmountRow[] | null | undefined) =>
+ (rows ?? []).reduce<BigNumberInput>((acc, row) => MathBN.add(acc, row.raw_amount ?? row.amount), 0)
+
+const refundsOf = (order: Pick<PayoutOrder, "payment_collections">) =>
+ (order.payment_collections ?? []).flatMap((c) => c.payments ?? []).flatMap((p) => p.refunds ?? [])
+
+const hold = (reason: PayoutStatusReasonCode, detail: string | null = null): PayoutDecision => ({
+ status: PayoutStatus.ON_HOLD,
+ status_reason: reason,
+ status_detail: detail,
+ amount: 0,
+})
+
+const abort = (reason: PayoutStatusReasonCode, detail: string | null = null): PayoutDecision => ({
+ status: PayoutStatus.ABORTED,
+ status_reason: reason,
+ status_detail: detail,
+ amount: 0,
+})
+
+const ready = (amount: BigNumberInput, currencyCode?: string | null): PayoutDecision => {
+ const rounded = MathBN.convert(amount, getCurrencyDecimalDigits(currencyCode))
+ return MathBN.lte(rounded, 0)
+ ? abort(PayoutStatusReason.INVALID_AMOUNT, `Amount must be positive, input was: ${MathBN.convert(amount).toString()}`)
+ : { status: PayoutStatus.PENDING, status_reason: null, status_detail: null, amount: rounded }
+}
+
+const countBy = (statuses: string[]) =>
+ statuses.reduce<Record<string, number>>((counts, status) => {
+ counts[status] = (counts[status] ?? 0) + 1
+ return counts
+ }, {})
+
+/** Order total before refunds: Medusa books a refund as a credit line that lowers `total`. */
+export function grossTotalOf(order: Pick<PayoutOrder, "total" | "credit_lines">): BigNumberInput {
+ return (order.credit_lines ?? []).reduce<BigNumberInput>((acc, line) => MathBN.add(acc, line.amount), order.total)
+}
+
+export function paymentStateOf(order: Pick<PayoutOrder, "payment_collections">): PaymentState {
+ const payments = (order.payment_collections ?? []).flatMap((c) => c.payments ?? [])
+ const payment = payments.find((p) => !p.canceled_at) ?? payments[0]
+ if (!payment) {
+ return null
+ }
+
+ const captured = sum(payment.captures)
+ const isCaptured = !!payment.captured_at || MathBN.gt(captured, 0)
+
+ return {
+ id: payment.id,
+ captured: isCaptured,
+ canceled: !!payment.canceled_at,
+ fully_refunded:
+ isCaptured &&
+ MathBN.gte(sum(payment.refunds), MathBN.gt(captured, 0) ? captured : payment.raw_amount ?? payment.amount),
+ data: (payment.data ?? {}) as Record<string, unknown>,
+ }
+}
+
+export function commissionTotalsOf(
+ orders: Pick<PayoutOrder, "id" | "items" | "shipping_methods">[],
+ lines: CommissionLine[]
+): Map<string, BigNumberInput> {
+ const owner = new Map<string, string>()
+ for (const order of orders) {
+ for (const item of order.items ?? []) owner.set(item.id, order.id)
+ for (const method of order.shipping_methods ?? []) owner.set(method.id, order.id)
+ }
+
+ const totals = new Map<string, BigNumberInput>(orders.map((order) => [order.id, 0]))
+ for (const line of lines) {
+ const orderId = owner.get(line.item_id ?? "") ?? owner.get(line.shipping_method_id ?? "")
+ if (orderId) {
+ totals.set(orderId, MathBN.add(totals.get(orderId) ?? 0, line.amount ?? 0))
+ }
+ }
+
+ return totals
+}
+
+export function commissionLineFilters(orders: Pick<PayoutOrder, "items" | "shipping_methods">[]) {
+ const itemIds = orders.flatMap((order) => (order.items ?? []).map((item) => item.id))
+ const shippingMethodIds = orders.flatMap((order) => (order.shipping_methods ?? []).map((method) => method.id))
+
+ return {
+ $or: [
+ ...(itemIds.length ? [{ item_id: itemIds }] : []),
+ ...(shippingMethodIds.length ? [{ shipping_method_id: shippingMethodIds }] : []),
+ ],
+ }
+}
+
+/**
+ * Order of checks: canceled, account, fulfilled, paid, amount.
+ */
+export function decideOrderPayout(input: {
+ order: {
+ seller_id: string
+ status: string
+ canceled_at?: Date | string | null
+ fulfillment_status: string | null
+ total: BigNumberInput
+ currency_code?: string | null
+ }
+ account: { id: string; payouts_enabled: boolean } | null
+ payment: PaymentState
+ commission_total: BigNumberInput
+ required_fulfillment_status: FulfillmentStatus
+}): PayoutDecision {
+ const { order, account, payment } = input
+
+ if (order.status === "canceled" || order.canceled_at) {
+ return abort(PayoutStatusReason.ORDER_ABORTED, `Order cannot be processed, status is ${order.status}`)
+ }
+ if (!account) {
+ return hold(PayoutStatusReason.ACCOUNT_NOT_READY, `Cannot find payout account for seller ${order.seller_id}`)
+ }
+ if (!account.payouts_enabled) {
+ return hold(PayoutStatusReason.ACCOUNT_PAYOUTS_DISABLED, `Payouts are disabled for seller ${order.seller_id}`)
+ }
+ if (!fulfillmentReached(order.fulfillment_status, input.required_fulfillment_status)) {
+ return hold(
+ PayoutStatusReason.ORDER_NOT_READY,
+ `Order is not ready yet, status is ${order.fulfillment_status ?? "not_fulfilled"}`
+ )
+ }
+ if (!payment) {
+ return hold(PayoutStatusReason.PAYMENT_NOT_READY, "Payment is not ready yet, status is missing")
+ }
+ if (payment.canceled) {
+ return abort(PayoutStatusReason.PAYMENT_CANCELED, `Payment ${payment.id} has been canceled`)
+ }
+ if (payment.fully_refunded) {
+ return abort(PayoutStatusReason.PAYMENT_REFUNDED, `Payment ${payment.id} has been fully refunded`)
+ }
+ if (!payment.captured) {
+ return hold(PayoutStatusReason.PAYMENT_NOT_READY, `Payment ${payment.id} is not ready yet, status is authorized`)
+ }
+
+ return ready(MathBN.sub(order.total, input.commission_total), order.currency_code)
+}
+
+/**
+ * The seller gives back the refunded amount minus the commission share on
+ * it, once the order payout is paid.
+ */
+export function decideReversal(input: {
+ refund_id: string
+ refund_amount: BigNumberInput
+ refund_canceled: boolean
+ order_total: BigNumberInput
+ commission_total: BigNumberInput
+ currency_code?: string | null
+ payout: { id: string; status: PayoutStatus; provider_payout_id: string | null } | null
+}): PayoutDecision {
+ const payout = input.payout
+
+ if (input.refund_canceled || payout?.status === PayoutStatus.ABORTED) {
+ return abort(PayoutStatusReason.REFUND_ABORTED, `Refund ${input.refund_id} has been aborted`)
+ }
+ if (!payout || payout.status !== PayoutStatus.PAID || !payout.provider_payout_id) {
+ return hold(
+ PayoutStatusReason.PAYOUT_NOT_READY,
+ "The payout has to be paid before it can be reversed for a refund"
+ )
+ }
+
+ const share = MathBN.gt(input.order_total, 0)
+ ? MathBN.div(MathBN.mult(input.commission_total, input.refund_amount), input.order_total)
+ : 0
+
+ return ready(MathBN.sub(input.refund_amount, share), input.currency_code)
+}
+
+export type OrderPayoutsPlan = {
+ create: {
+ seller_id: string
+ order_id: string
+ account_id: string
+ amount: number
+ currency_code: string
+ status: PayoutStatus
+ status_reason: string | null
+ data: Record<string, unknown>
+ }[]
+ update: {
+ id: string
+ account_id: string
+ amount: number
+ status: PayoutStatus
+ status_reason: string | null
+ data: Record<string, unknown>
+ }[]
+ counts: Record<string, number>
+}
+
+/**
+ * A payout that is paid, processing or aborted is left alone; one on hold or
+ * failed is re-decided. A refund that landed before the payout cannot be
+ * reversed later, so the payout is built net of it and carries its commission share.
+ */
+export function planOrderPayouts(input: {
+ orders: PayoutOrder[]
+ commission_lines: CommissionLine[]
+ payouts: PayoutDTO[]
+ required_fulfillment_status: FulfillmentStatus
+}): OrderPayoutsPlan {
+ const commissions = commissionTotalsOf(input.orders, input.commission_lines)
+ const existing = new Map(input.payouts.map((payout) => [payout.order_id as string, payout]))
+ const plan: OrderPayoutsPlan = { create: [], update: [], counts: {} }
+ const statuses: string[] = []
+
+ for (const order of input.orders) {
+ const current = existing.get(order.id)
+ if (current && !RETRIABLE.includes(current.status)) {
+ continue
+ }
+
+ const account = order.seller?.payout_account ?? null
+ const payment = paymentStateOf(order)
+ const refunds = refundsOf(order)
+ const gross = grossTotalOf(order)
+ const absorbed = sum(refunds)
+ const net = MathBN.sub(gross, absorbed)
+ const commission = commissions.get(order.id) ?? 0
+
+ const decision = decideOrderPayout({
+ order: {
+ seller_id: order.seller?.id ?? "",
+ status: order.status,
+ canceled_at: order.canceled_at,
+ fulfillment_status: deriveFulfillmentStatus(order),
+ total: net,
+ currency_code: order.currency_code,
+ },
+ account,
+ payment,
+ commission_total:
+ MathBN.gt(absorbed, 0) && MathBN.gt(gross, 0) ? MathBN.div(MathBN.mult(commission, net), gross) : commission,
+ required_fulfillment_status: input.required_fulfillment_status,
+ })
+
+ const data = {
+ source_payment: payment ? { id: payment.id, data: payment.data } : null,
+ status_detail: decision.status_detail,
+ absorbed_refund_ids: refunds.map((refund) => refund.id),
+ }
+
+ if (current) {
+ plan.update.push({
+ id: current.id,
+ account_id: account?.id ?? current.account_id,
+ amount: Number(decision.amount),
+ status: decision.status,
+ status_reason: decision.status_reason,
+ data: { ...(current.data ?? {}), ...data },
+ })
+ } else if (account && order.seller) {
+ plan.create.push({
+ seller_id: order.seller.id,
+ order_id: order.id,
+ account_id: account.id,
+ amount: Number(decision.amount),
+ currency_code: order.currency_code,
+ status: decision.status,
+ status_reason: decision.status_reason,
+ data,
+ })
+ } else {
+ statuses.push("awaiting_account")
+ continue
+ }
+
+ statuses.push(decision.status)
+ }
+
+ plan.counts = countBy(statuses)
+ return plan
+}
+
+export type PayoutReversalsPlan = {
+ create: {
+ payout_id: string
+ refund_id: string
+ amount: number
+ status: PayoutStatus
+ status_reason: string | null
+ data: Record<string, unknown>
+ }[]
+ update: {
+ id: string
+ amount: number
+ status: PayoutStatus
+ status_reason: string | null
+ data: Record<string, unknown>
+ }[]
+ counts: Record<string, number>
+}
+
+/**
+ * Every refund on an order whose payout exists gets one reversal, net of the
+ * commission share on it. Refunds the payout already absorbed are skipped.
+ */
+export function planPayoutReversals(input: {
+ orders: PayoutOrder[]
+ commission_lines: CommissionLine[]
+ payouts: (PayoutDTO & { reversals?: PayoutReversalDTO[] })[]
+}): PayoutReversalsPlan {
+ const commissions = commissionTotalsOf(input.orders, input.commission_lines)
+ const payoutByOrder = new Map(input.payouts.map((payout) => [payout.order_id as string, payout]))
+ const plan: PayoutReversalsPlan = { create: [], update: [], counts: {} }
+ const statuses: string[] = []
+
+ for (const order of input.orders) {
+ const payout = payoutByOrder.get(order.id)
+ if (!payout) {
+ continue
+ }
+
+ const reversals = new Map((payout.reversals ?? []).map((reversal) => [reversal.refund_id, reversal]))
+ const absorbed = new Set((payout.data?.absorbed_refund_ids ?? []) as string[])
+
+ for (const refund of refundsOf(order)) {
+ const existing = reversals.get(refund.id)
+ if (existing && !RETRIABLE.includes(existing.status)) {
+ continue
+ }
+
+ if (absorbed.has(refund.id)) {
+ if (existing) {
+ plan.update.push({
+ id: existing.id,
+ amount: 0,
+ status: PayoutStatus.ABORTED,
+ status_reason: PayoutStatusReason.REFUND_ABSORBED,
+ data: { ...(existing.data ?? {}), status_detail: `Refund ${refund.id} was deducted from the payout` },
+ })
+ }
+ statuses.push("absorbed")
+ continue
+ }
+
+ const decision = decideReversal({
+ refund_id: refund.id,
+ refund_amount: refund.raw_amount ?? refund.amount,
+ refund_canceled: false,
+ order_total: grossTotalOf(order),
+ commission_total: commissions.get(order.id) ?? 0,
+ currency_code: order.currency_code,
+ payout: {
+ id: payout.id,
+ status: payout.status,
+ provider_payout_id: ((payout.data?.provider as { id?: string } | undefined)?.id) ?? null,
+ },
+ })
+
+ const row = { amount: Number(decision.amount), status: decision.status, status_reason: decision.status_reason }
+ if (existing) {
+ plan.update.push({ id: existing.id, ...row, data: { ...(existing.data ?? {}), status_detail: decision.status_detail } })
+ } else {
+ plan.create.push({ payout_id: payout.id, refund_id: refund.id, ...row, data: { status_detail: decision.status_detail } })
+ }
+ statuses.push(decision.status)
+ }
+ }
+
+ plan.counts = countBy(statuses)
+ return plan
+}
diff --git a/packages/core/src/workflows/payout/utils/sent-to-provider.ts b/packages/core/src/workflows/payout/utils/sent-to-provider.ts
new file mode 100644
index 000000000..7a57db092
--- /dev/null
+++ b/packages/core/src/workflows/payout/utils/sent-to-provider.ts
@@ -0,0 +1,17 @@
+import { PayoutStatus } from "@mercurjs/types"
+
+type Attempted = { status: PayoutStatus; data?: Record<string, unknown> | null }
+
+const attemptsOf = (row: Pick<Attempted, "data"> | null | undefined) => Number(row?.data?.attempts ?? 0)
+
+/**
+ * Whether the payout or reversal went to the provider after `previous` was
+ * read. A rollback must leave such a row alone: the money may have left.
+ */
+export function sentToProvider(current: Attempted, previous?: Pick<Attempted, "data"> | null): boolean {
+ return (
+ current.status === PayoutStatus.PROCESSING ||
+ current.status === PayoutStatus.PAID ||
+ attemptsOf(current) > attemptsOf(previous)
+ )
+}
diff --git a/packages/core/src/workflows/payout/workflows/create-onboarding.ts b/packages/core/src/workflows/payout/workflows/create-onboarding.ts
index 0a8c6791c..3755118b3 100644
--- a/packages/core/src/workflows/payout/workflows/create-onboarding.ts
+++ b/packages/core/src/workflows/payout/workflows/create-onboarding.ts
@@ -3,8 +3,14 @@ import { CreateOnboardingDTO } from "@mercurjs/types"
import { createOnboardingStep } from "../steps"
+export const createOnboardingWorkflowId = "create-onboarding-workflow"
+
+/**
+ * Publishes the seller's next link: onboarding until their details are
+ * submitted, the provider dashboard login afterwards.
+ */
export const createOnboardingWorkflow = createWorkflow(
- "create-onboarding",
+ createOnboardingWorkflowId,
function (input: CreateOnboardingDTO) {
const onboarding = createOnboardingStep(input)
diff --git a/packages/core/src/workflows/payout/workflows/create-or-refresh-seller-payout-account.ts b/packages/core/src/workflows/payout/workflows/create-or-refresh-seller-payout-account.ts
new file mode 100644
index 000000000..176270217
--- /dev/null
+++ b/packages/core/src/workflows/payout/workflows/create-or-refresh-seller-payout-account.ts
@@ -0,0 +1,62 @@
+import { ReturnWorkflow, WorkflowResponse, createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { PayoutProviderInput } from "@mercurjs/types"
+
+import { createOnboardingStep } from "../steps"
+import { createPayoutAccountWorkflow } from "./create-payout-account"
+
+export type CreateOrRefreshSellerPayoutAccountWorkflowInput = PayoutProviderInput & {
+ seller_id: string
+}
+
+export type CreateOrRefreshSellerPayoutAccountWorkflowOutput = {
+ account_id: string | null
+ onboarding_published: boolean
+}
+
+export const createOrRefreshSellerPayoutAccountWorkflowId = "create-or-refresh-seller-payout-account"
+
+/**
+ * Creates the seller's payout account when missing and publishes a fresh
+ * onboarding link until the seller has finished onboarding.
+ */
+export const createOrRefreshSellerPayoutAccountWorkflow: ReturnWorkflow<
+ CreateOrRefreshSellerPayoutAccountWorkflowInput,
+ CreateOrRefreshSellerPayoutAccountWorkflowOutput,
+ []
+> = createWorkflow(createOrRefreshSellerPayoutAccountWorkflowId, function (input: CreateOrRefreshSellerPayoutAccountWorkflowInput) {
+ const { data: seller } = useQueryGraphStep({
+ entity: "seller",
+ fields: ["id", "payout_account.id", "payout_account.details_submitted"],
+ filters: { id: input.seller_id },
+ options: { isList: false, throwIfKeyNotFound: true },
+ }).config({ name: "create-or-refresh-payout-account-seller-query" })
+
+ const created = when("create-missing-payout-account", { seller }, ({ seller }) => !seller.payout_account).then(
+ () =>
+ createPayoutAccountWorkflow.runAsStep({
+ input: { seller_id: input.seller_id, data: input.data, context: input.context },
+ })
+ )
+
+ const onboarding = transform({ seller, created }, ({ seller, created }) => ({
+ account_id: (seller.payout_account?.id ?? created?.id ?? null) as string | null,
+ refresh_link: !!seller.payout_account && !seller.payout_account.details_submitted,
+ created: !!created,
+ }))
+
+ // A new account already got its link from createPayoutAccountWorkflow; an
+ // existing one gets a fresh link because provider onboarding links expire.
+ when("refresh-onboarding-link", { onboarding }, ({ onboarding }) => onboarding.refresh_link).then(() => {
+ createOnboardingStep(
+ transform({ onboarding }, ({ onboarding }) => ({ account_id: onboarding.account_id as string }))
+ )
+ })
+
+ return new WorkflowResponse(
+ transform({ onboarding }, ({ onboarding }) => ({
+ account_id: onboarding.account_id,
+ onboarding_published: onboarding.created || onboarding.refresh_link,
+ }))
+ )
+})
diff --git a/packages/core/src/workflows/payout/workflows/create-order-payouts.ts b/packages/core/src/workflows/payout/workflows/create-order-payouts.ts
new file mode 100644
index 000000000..c54ec0c8d
--- /dev/null
+++ b/packages/core/src/workflows/payout/workflows/create-order-payouts.ts
@@ -0,0 +1,138 @@
+import { FulfillmentStatus, LinkDefinition } from "@medusajs/framework/types"
+import { Modules } from "@medusajs/framework/utils"
+import {
+ Hook,
+ ReturnWorkflow,
+ WorkflowResponse,
+ createHook,
+ createWorkflow,
+ transform,
+ when,
+} from "@medusajs/framework/workflows-sdk"
+import { createRemoteLinkStep, emitEventStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { MercurModules, PayoutDTO, PayoutModuleEvents, PayoutStatus } from "@mercurjs/types"
+
+import { createPayoutsStep, processPayoutsStep, updatePayoutsStep } from "../steps"
+import {
+ CommissionLine,
+ PAYOUT_ORDER_FIELDS,
+ PayoutOrder,
+ commissionLineFilters,
+ planOrderPayouts,
+} from "../utils/payout-amounts"
+import { failedPayoutEvents } from "./process-payout"
+
+export type CreateOrderPayoutsWorkflowInput = {
+ order_ids: string[]
+ /**
+ * How far an order has to be fulfilled before its seller is paid out.
+ * Defaults to `fulfilled`.
+ */
+ required_fulfillment_status?: FulfillmentStatus
+}
+
+export type CreateOrderPayoutsWorkflowOutput = {
+ counts: Record<string, number>
+ payouts: PayoutDTO[]
+}
+
+export const createOrderPayoutsWorkflowId = "create-order-payouts"
+
+/**
+ * Pays each order's seller their share: the order total minus commission,
+ * net of refunds that landed before the payout. An order that is not ready
+ * (no active payout account, not fulfilled, payment not captured) gets a
+ * payout on hold, which the next run re-decides; a canceled one is aborted.
+ */
+export const createOrderPayoutsWorkflow: ReturnWorkflow<
+ CreateOrderPayoutsWorkflowInput,
+ CreateOrderPayoutsWorkflowOutput,
+ [Hook<"payoutsCreated", { order_ids: string[]; payouts: PayoutDTO[] }, unknown>]
+> = createWorkflow(createOrderPayoutsWorkflowId, function (input: CreateOrderPayoutsWorkflowInput) {
+ const loaded = when("orders-to-pay-out", { input }, ({ input }) => input.order_ids.length > 0).then(() => {
+ const { data: orders } = useQueryGraphStep({
+ entity: "order",
+ fields: PAYOUT_ORDER_FIELDS,
+ filters: { id: input.order_ids },
+ }).config({ name: "payout-orders-query" })
+
+ const { data: payouts } = useQueryGraphStep({
+ entity: "payout",
+ fields: ["*"],
+ filters: { order_id: input.order_ids },
+ }).config({ name: "existing-payouts-query" })
+
+ return transform({ orders, payouts }, ({ orders, payouts }) => ({
+ orders: orders as unknown as PayoutOrder[],
+ payouts: payouts as unknown as PayoutDTO[],
+ }))
+ })
+
+ const commissionFilters = transform({ loaded }, ({ loaded }) => commissionLineFilters(loaded?.orders ?? []))
+
+ const commissionLines = when(
+ "orders-with-commission-lines",
+ { commissionFilters },
+ ({ commissionFilters }) => commissionFilters.$or.length > 0
+ ).then(() => {
+ const { data } = useQueryGraphStep({
+ entity: "commission_line",
+ fields: ["amount", "item_id", "shipping_method_id"],
+ filters: commissionFilters,
+ }).config({ name: "payout-commission-lines-query" })
+
+ return data
+ })
+
+ const plan = transform({ input, loaded, commissionLines }, ({ input, loaded, commissionLines }) =>
+ planOrderPayouts({
+ orders: loaded?.orders ?? [],
+ payouts: loaded?.payouts ?? [],
+ commission_lines: (commissionLines ?? []) as unknown as CommissionLine[],
+ required_fulfillment_status: input.required_fulfillment_status ?? "fulfilled",
+ })
+ )
+
+ const created = createPayoutsStep(
+ transform({ plan }, ({ plan }) => plan.create.map(({ seller_id: _seller, ...payout }) => payout))
+ )
+ const updated = updatePayoutsStep(transform({ plan }, ({ plan }) => plan.update))
+
+ const links = transform({ plan, created }, ({ plan, created }) => {
+ const sellerByOrder = new Map(plan.create.map((row) => [row.order_id, row.seller_id]))
+
+ return created.flatMap((payout): LinkDefinition[] => [
+ {
+ [MercurModules.PAYOUT]: { payout_id: payout.id },
+ [MercurModules.SELLER]: { seller_id: sellerByOrder.get(payout.order_id as string) as string },
+ },
+ {
+ [Modules.ORDER]: { order_id: payout.order_id as string },
+ [MercurModules.PAYOUT]: { payout_id: payout.id },
+ },
+ ])
+ })
+ createRemoteLinkStep(links)
+
+ const pendingIds = transform({ created, updated }, ({ created, updated }) =>
+ [...created, ...updated].filter((payout) => payout.status === PayoutStatus.PENDING).map((payout) => payout.id)
+ )
+ const payouts = processPayoutsStep({ ids: pendingIds })
+
+ emitEventStep({
+ eventName: PayoutModuleEvents.PAYOUT_FAILED,
+ data: transform({ payouts }, ({ payouts }) => failedPayoutEvents(payouts)),
+ })
+
+ const output = transform({ plan, payouts }, ({ plan, payouts }): CreateOrderPayoutsWorkflowOutput => ({
+ counts: plan.counts,
+ payouts,
+ }))
+
+ const payoutsCreated = createHook("payoutsCreated", {
+ order_ids: input.order_ids,
+ payouts: output.payouts,
+ })
+
+ return new WorkflowResponse(output, { hooks: [payoutsCreated] })
+})
diff --git a/packages/core/src/workflows/payout/workflows/create-payout-account.ts b/packages/core/src/workflows/payout/workflows/create-payout-account.ts
index 8079a6f66..cd8cbda76 100644
--- a/packages/core/src/workflows/payout/workflows/create-payout-account.ts
+++ b/packages/core/src/workflows/payout/workflows/create-payout-account.ts
@@ -1,39 +1,65 @@
-import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
-import { WorkflowResponse, createWorkflow } from "@medusajs/framework/workflows-sdk"
-import { CreatePayoutAccountDTO, MercurModules } from "@mercurjs/types"
+import { WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
+import { createRemoteLinkStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { CreatePayoutAccountDTO, MercurModules, PayoutProviderInput } from "@mercurjs/types"
-import {
- createPayoutAccountStep,
- validateSellerPayoutAccountStep,
-} from "../steps"
+import { createOnboardingStep, createPayoutAccountStep, validateSellerWithoutPayoutAccountStep } from "../steps"
-interface CreatePayoutAccountInput extends CreatePayoutAccountDTO {
+export type CreatePayoutAccountWorkflowInput = PayoutProviderInput & {
seller_id: string
}
+export const createPayoutAccountWorkflowId = "create-payout-account-workflow"
+
+/**
+ * Creates the seller's account at the payout provider, prefilled from the
+ * seller's profile, links it to the seller and publishes the onboarding link.
+ */
export const createPayoutAccountWorkflow = createWorkflow(
- "create-payout-account-for-seller",
- function (input: CreatePayoutAccountInput) {
- validateSellerPayoutAccountStep({
- seller_id: input.seller_id,
- })
+ createPayoutAccountWorkflowId,
+ function (input: CreatePayoutAccountWorkflowInput) {
+ const { data: seller } = useQueryGraphStep({
+ entity: "seller",
+ fields: [
+ "id",
+ "name",
+ "email",
+ "phone",
+ "website_url",
+ "address.country_code",
+ "professional_details.corporate_name",
+ "payout_account.id",
+ ],
+ filters: { id: input.seller_id },
+ options: { isList: false, throwIfKeyNotFound: true },
+ }).config({ name: "payout-account-seller-query" })
+
+ validateSellerWithoutPayoutAccountStep({ seller })
- const payoutAccount = createPayoutAccountStep({
- context: input.context,
- data: input.data,
- })
+ const accountInput = transform({ input, seller }, ({ input, seller }): CreatePayoutAccountDTO => ({
+ data: input.data ?? {},
+ context: input.context ?? {},
+ seller: {
+ id: seller.id,
+ name: seller.name ?? null,
+ email: seller.email ?? null,
+ phone: seller.phone ?? null,
+ website_url: seller.website_url ?? null,
+ country_code: seller.address?.country_code ?? null,
+ is_company: !!seller.professional_details?.corporate_name,
+ },
+ }))
+
+ const payoutAccount = createPayoutAccountStep(accountInput)
createRemoteLinkStep([
{
- [MercurModules.SELLER]: {
- seller_id: input.seller_id,
- },
- [MercurModules.PAYOUT]: {
- payout_account_id: payoutAccount.id,
- },
+ [MercurModules.SELLER]: { seller_id: input.seller_id },
+ [MercurModules.PAYOUT]: { payout_account_id: payoutAccount.id },
},
])
+ createOnboardingStep(transform({ payoutAccount }, ({ payoutAccount }) => ({ account_id: payoutAccount.id })))
+
return new WorkflowResponse(payoutAccount)
}
)
diff --git a/packages/core/src/workflows/payout/workflows/create-payout-reversals.ts b/packages/core/src/workflows/payout/workflows/create-payout-reversals.ts
new file mode 100644
index 000000000..c48d69bfa
--- /dev/null
+++ b/packages/core/src/workflows/payout/workflows/create-payout-reversals.ts
@@ -0,0 +1,103 @@
+import {
+ WorkflowResponse,
+ createWorkflow,
+ transform,
+ when,
+} from "@medusajs/framework/workflows-sdk"
+import { emitEventStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { PayoutDTO, PayoutModuleEvents, PayoutReversalDTO, PayoutStatus } from "@mercurjs/types"
+
+import { createPayoutReversalsStep, processPayoutReversalsStep, updatePayoutReversalsStep } from "../steps"
+import {
+ CommissionLine,
+ PayoutOrder,
+ REVERSAL_ORDER_FIELDS,
+ commissionLineFilters,
+ planPayoutReversals,
+} from "../utils/payout-amounts"
+import { failedReversalEvents } from "./process-payout-reversal"
+
+export type CreatePayoutReversalsWorkflowInput = {
+ order_ids: string[]
+}
+
+export type CreatePayoutReversalsWorkflowOutput = {
+ counts: Record<string, number>
+ reversals: PayoutReversalDTO[]
+}
+
+export const createPayoutReversalsWorkflowId = "create-payout-reversals"
+
+/**
+ * Takes the refunded share back from the seller: one reversal per refund on
+ * an order whose payout is paid, net of the commission on that share.
+ */
+export const createPayoutReversalsWorkflow = createWorkflow(
+ createPayoutReversalsWorkflowId,
+ function (input: CreatePayoutReversalsWorkflowInput) {
+ const loaded = when("orders-to-reverse", { input }, ({ input }) => input.order_ids.length > 0).then(() => {
+ const { data: orders } = useQueryGraphStep({
+ entity: "order",
+ fields: REVERSAL_ORDER_FIELDS,
+ filters: { id: input.order_ids },
+ }).config({ name: "reversal-orders-query" })
+
+ const { data: payouts } = useQueryGraphStep({
+ entity: "payout",
+ fields: ["*", "reversals.*"],
+ filters: { order_id: input.order_ids },
+ }).config({ name: "reversal-payouts-query" })
+
+ return transform({ orders, payouts }, ({ orders, payouts }) => ({
+ orders: orders as unknown as PayoutOrder[],
+ payouts: payouts as unknown as (PayoutDTO & { reversals?: PayoutReversalDTO[] })[],
+ }))
+ })
+
+ const commissionFilters = transform({ loaded }, ({ loaded }) => commissionLineFilters(loaded?.orders ?? []))
+
+ const commissionLines = when(
+ "reversal-orders-with-commission-lines",
+ { commissionFilters },
+ ({ commissionFilters }) => commissionFilters.$or.length > 0
+ ).then(() => {
+ const { data } = useQueryGraphStep({
+ entity: "commission_line",
+ fields: ["amount", "item_id", "shipping_method_id"],
+ filters: commissionFilters,
+ }).config({ name: "reversal-commission-lines-query" })
+
+ return data
+ })
+
+ const plan = transform({ loaded, commissionLines }, ({ loaded, commissionLines }) =>
+ planPayoutReversals({
+ orders: loaded?.orders ?? [],
+ payouts: loaded?.payouts ?? [],
+ commission_lines: (commissionLines ?? []) as unknown as CommissionLine[],
+ })
+ )
+
+ const created = createPayoutReversalsStep(transform({ plan }, ({ plan }) => plan.create))
+ const updated = updatePayoutReversalsStep(transform({ plan }, ({ plan }) => plan.update))
+
+ const pendingIds = transform({ created, updated }, ({ created, updated }) =>
+ [...created, ...updated]
+ .filter((reversal) => reversal.status === PayoutStatus.PENDING)
+ .map((reversal) => reversal.id)
+ )
+ const reversals = processPayoutReversalsStep({ ids: pendingIds })
+
+ emitEventStep({
+ eventName: PayoutModuleEvents.PAYOUT_REVERSAL_FAILED,
+ data: transform({ reversals }, ({ reversals }) => failedReversalEvents(reversals)),
+ })
+
+ return new WorkflowResponse(
+ transform({ plan, reversals }, ({ plan, reversals }): CreatePayoutReversalsWorkflowOutput => ({
+ counts: plan.counts,
+ reversals,
+ }))
+ )
+ }
+)
diff --git a/packages/core/src/workflows/payout/workflows/create-payout.ts b/packages/core/src/workflows/payout/workflows/create-payout.ts
deleted file mode 100644
index a1b7ad6b2..000000000
--- a/packages/core/src/workflows/payout/workflows/create-payout.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import { createRemoteLinkStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"
-import {
- WorkflowData,
- WorkflowResponse,
- createHook,
- createWorkflow,
- transform,
-} from "@medusajs/framework/workflows-sdk"
-import { MathBN, MedusaError } from "@medusajs/framework/utils"
-import { MercurModules } from "@mercurjs/types"
-
-import { createPayoutStep } from "../steps"
-
-type CreatePayoutWorkflowInput = {
- order_id: string
-}
-
-export const createPayoutWorkflowId = "create-payout"
-
-export const createPayoutWorkflow = createWorkflow(
- createPayoutWorkflowId,
- function (input: WorkflowData<CreatePayoutWorkflowInput>) {
- const { data: orders } = useQueryGraphStep({
- entity: "order",
- fields: [
- 'id',
- 'currency_code',
- 'total',
- 'seller.*',
- 'seller.payout_account.*',
- 'items.*',
- 'shipping_methods.*',
- ],
- filters: { id: input.order_id },
- options: { throwIfKeyNotFound: true },
- }).config({ name: "fetch-order" })
-
- const order = transform({ orders }, ({ orders }) => orders[0])
-
- const commissionFilters = transform({ order }, ({ order }) => ({
- $or: [
- { item_id: (order.items ?? []).map((item: any) => item.id) },
- {
- shipping_method_id: ((order as any).shipping_methods ?? []).map(
- (method: any) => method.id
- ),
- },
- ],
- }))
-
- // The order→commission links resolve for items but not shipping methods,
- // so read the order's commission lines (item + shipping) straight from
- // the commission module via query.
- const { data: commissionLines } = useQueryGraphStep({
- entity: "commission_line",
- fields: ["amount"],
- filters: commissionFilters,
- }).config({ name: "fetch-commission-lines" })
-
- const payoutInput = transform(
- { order, commissionLines },
- ({ order, commissionLines }) => {
- const payoutAccountId = (order as any).seller?.payout_account?.id
- const sellerId = (order as any).seller?.id
-
- if (!payoutAccountId) {
- throw new MedusaError(
- MedusaError.Types.NOT_FOUND,
- `Seller does not have a payout account`
- )
- }
-
- const totalCommission = (commissionLines ?? []).reduce(
- (acc: number, line: any) =>
- MathBN.add(acc, line?.amount ?? 0) as unknown as number,
- 0
- )
-
- const amount = MathBN.sub(
- order.total,
- totalCommission
- ) as unknown as number
-
- return {
- account_id: payoutAccountId,
- seller_id: sellerId,
- amount,
- currency_code: order.currency_code,
- data: {
- order_id: order.id,
- seller_id: sellerId
- },
- 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([
- {
- [MercurModules.PAYOUT]: {
- payout_id: payout.id,
- },
- [MercurModules.SELLER]: {
- seller_id: payoutInput.seller_id,
- },
- },
- ])
-
- const payoutCreated = createHook("payoutCreated", {
- order_id: input.order_id,
- payout_id: payout.id,
- })
-
- return new WorkflowResponse(payout, { hooks: [payoutCreated] })
- }
-)
diff --git a/packages/core/src/workflows/payout/workflows/index.ts b/packages/core/src/workflows/payout/workflows/index.ts
index 914d7c8ce..0d109cf83 100644
--- a/packages/core/src/workflows/payout/workflows/index.ts
+++ b/packages/core/src/workflows/payout/workflows/index.ts
@@ -1,4 +1,13 @@
-export * from "./create-payout-account"
export * from "./create-onboarding"
-export * from "./create-payout"
+export * from "./create-or-refresh-seller-payout-account"
+export * from "./create-order-payouts"
+export * from "./create-payout-account"
+export * from "./create-payout-reversals"
+export * from "./link-payout-account"
+export * from "./process-payout"
export * from "./process-payout-for-webhook"
+export * from "./process-payout-reversal"
+export * from "./refresh-onboarding"
+export * from "./refresh-payout-account-link"
+export * from "./retry-payout"
+export * from "./sync-payout-account"
diff --git a/packages/core/src/workflows/payout/workflows/link-payout-account.ts b/packages/core/src/workflows/payout/workflows/link-payout-account.ts
new file mode 100644
index 000000000..ab7137dc8
--- /dev/null
+++ b/packages/core/src/workflows/payout/workflows/link-payout-account.ts
@@ -0,0 +1,50 @@
+import { WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
+import { createRemoteLinkStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { MercurModules } from "@mercurjs/types"
+
+import { createPayoutAccountsStep, validateSellerWithoutPayoutAccountStep } from "../steps"
+import { syncPayoutAccountWorkflow } from "./sync-payout-account"
+
+export type LinkPayoutAccountWorkflowInput = {
+ seller_id: string
+ /** The account's id at the payout provider. */
+ external_id: string
+}
+
+export const linkPayoutAccountWorkflowId = "link-payout-account"
+
+/**
+ * Attaches an account that already exists at the payout provider to a
+ * seller, then pulls its state from the provider.
+ */
+export const linkPayoutAccountWorkflow = createWorkflow(
+ linkPayoutAccountWorkflowId,
+ function (input: LinkPayoutAccountWorkflowInput) {
+ const { data: seller } = useQueryGraphStep({
+ entity: "seller",
+ fields: ["id", "payout_account.id"],
+ filters: { id: input.seller_id },
+ options: { isList: false, throwIfKeyNotFound: true },
+ }).config({ name: "link-payout-account-seller-query" })
+
+ validateSellerWithoutPayoutAccountStep({ seller })
+
+ const accounts = createPayoutAccountsStep(
+ transform({ input }, ({ input }) => [{ external_id: input.external_id, data: { id: input.external_id } }])
+ )
+ const account = transform({ accounts }, ({ accounts }) => accounts[0])
+
+ createRemoteLinkStep([
+ {
+ [MercurModules.SELLER]: { seller_id: input.seller_id },
+ [MercurModules.PAYOUT]: { payout_account_id: account.id },
+ },
+ ])
+
+ const synced = syncPayoutAccountWorkflow.runAsStep({
+ input: transform({ account }, ({ account }) => ({ id: account.id })),
+ })
+
+ return new WorkflowResponse(synced)
+ }
+)
diff --git a/packages/core/src/workflows/payout/workflows/process-payout-for-webhook.ts b/packages/core/src/workflows/payout/workflows/process-payout-for-webhook.ts
index 44546f3f9..1dfc08eaa 100644
--- a/packages/core/src/workflows/payout/workflows/process-payout-for-webhook.ts
+++ b/packages/core/src/workflows/payout/workflows/process-payout-for-webhook.ts
@@ -1,81 +1,84 @@
-import { createWorkflow, when } from "@medusajs/framework/workflows-sdk"
-import {
- PayoutWebhookResult,
- PayoutAccountStatus,
- PayoutStatus,
-} from "@mercurjs/types"
+import { createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { PayoutStatus, PayoutStatusReason, PayoutWebhookResult } from "@mercurjs/types"
-import { updatePayoutAccountStep } from "../steps/update-payout-account"
-import { updatePayoutStep } from "../steps/update-payout"
+import { updatePayoutsStep } from "../steps"
+import { syncPayoutAccountWorkflow } from "./sync-payout-account"
-export interface ProcessPayoutForWebhookWorkflowInput extends PayoutWebhookResult { }
+export type ProcessPayoutForWebhookWorkflowInput = PayoutWebhookResult
export const processPayoutForWebhookWorkflowId = "process-payout-for-webhook"
+const STATUS_BY_ACTION: Record<string, PayoutStatus> = {
+ "payout.paid": PayoutStatus.PAID,
+ "payout.failed": PayoutStatus.FAILED,
+}
+
+/**
+ * Applies a provider webhook: an `account.*` event re-syncs the account, a
+ * `payout.*` event moves the payout to its final status and stores the
+ * provider's id for the payout, which a later reversal needs.
+ */
export const processPayoutForWebhookWorkflow = createWorkflow(
processPayoutForWebhookWorkflowId,
- (input: ProcessPayoutForWebhookWorkflowInput) => {
- when({ input }, ({ input }) => {
- return input.action === "account.activated" && !!input.data?.id
- }).then(() => {
- updatePayoutAccountStep({
- id: input.data!.id,
- status: PayoutAccountStatus.ACTIVE,
- }).config({ name: "activate-payout-account" })
- })
+ function (input: ProcessPayoutForWebhookWorkflowInput) {
+ const accounts = when(
+ "account-webhook",
+ { input },
+ ({ input }) => input.action.startsWith("account.") && !!input.data?.id
+ ).then(() => {
+ const { data } = useQueryGraphStep({
+ entity: "payout_account",
+ fields: ["id"],
+ filters: transform({ input }, ({ input }) => ({ external_id: input.data?.id as string })),
+ }).config({ name: "webhook-account-query" })
- when({ input }, ({ input }) => {
- return input.action === "account.restricted" && !!input.data?.id
- }).then(() => {
- updatePayoutAccountStep({
- id: input.data!.id,
- status: PayoutAccountStatus.RESTRICTED,
- }).config({ name: "restrict-payout-account" })
+ return data
})
- when({ input }, ({ input }) => {
- return input.action === "account.rejected" && !!input.data?.id
- }).then(() => {
- updatePayoutAccountStep({
- id: input.data!.id,
- status: PayoutAccountStatus.REJECTED,
- }).config({ name: "reject-payout-account" })
+ when("known-account", { accounts }, ({ accounts }) => !!accounts?.length).then(() => {
+ syncPayoutAccountWorkflow.runAsStep({
+ input: transform({ accounts }, ({ accounts }) => ({ id: accounts![0].id })),
+ })
})
- when({ input }, ({ input }) => {
- return input.action === "payout.processing" && !!input.data?.id
- }).then(() => {
- updatePayoutStep({
- id: input.data!.id,
- status: PayoutStatus.PROCESSING,
- }).config({ name: "processing-payout" })
- })
+ const payouts = when(
+ "payout-webhook",
+ { input },
+ ({ input }) => !!STATUS_BY_ACTION[input.action] && !!input.data?.payout_id
+ ).then(() => {
+ const { data } = useQueryGraphStep({
+ entity: "payout",
+ fields: ["id", "data"],
+ filters: transform({ input }, ({ input }) => ({ id: input.data?.payout_id as string })),
+ }).config({ name: "webhook-payout-query" })
- when({ input }, ({ input }) => {
- return input.action === "payout.paid" && !!input.data?.id
- }).then(() => {
- updatePayoutStep({
- id: input.data!.id,
- status: PayoutStatus.PAID,
- }).config({ name: "paid-payout" })
+ return data
})
- when({ input }, ({ input }) => {
- return input.action === "payout.failed" && !!input.data?.id
- }).then(() => {
- updatePayoutStep({
- id: input.data!.id,
- status: PayoutStatus.FAILED,
- }).config({ name: "failed-payout" })
- })
+ updatePayoutsStep(
+ transform({ input, payouts }, ({ input, payouts }) =>
+ (payouts ?? []).map((payout) => {
+ const status = STATUS_BY_ACTION[input.action]
+ const data = (payout.data ?? {}) as Record<string, unknown>
+ const provider = (data.provider ?? {}) as Record<string, unknown>
- when({ input }, ({ input }) => {
- return input.action === "payout.canceled" && !!input.data?.id
- }).then(() => {
- updatePayoutStep({
- id: input.data!.id,
- status: PayoutStatus.CANCELED,
- }).config({ name: "canceled-payout" })
- })
+ return {
+ id: payout.id,
+ status,
+ status_reason: status === PayoutStatus.FAILED ? PayoutStatusReason.PROVIDER_ERROR : null,
+ data: {
+ ...data,
+ provider: { ...provider, id: input.data?.id ?? provider.id },
+ status_detail:
+ status === PayoutStatus.FAILED ? (input.data?.status_reason ?? data.status_detail ?? null) : null,
+ // The provider failed the payout it made under this key, so the
+ // retry must not get that payout back.
+ ...(status === PayoutStatus.FAILED ? { idempotency_key: null } : {}),
+ },
+ }
+ })
+ )
+ )
}
)
diff --git a/packages/core/src/workflows/payout/workflows/process-payout-reversal.ts b/packages/core/src/workflows/payout/workflows/process-payout-reversal.ts
new file mode 100644
index 000000000..acf3be0ea
--- /dev/null
+++ b/packages/core/src/workflows/payout/workflows/process-payout-reversal.ts
@@ -0,0 +1,32 @@
+import {
+ WorkflowResponse,
+ createWorkflow,
+ transform,
+} from "@medusajs/framework/workflows-sdk"
+import { emitEventStep } from "@medusajs/medusa/core-flows"
+import { PayoutModuleEvents, PayoutReversalDTO, PayoutStatus } from "@mercurjs/types"
+
+import { processPayoutReversalsStep } from "../steps"
+
+export type ProcessPayoutReversalWorkflowInput = {
+ reversal_ids: string[]
+}
+
+export const processPayoutReversalWorkflowId = "process-payout-reversal"
+
+export const failedReversalEvents = (reversals: PayoutReversalDTO[]) =>
+ reversals.filter((reversal) => reversal.status === PayoutStatus.FAILED).map((reversal) => ({ id: reversal.id }))
+
+export const processPayoutReversalWorkflow = createWorkflow(
+ processPayoutReversalWorkflowId,
+ function (input: ProcessPayoutReversalWorkflowInput) {
+ const reversals = processPayoutReversalsStep({ ids: input.reversal_ids })
+
+ emitEventStep({
+ eventName: PayoutModuleEvents.PAYOUT_REVERSAL_FAILED,
+ data: transform({ reversals }, ({ reversals }) => failedReversalEvents(reversals)),
+ })
+
+ return new WorkflowResponse(reversals)
+ }
+)
diff --git a/packages/core/src/workflows/payout/workflows/process-payout.ts b/packages/core/src/workflows/payout/workflows/process-payout.ts
new file mode 100644
index 000000000..15ebc163c
--- /dev/null
+++ b/packages/core/src/workflows/payout/workflows/process-payout.ts
@@ -0,0 +1,36 @@
+import {
+ WorkflowResponse,
+ createWorkflow,
+ transform,
+} from "@medusajs/framework/workflows-sdk"
+import { emitEventStep } from "@medusajs/medusa/core-flows"
+import { PayoutDTO, PayoutModuleEvents, PayoutStatus } from "@mercurjs/types"
+
+import { processPayoutsStep } from "../steps"
+
+export type ProcessPayoutWorkflowInput = {
+ payout_ids: string[]
+}
+
+export const processPayoutWorkflowId = "process-payout"
+
+export const failedPayoutEvents = (payouts: PayoutDTO[]) =>
+ payouts.filter((payout) => payout.status === PayoutStatus.FAILED).map((payout) => ({ id: payout.id }))
+
+/**
+ * Sends pending or failed payouts to the provider. A payout that is paid,
+ * processing or aborted is returned unchanged.
+ */
+export const processPayoutWorkflow = createWorkflow(
+ processPayoutWorkflowId,
+ function (input: ProcessPayoutWorkflowInput) {
+ const payouts = processPayoutsStep({ ids: input.payout_ids })
+
+ emitEventStep({
+ eventName: PayoutModuleEvents.PAYOUT_FAILED,
+ data: transform({ payouts }, ({ payouts }) => failedPayoutEvents(payouts)),
+ })
+
+ return new WorkflowResponse(payouts)
+ }
+)
diff --git a/packages/core/src/workflows/payout/workflows/refresh-onboarding.ts b/packages/core/src/workflows/payout/workflows/refresh-onboarding.ts
new file mode 100644
index 000000000..8951c35a3
--- /dev/null
+++ b/packages/core/src/workflows/payout/workflows/refresh-onboarding.ts
@@ -0,0 +1,44 @@
+import { WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+import { createOnboardingStep, validateOnboardingTokenStep } from "../steps"
+
+export type RefreshOnboardingWorkflowInput = {
+ token: string
+}
+
+export type RefreshOnboardingWorkflowOutput = {
+ url: string
+}
+
+export const refreshOnboardingWorkflowId = "refresh-onboarding"
+
+/**
+ * Exchanges an expired onboarding link's token for a fresh link. The token
+ * is rotated, so each refresh URL works once and only within the module's
+ * `onboarding.tokenTtlSeconds`.
+ */
+export const refreshOnboardingWorkflow = createWorkflow(
+ refreshOnboardingWorkflowId,
+ function (input: RefreshOnboardingWorkflowInput) {
+ const { data: accounts } = useQueryGraphStep({
+ entity: "payout_account",
+ fields: ["id", "onboarding_token_issued_at"],
+ filters: { onboarding_token: input.token },
+ }).config({ name: "onboarding-token-account-query" })
+
+ const account = transform({ accounts }, ({ accounts }) => accounts[0] ?? null)
+
+ validateOnboardingTokenStep({ account })
+
+ const onboarding = createOnboardingStep(
+ transform({ account }, ({ account }) => ({ account_id: (account as { id: string }).id, rotate_token: true }))
+ )
+
+ return new WorkflowResponse(
+ transform({ onboarding }, ({ onboarding }): RefreshOnboardingWorkflowOutput => ({
+ url: onboarding.data?.url as string,
+ }))
+ )
+ }
+)
diff --git a/packages/core/src/workflows/payout/workflows/refresh-payout-account-link.ts b/packages/core/src/workflows/payout/workflows/refresh-payout-account-link.ts
new file mode 100644
index 000000000..a8dec0818
--- /dev/null
+++ b/packages/core/src/workflows/payout/workflows/refresh-payout-account-link.ts
@@ -0,0 +1,22 @@
+import { WorkflowResponse, createWorkflow } from "@medusajs/framework/workflows-sdk"
+
+import { createOnboardingStep } from "../steps"
+
+export type RefreshPayoutAccountLinkWorkflowInput = {
+ id: string
+}
+
+export const refreshPayoutAccountLinkWorkflowId = "refresh-payout-account-link"
+
+/**
+ * Publishes a new link for the seller: onboarding until their details are
+ * submitted, the provider dashboard login afterwards.
+ */
+export const refreshPayoutAccountLinkWorkflow = createWorkflow(
+ refreshPayoutAccountLinkWorkflowId,
+ function (input: RefreshPayoutAccountLinkWorkflowInput) {
+ const onboarding = createOnboardingStep({ account_id: input.id })
+
+ return new WorkflowResponse(onboarding)
+ }
+)
diff --git a/packages/core/src/workflows/payout/workflows/retry-payout.ts b/packages/core/src/workflows/payout/workflows/retry-payout.ts
new file mode 100644
index 000000000..36694e847
--- /dev/null
+++ b/packages/core/src/workflows/payout/workflows/retry-payout.ts
@@ -0,0 +1,51 @@
+import { WorkflowResponse, createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { PayoutStatus } from "@mercurjs/types"
+
+import { validatePayoutRetryStep } from "../steps"
+import { createOrderPayoutsWorkflow } from "./create-order-payouts"
+import { processPayoutWorkflow } from "./process-payout"
+
+export type RetryPayoutWorkflowInput = {
+ id: string
+}
+
+export const retryPayoutWorkflowId = "retry-payout"
+
+/**
+ * Retries a failed, held or pending payout. A failed or held order payout is
+ * re-decided from its order, so one on hold only goes out once the order is
+ * ready. A pending payout, and any payout without an order, is sent as is.
+ */
+export const retryPayoutWorkflow = createWorkflow(retryPayoutWorkflowId, function (input: RetryPayoutWorkflowInput) {
+ const { data: payout } = useQueryGraphStep({
+ entity: "payout",
+ fields: ["id", "status", "order_id"],
+ filters: { id: input.id },
+ options: { isList: false, throwIfKeyNotFound: true },
+ }).config({ name: "retry-payout-query" })
+
+ validatePayoutRetryStep({ payout })
+
+ when(
+ "redecide-order-payout",
+ { payout },
+ ({ payout }) => !!payout.order_id && payout.status !== PayoutStatus.PENDING
+ ).then(() => {
+ createOrderPayoutsWorkflow.runAsStep({
+ input: transform({ payout }, ({ payout }) => ({ order_ids: [payout.order_id as string] })),
+ })
+ })
+
+ when(
+ "send-payout",
+ { payout },
+ ({ payout }) => !payout.order_id || payout.status === PayoutStatus.PENDING
+ ).then(() => {
+ processPayoutWorkflow.runAsStep({
+ input: transform({ payout }, ({ payout }) => ({ payout_ids: [payout.id] })),
+ })
+ })
+
+ return new WorkflowResponse(payout)
+})
diff --git a/packages/core/src/workflows/payout/workflows/sync-payout-account.ts b/packages/core/src/workflows/payout/workflows/sync-payout-account.ts
new file mode 100644
index 000000000..559ced9c7
--- /dev/null
+++ b/packages/core/src/workflows/payout/workflows/sync-payout-account.ts
@@ -0,0 +1,33 @@
+import { WorkflowResponse, createWorkflow, when } from "@medusajs/framework/workflows-sdk"
+import { emitEventStep } from "@medusajs/medusa/core-flows"
+import { PayoutModuleEvents } from "@mercurjs/types"
+
+import { createOnboardingStep, syncPayoutAccountStep } from "../steps"
+
+export type SyncPayoutAccountWorkflowInput = {
+ id: string
+}
+
+export const syncPayoutAccountWorkflowId = "sync-payout-account"
+
+/**
+ * Pulls the account from the provider, swaps the onboarding link for a login
+ * link once details are submitted, and emits `payout_account.updated`.
+ */
+export const syncPayoutAccountWorkflow = createWorkflow(
+ syncPayoutAccountWorkflowId,
+ function (input: SyncPayoutAccountWorkflowInput) {
+ const account = syncPayoutAccountStep({ id: input.id })
+
+ when("publish-login-link", { account }, ({ account }) => account.details_submitted).then(() => {
+ createOnboardingStep({ account_id: input.id })
+ })
+
+ emitEventStep({
+ eventName: PayoutModuleEvents.ACCOUNT_UPDATED,
+ data: { id: input.id },
+ })
+
+ return new WorkflowResponse(account)
+ }
+)
diff --git a/packages/dashboard-sdk/src/utils.ts b/packages/dashboard-sdk/src/utils.ts
index 27e6768e5..ca2b959ed 100644
--- a/packages/dashboard-sdk/src/utils.ts
+++ b/packages/dashboard-sdk/src/utils.ts
@@ -1,4 +1,5 @@
import fs from "fs"
+import { createRequire } from "module"
import path from "path"
import type { ParserOptions } from "@babel/parser"
import { traverse } from "./babel"
@@ -57,7 +58,9 @@ export function resolveExports(moduleExports: any) {
export async function getFileExports(path: string): Promise<any> {
const { unregister } = await safeRegister()
- const module = require(path)
+ // The ESM build has no `require`; a CJS consumer gets one via the shim.
+ const load = createRequire(import.meta.url)
+ const module = load(path)
unregister()
return resolveExports(module)
diff --git a/packages/dashboard-sdk/tsup.config.ts b/packages/dashboard-sdk/tsup.config.ts
index 31cb697cc..66dc22cad 100644
--- a/packages/dashboard-sdk/tsup.config.ts
+++ b/packages/dashboard-sdk/tsup.config.ts
@@ -5,5 +5,6 @@ export default defineConfig({
format: ["esm", "cjs"],
dts: true,
clean: true,
+ shims: true,
external: ["zod", "react"],
})
diff --git a/packages/dashboard-shared/src/components/common/sidebar-link/sidebar-link.tsx b/packages/dashboard-shared/src/components/common/sidebar-link/sidebar-link.tsx
index 7e0c2c9cb..dc79f0ca4 100644
--- a/packages/dashboard-shared/src/components/common/sidebar-link/sidebar-link.tsx
+++ b/packages/dashboard-shared/src/components/common/sidebar-link/sidebar-link.tsx
@@ -10,6 +10,7 @@ export interface SidebarLinkProps {
labelKey: string
descriptionKey: string
icon: ReactNode
+ dataTestid?: string
}
export const SidebarLink = ({
@@ -17,9 +18,10 @@ export const SidebarLink = ({
labelKey,
descriptionKey,
icon,
+ dataTestid,
}: SidebarLinkProps) => {
return (
- <Link to={to} className="group outline-none">
+ <Link to={to} className="group outline-none" data-testid={dataTestid}>
<div className="flex flex-col gap-2 px-2 pb-2">
<div className="shadow-elevation-card-rest bg-ui-bg-component transition-fg hover:bg-ui-bg-component-hover active:bg-ui-bg-component-pressed group-focus-visible:shadow-borders-interactive-with-active rounded-md px-4 py-2">
<div className="flex items-center gap-4">
diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/middlewares.ts b/packages/plugins/magento2-connector/src/api/admin/magento/middlewares.ts
index d6282f4a4..49a53d238 100644
--- a/packages/plugins/magento2-connector/src/api/admin/magento/middlewares.ts
+++ b/packages/plugins/magento2-connector/src/api/admin/magento/middlewares.ts
@@ -5,10 +5,6 @@ import {
import { MiddlewareRoute } from "@medusajs/framework/http"
import { requirePermission } from "@mercurjs/core/api/utils/permissions-middleware"
-import {
- AdminCancelExternalPayment,
- AdminCaptureExternalPayment,
-} from "./order-groups/validators"
import { AdminRecordExternalRefund } from "./orders/validators"
import {
adminMagentoWebhookDeliveryQueryConfig,
@@ -109,20 +105,4 @@ export const adminMagentoMiddlewares: MiddlewareRoute[] = [
validateAndTransformBody(AdminRecordExternalRefund),
],
},
- {
- method: ["POST"],
- matcher: "/admin/magento/order-groups/:id/payments/capture",
- middlewares: [
- requirePermission("integrations", "edit"),
- validateAndTransformBody(AdminCaptureExternalPayment),
- ],
- },
- {
- method: ["POST"],
- matcher: "/admin/magento/order-groups/:id/payments/cancel",
- middlewares: [
- requirePermission("integrations", "edit"),
- validateAndTransformBody(AdminCancelExternalPayment),
- ],
- },
]
diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/order-groups/[id]/payments/cancel/route.ts b/packages/plugins/magento2-connector/src/api/admin/magento/order-groups/[id]/payments/cancel/route.ts
deleted file mode 100644
index aadad4102..000000000
--- a/packages/plugins/magento2-connector/src/api/admin/magento/order-groups/[id]/payments/cancel/route.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import {
- AuthenticatedMedusaRequest,
- MedusaResponse,
- refetchEntity,
-} from "@medusajs/framework/http"
-
-import { AdminExternalPaymentResponse } from "../../../../../../../types"
-import { cancelExternalPaymentWorkflow } from "../../../../../../../workflows"
-import { EXTERNAL_PAYMENT_FIELDS } from "../../../payment-fields"
-import { AdminCancelExternalPaymentType } from "../../../validators"
-
-export const POST = async (
- req: AuthenticatedMedusaRequest<AdminCancelExternalPaymentType>,
- res: MedusaResponse<AdminExternalPaymentResponse>
-) => {
- const { result } = await cancelExternalPaymentWorkflow(req.scope).run({
- input: {
- order_group_id: req.params.id,
- canceled_by: req.auth_context?.actor_id,
- ...req.validatedBody,
- },
- })
-
- const payment = await refetchEntity({
- entity: "payment",
- idOrFilter: result.payment_id,
- scope: req.scope,
- fields: EXTERNAL_PAYMENT_FIELDS,
- })
-
- res.status(200).json({ payment })
-}
diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/order-groups/[id]/payments/capture/route.ts b/packages/plugins/magento2-connector/src/api/admin/magento/order-groups/[id]/payments/capture/route.ts
deleted file mode 100644
index 56b0938ee..000000000
--- a/packages/plugins/magento2-connector/src/api/admin/magento/order-groups/[id]/payments/capture/route.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import {
- AuthenticatedMedusaRequest,
- MedusaResponse,
- refetchEntity,
-} from "@medusajs/framework/http"
-
-import { AdminExternalPaymentResponse } from "../../../../../../../types"
-import { captureExternalPaymentWorkflow } from "../../../../../../../workflows"
-import { EXTERNAL_PAYMENT_FIELDS } from "../../../payment-fields"
-import { AdminCaptureExternalPaymentType } from "../../../validators"
-
-export const POST = async (
- req: AuthenticatedMedusaRequest<AdminCaptureExternalPaymentType>,
- res: MedusaResponse<AdminExternalPaymentResponse>
-) => {
- const { result } = await captureExternalPaymentWorkflow(req.scope).run({
- input: {
- order_group_id: req.params.id,
- captured_by: req.auth_context?.actor_id,
- ...req.validatedBody,
- },
- })
-
- const payment = await refetchEntity({
- entity: "payment",
- idOrFilter: result.payment_id,
- scope: req.scope,
- fields: EXTERNAL_PAYMENT_FIELDS,
- })
-
- res.status(200).json({ payment })
-}
diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/order-groups/payment-fields.ts b/packages/plugins/magento2-connector/src/api/admin/magento/order-groups/payment-fields.ts
deleted file mode 100644
index 44229d649..000000000
--- a/packages/plugins/magento2-connector/src/api/admin/magento/order-groups/payment-fields.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-export const EXTERNAL_PAYMENT_FIELDS = [
- "id",
- "amount",
- "currency_code",
- "provider_id",
- "captured_at",
- "canceled_at",
- "refunds.id",
- "refunds.amount",
- "refunds.note",
- "refunds.created_at",
-]
diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/order-groups/validators.ts b/packages/plugins/magento2-connector/src/api/admin/magento/order-groups/validators.ts
deleted file mode 100644
index d90b0c210..000000000
--- a/packages/plugins/magento2-connector/src/api/admin/magento/order-groups/validators.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { z } from "@medusajs/framework/zod"
-
-export type AdminCaptureExternalPaymentType = z.infer<typeof AdminCaptureExternalPayment>
-export const AdminCaptureExternalPayment = z
- .object({
- reference: z.string().min(1).optional(),
- })
- .strict()
-
-export type AdminCancelExternalPaymentType = z.infer<typeof AdminCancelExternalPayment>
-export const AdminCancelExternalPayment = z
- .object({
- reference: z.string().min(1).optional(),
- })
- .strict()
diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/orders/[id]/refunds/external/route.ts b/packages/plugins/magento2-connector/src/api/admin/magento/orders/[id]/refunds/external/route.ts
index 2a32721da..232ab6aa8 100644
--- a/packages/plugins/magento2-connector/src/api/admin/magento/orders/[id]/refunds/external/route.ts
+++ b/packages/plugins/magento2-connector/src/api/admin/magento/orders/[id]/refunds/external/route.ts
@@ -6,9 +6,20 @@ import {
import { AdminExternalRefundResponse } from "../../../../../../../types"
import { recordExternalRefundWorkflow } from "../../../../../../../workflows"
-import { EXTERNAL_PAYMENT_FIELDS } from "../../../../order-groups/payment-fields"
import { AdminRecordExternalRefundType } from "../../../validators"
+const PAYMENT_FIELDS = [
+ "id",
+ "amount",
+ "currency_code",
+ "provider_id",
+ "captured_at",
+ "refunds.id",
+ "refunds.amount",
+ "refunds.note",
+ "refunds.created_at",
+]
+
export const POST = async (
req: AuthenticatedMedusaRequest<AdminRecordExternalRefundType>,
res: MedusaResponse<AdminExternalRefundResponse>
@@ -25,7 +36,7 @@ export const POST = async (
entity: "payment",
idOrFilter: result.id,
scope: req.scope,
- fields: EXTERNAL_PAYMENT_FIELDS,
+ fields: PAYMENT_FIELDS,
})
res.status(200).json({ payment })
diff --git a/packages/plugins/magento2-connector/src/providers/payment-external/service.ts b/packages/plugins/magento2-connector/src/providers/payment-external/service.ts
index d1346274b..e5b26802d 100644
--- a/packages/plugins/magento2-connector/src/providers/payment-external/service.ts
+++ b/packages/plugins/magento2-connector/src/providers/payment-external/service.ts
@@ -33,19 +33,6 @@ import { ExternalPaymentSessionData } from "../../types"
const toNumber = (value: unknown): number =>
new BigNumber(value as never).numeric
-const asSessionData = (data: unknown): ExternalPaymentSessionData =>
- (data ?? {}) as ExternalPaymentSessionData
-
-const statusOf = (data: ExternalPaymentSessionData): PaymentSessionStatus => {
- if (data.canceled_at) {
- return PaymentSessionStatus.CANCELED
- }
- if (data.captured_at) {
- return PaymentSessionStatus.CAPTURED
- }
- return PaymentSessionStatus.AUTHORIZED
-}
-
type InjectedDependencies = {
logger: Logger
}
@@ -53,9 +40,7 @@ type InjectedDependencies = {
type ExternalPaymentOptions = Record<string, never>
/**
- * Tracks a payment the external storefront holds; no provider is charged.
- * The storefront authorizes at placement and reports the capture later, or
- * passes `captured_at` up front when it already settled.
+ * Records a payment the external storefront already captured; no provider is charged.
*/
class ExternalPaymentProviderService extends AbstractPaymentProvider<ExternalPaymentOptions> {
static identifier = "external"
@@ -67,51 +52,45 @@ class ExternalPaymentProviderService extends AbstractPaymentProvider<ExternalPay
async initiatePayment(
input: InitiatePaymentInput
): Promise<InitiatePaymentOutput> {
- const data = asSessionData(input.data)
+ const data = (input.data ?? {}) as ExternalPaymentSessionData
const id = data.reference ?? `ext_${Date.now()}`
- const next: ExternalPaymentSessionData = {
- ...data,
- reference: id,
- amount: toNumber(input.amount),
- currency_code: input.currency_code,
- authorized_at: data.authorized_at ?? new Date().toISOString(),
- }
- return { id, status: statusOf(next), data: next }
+ return {
+ id,
+ status: PaymentSessionStatus.CAPTURED,
+ data: {
+ ...data,
+ reference: id,
+ amount: toNumber(input.amount),
+ currency_code: input.currency_code,
+ captured_at: data.captured_at ?? new Date().toISOString(),
+ },
+ }
}
async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
- const next: ExternalPaymentSessionData = {
- ...asSessionData(input.data),
- amount: toNumber(input.amount),
- currency_code: input.currency_code,
+ return {
+ status: PaymentSessionStatus.AUTHORIZED,
+ data: {
+ ...(input.data ?? {}),
+ amount: toNumber(input.amount),
+ currency_code: input.currency_code,
+ },
}
-
- return { status: statusOf(next), data: next }
}
async authorizePayment(
input: AuthorizePaymentInput
): Promise<AuthorizePaymentOutput> {
- const next: ExternalPaymentSessionData = {
- ...asSessionData(input.data),
- authorized_at:
- asSessionData(input.data).authorized_at ?? new Date().toISOString(),
- }
-
- return { status: statusOf(next), data: next }
+ return { status: PaymentSessionStatus.CAPTURED, data: input.data }
}
async capturePayment(input: CapturePaymentInput): Promise<CapturePaymentOutput> {
- const data = asSessionData(input.data)
-
- return {
- data: { ...data, captured_at: data.captured_at ?? new Date().toISOString() },
- }
+ return { data: input.data }
}
async refundPayment(input: RefundPaymentInput): Promise<RefundPaymentOutput> {
- const data = asSessionData(input.data)
+ const data = (input.data ?? {}) as ExternalPaymentSessionData
return {
data: {
@@ -122,11 +101,7 @@ class ExternalPaymentProviderService extends AbstractPaymentProvider<ExternalPay
}
async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {
- const data = asSessionData(input.data)
-
- return {
- data: { ...data, canceled_at: data.canceled_at ?? new Date().toISOString() },
- }
+ return { data: input.data }
}
async deletePayment(input: DeletePaymentInput): Promise<DeletePaymentOutput> {
@@ -142,7 +117,7 @@ class ExternalPaymentProviderService extends AbstractPaymentProvider<ExternalPay
async getPaymentStatus(
input: GetPaymentStatusInput
): Promise<GetPaymentStatusOutput> {
- return { status: statusOf(asSessionData(input.data)), data: input.data }
+ return { status: PaymentSessionStatus.CAPTURED, data: input.data }
}
async getWebhookActionAndData(
diff --git a/packages/plugins/magento2-connector/src/types/common.ts b/packages/plugins/magento2-connector/src/types/common.ts
index 4c742ea55..77c1630cc 100644
--- a/packages/plugins/magento2-connector/src/types/common.ts
+++ b/packages/plugins/magento2-connector/src/types/common.ts
@@ -27,7 +27,6 @@ export const MAGENTO_WEBHOOK_EVENTS = [
"order.return_received",
"order.refund_recorded",
"order.refund_requested",
- "order.payment_captured",
] as const
/**
@@ -41,7 +40,6 @@ export const MagentoWebhookEvents = {
DELIVERY_CREATED: "magento_webhook_delivery.created",
REFUND_RECORDED: "order.refund_recorded",
REFUND_REQUESTED: "order.refund_requested",
- PAYMENT_CAPTURED: "order.payment_captured",
} as const
export const EXTERNAL_REFUND_SOURCE = "external"
@@ -136,10 +134,7 @@ export type FilterableMagentoWebhookDeliveryProps =
export type ExternalPaymentSessionData = {
reference?: string
- authorized_at?: string
captured_at?: string
- canceled_at?: string
- payment_method?: string
channel?: string
amount?: number
currency_code?: string
diff --git a/packages/plugins/magento2-connector/src/types/http.ts b/packages/plugins/magento2-connector/src/types/http.ts
index bd8864627..c8f699646 100644
--- a/packages/plugins/magento2-connector/src/types/http.ts
+++ b/packages/plugins/magento2-connector/src/types/http.ts
@@ -75,14 +75,6 @@ export interface AdminRecordExternalRefund {
note?: string
}
-export interface AdminCaptureExternalPayment {
- reference?: string
-}
-
-export interface AdminCancelExternalPayment {
- reference?: string
-}
-
export interface AdminMagentoWebhookResponse {
webhook: AdminMagentoWebhook
}
@@ -118,20 +110,13 @@ export interface AdminMagentoStatusResponse {
orders: { channel: string; last_24h: number }
}
-export interface AdminExternalPayment {
- id: string
- amount: number
- currency_code: string
- provider_id: string
- captured_at: string | null
- canceled_at: string | null
- refunds: { id: string; amount: number; note: string | null; created_at: string }[]
-}
-
export interface AdminExternalRefundResponse {
- payment: AdminExternalPayment
-}
-
-export interface AdminExternalPaymentResponse {
- payment: AdminExternalPayment
+ payment: {
+ id: string
+ amount: number
+ currency_code: string
+ provider_id: string
+ captured_at: string | null
+ refunds: { id: string; amount: number; note: string | null; created_at: string }[]
+ }
}
diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/steps/cancel-order-group-orders.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/steps/cancel-order-group-orders.ts
deleted file mode 100644
index aa50ec2a3..000000000
--- a/packages/plugins/magento2-connector/src/workflows/external-payment/steps/cancel-order-group-orders.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { ContainerRegistrationKeys, OrderStatus } from "@medusajs/framework/utils"
-import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
-import { cancelOrderWorkflow } from "@medusajs/medusa/core-flows"
-
-export type CancelOrderGroupOrdersStepInput = {
- order_ids: string[]
- canceled_by?: string
-}
-
-export const cancelOrderGroupOrdersStepId = "cancel-order-group-orders"
-export const cancelOrderGroupOrdersStep = createStep(
- cancelOrderGroupOrdersStepId,
- async (input: CancelOrderGroupOrdersStepInput, { container }) => {
- const query = container.resolve(ContainerRegistrationKeys.QUERY)
- const { data: orders } = await query.graph({
- entity: "order",
- fields: ["id", "status", "canceled_at"],
- filters: { id: input.order_ids },
- })
-
- const canceled: string[] = []
- for (const order of orders) {
- if (order.status === OrderStatus.CANCELED || order.canceled_at) {
- continue
- }
- await cancelOrderWorkflow(container).run({
- input: { order_id: order.id, canceled_by: input.canceled_by },
- })
- canceled.push(order.id)
- }
-
- return new StepResponse(canceled)
- }
-)
diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/steps/index.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/steps/index.ts
index ee7f6033c..602d7c925 100644
--- a/packages/plugins/magento2-connector/src/workflows/external-payment/steps/index.ts
+++ b/packages/plugins/magento2-connector/src/workflows/external-payment/steps/index.ts
@@ -1,5 +1,2 @@
export * from "./build-refund-requested-event"
-export * from "./cancel-order-group-orders"
-export * from "./resolve-external-cart-payment"
export * from "./validate-external-payment"
-export * from "./validate-external-payment-cancelable"
diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/steps/resolve-external-cart-payment.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/steps/resolve-external-cart-payment.ts
deleted file mode 100644
index ac7ae2110..000000000
--- a/packages/plugins/magento2-connector/src/workflows/external-payment/steps/resolve-external-cart-payment.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { ContainerRegistrationKeys, MedusaError } from "@medusajs/framework/utils"
-import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
-import { resolveSplitOrderCartId } from "@mercurjs/core/workflows"
-
-import { EXTERNAL_PAYMENT_PROVIDER_ID } from "../../../types"
-
-export type ResolveExternalCartPaymentStepInput = {
- order_group_id: string
- order_ids: string[]
-}
-
-export type ExternalCartPayment = {
- cart_id: string
- payment_id: string
- captured: boolean
- canceled: boolean
-}
-
-type CartPaymentRow = {
- id: string
- provider_id: string
- captured_at: Date | string | null
- canceled_at: Date | string | null
-}
-
-export const resolveExternalCartPaymentStepId = "resolve-external-cart-payment"
-/**
- * Finds the cart-level payment held by the external provider for an order
- * group. Until it is captured, the child orders have no payment of their own.
- */
-export const resolveExternalCartPaymentStep = createStep(
- resolveExternalCartPaymentStepId,
- async (input: ResolveExternalCartPaymentStepInput, { container }) => {
- const [orderId] = input.order_ids
- if (!orderId) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- `Order group with id "${input.order_group_id}" has no orders`
- )
- }
-
- const cartId = await resolveSplitOrderCartId(container, { order_id: orderId })
- if (!cartId) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- `Order group with id "${input.order_group_id}" is not linked to a cart`
- )
- }
-
- const query = container.resolve(ContainerRegistrationKeys.QUERY)
- const { data } = await query.graph({
- entity: "cart_payment_collection",
- fields: [
- "payment_collection.payments.id",
- "payment_collection.payments.provider_id",
- "payment_collection.payments.captured_at",
- "payment_collection.payments.canceled_at",
- ],
- filters: { cart_id: cartId },
- })
-
- const payments = data.flatMap(
- (link) => (link.payment_collection?.payments ?? []) as (CartPaymentRow | null)[]
- )
- const payment = payments.find(
- (p): p is CartPaymentRow =>
- !!p && p.provider_id === EXTERNAL_PAYMENT_PROVIDER_ID && !p.canceled_at
- ) ?? payments.find(
- (p): p is CartPaymentRow => !!p && p.provider_id === EXTERNAL_PAYMENT_PROVIDER_ID
- )
-
- if (!payment) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- `Order group with id "${input.order_group_id}" has no payment on the external provider`
- )
- }
-
- return new StepResponse<ExternalCartPayment>({
- cart_id: cartId,
- payment_id: payment.id,
- captured: !!payment.captured_at,
- canceled: !!payment.canceled_at,
- })
- }
-)
diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/steps/validate-external-payment-cancelable.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/steps/validate-external-payment-cancelable.ts
deleted file mode 100644
index 497ecdfd5..000000000
--- a/packages/plugins/magento2-connector/src/workflows/external-payment/steps/validate-external-payment-cancelable.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { MedusaError } from "@medusajs/framework/utils"
-import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
-
-import { ExternalCartPayment } from "./resolve-external-cart-payment"
-
-export type ValidateExternalPaymentCancelableStepInput = {
- order_group_id: string
- payment: ExternalCartPayment
-}
-
-export const validateExternalPaymentCancelableStepId =
- "validate-external-payment-cancelable"
-export const validateExternalPaymentCancelableStep = createStep(
- validateExternalPaymentCancelableStepId,
- async (input: ValidateExternalPaymentCancelableStepInput) => {
- if (input.payment.captured) {
- throw new MedusaError(
- MedusaError.Types.INVALID_DATA,
- `Payment of order group "${input.order_group_id}" is already captured; record a refund instead`
- )
- }
-
- return new StepResponse(void 0)
- }
-)
diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/steps/validate-external-payment.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/steps/validate-external-payment.ts
index 309fd0652..b6cdf3da4 100644
--- a/packages/plugins/magento2-connector/src/workflows/external-payment/steps/validate-external-payment.ts
+++ b/packages/plugins/magento2-connector/src/workflows/external-payment/steps/validate-external-payment.ts
@@ -3,33 +3,23 @@ import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
import { EXTERNAL_PAYMENT_PROVIDER_ID } from "../../../types"
-type PaymentRow = { id: string; provider_id: string; captured_at: Date | string | null }
-
export type ValidateExternalPaymentStepInput = {
order_id: string
- payments: (PaymentRow | null)[]
- cart_payments?: (PaymentRow | null)[]
+ payments: { id: string; provider_id: string; captured_at: Date | string | null }[]
}
-const isExternal = (p: PaymentRow | null): p is PaymentRow =>
- !!p && p.provider_id === EXTERNAL_PAYMENT_PROVIDER_ID
-
export const validateExternalPaymentStepId = "validate-external-payment"
export const validateExternalPaymentStep = createStep(
validateExternalPaymentStepId,
async (input: ValidateExternalPaymentStepInput) => {
- // An order only holds its own external payment once the cart payment is
- // captured and split; before that the cart's shared one is all there is.
- const payment = input.payments.filter(isExternal).find((p) => !!p.captured_at)
+ const payment = input.payments.find(
+ (p) => p.provider_id === EXTERNAL_PAYMENT_PROVIDER_ID && !!p.captured_at
+ )
if (!payment) {
- const pending = (input.cart_payments ?? []).some(isExternal) ||
- input.payments.some(isExternal)
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
- pending
- ? `Order with id "${input.order_id}" has an external payment that is not yet captured; capture the order group payment first`
- : `Order with id "${input.order_id}" has no payment on the external provider`
+ `Order with id "${input.order_id}" has no captured payment on the external provider`
)
}
diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/cancel-external-payment.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/cancel-external-payment.ts
deleted file mode 100644
index ea63b8104..000000000
--- a/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/cancel-external-payment.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import {
- WorkflowData,
- WorkflowResponse,
- createWorkflow,
- transform,
-} from "@medusajs/framework/workflows-sdk"
-import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
-import { voidCanceledCartPaymentWorkflow } from "@mercurjs/core/workflows"
-
-import {
- cancelOrderGroupOrdersStep,
- resolveExternalCartPaymentStep,
- validateExternalPaymentCancelableStep,
-} from "../steps"
-
-export type CancelExternalPaymentWorkflowInput = {
- order_group_id: string
- reference?: string
- canceled_by?: string
-}
-
-export const cancelExternalPaymentWorkflowId = "cancel-external-payment"
-/**
- * Mirrors a storefront cancellation of an order whose payment was never
- * captured: every child order is canceled, which releases the shared cart
- * authorization on the external provider.
- */
-export const cancelExternalPaymentWorkflow = createWorkflow(
- cancelExternalPaymentWorkflowId,
- (input: WorkflowData<CancelExternalPaymentWorkflowInput>) => {
- const groups = useQueryGraphStep({
- entity: "order_group",
- fields: ["id", "orders.id"],
- filters: { id: input.order_group_id },
- options: { throwIfKeyNotFound: true },
- })
-
- const orderIds = transform({ groups }, ({ groups }) =>
- (groups.data[0]?.orders ?? []).flatMap((o) => (o ? [o.id] : []))
- )
-
- const payment = resolveExternalCartPaymentStep(
- transform({ input, orderIds }, ({ input, orderIds }) => ({
- order_group_id: input.order_group_id,
- order_ids: orderIds,
- }))
- )
-
- validateExternalPaymentCancelableStep(
- transform({ input, payment }, ({ input, payment }) => ({
- order_group_id: input.order_group_id,
- payment,
- }))
- )
-
- cancelOrderGroupOrdersStep(
- transform({ input, orderIds }, ({ input, orderIds }) => ({
- order_ids: orderIds,
- canceled_by: input.canceled_by,
- }))
- )
-
- voidCanceledCartPaymentWorkflow.runAsStep({
- input: transform({ payment }, ({ payment }) => ({ cart_id: payment.cart_id })),
- })
-
- return new WorkflowResponse(payment)
- }
-)
diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/capture-external-payment.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/capture-external-payment.ts
deleted file mode 100644
index 92162356d..000000000
--- a/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/capture-external-payment.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import {
- WorkflowData,
- WorkflowResponse,
- createWorkflow,
- transform,
- when,
-} from "@medusajs/framework/workflows-sdk"
-import {
- capturePaymentWorkflow,
- emitEventStep,
- useQueryGraphStep,
-} from "@medusajs/medusa/core-flows"
-
-import { MagentoWebhookEvents } from "../../../types"
-import { resolveExternalCartPaymentStep } from "../steps"
-
-export type CaptureExternalPaymentWorkflowInput = {
- order_group_id: string
- reference?: string
- captured_by?: string
-}
-
-export const captureExternalPaymentWorkflowId = "capture-external-payment"
-/**
- * Records that the storefront settled the payment of an order group. The
- * cart-level payment is captured once; core splits it between the child
- * orders on `payment.captured`.
- */
-export const captureExternalPaymentWorkflow = createWorkflow(
- captureExternalPaymentWorkflowId,
- (input: WorkflowData<CaptureExternalPaymentWorkflowInput>) => {
- const groups = useQueryGraphStep({
- entity: "order_group",
- fields: ["id", "orders.id"],
- filters: { id: input.order_group_id },
- options: { throwIfKeyNotFound: true },
- })
-
- const payment = resolveExternalCartPaymentStep(
- transform({ input, groups }, ({ input, groups }) => ({
- order_group_id: input.order_group_id,
- order_ids: (groups.data[0]?.orders ?? []).flatMap((o) => (o ? [o.id] : [])),
- }))
- )
-
- when({ payment }, ({ payment }) => !payment.captured).then(() => {
- capturePaymentWorkflow.runAsStep({
- input: transform({ input, payment }, ({ input, payment }) => ({
- payment_id: payment.payment_id,
- captured_by: input.captured_by,
- })),
- })
-
- emitEventStep({
- eventName: MagentoWebhookEvents.PAYMENT_CAPTURED,
- data: transform({ input, payment }, ({ input, payment }) => ({
- id: input.order_group_id,
- payment_id: payment.payment_id,
- reference: input.reference ?? null,
- })),
- })
- })
-
- return new WorkflowResponse(payment)
- }
-)
diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/index.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/index.ts
index c3084491b..a607ac0f9 100644
--- a/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/index.ts
+++ b/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/index.ts
@@ -1,4 +1,2 @@
-export * from "./cancel-external-payment"
-export * from "./capture-external-payment"
export * from "./emit-refund-requested"
export * from "./record-external-refund"
diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/record-external-refund.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/record-external-refund.ts
index 60a047de8..c5237f38d 100644
--- a/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/record-external-refund.ts
+++ b/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/record-external-refund.ts
@@ -37,9 +37,6 @@ export const recordExternalRefundWorkflow = createWorkflow(
"payment_collections.payments.id",
"payment_collections.payments.provider_id",
"payment_collections.payments.captured_at",
- "cart.payment_collection.payments.id",
- "cart.payment_collection.payments.provider_id",
- "cart.payment_collection.payments.captured_at",
],
filters: { id: input.order_id },
options: { throwIfKeyNotFound: true },
@@ -50,7 +47,6 @@ export const recordExternalRefundWorkflow = createWorkflow(
payments: (orders.data[0]?.payment_collections ?? []).flatMap(
(pc) => pc?.payments ?? []
),
- cart_payments: orders.data[0]?.cart?.payment_collection?.payments ?? [],
}))
const paymentId = validateExternalPaymentStep(validationInput)
diff --git a/packages/plugins/stripe-connector/.gitignore b/packages/plugins/stripe-connector/.gitignore
new file mode 100644
index 000000000..f02823277
--- /dev/null
+++ b/packages/plugins/stripe-connector/.gitignore
@@ -0,0 +1,2 @@
+.medusa
+node_modules
diff --git a/packages/plugins/stripe-connector/README.md b/packages/plugins/stripe-connector/README.md
new file mode 100644
index 000000000..c33f2b096
--- /dev/null
+++ b/packages/plugins/stripe-connector/README.md
@@ -0,0 +1,111 @@
+# @mercurjs/stripe-connector-plugin
+
+Connects a Mercur marketplace to Stripe. Mercur's payout module keeps the
+seller's payout account, one payout per order and the reversals of refunds;
+this plugin adds the Stripe adapters, the scheduled jobs that drive them, and
+the Stripe-specific bookkeeping (captures, settlements, bank payouts,
+adjustments).
+
+- **Payment provider** `pp_stripe-connector_<id>`: Medusa's Stripe provider
+ with manual capture, so the platform account charges the whole cart once and
+ the captures job captures it when every seller order is decided.
+- **Payout provider** `pop_stripe-connect_<id>`: Express accounts, onboarding
+ and login links; a payout is a transfer to the connected account with
+ `source_transaction`, a reversal is a transfer reversal.
+- **Module** `stripe_connector`: job runs, checkpoints, operator notifications,
+ settlements with their bank payouts, and operator adjustments.
+- **Jobs and subscribers**: the schedule below, plus faster runs on order
+ fulfillment, cancellation, payment capture and refunds.
+- **Admin** Finance → Stripe: one tab per job with its run card and table, a
+ run history, Settings → Stripe with the webhook URLs, a Stripe section on the
+ seller page and a payout widget on the order page.
+- **Vendor** Integrations → Stripe: set-up form, the Stripe account with what
+ Stripe still needs, and settlements. The payout account itself (status,
+ onboarding, verification) shows on the core vendor Payouts page.
+
+## Install
+
+```ts
+// medusa-config.ts
+module.exports = withMercur({
+ plugins: [
+ {
+ resolve: "@mercurjs/stripe-connector-plugin",
+ options: {
+ apiKey: process.env.STRIPE_SECRET_KEY,
+ webhookSecret: process.env.STRIPE_SELLERS_WEBHOOK_SECRET,
+ settlements: { mode: "plugin" },
+ alerting: { technicalEmail: "[email protected]", from: "[email protected]" },
+ },
+ },
+ ],
+ modules: [
+ {
+ resolve: "@medusajs/medusa/payment",
+ options: {
+ providers: [
+ {
+ resolve: "@mercurjs/stripe-connector-plugin/providers/payment-stripe",
+ id: "stripe",
+ options: {
+ apiKey: process.env.STRIPE_SECRET_KEY,
+ webhookSecret: process.env.STRIPE_OPERATOR_WEBHOOK_SECRET,
+ },
+ },
+ ],
+ },
+ },
+ {
+ resolve: "@mercurjs/core/modules/payout",
+ options: {
+ providers: [
+ {
+ resolve: "@mercurjs/stripe-connector-plugin/providers/payout-stripe-connect",
+ id: "stripe",
+ options: {
+ apiKey: process.env.STRIPE_SECRET_KEY,
+ webhookSecret: process.env.STRIPE_SELLERS_WEBHOOK_SECRET,
+ manualPayouts: true,
+ },
+ },
+ ],
+ onboarding: {
+ returnUrl: `${process.env.VENDOR_URL}/stripe`,
+ refreshBaseUrl: process.env.BACKEND_URL,
+ },
+ },
+ },
+ ],
+})
+```
+
+`settlements.mode: "plugin"` sends each settlement to the seller's bank
+from the plugin, so pair it with `manualPayouts: true` on the payout provider.
+With `mode: "provider"` Stripe pays out on its own schedule and settlements are
+only recorded. A bank payout waits (`on_hold`, `insufficient_available_balance`)
+until the connected account's available balance in the settlement currency
+covers it, and is retried on the next run.
+
+Set `notifications.secret` to sign each operator notification: the body's
+HMAC-SHA256, hex-encoded, is sent as `x-mercur-signature: sha256=<hex>`.
+
+Run `medusa db:migrate`, then register two webhooks in the Stripe dashboard:
+
+| Endpoint | Events |
+| --- | --- |
+| `POST /hooks/payment/pp_stripe-connector_stripe` | `payment_intent.*`, `charge.*` (platform account) |
+| `POST /hooks/payout` | `account.updated`, `payout.paid`, `payout.failed`, `payout.canceled`, `payout.updated` (listen on connected accounts) |
+
+## Schedule
+
+| Job | Schedule (UTC) | Does |
+| --- | --- | --- |
+| `payout-sync-onboarding` | every minute | Express accounts and onboarding links for new sellers |
+| `payout-validate-captures` | every 5 min | captures or cancels decided order groups |
+| `payout-process-transfers` | every 5 min, minute 1 | backlog, then payouts for fulfilled orders |
+| `payout-process-reversals` | every 5 min, minute 2 | backlog, then reversals for refunds |
+| `payout-process-settlements` | daily 01:03 | adjustments, failed bank payouts, settlements, bank payouts |
+| `payout-alert-failed-operations` | daily 08:04 | digest email of everything failed |
+| `payout-monitor-kyc` | every 6 h, opt-in | re-reads every account's requirements |
+
+Every plugin option is documented on `StripeConnectorPluginOptions`.
diff --git a/packages/plugins/stripe-connector/jest.config.js b/packages/plugins/stripe-connector/jest.config.js
new file mode 100644
index 000000000..7ceef2752
--- /dev/null
+++ b/packages/plugins/stripe-connector/jest.config.js
@@ -0,0 +1,22 @@
+module.exports = {
+ testEnvironment: "node",
+ transform: {
+ "^.+\\.ts$": [
+ "ts-jest",
+ {
+ tsconfig: {
+ module: "commonjs",
+ esModuleInterop: true,
+ strict: false,
+ baseUrl: ".",
+ paths: { "@mercurjs/types": ["../../types/src/index.ts"] },
+ },
+ },
+ ],
+ },
+ testMatch: ["**/__tests__/**/*.spec.ts"],
+ moduleNameMapper: {
+ "^@mercurjs/types$": "<rootDir>/../../types/src/index.ts",
+ "^@mercurjs/core/workflows/payout/utils/(.*)$": "<rootDir>/../../core/src/workflows/payout/utils/$1.ts",
+ },
+}
diff --git a/packages/plugins/stripe-connector/package.json b/packages/plugins/stripe-connector/package.json
new file mode 100644
index 000000000..b47ccf19f
--- /dev/null
+++ b/packages/plugins/stripe-connector/package.json
@@ -0,0 +1,115 @@
+{
+ "name": "@mercurjs/stripe-connector-plugin",
+ "version": "2.3.9-canary.4",
+ "description": "Mercur plugin that connects a marketplace to Stripe: a manual-capture payment provider for the platform account and a Stripe Connect payout provider for seller accounts, transfers, reversals and payouts, with the admin and vendor screens to run them.",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/mercurjs/mercur",
+ "directory": "packages/plugins/stripe-connector"
+ },
+ "author": "Mercur",
+ "license": "MIT",
+ "files": [
+ ".medusa/server"
+ ],
+ "exports": {
+ "./package.json": "./package.json",
+ "./.medusa/server/src/modules/*": "./.medusa/server/src/modules/*/index.js",
+ "./modules/*": {
+ "types": "./.medusa/server/src/modules/*/index.d.ts",
+ "default": "./.medusa/server/src/modules/*/index.js"
+ },
+ "./types": "./.medusa/server/src/types/index.js",
+ "./providers/*": {
+ "types": "./.medusa/server/src/providers/*/index.d.ts",
+ "default": "./.medusa/server/src/providers/*/index.js"
+ },
+ "./*": "./.medusa/server/src/*.js",
+ "./admin": {
+ "import": "./.medusa/server/src/admin/index.mjs",
+ "default": "./.medusa/server/src/admin/index.js"
+ },
+ "./vendor": {
+ "import": "./.medusa/server/src/vendor/index.mjs",
+ "default": "./.medusa/server/src/vendor/index.js"
+ }
+ },
+ "keywords": [
+ "medusa-plugin",
+ "medusa-v2",
+ "mercur",
+ "marketplace",
+ "stripe",
+ "stripe-connect"
+ ],
+ "scripts": {
+ "build": "rm -rf .medusa && tsc --declaration --outDir .medusa/server && bun run build:dashboards",
+ "build:dashboards": "bun ./node_modules/@mercurjs/cli/dist/index.js dashboard:build --app admin --src src/admin --out .medusa/server/src/admin/index.mjs && bun ./node_modules/@mercurjs/cli/dist/index.js dashboard:build --app vendor --src src/vendor --out .medusa/server/src/vendor/index.mjs",
+ "typecheck:admin": "tsc -p src/admin/tsconfig.json",
+ "typecheck:vendor": "tsc -p src/vendor/tsconfig.json",
+ "test": "jest --passWithNoTests",
+ "dev": "medusa plugin:develop",
+ "prepublishOnly": "tsc --declaration --outDir .medusa/server && bun run build:dashboards"
+ },
+ "devDependencies": {
+ "@medusajs/cli": "2.22.0",
+ "@medusajs/core-flows": "2.22.0",
+ "@medusajs/framework": "2.22.0",
+ "@medusajs/medusa": "2.22.0",
+ "@medusajs/payment-stripe": "2.22.0",
+ "@medusajs/types": "2.22.0",
+ "@mercurjs/core": "2.3.9-canary.4",
+ "@mercurjs/types": "2.3.9-canary.4",
+ "@types/jest": "^29.5.14",
+ "@types/node": "^26.1.0",
+ "jest": "^29.7.0",
+ "ts-jest": "^29.2.5",
+ "typescript": "5.9.3",
+ "@hookform/resolvers": "5.4.0",
+ "@medusajs/icons": "2.22.0",
+ "@medusajs/ui": "4.2.3",
+ "@mercurjs/cli": "2.3.9-canary.4",
+ "@mercurjs/client": "2.3.9-canary.4",
+ "@mercurjs/dashboard-sdk": "2.3.9-canary.4",
+ "@mercurjs/dashboard-shared": "2.3.9-canary.4",
+ "@tanstack/react-query": "5.64.2",
+ "@tanstack/react-table": "8.21.3",
+ "@types/react": "^18.3.2",
+ "react": "^18.3.1",
+ "react-dom": "^18.3.1",
+ "react-hook-form": "7.88.0",
+ "react-router-dom": "7.18.1",
+ "radix-ui": "1.1.2",
+ "i18next": "26.4.2",
+ "react-i18next": "17.0.14"
+ },
+ "peerDependencies": {
+ "@medusajs/core-flows": ">=2.22.0",
+ "@medusajs/framework": ">=2.22.0",
+ "@medusajs/medusa": ">=2.22.0",
+ "@medusajs/payment-stripe": ">=2.22.0",
+ "@mercurjs/core": "*",
+ "@medusajs/icons": ">=2.22.0",
+ "@medusajs/ui": ">=4.1.19",
+ "@mercurjs/client": ">=2.3.9-canary.4",
+ "@mercurjs/dashboard-sdk": ">=2.3.9-canary.4",
+ "@mercurjs/dashboard-shared": ">=2.3.9-canary.4",
+ "@tanstack/react-query": "^5.64.2",
+ "@tanstack/react-table": "^8.20.5",
+ "react": "^18.0.0",
+ "react-dom": "^18.0.0",
+ "react-hook-form": "^7.49.1",
+ "react-router-dom": "^7.0.0",
+ "@hookform/resolvers": "^5.4.0",
+ "i18next": "26.4.2",
+ "react-i18next": "17.0.14"
+ },
+ "dependencies": {
+ "cronstrue": "3.27.0",
+ "stripe": "^19.1.0",
+ "zod": "4.6.5"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+}
diff --git a/packages/plugins/stripe-connector/src/admin/_layouts.ts b/packages/plugins/stripe-connector/src/admin/_layouts.ts
new file mode 100644
index 000000000..ba663e175
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/_layouts.ts
@@ -0,0 +1,7 @@
+import { defineLayoutPreferences } from "@mercurjs/dashboard-sdk"
+
+export default defineLayoutPreferences({
+ "nav.main": {
+ groups: [{ id: "integrations", label: "Integrations", rank: 5 }],
+ },
+})
diff --git a/packages/plugins/stripe-connector/src/admin/components/seller-combobox.tsx b/packages/plugins/stripe-connector/src/admin/components/seller-combobox.tsx
new file mode 100644
index 000000000..2e4bfcab5
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/components/seller-combobox.tsx
@@ -0,0 +1,54 @@
+import { Combobox } from "@mercurjs/dashboard-shared"
+import { keepPreviousData } from "@tanstack/react-query"
+import { forwardRef, useEffect, useMemo, useRef, useState } from "react"
+
+import { useSellers } from "../hooks/api/stripe"
+
+type SellerComboboxProps = {
+ value?: string
+ onChange: (value?: string) => void
+ "data-testid"?: string
+}
+
+export const SellerCombobox = forwardRef<HTMLInputElement, SellerComboboxProps>(
+ ({ value, onChange, ...props }, ref) => {
+ const [search, setSearch] = useState("")
+ const [q, setQ] = useState("")
+ const seen = useRef(new Map<string, string>())
+
+ useEffect(() => {
+ const timeout = setTimeout(() => setQ(search), 300)
+ return () => clearTimeout(timeout)
+ }, [search])
+
+ const { sellers } = useSellers({ limit: 20, ...(q ? { q } : {}) }, { placeholderData: keepPreviousData })
+
+ const options = useMemo(() => {
+ for (const seller of sellers ?? []) {
+ seen.current.set(seller.id, seller.name)
+ }
+
+ const list = (sellers ?? []).map((seller) => ({ label: seller.name, value: seller.id }))
+ const selected = value ? seen.current.get(value) : undefined
+
+ if (value && selected && !list.some((option) => option.value === value)) {
+ list.unshift({ label: selected, value })
+ }
+
+ return list
+ }, [sellers, value])
+
+ return (
+ <Combobox
+ ref={ref}
+ value={value}
+ onChange={onChange}
+ onSearchValueChange={setSearch}
+ options={options}
+ {...props}
+ />
+ )
+ }
+)
+
+SellerCombobox.displayName = "SellerCombobox"
diff --git a/packages/plugins/stripe-connector/src/admin/components/stripe-icon.tsx b/packages/plugins/stripe-connector/src/admin/components/stripe-icon.tsx
new file mode 100644
index 000000000..e3959021f
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/components/stripe-icon.tsx
@@ -0,0 +1,25 @@
+import type { ComponentProps } from "react"
+
+// Brand mark: the Stripe purple and glyph are fixed by Stripe, not theme tokens.
+export const StripeIcon = (props: ComponentProps<"svg">) => (
+ <svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>
+ <rect width="15" height="15" fill="#635BFF" />
+ <rect width="15" height="15" fill="url(#stripe_icon_gradient)" fillOpacity="0.2" />
+ <g clipPath="url(#stripe_icon_clip)">
+ <path
+ transform="translate(3 3) scale(0.375)"
+ fill="white"
+ d="M13.976 9.15c-2.172-.806-3.356-1.426-3.356-2.409 0-.831.683-1.305 1.901-1.305 2.227 0 4.515.858 6.09 1.631l.89-5.494C18.252.975 15.697 0 12.165 0 9.667 0 7.589.654 6.104 1.872 4.56 3.147 3.757 4.992 3.757 7.218c0 4.039 2.467 5.76 6.476 7.219 2.585.92 3.445 1.574 3.445 2.583 0 .98-.84 1.545-2.354 1.545-1.875 0-4.965-.921-6.99-2.109l-.9 5.555C5.175 22.99 8.385 24 11.714 24c2.641 0 4.843-.624 6.328-1.813 1.664-1.305 2.525-3.236 2.525-5.732 0-4.128-2.524-5.851-6.594-7.305h.003z"
+ />
+ </g>
+ <defs>
+ <linearGradient id="stripe_icon_gradient" x1="7.5" y1="0" x2="7.5" y2="15" gradientUnits="userSpaceOnUse">
+ <stop stopColor="white" />
+ <stop offset="1" stopColor="white" stopOpacity="0" />
+ </linearGradient>
+ <clipPath id="stripe_icon_clip">
+ <rect width="9" height="9" fill="white" transform="translate(3 3)" />
+ </clipPath>
+ </defs>
+ </svg>
+)
diff --git a/packages/plugins/stripe-connector/src/admin/hooks/api/stripe.tsx b/packages/plugins/stripe-connector/src/admin/hooks/api/stripe.tsx
new file mode 100644
index 000000000..53c2733ba
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/hooks/api/stripe.tsx
@@ -0,0 +1,253 @@
+import { queryKeysFactory } from "@mercurjs/dashboard-shared"
+import {
+ useMutation,
+ useQuery,
+ useQueryClient,
+ type QueryClient,
+ type UseMutationOptions,
+ type UseQueryOptions,
+} from "@tanstack/react-query"
+
+import { client, type ListQuery, type SellerListResponse } from "../../lib/client"
+import type {
+ AdminAdjustmentListResponse,
+ AdminAdjustmentResponse,
+ AdminPayoutAccountListResponse,
+ AdminPayoutAccountResponse,
+ AdminStripeCaptureListResponse,
+ AdminStripeCaptureResponse,
+ AdminPayoutJobListResponse,
+ AdminPayoutJobRunListResponse,
+ AdminPayoutJobRunResponse,
+ AdminPayoutListResponse,
+ AdminPayoutNotificationListResponse,
+ AdminPayoutResponse,
+ AdminPayoutStatusResponse,
+ AdminSettlementListResponse,
+ AdminSettlementResponse,
+} from "../../../types/http"
+
+export const stripeStatusKeys = queryKeysFactory("admin_stripe_status")
+export const stripeJobKeys = queryKeysFactory("admin_stripe_jobs")
+export const stripeJobRunKeys = queryKeysFactory("admin_stripe_job_runs")
+export const stripeAccountKeys = queryKeysFactory("admin_stripe_accounts")
+export const stripePayoutKeys = queryKeysFactory("admin_stripe_payouts")
+export const stripeSettlementKeys = queryKeysFactory("admin_stripe_settlements")
+export const stripeAdjustmentKeys = queryKeysFactory("admin_stripe_adjustments")
+export const stripeCaptureKeys = queryKeysFactory("admin_stripe_captures")
+export const stripeNotificationKeys = queryKeysFactory("admin_stripe_notifications")
+export const stripeSellerKeys = queryKeysFactory("admin_stripe_sellers")
+
+type QueryOptions<T> = Omit<UseQueryOptions<T, Error, T>, "queryKey" | "queryFn">
+type MutationOptions<TData, TVariables = void> = UseMutationOptions<TData, Error, TVariables>
+
+const ACCOUNT_FIELDS = "+seller.name,+seller.metadata,+onboarding.id,+onboarding.data"
+const PAYOUT_FIELDS = "+reversals.*,+seller.name,+seller.handle"
+
+// Every Stripe operation can move several entities at once (a capture decides
+// payouts, a settlement retry touches adjustments), so mutations refresh them all.
+const invalidateStripe = (qc: QueryClient) =>
+ Promise.all(
+ [
+ stripeStatusKeys,
+ stripeJobKeys,
+ stripeJobRunKeys,
+ stripeAccountKeys,
+ stripePayoutKeys,
+ stripeSettlementKeys,
+ stripeAdjustmentKeys,
+ stripeCaptureKeys,
+ stripeNotificationKeys,
+ ].map((keys) => qc.invalidateQueries({ queryKey: keys.all }))
+ )
+
+const useStripeMutation = <TData, TVariables>(
+ mutationFn: (variables: TVariables) => Promise<TData>,
+ options?: MutationOptions<TData, TVariables>
+) => {
+ const qc = useQueryClient()
+
+ return useMutation<TData, Error, TVariables>({
+ mutationFn,
+ ...options,
+ onSuccess: async (data, variables, context) => {
+ await invalidateStripe(qc)
+ await options?.onSuccess?.(data, variables, context)
+ },
+ })
+}
+
+export const useStripeStatus = (options?: QueryOptions<AdminPayoutStatusResponse>) => {
+ const { data, ...rest } = useQuery({
+ queryKey: stripeStatusKeys.all,
+ queryFn: () => client.admin.stripe.status.query({}),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
+
+export const useStripeJobs = (options?: QueryOptions<AdminPayoutJobListResponse>) => {
+ const { data, ...rest } = useQuery({
+ queryKey: stripeJobKeys.lists(),
+ queryFn: () => client.admin.stripe.jobs.query({}),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
+
+export const useStripeJobRuns = (
+ job: string,
+ query?: ListQuery,
+ options?: QueryOptions<AdminPayoutJobRunListResponse>
+) => {
+ const { data, ...rest } = useQuery({
+ queryKey: stripeJobRunKeys.list({ job, ...query }),
+ queryFn: () => client.admin.stripe.jobs.$job.runs.query({ $job: job, ...query }),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
+
+export const useRunStripeJob = (job: string, options?: MutationOptions<AdminPayoutJobRunResponse>) =>
+ useStripeMutation(() => client.admin.stripe.jobs.$job.run.mutate({ $job: job }), options)
+
+export const useStripeAccounts = (query?: ListQuery, options?: QueryOptions<AdminPayoutAccountListResponse>) => {
+ const { data, ...rest } = useQuery({
+ queryKey: stripeAccountKeys.list(query),
+ queryFn: () => client.admin["payout-accounts"].query({ fields: ACCOUNT_FIELDS, ...query }),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
+
+export const useStripeAccount = (id: string, options?: QueryOptions<AdminPayoutAccountResponse>) => {
+ const { data, ...rest } = useQuery({
+ queryKey: stripeAccountKeys.detail(id),
+ queryFn: () => client.admin["payout-accounts"].$id.query({ $id: id, fields: ACCOUNT_FIELDS }),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
+
+export const useSyncStripeAccount = (id: string, options?: MutationOptions<AdminPayoutAccountResponse>) =>
+ useStripeMutation(() => client.admin["payout-accounts"].$id.sync.mutate({ $id: id }), options)
+
+export const useRefreshStripeAccountLink = (id: string, options?: MutationOptions<AdminPayoutAccountResponse>) =>
+ useStripeMutation(() => client.admin["payout-accounts"].$id["refresh-link"].mutate({ $id: id }), options)
+
+export const useIgnoreStripeAccount = (id: string, options?: MutationOptions<AdminPayoutAccountResponse, boolean>) =>
+ useStripeMutation((ignored: boolean) => client.admin.stripe.accounts.$id.ignore.mutate({ $id: id, ignored }), options)
+
+export const useMapStripeAccount = (
+ options?: MutationOptions<AdminPayoutAccountResponse, { seller_id: string; external_id: string }>
+) => useStripeMutation((body) => client.admin["payout-accounts"].mutate(body), options)
+
+export const useStripePayouts = (query?: ListQuery, options?: QueryOptions<AdminPayoutListResponse>) => {
+ const { data, ...rest } = useQuery({
+ queryKey: stripePayoutKeys.list(query),
+ queryFn: () => client.admin.payouts.query({ fields: PAYOUT_FIELDS, ...query }),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
+
+export const useRetryPayout = (options?: MutationOptions<AdminPayoutResponse, string>) =>
+ useStripeMutation((id: string) => client.admin.payouts.$id.retry.mutate({ $id: id }), options)
+
+export const useStripeSettlements = (query?: ListQuery, options?: QueryOptions<AdminSettlementListResponse>) => {
+ const { data, ...rest } = useQuery({
+ queryKey: stripeSettlementKeys.list(query),
+ queryFn: () => client.admin.stripe.settlements.query(query ?? {}),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
+
+export const useStripeSettlement = (id: string, options?: QueryOptions<AdminSettlementResponse>) => {
+ const { data, ...rest } = useQuery({
+ queryKey: stripeSettlementKeys.detail(id),
+ queryFn: () => client.admin.stripe.settlements.$id.query({ $id: id }),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
+
+export const useRetrySettlementPayout = (id: string, options?: MutationOptions<AdminSettlementResponse>) =>
+ useStripeMutation(() => client.admin.stripe.settlements.$id.retry.mutate({ $id: id }), options)
+
+export const useStripeAdjustments = (query?: ListQuery, options?: QueryOptions<AdminAdjustmentListResponse>) => {
+ const { data, ...rest } = useQuery({
+ queryKey: stripeAdjustmentKeys.list(query),
+ queryFn: () => client.admin.stripe.adjustments.query(query ?? {}),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
+
+export type CreateAdjustmentPayload = {
+ seller_id: string
+ type: string
+ amount: number
+ currency_code: string
+ reason?: string | null
+}
+
+export const useCreateAdjustment = (options?: MutationOptions<AdminAdjustmentResponse, CreateAdjustmentPayload>) =>
+ useStripeMutation((body: CreateAdjustmentPayload) => client.admin.stripe.adjustments.mutate(body), options)
+
+export const useStripeCaptures = (query?: ListQuery, options?: QueryOptions<AdminStripeCaptureListResponse>) => {
+ const { data, ...rest } = useQuery({
+ queryKey: stripeCaptureKeys.list(query),
+ queryFn: () => client.admin.stripe.captures.query(query ?? {}),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
+
+export const useCapturePayment = (groupId: string, options?: MutationOptions<AdminStripeCaptureResponse>) =>
+ useStripeMutation(
+ () => client.admin.stripe.captures.$order_group_id.capture.mutate({ $order_group_id: groupId }),
+ options
+ )
+
+export const useCancelPayment = (groupId: string, options?: MutationOptions<AdminStripeCaptureResponse>) =>
+ useStripeMutation(
+ () => client.admin.stripe.captures.$order_group_id.cancel.mutate({ $order_group_id: groupId }),
+ options
+ )
+
+export const useStripeNotifications = (
+ query?: ListQuery,
+ options?: QueryOptions<AdminPayoutNotificationListResponse>
+) => {
+ const { data, ...rest } = useQuery({
+ queryKey: stripeNotificationKeys.list(query),
+ queryFn: () => client.admin.stripe.notifications.query(query ?? {}),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
+
+export const useSendTestNotification = (options?: MutationOptions<{ notification: unknown }>) =>
+ useStripeMutation(() => client.admin.stripe.notifications.test.mutate({}), options)
+
+export const useSellers = (query?: ListQuery, options?: QueryOptions<SellerListResponse>) => {
+ const { data, ...rest } = useQuery({
+ queryKey: stripeSellerKeys.list(query),
+ queryFn: () => client.admin.sellers.query({ fields: "id,name", ...query }),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
diff --git a/packages/plugins/stripe-connector/src/admin/hooks/use-stripe-table-query.ts b/packages/plugins/stripe-connector/src/admin/hooks/use-stripe-table-query.ts
new file mode 100644
index 000000000..2cda2e342
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/hooks/use-stripe-table-query.ts
@@ -0,0 +1,41 @@
+import { useQueryParams } from "@mercurjs/dashboard-shared"
+
+import type { ListQuery } from "../lib/client"
+
+export const PAGE_SIZE = 20
+
+type UseStripeTableQueryProps = {
+ filters?: string[]
+ dateFilters?: string[]
+ pageSize?: number
+}
+
+export const useStripeTableQuery = ({
+ filters = [],
+ dateFilters = [],
+ pageSize = PAGE_SIZE,
+}: UseStripeTableQueryProps = {}) => {
+ const raw = useQueryParams(["offset", ...filters, ...dateFilters])
+
+ const searchParams: ListQuery = {
+ limit: pageSize,
+ offset: raw.offset ? Number(raw.offset) : 0,
+ }
+
+ // The client serializes `undefined` as a literal string, so only set what is present.
+ for (const key of filters) {
+ const value = raw[key]
+ if (value) {
+ searchParams[key] = value.split(",")
+ }
+ }
+
+ for (const key of dateFilters) {
+ const value = raw[key]
+ if (value) {
+ searchParams[key] = JSON.parse(value)
+ }
+ }
+
+ return { searchParams, raw }
+}
diff --git a/packages/plugins/stripe-connector/src/admin/lib/client.ts b/packages/plugins/stripe-connector/src/admin/lib/client.ts
new file mode 100644
index 000000000..0b1d1c43e
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/lib/client.ts
@@ -0,0 +1,125 @@
+import { adminAuth, createClient, type InferClient } from "@mercurjs/client"
+import type { MedusaResponse } from "@medusajs/framework"
+import type { PayoutReversalDTO } from "@mercurjs/types"
+import type {
+ AdminAdjustmentListResponse,
+ AdminAdjustmentResponse,
+ AdminPayoutAccountListResponse,
+ AdminPayoutAccountResponse,
+ AdminPayoutJobListResponse,
+ AdminPayoutJobRunListResponse,
+ AdminPayoutJobRunResponse,
+ AdminPayoutListResponse,
+ AdminPayoutNotificationListResponse,
+ AdminPayoutResponse,
+ AdminPayoutStatusResponse,
+ AdminSettlementListResponse,
+ AdminSettlementResponse,
+ AdminStripeCaptureListResponse,
+ AdminStripeCaptureResponse,
+} from "../../types/http"
+
+export type {
+ AdminPayoutAccountListResponse,
+ AdminStripeCapture,
+ AdminPayoutJob,
+ AdminPayoutStatusResponse,
+ AdminSettlementListResponse,
+} from "../../types/http"
+
+export type ListQuery = Record<string, unknown> & { limit?: number; offset?: number }
+type Route<Input, Output> = (req: { validatedBody: Input }, res: MedusaResponse<Output>) => Promise<void>
+type Empty = { fields?: string }
+
+type SellerRef = { id: string; name: string; handle: string; metadata?: Record<string, unknown> | null }
+
+export type PayoutAccountRow = AdminPayoutAccountListResponse["payout_accounts"][number] & {
+ seller?: SellerRef | null
+ onboarding?: { id: string; data: Record<string, unknown> | null } | null
+}
+export type PayoutRow = AdminPayoutListResponse["payouts"][number] & {
+ seller?: SellerRef | null
+ reversals?: PayoutReversalDTO[]
+}
+export type SettlementRow = AdminSettlementListResponse["settlements"][number]
+export type SettlementDetail = AdminSettlementResponse["settlement"]
+export type AdjustmentRow = AdminAdjustmentListResponse["adjustments"][number]
+export type JobRunRow = AdminPayoutJobRunListResponse["runs"][number]
+export type NotificationRow = AdminPayoutNotificationListResponse["notifications"][number]
+
+export type SellerListResponse = {
+ sellers: { id: string; name: string }[]
+ count: number
+ offset: number
+ limit: number
+}
+
+export const PAYOUT_IGNORED_KEY = "payout_ignored"
+
+export const isIgnored = (account: PayoutAccountRow) =>
+ String(account.seller?.metadata?.[PAYOUT_IGNORED_KEY] ?? "") === "true"
+
+type Routes = {
+ admin: {
+ sellers: {
+ GET: Route<ListQuery, SellerListResponse>
+ }
+ "payout-accounts": {
+ GET: Route<ListQuery, AdminPayoutAccountListResponse>
+ POST: Route<{ seller_id: string; external_id: string }, AdminPayoutAccountResponse>
+ $id: {
+ GET: Route<Empty, AdminPayoutAccountResponse>
+ "refresh-link": { POST: Route<Empty, AdminPayoutAccountResponse> }
+ sync: { POST: Route<Empty, AdminPayoutAccountResponse> }
+ }
+ }
+ payouts: {
+ GET: Route<ListQuery, AdminPayoutListResponse>
+ $id: { retry: { POST: Route<Empty, AdminPayoutResponse> } }
+ }
+ stripe: {
+ status: { GET: Route<Empty, AdminPayoutStatusResponse> }
+ accounts: {
+ $id: { ignore: { POST: Route<{ ignored: boolean }, AdminPayoutAccountResponse> } }
+ }
+ settlements: {
+ GET: Route<ListQuery, AdminSettlementListResponse>
+ $id: {
+ GET: Route<Empty, AdminSettlementResponse>
+ retry: { POST: Route<Empty, AdminSettlementResponse> }
+ }
+ }
+ adjustments: {
+ GET: Route<ListQuery, AdminAdjustmentListResponse>
+ POST: Route<
+ { seller_id: string; type: string; amount: number; currency_code: string; reason?: string | null },
+ AdminAdjustmentResponse
+ >
+ }
+ jobs: {
+ GET: Route<Empty, AdminPayoutJobListResponse>
+ $job: {
+ runs: { GET: Route<ListQuery, AdminPayoutJobRunListResponse> }
+ run: { POST: Route<Empty, AdminPayoutJobRunResponse> }
+ }
+ }
+ captures: {
+ GET: Route<ListQuery, AdminStripeCaptureListResponse>
+ $order_group_id: {
+ capture: { POST: Route<Empty, AdminStripeCaptureResponse> }
+ cancel: { POST: Route<Empty, AdminStripeCaptureResponse> }
+ }
+ }
+ notifications: {
+ GET: Route<ListQuery, AdminPayoutNotificationListResponse>
+ test: { POST: Route<Empty, { notification: unknown }> }
+ }
+ }
+ }
+}
+
+export const client: InferClient<Routes> = createClient({
+ baseUrl: import.meta.env.VITE_MERCUR_BACKEND_URL || "http://localhost:9000",
+ fetchOptions: { credentials: "omit" },
+ auth: adminAuth(),
+})
diff --git a/packages/plugins/stripe-connector/src/admin/lib/status.ts b/packages/plugins/stripe-connector/src/admin/lib/status.ts
new file mode 100644
index 000000000..96a8e3d36
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/lib/status.ts
@@ -0,0 +1,234 @@
+import { getStylizedAmount } from "@mercurjs/dashboard-shared"
+import cronstrue from "cronstrue"
+
+export type BadgeColor = "green" | "red" | "orange" | "grey" | "blue" | "purple"
+
+export const PAYOUT_STATUS_COLOR: Record<string, BadgeColor> = {
+ pending: "blue",
+ processing: "blue",
+ paid: "green",
+ failed: "red",
+ on_hold: "orange",
+ aborted: "grey",
+}
+
+export const PAYOUT_STATUS_LABEL: Record<string, string> = {
+ pending: "Pending",
+ processing: "Processing",
+ refunds: "Refunds",
+ paid: "Paid",
+ failed: "Failed",
+ on_hold: "On hold",
+ aborted: "Aborted",
+}
+
+const PAYOUT_STATUS_REASON_LABEL: Record<string, string> = {
+ account_not_ready: "The store's payout account cannot receive payouts yet.",
+ account_payouts_disabled: "Payouts are disabled on the store's payout account.",
+ order_not_ready: "The order is not fulfilled yet.",
+ order_aborted: "The order was canceled.",
+ payment_not_ready: "The order's payment is not captured yet.",
+ payment_failed: "The order's payment failed.",
+ payment_canceled: "The order's payment was canceled.",
+ payment_refunded: "The order's payment was refunded in full.",
+ payout_not_ready: "The payout for this order has not been sent yet.",
+ refund_aborted: "The refund was canceled.",
+ refund_absorbed: "The refund was deducted before the payout was sent.",
+ invalid_amount: "The amount to pay out is not valid.",
+ provider_error: "Stripe returned an error.",
+}
+
+export const payoutStatusReasonLabel = (reason: string) =>
+ PAYOUT_STATUS_REASON_LABEL[reason] ?? "This payout needs attention."
+
+export const payoutStatusDetail = (data: Record<string, unknown> | null | undefined) => {
+ const detail = data?.status_detail
+ return typeof detail === "string" && detail.length > 0 ? detail : null
+}
+
+export const SETTLEMENT_STATUS_COLOR: Record<string, BadgeColor> = {
+ open: "blue",
+ paid_out: "green",
+ failed: "red",
+ aborted: "grey",
+}
+
+export const SETTLEMENT_STATUS_LABEL: Record<string, string> = {
+ open: "Open",
+ paid_out: "Paid out",
+ failed: "Failed",
+ aborted: "Aborted",
+}
+
+export const JOB_LABEL: Record<string, string> = {
+ "payout-sync-onboarding": "Onboarding",
+ "payout-validate-captures": "Captures",
+ "payout-process-transfers": "Payouts",
+ "payout-process-reversals": "Reversals",
+ "payout-process-settlements": "Settlements",
+ "payout-alert-failed-operations": "Alerts",
+ "payout-monitor-kyc": "KYC",
+}
+
+export const JOB_DESCRIPTION: Record<string, string> = {
+ "payout-sync-onboarding": "Creates Stripe Express accounts for new sellers and publishes their onboarding links.",
+ "payout-validate-captures": "Captures or cancels the authorized card payment once every seller order in the group is decided.",
+ "payout-process-transfers": "Pays each fulfilled order's total minus commission into the seller's connected account.",
+ "payout-process-reversals": "Reverses the seller's share of every refund, net of commission.",
+ "payout-process-settlements": "Sends adjustments, retries failed bank payouts, builds settlements and pays them out.",
+ "payout-alert-failed-operations": "Emails the technical contact everything that is still failed.",
+ "payout-monitor-kyc": "Re-reads every connected account's requirements and KYC status.",
+}
+
+type StripeRequirements = {
+ currently_due: string[]
+ past_due: string[]
+ pending_verification: string[]
+}
+
+/** The connected account Stripe returned, kept on the payout account as `data`. */
+export const stripeRequirementsOf = (data: Record<string, unknown> | null | undefined): StripeRequirements => {
+ const requirements = data?.requirements as Partial<StripeRequirements> | undefined
+ return {
+ currently_due: requirements?.currently_due ?? [],
+ past_due: requirements?.past_due ?? [],
+ pending_verification: requirements?.pending_verification ?? [],
+ }
+}
+
+export const JOB_RUN_STATUS_COLOR: Record<string, BadgeColor> = {
+ running: "blue",
+ succeeded: "green",
+ failed: "red",
+}
+
+export const JOB_RUN_STATUS_LABEL: Record<string, string> = {
+ running: "Running",
+ succeeded: "Succeeded",
+ failed: "Failed",
+}
+
+export const JOB_TRIGGER_LABEL: Record<string, string> = {
+ schedule: "Schedule",
+ manual: "Manual",
+ subscriber: "Event",
+}
+
+const JOB_STAT_LABEL: Record<string, string> = {
+ accounts: "Accounts",
+ adjustments: "Adjustments",
+ adjustments_processed: "Adjustments sent",
+ attention: "Need attention",
+ aborted: "Aborted",
+ awaiting_account: "Awaiting account",
+ backlog: "Backlog",
+ blocked: "Blocked",
+ canceled: "Canceled",
+ captured: "Captured",
+ captures: "Captures",
+ expired: "Expired",
+ failed: "Failed",
+ ignored: "Ignored",
+ new_orders: "New orders",
+ on_hold: "On hold",
+ orders: "Orders",
+ paid: "Paid",
+ payouts: "Payouts",
+ payouts_retried: "Bank payouts retried",
+ pending: "Pending",
+ processed: "Processed",
+ processing: "Processing",
+ refunds: "Refunds",
+ reversals: "Reversals",
+ sellers: "Stores",
+ sent: "Emails sent",
+ settlements: "Settlements",
+ skipped: "Skipped",
+ synced: "Synced",
+ total: "Total",
+}
+
+const humanizeKey = (key: string) => {
+ const text = key.replace(/_/g, " ")
+ return text.charAt(0).toUpperCase() + text.slice(1)
+}
+
+export const formatJobStats = (stats: Record<string, unknown> | null | undefined) =>
+ stats && Object.keys(stats).length
+ ? Object.entries(stats)
+ .map(([key, value]) => `${JOB_STAT_LABEL[key] ?? humanizeKey(key)}: ${String(value)}`)
+ .join(", ")
+ : "-"
+
+export const ADJUSTMENT_TYPE_LABEL: Record<string, string> = {
+ subscription: "Subscription",
+ extra_invoice: "Extra invoice",
+ extra_credit: "Extra credit",
+}
+
+export const RETRYABLE_STATUSES = ["failed", "on_hold", "pending"]
+
+export const statusProps = (
+ status: string | null | undefined,
+ colors: Record<string, BadgeColor>,
+ labels: Record<string, string>
+): { color: BadgeColor; label: string } => ({
+ color: (status && colors[status]) || "grey",
+ label: (status && labels[status]) || status || "-",
+})
+
+export const toNumber = (amount: unknown) => Number(amount ?? 0)
+
+/** The bank payout: what landed on the connected balance, else the net amount. */
+export const formatSettlementPayout = (settlement: {
+ amount: unknown
+ currency_code: string
+ payout_amount?: unknown
+ payout_currency_code?: string | null
+}) =>
+ getStylizedAmount(
+ toNumber(settlement.payout_amount ?? settlement.amount),
+ settlement.payout_currency_code ?? settlement.currency_code
+ )
+
+// Stripe's `requirements.disabled_reason` values:
+// https://docs.stripe.com/api/accounts/object#account_object-requirements-disabled_reason
+const DISABLED_REASON_LABEL: Record<string, string> = {
+ "action_required.requested_capabilities": "Capabilities need to be requested",
+ listed: "Under review: account appears on a restricted list",
+ other: "Disabled by Stripe",
+ platform_paused: "Paused by the platform",
+ "rejected.fraud": "Rejected for suspected fraud",
+ "rejected.incomplete_verification": "Rejected: verification was not completed in time",
+ "rejected.listed": "Rejected: account appears on a prohibited list",
+ "rejected.other": "Rejected by Stripe",
+ "rejected.platform_fraud": "Rejected by the platform for suspected fraud",
+ "rejected.platform_other": "Rejected by the platform",
+ "rejected.platform_terms_of_service": "Rejected by the platform for a terms of service violation",
+ "rejected.terms_of_service": "Rejected for a terms of service violation",
+ "requirements.past_due": "Required information is overdue",
+ "requirements.pending_verification": "Stripe is verifying the submitted information",
+ under_review: "Under review by Stripe",
+}
+
+export const disabledReasonLabel = (reason: string) =>
+ DISABLED_REASON_LABEL[reason] ?? humanizeRequirement(reason)
+
+// Requirement entries are field paths such as `individual.verification.document`.
+export const humanizeRequirement = (requirement: string) => {
+ const text = requirement.split(".").join(" › ").replace(/_/g, " ")
+ return text.charAt(0).toUpperCase() + text.slice(1)
+}
+
+// Jobs stagger their minute (`1-59/5`) so they don't all fire at once; the
+// offset means nothing to an operator, so describe them as plain intervals.
+export const describeSchedule = (cron: string) => {
+ const [minute, ...rest] = cron.trim().split(/\s+/)
+ const normalized = [minute.replace(/^\d+-59\/(\d+)$/, "*/$1"), ...rest].join(" ")
+
+ try {
+ return cronstrue.toString(normalized, { use24HourTimeFormat: true })
+ } catch {
+ return cron
+ }
+}
diff --git a/packages/plugins/stripe-connector/src/admin/providers/settings-providers.tsx b/packages/plugins/stripe-connector/src/admin/providers/settings-providers.tsx
new file mode 100644
index 000000000..eaecb2571
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/providers/settings-providers.tsx
@@ -0,0 +1,11 @@
+import { TooltipProvider } from "@medusajs/ui"
+import { queryClient } from "@mercurjs/dashboard-shared"
+import { QueryClientProvider } from "@tanstack/react-query"
+import type { ReactNode } from "react"
+
+/** Settings routes mount outside the host dashboard's React providers, so each one supplies its own. */
+export const SettingsProviders = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>
+ <TooltipProvider>{children}</TooltipProvider>
+ </QueryClientProvider>
+)
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/adjustments/@create/page.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/adjustments/@create/page.tsx
new file mode 100644
index 000000000..03cfb2979
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/adjustments/@create/page.tsx
@@ -0,0 +1,194 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Heading, Input, Select, Textarea, toast } from "@medusajs/ui"
+import {
+ Form,
+ KeyboundForm,
+ RouteDrawer,
+ currencies,
+ useDocumentDirection,
+ useRouteModal,
+} from "@mercurjs/dashboard-shared"
+import { useForm } from "react-hook-form"
+import * as zod from "zod"
+
+import { SellerCombobox } from "../../../../../components/seller-combobox"
+import { useCreateAdjustment } from "../../../../../hooks/api/stripe"
+import { ADJUSTMENT_TYPE_LABEL } from "../../../../../lib/status"
+import { SettingsProviders } from "../../../../../providers/settings-providers"
+
+const CreateAdjustmentSchema = zod.object({
+ seller_id: zod.string().min(1, "Select a store"),
+ type: zod.enum(["subscription", "extra_invoice", "extra_credit"]),
+ amount: zod.string().refine((value) => Number(value) > 0, "Enter an amount greater than zero"),
+ currency_code: zod.string().length(3, "Select a currency"),
+ reason: zod.string().optional(),
+})
+
+type CreateAdjustmentSchemaType = zod.infer<typeof CreateAdjustmentSchema>
+
+const TYPE_HINT: Record<CreateAdjustmentSchemaType["type"], string> = {
+ subscription: "Charged to the store on its next settlement.",
+ extra_invoice: "Charged to the store on its next settlement.",
+ extra_credit: "Paid to the store on its next settlement.",
+}
+
+const CreateAdjustmentForm = () => {
+ const { handleSuccess } = useRouteModal()
+ const direction = useDocumentDirection()
+
+ const form = useForm<CreateAdjustmentSchemaType>({
+ defaultValues: { seller_id: "", type: "subscription", amount: "", currency_code: "eur", reason: "" },
+ resolver: zodResolver(CreateAdjustmentSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateAdjustment()
+ const type = form.watch("type")
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ seller_id: data.seller_id,
+ type: data.type,
+ amount: Number(data.amount),
+ currency_code: data.currency_code,
+ reason: data.reason || null,
+ },
+ {
+ onSuccess: () => {
+ toast.success("Adjustment created")
+ handleSuccess()
+ },
+ onError: (error) => toast.error(error.message),
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex flex-1 flex-col overflow-hidden">
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-4 overflow-y-auto">
+ <Form.Field
+ control={form.control}
+ name="seller_id"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Label>Store</Form.Label>
+ <Form.Control>
+ <SellerCombobox {...field} data-testid="stripe-adjustment-store-input" />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="type"
+ render={({ field: { ref, onChange, ...field } }) => (
+ <Form.Item>
+ <Form.Label>Type</Form.Label>
+ <Form.Control>
+ <Select dir={direction} onValueChange={onChange} {...field}>
+ <Select.Trigger ref={ref} data-testid="stripe-adjustment-type-select">
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ {Object.entries(ADJUSTMENT_TYPE_LABEL).map(([value, label]) => (
+ <Select.Item key={value} value={value}>
+ {label}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.Hint>{TYPE_HINT[type]}</Form.Hint>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="amount"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Label>Amount</Form.Label>
+ <Form.Control>
+ <Input type="number" min="0" step="0.01" data-testid="stripe-adjustment-amount-input" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="currency_code"
+ render={({ field: { ref, onChange, ...field } }) => (
+ <Form.Item>
+ <Form.Label>Currency</Form.Label>
+ <Form.Control>
+ <Select dir={direction} onValueChange={onChange} {...field}>
+ <Select.Trigger ref={ref} data-testid="stripe-adjustment-currency-select">
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ {Object.values(currencies).map((currency) => (
+ <Select.Item key={currency.code} value={currency.code.toLowerCase()}>
+ {currency.code} · {currency.name}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ </div>
+ <Form.Field
+ control={form.control}
+ name="reason"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Label optional>Reason</Form.Label>
+ <Form.Control>
+ <Textarea rows={3} data-testid="stripe-adjustment-reason-input" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary" data-testid="stripe-adjustment-cancel-button">
+ Cancel
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending} data-testid="stripe-adjustment-save-button">
+ Save
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
+
+const CreateAdjustmentPage = () => (
+ <SettingsProviders>
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading data-testid="stripe-adjustment-create-heading">Create adjustment</Heading>
+ </RouteDrawer.Title>
+ <RouteDrawer.Description className="sr-only">
+ Charge or credit a store on its next settlement.
+ </RouteDrawer.Description>
+ </RouteDrawer.Header>
+ <CreateAdjustmentForm />
+ </RouteDrawer>
+ </SettingsProviders>
+)
+
+export default CreateAdjustmentPage
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/adjustments/page.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/adjustments/page.tsx
new file mode 100644
index 000000000..4be8677e0
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/adjustments/page.tsx
@@ -0,0 +1,192 @@
+import { Button, Container, Heading, Text } from "@medusajs/ui"
+import {
+ DateCell,
+ MoneyAmountCell,
+ SingleColumnPage,
+ StatusCell,
+ TextCell,
+ TextHeader,
+ WidgetZone,
+ _DataTable,
+ PermissionGuard,
+ useDataTable,
+ type Filter,
+} from "@mercurjs/dashboard-shared"
+import { defineRouteConfig } from "@mercurjs/dashboard-sdk"
+import { keepPreviousData } from "@tanstack/react-query"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { Link } from "react-router-dom"
+
+import { useStripeAccounts, useStripeAdjustments } from "../../../../hooks/api/stripe"
+import { PAGE_SIZE, useStripeTableQuery } from "../../../../hooks/use-stripe-table-query"
+import type { AdjustmentRow, PayoutAccountRow } from "../../../../lib/client"
+import {
+ ADJUSTMENT_TYPE_LABEL,
+ PAYOUT_STATUS_COLOR,
+ PAYOUT_STATUS_LABEL,
+ statusProps,
+ toNumber,
+} from "../../../../lib/status"
+import { SettingsProviders } from "../../../../providers/settings-providers"
+
+const AdjustmentListHeader = () => {
+ return (
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading data-testid="stripe-adjustments-heading">Adjustments</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ Fees and credits applied to a store's next settlement.
+ </Text>
+ </div>
+ <PermissionGuard permission="payouts:edit">
+ <Button size="small" variant="secondary" asChild data-testid="stripe-adjustment-create-button">
+ <Link to="create">Create</Link>
+ </Button>
+ </PermissionGuard>
+ </div>
+ )
+}
+
+const AdjustmentListDataTable = () => {
+ const { searchParams, raw } = useStripeTableQuery({ filters: ["type", "status"] })
+
+ const { adjustments, count, isPending, isError, error } = useStripeAdjustments(searchParams, {
+ placeholderData: keepPreviousData,
+ })
+
+ const accountIds = useMemo(() => [...new Set((adjustments ?? []).map((a) => a.account_id))], [adjustments])
+ const { payout_accounts } = useStripeAccounts(
+ { id: accountIds, limit: accountIds.length },
+ { enabled: accountIds.length > 0, placeholderData: keepPreviousData }
+ )
+
+ const storeNames = useMemo(
+ () =>
+ new Map(((payout_accounts ?? []) as PayoutAccountRow[]).map((account) => [account.id, account.seller?.name ?? ""])),
+ [payout_accounts]
+ )
+
+ const columns = useColumns(storeNames)
+ const filters = useFilters()
+
+ const { table } = useDataTable({
+ data: adjustments ?? [],
+ columns,
+ count: count ?? 0,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count ?? 0}
+ pageSize={PAGE_SIZE}
+ filters={filters}
+ isLoading={isPending}
+ queryObject={raw}
+ pagination
+ noRecords={{ message: "Create an adjustment to charge or credit a store outside of orders." }}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<AdjustmentRow>()
+
+const useColumns = (storeNames: Map<string, string>) =>
+ useMemo(
+ () => [
+ columnHelper.accessor("created_at", {
+ header: () => <TextHeader text="Created" />,
+ cell: ({ getValue }) => <DateCell date={getValue()} />,
+ }),
+ columnHelper.accessor("account_id", {
+ header: () => <TextHeader text="Store" />,
+ cell: ({ getValue }) => <TextCell text={storeNames.get(getValue()) || "-"} />,
+ }),
+ columnHelper.accessor("type", {
+ header: () => <TextHeader text="Type" />,
+ cell: ({ getValue }) => <TextCell text={ADJUSTMENT_TYPE_LABEL[getValue()] ?? getValue()} />,
+ }),
+ columnHelper.accessor("reason", {
+ header: () => <TextHeader text="Reason" />,
+ cell: ({ getValue }) => <TextCell text={getValue() ?? "-"} />,
+ }),
+ columnHelper.accessor("status", {
+ header: () => <TextHeader text="Status" />,
+ cell: ({ getValue }) => {
+ const { color, label } = statusProps(getValue(), PAYOUT_STATUS_COLOR, PAYOUT_STATUS_LABEL)
+ return <StatusCell color={color}>{label}</StatusCell>
+ },
+ }),
+ columnHelper.accessor("amount", {
+ header: () => (
+ <div className="flex h-full w-full items-center justify-end">
+ <span className="truncate">Amount</span>
+ </div>
+ ),
+ cell: ({ row }) => {
+ const amount = toNumber(row.original.amount)
+ return (
+ <MoneyAmountCell
+ amount={row.original.type === "extra_credit" ? amount : -amount}
+ currencyCode={row.original.currency_code}
+ align="right"
+ />
+ )
+ },
+ }),
+ ],
+ [storeNames]
+ )
+
+const useFilters = (): Filter[] => [
+ {
+ key: "type",
+ label: "Type",
+ type: "select",
+ multiple: true,
+ options: Object.entries(ADJUSTMENT_TYPE_LABEL).map(([value, label]) => ({ value, label })),
+ },
+ {
+ key: "status",
+ label: "Status",
+ type: "select",
+ multiple: true,
+ options: Object.entries(PAYOUT_STATUS_LABEL).map(([value, label]) => ({ value, label })),
+ },
+]
+
+const AdjustmentListPage = () => (
+ <SettingsProviders>
+ <SingleColumnPage hasOutlet data-testid="stripe-adjustment-list-page">
+ <WidgetZone id="stripe.adjustments.list">
+ <Container className="divide-y p-0" data-testid="stripe-adjustment-list-table">
+ <AdjustmentListHeader />
+ <AdjustmentListDataTable />
+ </Container>
+ </WidgetZone>
+ </SingleColumnPage>
+ </SettingsProviders>
+)
+
+export const config = defineRouteConfig({
+ label: "Adjustments",
+ nested: "/finance/stripe",
+ rank: 10,
+ permissions: ["payouts:view"],
+})
+
+export const handle = {
+ breadcrumb: () => "Adjustments",
+ permissions: "payouts:view",
+}
+
+export default AdjustmentListPage
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/captures/page.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/captures/page.tsx
new file mode 100644
index 000000000..7fbc62d12
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/captures/page.tsx
@@ -0,0 +1,261 @@
+import { CheckCircle, ExclamationCircle, XCircle } from "@medusajs/icons"
+import { Container, Heading, Text, Tooltip, toast, usePrompt } from "@medusajs/ui"
+import {
+ ActionMenu,
+ type Filter,
+ DateCell,
+ MoneyAmountCell,
+ SingleColumnPage,
+ StatusCell,
+ TextCell,
+ TextHeader,
+ WidgetZone,
+ _DataTable,
+ getStylizedAmount,
+ useDataTable,
+} from "@mercurjs/dashboard-shared"
+import { defineRouteConfig } from "@mercurjs/dashboard-sdk"
+import { keepPreviousData } from "@tanstack/react-query"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+
+import { useCancelPayment, useCapturePayment, useStripeCaptures } from "../../../../hooks/api/stripe"
+import { PAGE_SIZE, useStripeTableQuery } from "../../../../hooks/use-stripe-table-query"
+import type { AdminStripeCapture } from "../../../../lib/client"
+import { type BadgeColor, toNumber } from "../../../../lib/status"
+import { SettingsProviders } from "../../../../providers/settings-providers"
+
+const CAPTURE_STATUS: Record<AdminStripeCapture["status"], { color: BadgeColor; label: string }> = {
+ pending: { color: "grey", label: "Awaiting orders" },
+ ready: { color: "blue", label: "Ready to capture" },
+ cancelable: { color: "orange", label: "Ready to cancel" },
+ captured: { color: "green", label: "Captured" },
+ canceled: { color: "grey", label: "Canceled" },
+ expired: { color: "red", label: "Expired" },
+ failed: { color: "red", label: "Failed" },
+}
+
+const SETTLED = ["captured", "canceled"]
+
+const useFilters = (): Filter[] => [
+ {
+ key: "status",
+ label: "Status",
+ type: "select",
+ multiple: true,
+ options: Object.entries(CAPTURE_STATUS).map(([value, { label }]) => ({ value, label })),
+ },
+ { key: "expires_at", label: "Expires", type: "date" },
+]
+
+const CaptureRowActions = ({ capture }: { capture: AdminStripeCapture }) => {
+ const prompt = usePrompt()
+ const { mutateAsync: captureAsync } = useCapturePayment(capture.order_group_id)
+ const { mutateAsync: cancelAsync } = useCancelPayment(capture.order_group_id)
+
+ const amount = getStylizedAmount(toNumber(capture.capturable_amount), capture.currency_code)
+
+ const handleCapture = async () => {
+ const confirmed = await prompt({
+ title: "Capture payment?",
+ description: `${amount} will be captured now, before every order in the group is decided.`,
+ confirmText: "Capture",
+ cancelText: "Cancel",
+ })
+
+ if (!confirmed) {
+ return
+ }
+
+ await captureAsync(undefined, {
+ onSuccess: () => toast.success("Payment captured"),
+ onError: (error) => toast.error(error.message),
+ })
+ }
+
+ const handleCancel = async () => {
+ const confirmed = await prompt({
+ title: "Cancel authorization?",
+ description: `The authorization of ${amount} will be released to the customer. This cannot be undone.`,
+ confirmText: "Cancel authorization",
+ cancelText: "Keep",
+ })
+
+ if (!confirmed) {
+ return
+ }
+
+ await cancelAsync(undefined, {
+ onSuccess: () => toast.success("Authorization canceled"),
+ onError: (error) => toast.error(error.message),
+ })
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: "Capture now",
+ icon: <CheckCircle />,
+ onClick: handleCapture,
+ permission: "payouts:edit",
+ disabled: toNumber(capture.capturable_amount) <= 0,
+ disabledTooltip: "Nothing left to capture",
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: "Cancel authorization",
+ icon: <XCircle />,
+ onClick: handleCancel,
+ permission: "payouts:edit",
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<AdminStripeCapture>()
+
+const useColumns = () =>
+ useMemo(
+ () => [
+ columnHelper.accessor("order_group_id", {
+ header: () => <TextHeader text="Order group" />,
+ cell: ({ row }) => (
+ <TextCell
+ text={
+ row.original.order_group?.display_id
+ ? `#${row.original.order_group.display_id}`
+ : row.original.order_group_id
+ }
+ />
+ ),
+ }),
+ columnHelper.accessor("authorized_at", {
+ header: () => <TextHeader text="Authorized" />,
+ cell: ({ getValue }) => <DateCell date={getValue() ?? null} />,
+ }),
+ columnHelper.accessor("expires_at", {
+ header: () => <TextHeader text="Expires" />,
+ cell: ({ getValue }) => <DateCell date={getValue() ?? null} />,
+ }),
+ columnHelper.accessor("orders_decided", {
+ header: () => <TextHeader text="Orders decided" />,
+ cell: ({ row }) => <TextCell text={`${row.original.orders_decided} of ${row.original.orders_total}`} />,
+ }),
+ columnHelper.accessor("status", {
+ header: () => <TextHeader text="Status" />,
+ cell: ({ row }) => {
+ const { color, label } = CAPTURE_STATUS[row.original.status]
+ return (
+ <div className="flex h-full w-full items-center gap-x-2">
+ <StatusCell color={color}>{label}</StatusCell>
+ {row.original.status_reason && (
+ <Tooltip content={row.original.status_reason}>
+ <ExclamationCircle className="text-ui-tag-orange-icon shrink-0" />
+ </Tooltip>
+ )}
+ </div>
+ )
+ },
+ }),
+ columnHelper.accessor("capturable_amount", {
+ header: () => (
+ <div className="flex h-full w-full items-center justify-end">
+ <span className="truncate">Capturable</span>
+ </div>
+ ),
+ cell: ({ row }) => (
+ <MoneyAmountCell
+ amount={toNumber(row.original.capturable_amount)}
+ currencyCode={row.original.currency_code}
+ align="right"
+ />
+ ),
+ }),
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) =>
+ SETTLED.includes(row.original.status) ? null : <CaptureRowActions capture={row.original} />,
+ }),
+ ],
+ []
+ )
+
+const CaptureListDataTable = () => {
+ const { searchParams, raw } = useStripeTableQuery({ filters: ["status"], dateFilters: ["expires_at"] })
+ const { captures, count, isPending, isError, error } = useStripeCaptures(searchParams, {
+ placeholderData: keepPreviousData,
+ })
+
+ const columns = useColumns()
+ const filters = useFilters()
+
+ const { table } = useDataTable({
+ data: captures ?? [],
+ columns,
+ count: count ?? 0,
+ enablePagination: true,
+ getRowId: (row) => row.order_group_id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count ?? 0}
+ pageSize={PAGE_SIZE}
+ isLoading={isPending}
+ queryObject={raw}
+ filters={filters}
+ pagination
+ noRecords={{ message: "Every authorized payment has been captured or canceled." }}
+ />
+ )
+}
+
+const CaptureListPage = () => (
+ <SettingsProviders>
+ <SingleColumnPage data-testid="stripe-capture-list-page">
+ <WidgetZone id="stripe.captures.list">
+ <Container className="divide-y p-0" data-testid="stripe-capture-list-table">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading data-testid="stripe-captures-heading">Captures</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ Card payments authorized at checkout and captured once every order in the group is decided.
+ </Text>
+ </div>
+ </div>
+ <CaptureListDataTable />
+ </Container>
+ </WidgetZone>
+ </SingleColumnPage>
+ </SettingsProviders>
+)
+
+export const config = defineRouteConfig({
+ label: "Captures",
+ nested: "/finance/stripe",
+ rank: 20,
+ permissions: ["payouts:view"],
+})
+
+export const handle = {
+ breadcrumb: () => "Captures",
+ permissions: "payouts:view",
+}
+
+export default CaptureListPage
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/components/settlement-list-table.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/components/settlement-list-table.tsx
new file mode 100644
index 000000000..0b545bec8
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/components/settlement-list-table.tsx
@@ -0,0 +1,149 @@
+import { Container, Heading, Text } from "@medusajs/ui"
+import {
+ DateCell,
+ MoneyAmountCell,
+ StatusCell,
+ TextCell,
+ TextHeader,
+ _DataTable,
+ useDataTable,
+ type Filter,
+} from "@mercurjs/dashboard-shared"
+import { keepPreviousData } from "@tanstack/react-query"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+
+import { useStripeSettlements } from "../../../../hooks/api/stripe"
+import { PAGE_SIZE, useStripeTableQuery } from "../../../../hooks/use-stripe-table-query"
+import type { SettlementRow } from "../../../../lib/client"
+import {
+ PAYOUT_STATUS_COLOR,
+ PAYOUT_STATUS_LABEL,
+ SETTLEMENT_STATUS_COLOR,
+ SETTLEMENT_STATUS_LABEL,
+ statusProps,
+ toNumber,
+} from "../../../../lib/status"
+
+export const SettlementListTable = () => (
+ <Container className="divide-y p-0" data-testid="stripe-settlement-list-table">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading data-testid="stripe-settlements-heading">Settlements</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ Payouts, reversals and adjustments netted per store and paid to its bank account.
+ </Text>
+ </div>
+ </div>
+ <SettlementListDataTable />
+ </Container>
+)
+
+const SettlementListDataTable = () => {
+ const { searchParams, raw } = useStripeTableQuery({
+ filters: ["status", "payout_status"],
+ dateFilters: ["period_end"],
+ })
+
+ const { settlements, count, isPending, isError, error } = useStripeSettlements(searchParams, {
+ placeholderData: keepPreviousData,
+ })
+
+ const columns = useColumns()
+ const filters = useFilters()
+
+ const { table } = useDataTable({
+ data: settlements ?? [],
+ columns,
+ count: count ?? 0,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count ?? 0}
+ pageSize={PAGE_SIZE}
+ filters={filters}
+ isLoading={isPending}
+ queryObject={raw}
+ pagination
+ navigateTo={(row) => `/finance/stripe/settlements/${row.original.id}`}
+ noRecords={{ message: "Settlements are built nightly from the payouts that landed." }}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<SettlementRow>()
+
+const useColumns = () =>
+ useMemo(
+ () => [
+ columnHelper.accessor("display_id", {
+ header: () => <TextHeader text="Settlement" />,
+ cell: ({ getValue }) => <TextCell text={`#${getValue()}`} />,
+ }),
+ columnHelper.accessor("period_end", {
+ header: () => <TextHeader text="Period end" />,
+ cell: ({ getValue }) => <DateCell date={getValue()} />,
+ }),
+ columnHelper.accessor((row) => row.payout_account?.seller?.name ?? "", {
+ id: "seller",
+ header: () => <TextHeader text="Store" />,
+ cell: ({ getValue }) => <TextCell text={getValue() || "-"} />,
+ }),
+ columnHelper.accessor("status", {
+ header: () => <TextHeader text="Status" />,
+ cell: ({ getValue }) => {
+ const { color, label } = statusProps(getValue(), SETTLEMENT_STATUS_COLOR, SETTLEMENT_STATUS_LABEL)
+ return <StatusCell color={color}>{label}</StatusCell>
+ },
+ }),
+ columnHelper.accessor("payout_status", {
+ header: () => <TextHeader text="Bank payout" />,
+ cell: ({ getValue }) => {
+ if (!getValue()) {
+ return <TextCell text="-" />
+ }
+ const { color, label } = statusProps(getValue(), PAYOUT_STATUS_COLOR, PAYOUT_STATUS_LABEL)
+ return <StatusCell color={color}>{label}</StatusCell>
+ },
+ }),
+ columnHelper.accessor("amount", {
+ header: () => (
+ <div className="flex h-full w-full items-center justify-end">
+ <span className="truncate">Amount</span>
+ </div>
+ ),
+ cell: ({ row }) => (
+ <MoneyAmountCell amount={toNumber(row.original.amount)} currencyCode={row.original.currency_code} align="right" />
+ ),
+ }),
+ ],
+ []
+ )
+
+const useFilters = (): Filter[] => [
+ {
+ key: "status",
+ label: "Status",
+ type: "select",
+ multiple: true,
+ options: Object.entries(SETTLEMENT_STATUS_LABEL).map(([value, label]) => ({ value, label })),
+ },
+ {
+ key: "payout_status",
+ label: "Bank payout",
+ type: "select",
+ multiple: true,
+ options: Object.entries(PAYOUT_STATUS_LABEL).map(([value, label]) => ({ value, label })),
+ },
+ { key: "period_end", label: "Period end", type: "date" },
+]
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/jobs/[job]/page.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/jobs/[job]/page.tsx
new file mode 100644
index 000000000..8e22aba38
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/jobs/[job]/page.tsx
@@ -0,0 +1,190 @@
+import { PlaySolid } from "@medusajs/icons"
+import { Container, Heading, StatusBadge, Text } from "@medusajs/ui"
+import {
+ ActionMenu,
+ DateCell,
+ SectionRow,
+ SingleColumnPage,
+ SingleColumnPageSkeleton,
+ StatusCell,
+ TextCell,
+ TextHeader,
+ WidgetZone,
+ _DataTable,
+ useDataTable,
+ useDate,
+} from "@mercurjs/dashboard-shared"
+import { keepPreviousData } from "@tanstack/react-query"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useParams, type UIMatch } from "react-router-dom"
+
+import { useStripeJobRuns, useStripeJobs } from "../../../../../hooks/api/stripe"
+import { PAGE_SIZE, useStripeTableQuery } from "../../../../../hooks/use-stripe-table-query"
+import type { AdminPayoutJob, JobRunRow } from "../../../../../lib/client"
+import {
+ JOB_DESCRIPTION,
+ JOB_LABEL,
+ JOB_RUN_STATUS_COLOR,
+ JOB_RUN_STATUS_LABEL,
+ JOB_TRIGGER_LABEL,
+ describeSchedule,
+ formatJobStats,
+ statusProps,
+} from "../../../../../lib/status"
+import { SettingsProviders } from "../../../../../providers/settings-providers"
+import { useRunJobAction } from "../common/use-run-job-action"
+
+const JobGeneralSection = ({ job }: { job: AdminPayoutJob }) => {
+ const { getFullDate } = useDate()
+ const { handleRun } = useRunJobAction(job.job)
+
+ const formatDate = (value: Date | string | null | undefined) =>
+ value ? getFullDate({ date: value, includeTime: true }) : "-"
+
+ return (
+ <Container className="divide-y p-0" data-testid="stripe-job-general-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading data-testid="stripe-job-heading">{JOB_LABEL[job.job] ?? job.job}</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {JOB_DESCRIPTION[job.job]}
+ </Text>
+ </div>
+ <div className="flex items-center gap-x-2">
+ <StatusBadge color={job.enabled ? "green" : "grey"}>{job.enabled ? "Enabled" : "Disabled"}</StatusBadge>
+ <ActionMenu
+ groups={[
+ {
+ actions: [{ label: "Run now", icon: <PlaySolid />, onClick: handleRun, permission: "payouts:edit" }],
+ },
+ ]}
+ />
+ </div>
+ </div>
+ <SectionRow title="Schedule (UTC)" value={describeSchedule(job.schedule)} />
+ <SectionRow title="Cron" value={<code className="txt-compact-small">{job.schedule}</code>} />
+ <SectionRow title="Checkpoint" value={formatDate(job.checkpoint)} />
+ <SectionRow title="Next run" value={formatDate(job.next_run_at)} />
+ <SectionRow title="Failing items" value={String(job.failed_count)} />
+ </Container>
+ )
+}
+
+const columnHelper = createColumnHelper<JobRunRow>()
+
+const useRunColumns = () =>
+ useMemo(
+ () => [
+ columnHelper.accessor("started_at", {
+ header: () => <TextHeader text="Started" />,
+ cell: ({ getValue }) => <DateCell date={getValue()} />,
+ }),
+ columnHelper.accessor("status", {
+ header: () => <TextHeader text="Status" />,
+ cell: ({ getValue }) => {
+ const { color, label } = statusProps(getValue(), JOB_RUN_STATUS_COLOR, JOB_RUN_STATUS_LABEL)
+ return <StatusCell color={color}>{label}</StatusCell>
+ },
+ }),
+ columnHelper.accessor("trigger", {
+ header: () => <TextHeader text="Trigger" />,
+ cell: ({ getValue }) => <TextCell text={JOB_TRIGGER_LABEL[getValue()] ?? getValue()} />,
+ }),
+ columnHelper.accessor("finished_at", {
+ header: () => <TextHeader text="Duration" />,
+ cell: ({ row }) => {
+ const { started_at, finished_at } = row.original
+ if (!finished_at) {
+ return <TextCell text="-" />
+ }
+ const seconds = (new Date(finished_at).getTime() - new Date(started_at).getTime()) / 1000
+ return <TextCell text={`${seconds.toFixed(1)}s`} />
+ },
+ }),
+ columnHelper.accessor((row) => row.error ?? formatJobStats(row.stats), {
+ id: "result",
+ header: () => <TextHeader text="Result" />,
+ cell: ({ getValue }) => <TextCell text={getValue()} />,
+ }),
+ ],
+ []
+ )
+
+const JobRunsSection = ({ job }: { job: string }) => {
+ const { searchParams, raw } = useStripeTableQuery()
+ const { runs, count, isPending, isError, error } = useStripeJobRuns(job, searchParams, {
+ placeholderData: keepPreviousData,
+ })
+
+ const columns = useRunColumns()
+
+ const { table } = useDataTable({
+ data: runs ?? [],
+ columns,
+ count: count ?? 0,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0" data-testid="stripe-job-runs-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2" data-testid="stripe-job-runs-heading">
+ Runs
+ </Heading>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count ?? 0}
+ pageSize={PAGE_SIZE}
+ isLoading={isPending}
+ queryObject={raw}
+ pagination
+ noRecords={{ message: "The job has not run yet." }}
+ />
+ </Container>
+ )
+}
+
+const JobDetail = () => {
+ const { job: name } = useParams()
+ const { jobs, isPending, isError, error } = useStripeJobs()
+ const job = jobs?.find((j) => j.job === name)
+
+ if (isError) {
+ throw error
+ }
+
+ if (isPending || !job) {
+ return <SingleColumnPageSkeleton sections={2} />
+ }
+
+ return (
+ <SingleColumnPage data={job} showJSON data-testid="stripe-job-detail-page">
+ <WidgetZone id="stripe.jobs.detail" data={job}>
+ <JobGeneralSection job={job} />
+ <JobRunsSection job={job.job} />
+ </WidgetZone>
+ </SingleColumnPage>
+ )
+}
+
+const JobDetailPage = () => (
+ <SettingsProviders>
+ <JobDetail />
+ </SettingsProviders>
+)
+
+export const handle = {
+ breadcrumb: (match: UIMatch) => JOB_LABEL[match.params.job ?? ""] ?? match.params.job,
+ permissions: "payouts:view",
+}
+
+export default JobDetailPage
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/jobs/common/use-run-job-action.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/jobs/common/use-run-job-action.tsx
new file mode 100644
index 000000000..e594f1427
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/jobs/common/use-run-job-action.tsx
@@ -0,0 +1,34 @@
+import { toast, usePrompt } from "@medusajs/ui"
+
+import { useRunStripeJob } from "../../../../../hooks/api/stripe"
+import { JOB_LABEL } from "../../../../../lib/status"
+
+export const useRunJobAction = (job: string) => {
+ const prompt = usePrompt()
+ const { mutateAsync, isPending } = useRunStripeJob(job)
+ const label = JOB_LABEL[job] ?? job
+
+ const handleRun = async () => {
+ const confirmed = await prompt({
+ title: `Run ${label.toLowerCase()} now?`,
+ description: "The job runs immediately, outside of its schedule, and moves its checkpoint forward.",
+ confirmText: "Run",
+ cancelText: "Cancel",
+ variant: "confirmation",
+ })
+
+ if (!confirmed) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: ({ run }) =>
+ run.status === "failed"
+ ? toast.error(`${label} failed`, { description: run.error ?? undefined })
+ : toast.success(`${label} finished`),
+ onError: (error) => toast.error(error.message),
+ })
+ }
+
+ return { handleRun, isPending }
+}
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/jobs/page.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/jobs/page.tsx
new file mode 100644
index 000000000..258c0baa8
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/jobs/page.tsx
@@ -0,0 +1,156 @@
+import { PlaySolid } from "@medusajs/icons"
+import { Container, Heading, Text } from "@medusajs/ui"
+import {
+ ActionMenu,
+ DateCell,
+ SingleColumnPage,
+ StatusCell,
+ TextCell,
+ TextHeader,
+ WidgetZone,
+ _DataTable,
+ useDataTable,
+} from "@mercurjs/dashboard-shared"
+import { defineRouteConfig } from "@mercurjs/dashboard-sdk"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+
+import { useStripeJobs } from "../../../../hooks/api/stripe"
+import type { AdminPayoutJob } from "../../../../lib/client"
+import {
+ JOB_LABEL,
+ JOB_RUN_STATUS_COLOR,
+ JOB_RUN_STATUS_LABEL,
+ describeSchedule,
+ statusProps,
+} from "../../../../lib/status"
+import { SettingsProviders } from "../../../../providers/settings-providers"
+import { useRunJobAction } from "./common/use-run-job-action"
+
+const JobRowActions = ({ job }: { job: AdminPayoutJob }) => {
+ const { handleRun } = useRunJobAction(job.job)
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [{ label: "Run now", icon: <PlaySolid />, onClick: handleRun, permission: "payouts:edit" }],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<AdminPayoutJob>()
+
+const useColumns = () =>
+ useMemo(
+ () => [
+ columnHelper.accessor("job", {
+ header: () => <TextHeader text="Job" />,
+ cell: ({ getValue }) => <TextCell text={JOB_LABEL[getValue()] ?? getValue()} />,
+ }),
+ columnHelper.accessor("schedule", {
+ header: () => <TextHeader text="Schedule (UTC)" />,
+ cell: ({ getValue }) => <TextCell text={describeSchedule(getValue())} />,
+ }),
+ columnHelper.accessor((row) => row.last_run?.status ?? null, {
+ id: "last_run",
+ header: () => <TextHeader text="Last run" />,
+ cell: ({ getValue }) => {
+ if (!getValue()) {
+ return <TextCell text="-" />
+ }
+ const { color, label } = statusProps(getValue(), JOB_RUN_STATUS_COLOR, JOB_RUN_STATUS_LABEL)
+ return <StatusCell color={color}>{label}</StatusCell>
+ },
+ }),
+ columnHelper.accessor((row) => row.last_run?.started_at ?? null, {
+ id: "last_run_at",
+ header: () => <TextHeader text="Last run at" />,
+ cell: ({ getValue }) => <DateCell date={getValue()} />,
+ }),
+ columnHelper.accessor("next_run_at", {
+ header: () => <TextHeader text="Next run" />,
+ cell: ({ getValue }) => <DateCell date={getValue()} />,
+ }),
+ columnHelper.accessor("failed_count", {
+ header: () => <TextHeader text="Failing items" />,
+ cell: ({ getValue }) => <TextCell text={String(getValue())} />,
+ }),
+ columnHelper.accessor("enabled", {
+ header: () => <TextHeader text="Status" />,
+ cell: ({ getValue }) =>
+ getValue() ? <StatusCell color="green">Enabled</StatusCell> : <StatusCell color="grey">Disabled</StatusCell>,
+ }),
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => <JobRowActions job={row.original} />,
+ }),
+ ],
+ []
+ )
+
+const JobListDataTable = () => {
+ const { jobs, isPending, isError, error } = useStripeJobs()
+ const columns = useColumns()
+ const count = jobs?.length ?? 0
+
+ const { table } = useDataTable({
+ data: jobs ?? [],
+ columns,
+ count,
+ getRowId: (row) => row.job,
+ pageSize: count || 1,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count}
+ pageSize={count || 10}
+ isLoading={isPending}
+ navigateTo={(row) => `/finance/stripe/jobs/${row.original.job}`}
+ noRecords={{ message: "No Stripe jobs are registered." }}
+ />
+ )
+}
+
+const JobListPage = () => (
+ <SettingsProviders>
+ <SingleColumnPage data-testid="stripe-job-list-page">
+ <WidgetZone id="stripe.jobs.list">
+ <Container className="divide-y p-0" data-testid="stripe-job-list-table">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading data-testid="stripe-jobs-heading">Jobs</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ Scheduled jobs that sync accounts and move money through Stripe.
+ </Text>
+ </div>
+ </div>
+ <JobListDataTable />
+ </Container>
+ </WidgetZone>
+ </SingleColumnPage>
+ </SettingsProviders>
+)
+
+export const config = defineRouteConfig({
+ label: "Jobs",
+ nested: "/finance/stripe",
+ rank: 30,
+ permissions: ["payouts:view"],
+})
+
+export const handle = {
+ breadcrumb: () => "Jobs",
+ permissions: "payouts:view",
+}
+
+export default JobListPage
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/page.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/page.tsx
new file mode 100644
index 000000000..ac4d4d5b8
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/page.tsx
@@ -0,0 +1,31 @@
+import { SingleColumnPage, WidgetZone } from "@mercurjs/dashboard-shared"
+import { defineRouteConfig } from "@mercurjs/dashboard-sdk"
+
+import { StripeIcon } from "../../../components/stripe-icon"
+import { SettingsProviders } from "../../../providers/settings-providers"
+import { SettlementListTable } from "./components/settlement-list-table"
+
+const SettlementListPage = () => (
+ <SettingsProviders>
+ <SingleColumnPage data-testid="stripe-settlement-list-page">
+ <WidgetZone id="stripe.settlements.list">
+ <SettlementListTable />
+ </WidgetZone>
+ </SingleColumnPage>
+ </SettingsProviders>
+)
+
+export const config = defineRouteConfig({
+ label: "Stripe",
+ icon: StripeIcon,
+ group: "integrations",
+ rank: 30,
+ permissions: ["payouts:view"],
+})
+
+export const handle = {
+ breadcrumb: () => "Stripe",
+ permissions: "payouts:view",
+}
+
+export default SettlementListPage
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/breadcrumb.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/breadcrumb.tsx
new file mode 100644
index 000000000..d7dd2712e
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/breadcrumb.tsx
@@ -0,0 +1,15 @@
+import type { UIMatch } from "react-router-dom"
+
+import { useStripeSettlement } from "../../../../../hooks/api/stripe"
+
+export const SettlementDetailBreadcrumb = (props: UIMatch) => {
+ const { id } = props.params || {}
+
+ const { settlement } = useStripeSettlement(id!, { enabled: Boolean(id) })
+
+ if (!settlement) {
+ return null
+ }
+
+ return <span>#{settlement.display_id}</span>
+}
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-bank-payout-section.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-bank-payout-section.tsx
new file mode 100644
index 000000000..0f560886c
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-bank-payout-section.tsx
@@ -0,0 +1,28 @@
+import { Container, Heading, StatusBadge } from "@medusajs/ui"
+import { SectionRow, useDate } from "@mercurjs/dashboard-shared"
+
+import type { SettlementDetail } from "../../../../../../lib/client"
+import { PAYOUT_STATUS_COLOR, PAYOUT_STATUS_LABEL, formatSettlementPayout, statusProps } from "../../../../../../lib/status"
+
+export const SettlementBankPayoutSection = ({ settlement }: { settlement: SettlementDetail }) => {
+ const { getFullDate } = useDate()
+ const status = settlement.payout_status
+ ? statusProps(settlement.payout_status, PAYOUT_STATUS_COLOR, PAYOUT_STATUS_LABEL)
+ : null
+
+ return (
+ <Container className="divide-y p-0" data-testid="stripe-settlement-bank-payout-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2" data-testid="stripe-settlement-bank-payout-heading">
+ Bank payout
+ </Heading>
+ {status ? <StatusBadge color={status.color}>{status.label}</StatusBadge> : null}
+ </div>
+ {settlement.payout_amount != null ? (
+ <SectionRow title="Paid out" value={formatSettlementPayout(settlement)} />
+ ) : null}
+ <SectionRow title="Stripe payout" value={settlement.provider_payout_id ?? "-"} />
+ <SectionRow title="Updated" value={getFullDate({ date: settlement.updated_at, includeTime: true })} />
+ </Container>
+ )
+}
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-general-section.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-general-section.tsx
new file mode 100644
index 000000000..1969d57e0
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-general-section.tsx
@@ -0,0 +1,80 @@
+import { ArrowPath } from "@medusajs/icons"
+import { Container, Heading, StatusBadge, toast, usePrompt } from "@medusajs/ui"
+import { ActionMenu, SectionRow, getStylizedAmount, useDate } from "@mercurjs/dashboard-shared"
+
+import { useRetrySettlementPayout } from "../../../../../../hooks/api/stripe"
+import type { SettlementDetail } from "../../../../../../lib/client"
+import {
+ RETRYABLE_STATUSES,
+ SETTLEMENT_STATUS_COLOR,
+ SETTLEMENT_STATUS_LABEL,
+ formatSettlementPayout,
+ statusProps,
+ toNumber,
+} from "../../../../../../lib/status"
+
+export const SettlementGeneralSection = ({ settlement }: { settlement: SettlementDetail }) => {
+ const prompt = usePrompt()
+ const { getFullDate } = useDate()
+ const { mutateAsync } = useRetrySettlementPayout(settlement.id)
+
+ const status = statusProps(settlement.status, SETTLEMENT_STATUS_COLOR, SETTLEMENT_STATUS_LABEL)
+ const canRetry = !!settlement.payout_status && RETRYABLE_STATUSES.includes(settlement.payout_status)
+ const amount = (value: unknown) => getStylizedAmount(toNumber(value), settlement.currency_code)
+
+ const handleRetry = async () => {
+ const confirmed = await prompt({
+ title: "Retry bank payout?",
+ description: `Stripe will be asked again to pay ${formatSettlementPayout(settlement)} to the store's bank account.`,
+ confirmText: "Retry",
+ cancelText: "Cancel",
+ })
+
+ if (!confirmed) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => toast.success("Bank payout retried"),
+ onError: (error) => toast.error(error.message),
+ })
+ }
+
+ return (
+ <Container className="divide-y p-0" data-testid="stripe-settlement-general-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading data-testid="stripe-settlement-heading">Settlement #{settlement.display_id}</Heading>
+ <div className="flex items-center gap-x-2">
+ <StatusBadge color={status.color}>{status.label}</StatusBadge>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: "Retry bank payout",
+ icon: <ArrowPath />,
+ onClick: handleRetry,
+ permission: "payouts:edit",
+ disabled: !canRetry,
+ disabledTooltip: "Only failed, held or pending bank payouts can be retried",
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ </div>
+ <SectionRow
+ title="Period"
+ value={`${getFullDate({ date: settlement.period_start, includeTime: true })} – ${getFullDate({
+ date: settlement.period_end,
+ includeTime: true,
+ })}`}
+ />
+ <SectionRow title="Payouts" value={amount(settlement.payouts_total)} />
+ <SectionRow title="Reversals" value={amount(-toNumber(settlement.reversals_total))} />
+ <SectionRow title="Adjustments" value={amount(settlement.adjustments_total)} />
+ <SectionRow title="Net amount" value={amount(settlement.amount)} />
+ </Container>
+ )
+}
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-lines-section.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-lines-section.tsx
new file mode 100644
index 000000000..35fc4e043
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-lines-section.tsx
@@ -0,0 +1,120 @@
+import { Container, Heading } from "@medusajs/ui"
+import {
+ MoneyAmountCell,
+ StatusCell,
+ TextCell,
+ TextHeader,
+ _DataTable,
+ useDataTable,
+} from "@mercurjs/dashboard-shared"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+
+import {
+ ADJUSTMENT_TYPE_LABEL,
+ PAYOUT_STATUS_COLOR,
+ PAYOUT_STATUS_LABEL,
+ statusProps,
+ toNumber,
+} from "../../../../../../lib/status"
+
+export type SettlementLine = {
+ id: string
+ amount: unknown
+ status: string | null
+ reference: string | null
+ order_id?: string | null
+ order_display_id?: number | null
+ type?: string
+ reason?: string | null
+}
+
+type SettlementLinesSectionProps = {
+ title: string
+ currencyCode: string
+ lines: SettlementLine[]
+ emptyMessage: string
+ testId: string
+}
+
+const columnHelper = createColumnHelper<SettlementLine>()
+
+const useColumns = (currencyCode: string) =>
+ useMemo(
+ () => [
+ columnHelper.accessor("id", {
+ header: () => <TextHeader text="Reference" />,
+ cell: ({ row }) => {
+ const line = row.original
+ if (line.order_id) {
+ return <TextCell text={`Order #${line.order_display_id ?? line.order_id}`} />
+ }
+ return <TextCell text={line.type ? ADJUSTMENT_TYPE_LABEL[line.type] ?? line.type : line.id} />
+ },
+ }),
+ columnHelper.accessor((row) => row.reason ?? row.reference ?? "", {
+ id: "details",
+ header: () => <TextHeader text="Details" />,
+ cell: ({ getValue }) => <TextCell text={getValue() || "-"} />,
+ }),
+ columnHelper.accessor("status", {
+ header: () => <TextHeader text="Status" />,
+ cell: ({ getValue }) => {
+ if (!getValue()) {
+ return <TextCell text="-" />
+ }
+ const { color, label } = statusProps(getValue(), PAYOUT_STATUS_COLOR, PAYOUT_STATUS_LABEL)
+ return <StatusCell color={color}>{label}</StatusCell>
+ },
+ }),
+ columnHelper.accessor("amount", {
+ header: () => (
+ <div className="flex h-full w-full items-center justify-end">
+ <span className="truncate">Amount</span>
+ </div>
+ ),
+ cell: ({ getValue }) => (
+ <MoneyAmountCell amount={toNumber(getValue())} currencyCode={currencyCode} align="right" />
+ ),
+ }),
+ ],
+ [currencyCode]
+ )
+
+export const SettlementLinesSection = ({
+ title,
+ currencyCode,
+ lines,
+ emptyMessage,
+ testId,
+}: SettlementLinesSectionProps) => {
+ const columns = useColumns(currencyCode)
+
+ const { table } = useDataTable({
+ data: lines,
+ columns,
+ count: lines.length,
+ getRowId: (row) => row.id,
+ pageSize: Math.max(lines.length, 1),
+ })
+
+ return (
+ <Container className="divide-y p-0" data-testid={testId}>
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2" data-testid={`${testId}-heading`}>
+ {title}
+ </Heading>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={lines.length}
+ pageSize={Math.max(lines.length, 1)}
+ navigateTo={
+ lines.every((line) => line.order_id) ? (row) => `/orders/${row.original.order_id}` : undefined
+ }
+ noRecords={{ message: emptyMessage }}
+ />
+ </Container>
+ )
+}
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-status-alert.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-status-alert.tsx
new file mode 100644
index 000000000..2c05545e4
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-status-alert.tsx
@@ -0,0 +1,17 @@
+import { Alert } from "@medusajs/ui"
+
+import type { SettlementDetail } from "../../../../../../lib/client"
+
+export const SettlementStatusAlert = ({ settlement }: { settlement: SettlementDetail }) => {
+ if (!settlement.status_reason) {
+ return null
+ }
+
+ const variant = settlement.status === "failed" || settlement.payout_status === "failed" ? "error" : "warning"
+
+ return (
+ <Alert variant={variant} data-testid="stripe-settlement-status-alert">
+ {settlement.status_reason}
+ </Alert>
+ )
+}
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-store-section.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-store-section.tsx
new file mode 100644
index 000000000..39bcaab6b
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/components/settlement-store-section.tsx
@@ -0,0 +1,34 @@
+import { BuildingStorefront } from "@medusajs/icons"
+import { Container, Heading, Text } from "@medusajs/ui"
+import { SidebarLink } from "@mercurjs/dashboard-shared"
+
+import type { SettlementDetail } from "../../../../../../lib/client"
+
+export const SettlementStoreSection = ({ settlement }: { settlement: SettlementDetail }) => {
+ const seller = settlement.payout_account?.seller
+
+ return (
+ <Container className="p-0" data-testid="stripe-settlement-store-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2" data-testid="stripe-settlement-store-heading">
+ Store
+ </Heading>
+ </div>
+ {seller ? (
+ <SidebarLink
+ to={`/stores/${seller.id}`}
+ labelKey={seller.name}
+ descriptionKey={seller.handle}
+ icon={<BuildingStorefront />}
+ dataTestid="stripe-settlement-store-link"
+ />
+ ) : (
+ <div className="border-t px-6 py-4">
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ The store was removed
+ </Text>
+ </div>
+ )}
+ </Container>
+ )
+}
diff --git a/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/page.tsx b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/page.tsx
new file mode 100644
index 000000000..56a2c9b77
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/finance/stripe/settlements/[id]/page.tsx
@@ -0,0 +1,107 @@
+import { TwoColumnPage, TwoColumnPageSkeleton, WidgetZone } from "@mercurjs/dashboard-shared"
+import { useParams, type UIMatch } from "react-router-dom"
+
+import { useStripeSettlement } from "../../../../../hooks/api/stripe"
+import { providerIdOf } from "../../../../../../lib/provider-data"
+import { SettlementLineType } from "../../../../../../types/common"
+import { SettingsProviders } from "../../../../../providers/settings-providers"
+import { SettlementDetailBreadcrumb } from "./breadcrumb"
+import { SettlementBankPayoutSection } from "./components/settlement-bank-payout-section"
+import { SettlementGeneralSection } from "./components/settlement-general-section"
+import { SettlementLinesSection } from "./components/settlement-lines-section"
+import { SettlementStatusAlert } from "./components/settlement-status-alert"
+import { SettlementStoreSection } from "./components/settlement-store-section"
+
+const SettlementDetail = () => {
+ const { id } = useParams()
+ const { settlement, isLoading, isError, error } = useStripeSettlement(id!)
+
+ if (isError) {
+ throw error
+ }
+
+ if (isLoading || !settlement) {
+ return <TwoColumnPageSkeleton mainSections={4} sidebarSections={2} showJSON />
+ }
+
+ const lines = settlement.lines ?? []
+ const ofType = (...types: SettlementLineType[]) => lines.filter((line) => types.includes(line.type))
+
+ const payouts = ofType(SettlementLineType.PAYOUT).map((line) => ({
+ id: line.id,
+ amount: line.amount,
+ status: line.payout?.status ?? null,
+ reference: providerIdOf(line.payout?.data),
+ order_id: line.payout?.order_id ?? null,
+ order_display_id: line.payout?.order?.display_id ?? null,
+ }))
+
+ const reversals = ofType(SettlementLineType.REVERSAL).map((line) => ({
+ id: line.id,
+ amount: -Number(line.amount),
+ status: line.payout_reversal?.status ?? null,
+ reference: providerIdOf(line.payout_reversal?.data),
+ order_id: line.payout_reversal?.payout?.order_id ?? null,
+ order_display_id: line.payout_reversal?.payout?.order?.display_id ?? null,
+ }))
+
+ const adjustments = ofType(SettlementLineType.ADJUSTMENT_CREDIT, SettlementLineType.ADJUSTMENT_DEBIT).map((line) => ({
+ id: line.id,
+ amount: line.type === SettlementLineType.ADJUSTMENT_CREDIT ? line.amount : -Number(line.amount),
+ status: line.adjustment?.status ?? null,
+ reference: line.adjustment?.provider_transfer_id ?? null,
+ reason: line.adjustment?.reason ?? null,
+ type: line.adjustment?.type,
+ }))
+
+ return (
+ <TwoColumnPage data={settlement} showJSON>
+ <TwoColumnPage.Main>
+ <WidgetZone id="stripe.settlements.detail.main" data={settlement}>
+ <SettlementStatusAlert settlement={settlement} />
+ <SettlementGeneralSection settlement={settlement} />
+ <SettlementLinesSection
+ title="Payouts"
+ currencyCode={settlement.currency_code}
+ lines={payouts}
+ emptyMessage="No payouts landed in this period."
+ testId="stripe-settlement-payouts"
+ />
+ <SettlementLinesSection
+ title="Reversals"
+ currencyCode={settlement.currency_code}
+ lines={reversals}
+ emptyMessage="No refunds were reversed in this period."
+ testId="stripe-settlement-reversals"
+ />
+ <SettlementLinesSection
+ title="Adjustments"
+ currencyCode={settlement.currency_code}
+ lines={adjustments}
+ emptyMessage="No adjustments were applied in this period."
+ testId="stripe-settlement-adjustments"
+ />
+ </WidgetZone>
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <WidgetZone id="stripe.settlements.detail.side" data={settlement}>
+ <SettlementStoreSection settlement={settlement} />
+ <SettlementBankPayoutSection settlement={settlement} />
+ </WidgetZone>
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
+ )
+}
+
+const SettlementDetailPage = () => (
+ <SettingsProviders>
+ <SettlementDetail />
+ </SettingsProviders>
+)
+
+export const handle = {
+ breadcrumb: (match: UIMatch) => <SettlementDetailBreadcrumb {...match} />,
+ permissions: "payouts:view",
+}
+
+export default SettlementDetailPage
diff --git a/packages/plugins/stripe-connector/src/admin/routes/settings/stripe/@map-account/page.tsx b/packages/plugins/stripe-connector/src/admin/routes/settings/stripe/@map-account/page.tsx
new file mode 100644
index 000000000..7e7411a82
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/settings/stripe/@map-account/page.tsx
@@ -0,0 +1,103 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Heading, Input, toast } from "@medusajs/ui"
+import { Form, KeyboundForm, RouteDrawer, useRouteModal } from "@mercurjs/dashboard-shared"
+import { useForm } from "react-hook-form"
+import * as zod from "zod"
+
+import { SellerCombobox } from "../../../../components/seller-combobox"
+import { useMapStripeAccount } from "../../../../hooks/api/stripe"
+import { SettingsProviders } from "../../../../providers/settings-providers"
+
+const MapAccountSchema = zod.object({
+ seller_id: zod.string().min(1, "Select a store"),
+ external_id: zod.string().regex(/^acct_\w+$/, "Enter a Stripe account ID, e.g. acct_1Nv0FGQ9RKHgCVdK"),
+})
+
+type MapAccountSchemaType = zod.infer<typeof MapAccountSchema>
+
+const MapAccountForm = () => {
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<MapAccountSchemaType>({
+ defaultValues: { seller_id: "", external_id: "" },
+ resolver: zodResolver(MapAccountSchema),
+ })
+
+ const { mutateAsync, isPending } = useMapStripeAccount()
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(data, {
+ onSuccess: ({ payout_account }) => {
+ toast.success("Account mapped")
+ handleSuccess(`/payout-accounts/${payout_account.id}`)
+ },
+ onError: (error) => toast.error(error.message),
+ })
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex flex-1 flex-col overflow-hidden">
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-4 overflow-y-auto">
+ <Form.Field
+ control={form.control}
+ name="seller_id"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Label>Store</Form.Label>
+ <Form.Control>
+ <SellerCombobox {...field} data-testid="stripe-map-account-store-input" />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="external_id"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Label>Stripe account ID</Form.Label>
+ <Form.Control>
+ <Input placeholder="acct_..." autoComplete="off" data-testid="stripe-map-account-id-input" {...field} />
+ </Form.Control>
+ <Form.Hint>A connected account that already exists in your Stripe platform.</Form.Hint>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary" data-testid="stripe-map-account-cancel-button">
+ Cancel
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending} data-testid="stripe-map-account-save-button">
+ Save
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
+
+const MapAccountPage = () => (
+ <SettingsProviders>
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading data-testid="stripe-map-account-heading">Map existing account</Heading>
+ </RouteDrawer.Title>
+ <RouteDrawer.Description className="sr-only">
+ Attach a connected account that already exists in Stripe to a store.
+ </RouteDrawer.Description>
+ </RouteDrawer.Header>
+ <MapAccountForm />
+ </RouteDrawer>
+ </SettingsProviders>
+)
+
+export default MapAccountPage
diff --git a/packages/plugins/stripe-connector/src/admin/routes/settings/stripe/page.tsx b/packages/plugins/stripe-connector/src/admin/routes/settings/stripe/page.tsx
new file mode 100644
index 000000000..1da0e81f9
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/routes/settings/stripe/page.tsx
@@ -0,0 +1,259 @@
+import { Link as LinkIcon, PaperPlane } from "@medusajs/icons"
+import { Container, Heading, StatusBadge, Text, toast } from "@medusajs/ui"
+import {
+ ActionMenu,
+ DateCell,
+ SectionRow,
+ SingleColumnPage,
+ SingleColumnPageSkeleton,
+ StatusCell,
+ TextCell,
+ TextHeader,
+ WidgetZone,
+ _DataTable,
+ useDataTable,
+ useDate,
+} from "@mercurjs/dashboard-shared"
+import { defineRouteConfig } from "@mercurjs/dashboard-sdk"
+import { keepPreviousData } from "@tanstack/react-query"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+
+import { useSendTestNotification, useStripeNotifications, useStripeStatus } from "../../../hooks/api/stripe"
+import { PAGE_SIZE, useStripeTableQuery } from "../../../hooks/use-stripe-table-query"
+import type { AdminPayoutStatusResponse, NotificationRow } from "../../../lib/client"
+import { StripeIcon } from "../../../components/stripe-icon"
+import { SettingsProviders } from "../../../providers/settings-providers"
+
+const PAYOUT_EVENTS = [
+ "account.updated",
+ "payout.paid",
+ "payout.failed",
+ "payout.canceled",
+ "payout.updated",
+]
+const PAYMENT_EVENTS = [
+ "payment_intent.succeeded",
+ "payment_intent.amount_capturable_updated",
+ "payment_intent.payment_failed",
+ "payment_intent.canceled",
+ "charge.refunded",
+]
+
+type StripeOptions = { notifications?: { url?: string } }
+
+type StripeGeneralSectionProps = {
+ configured: boolean
+ lastWebhookAt: AdminPayoutStatusResponse["last_webhook_at"]
+ notificationUrl?: string
+}
+
+const StripeGeneralSection = ({ configured, lastWebhookAt, notificationUrl }: StripeGeneralSectionProps) => {
+ const { getFullDate } = useDate()
+ const { mutateAsync } = useSendTestNotification()
+
+ const handleTest = async () => {
+ await mutateAsync(undefined, {
+ onSuccess: () => toast.success("Test notification sent"),
+ onError: (error) => toast.error(error.message),
+ })
+ }
+
+ return (
+ <Container className="divide-y p-0" data-testid="stripe-settings-general-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading data-testid="stripe-settings-general-heading">Stripe</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ Card payments and payouts to stores through Stripe Connect.
+ </Text>
+ </div>
+ <div className="flex items-center gap-x-2">
+ <StatusBadge color={configured ? "green" : "orange"}>
+ {configured ? "Connected" : "Not configured"}
+ </StatusBadge>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: "Map existing account",
+ icon: <LinkIcon />,
+ to: "map-account",
+ permission: "payouts:edit",
+ },
+ {
+ label: "Send test notification",
+ icon: <PaperPlane />,
+ onClick: handleTest,
+ permission: "payouts:edit",
+ disabled: !notificationUrl,
+ disabledTooltip: "Set notifications.url in the plugin options first",
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ </div>
+ <SectionRow
+ title="API key"
+ value={configured ? "Set in the plugin options" : "Missing from the plugin options"}
+ />
+ <SectionRow
+ title="Last webhook"
+ value={lastWebhookAt ? getFullDate({ date: lastWebhookAt, includeTime: true }) : "-"}
+ />
+ </Container>
+ )
+}
+
+const StripeWebhooksSection = () => {
+ const backend = import.meta.env.VITE_MERCUR_BACKEND_URL || "http://localhost:9000"
+
+ return (
+ <Container className="divide-y p-0" data-testid="stripe-settings-webhooks-section">
+ <div className="px-6 py-4">
+ <Heading level="h2" data-testid="stripe-settings-webhooks-heading">
+ Webhooks
+ </Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ Register both endpoints in the Stripe dashboard.
+ </Text>
+ </div>
+ <SectionRow title="Connect endpoint" value={<code className="txt-compact-small select-all">{`${backend}/hooks/payout`}</code>} />
+ <SectionRow title="Connect events" value={PAYOUT_EVENTS.join(", ")} />
+ <SectionRow
+ title="Payment endpoint"
+ value={<code className="txt-compact-small select-all">{`${backend}/hooks/payment/pp_stripe-connector_stripe`}</code>}
+ />
+ <SectionRow title="Payment events" value={PAYMENT_EVENTS.join(", ")} />
+ </Container>
+ )
+}
+
+const columnHelper = createColumnHelper<NotificationRow>()
+
+const useNotificationColumns = () =>
+ useMemo(
+ () => [
+ columnHelper.accessor("created_at", {
+ header: () => <TextHeader text="Sent" />,
+ cell: ({ getValue }) => <DateCell date={getValue()} />,
+ }),
+ columnHelper.accessor("type", {
+ header: () => <TextHeader text="Type" />,
+ cell: ({ getValue }) => <TextCell text={getValue()} />,
+ }),
+ columnHelper.accessor("attempts", {
+ header: () => <TextHeader text="Attempts" />,
+ cell: ({ getValue }) => <TextCell text={String(getValue())} />,
+ }),
+ columnHelper.accessor("delivered", {
+ header: () => <TextHeader text="Status" />,
+ cell: ({ row }) =>
+ row.original.delivered ? (
+ <StatusCell color="green">Delivered</StatusCell>
+ ) : (
+ <StatusCell color="red">Failed</StatusCell>
+ ),
+ }),
+ columnHelper.accessor((row) => row.error ?? (row.response_status ? String(row.response_status) : ""), {
+ id: "response",
+ header: () => <TextHeader text="Response" />,
+ cell: ({ getValue }) => <TextCell text={getValue() || "-"} />,
+ }),
+ ],
+ []
+ )
+
+const StripeNotificationsSection = ({ url }: { url?: string }) => {
+ const { searchParams, raw } = useStripeTableQuery()
+ const { notifications, count, isPending, isError, error } = useStripeNotifications(searchParams, {
+ placeholderData: keepPreviousData,
+ })
+
+ const columns = useNotificationColumns()
+
+ const { table } = useDataTable({
+ data: notifications ?? [],
+ columns,
+ count: count ?? 0,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0" data-testid="stripe-settings-notifications-section">
+ <div className="px-6 py-4">
+ <Heading level="h2" data-testid="stripe-settings-notifications-heading">
+ Notifications
+ </Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {url ? `Failed payouts, reversals and settlements are posted to ${url}.` : "No notification URL is set in the plugin options."}
+ </Text>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count ?? 0}
+ pageSize={PAGE_SIZE}
+ isLoading={isPending}
+ queryObject={raw}
+ pagination
+ noRecords={{ message: "A notification is sent when a payout, reversal or settlement fails." }}
+ />
+ </Container>
+ )
+}
+
+const StripeSettings = () => {
+ const { configured, options, last_webhook_at, isPending, isError, error } = useStripeStatus()
+
+ if (isError) {
+ throw error
+ }
+
+ if (isPending || !options) {
+ return <SingleColumnPageSkeleton sections={3} />
+ }
+
+ const notificationUrl = (options as StripeOptions).notifications?.url
+
+ return (
+ <SingleColumnPage hasOutlet data={options} showJSON data-testid="stripe-settings-page">
+ <WidgetZone id="stripe.settings" data={options}>
+ <StripeGeneralSection
+ configured={!!configured}
+ lastWebhookAt={last_webhook_at ?? null}
+ notificationUrl={notificationUrl}
+ />
+ <StripeWebhooksSection />
+ <StripeNotificationsSection url={notificationUrl} />
+ </WidgetZone>
+ </SingleColumnPage>
+ )
+}
+
+const StripeSettingsPage = () => (
+ <SettingsProviders>
+ <StripeSettings />
+ </SettingsProviders>
+)
+
+export const config = defineRouteConfig({
+ label: "Stripe",
+ icon: StripeIcon,
+ group: "integrations",
+ rank: 110,
+ permissions: ["payouts:view"],
+})
+
+export const handle = { breadcrumb: () => "Stripe", permissions: "payouts:view" }
+
+export default StripeSettingsPage
diff --git a/packages/plugins/stripe-connector/src/admin/tsconfig.json b/packages/plugins/stripe-connector/src/admin/tsconfig.json
new file mode 100644
index 000000000..89f49d8ea
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ES2021",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "jsx": "react-jsx",
+ "lib": ["ES2021", "DOM"],
+ "strict": true,
+ "strictNullChecks": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "noEmit": true,
+ "resolveJsonModule": true
+ },
+ "include": ["./**/*", "./vite-env.d.ts"],
+ "exclude": ["node_modules"]
+}
diff --git a/packages/plugins/stripe-connector/src/admin/vite-env.d.ts b/packages/plugins/stripe-connector/src/admin/vite-env.d.ts
new file mode 100644
index 000000000..a7707bed6
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/vite-env.d.ts
@@ -0,0 +1,7 @@
+interface ImportMetaEnv {
+ readonly VITE_MERCUR_BACKEND_URL?: string
+}
+
+interface ImportMeta {
+ readonly env: ImportMetaEnv
+}
diff --git a/packages/plugins/stripe-connector/src/admin/widgets/stripe-order-transfer.tsx b/packages/plugins/stripe-connector/src/admin/widgets/stripe-order-transfer.tsx
new file mode 100644
index 000000000..7bbc5a067
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/widgets/stripe-order-transfer.tsx
@@ -0,0 +1,187 @@
+import { defineWidgetConfig } from "@mercurjs/dashboard-sdk"
+import type { DetailWidgetProps } from "@medusajs/framework/types"
+import { ArrowPath } from "@medusajs/icons"
+import { Container, Heading, StatusBadge, Text, toast, usePrompt } from "@medusajs/ui"
+import { ActionMenu, getStylizedAmount, useDate } from "@mercurjs/dashboard-shared"
+import { Link } from "react-router-dom"
+
+import { useRetryPayout, useStripePayouts } from "../hooks/api/stripe"
+import type { PayoutRow } from "../lib/client"
+import {
+ PAYOUT_STATUS_COLOR,
+ PAYOUT_STATUS_LABEL,
+ RETRYABLE_STATUSES,
+ payoutStatusDetail,
+ payoutStatusReasonLabel,
+ statusProps,
+ toNumber,
+} from "../lib/status"
+import { SettingsProviders } from "../providers/settings-providers"
+
+type Line = {
+ id: string
+ title: string
+ link: string | null
+ date: Date | string
+ amount: number
+ currency_code: string
+ status: string
+ status_reason: string | null
+ status_detail: string | null
+ retry_id: string | null
+}
+
+const toLines = (payouts: PayoutRow[]): Line[] =>
+ payouts.flatMap((payout) => [
+ {
+ id: payout.id,
+ title: `Payout #${payout.display_id}`,
+ link: `/payouts/${payout.id}`,
+ date: payout.created_at,
+ amount: toNumber(payout.amount),
+ currency_code: payout.currency_code,
+ status: payout.status,
+ status_reason: payout.status_reason,
+ status_detail: payoutStatusDetail(payout.data),
+ retry_id: RETRYABLE_STATUSES.includes(payout.status) ? payout.id : null,
+ },
+ ...(payout.reversals ?? []).map((reversal) => ({
+ id: reversal.id,
+ title: "Reversal",
+ link: null,
+ date: reversal.created_at,
+ amount: -toNumber(reversal.amount),
+ currency_code: payout.currency_code,
+ status: reversal.status,
+ status_reason: reversal.status_reason,
+ status_detail: payoutStatusDetail(reversal.data),
+ retry_id: null,
+ })),
+ ])
+
+const LineRow = ({ line }: { line: Line }) => {
+ const { getFullDate } = useDate()
+ const prompt = usePrompt()
+ const { mutateAsync } = useRetryPayout()
+ const status = statusProps(line.status, PAYOUT_STATUS_COLOR, PAYOUT_STATUS_LABEL)
+
+ const handleRetry = async () => {
+ const confirmed = await prompt({
+ title: "Retry payout?",
+ description: "The payout is sent to Stripe again.",
+ confirmText: "Retry",
+ cancelText: "Cancel",
+ })
+
+ if (!confirmed || !line.retry_id) {
+ return
+ }
+
+ await mutateAsync(line.retry_id, {
+ onSuccess: () => toast.success("Payout retried"),
+ onError: (error) => toast.error(error.message),
+ })
+ }
+
+ return (
+ <div className="flex flex-col gap-y-2 px-6 py-4" data-testid={`stripe-order-payout-${line.id}`}>
+ <div className="flex items-start justify-between gap-x-4">
+ <div className="flex min-w-0 flex-col">
+ {line.link ? (
+ <Link
+ to={line.link}
+ className="txt-compact-small-plus text-ui-fg-base hover:text-ui-fg-interactive transition-fg"
+ >
+ {line.title}
+ </Link>
+ ) : (
+ <Text size="small" leading="compact" weight="plus">
+ {line.title}
+ </Text>
+ )}
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ {getFullDate({ date: line.date, includeTime: true })}
+ </Text>
+ </div>
+ <div className="flex shrink-0 items-center gap-x-2">
+ <Text size="small" leading="compact">
+ {getStylizedAmount(line.amount, line.currency_code)}
+ </Text>
+ <StatusBadge color={status.color}>{status.label}</StatusBadge>
+ {line.retry_id ? (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ { label: "Retry", icon: <ArrowPath />, onClick: handleRetry, permission: "payouts:edit" },
+ ],
+ },
+ ]}
+ />
+ ) : null}
+ </div>
+ </div>
+ {line.status_reason ? (
+ <div className="flex flex-col gap-y-1">
+ <Text size="small" leading="compact" className="text-ui-fg-subtle break-words">
+ {payoutStatusReasonLabel(line.status_reason)}
+ </Text>
+ {line.status_detail ? (
+ <Text size="xsmall" leading="compact" className="text-ui-fg-muted break-words">
+ {line.status_detail}
+ </Text>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ )
+}
+
+const Body = ({ orderId }: { orderId: string }) => {
+ const { payouts, isPending } = useStripePayouts({ limit: 20, offset: 0, order_id: orderId })
+
+ if (isPending) {
+ return null
+ }
+
+ const lines = toLines((payouts ?? []) as PayoutRow[])
+
+ return (
+ <Container className="divide-y p-0" data-testid="stripe-order-transfers">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2" data-testid="stripe-order-transfers-heading">
+ Stripe payouts
+ </Heading>
+ </div>
+ {lines.length ? (
+ lines.map((line) => <LineRow key={line.id} line={line} />)
+ ) : (
+ <div className="px-6 py-4">
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ No payout yet
+ </Text>
+ </div>
+ )}
+ </Container>
+ )
+}
+
+const StripeOrderTransferWidget = ({ data }: DetailWidgetProps<{ id?: string }>) => {
+ if (!data?.id) {
+ return null
+ }
+
+ return (
+ <SettingsProviders>
+ <Body orderId={data.id} />
+ </SettingsProviders>
+ )
+}
+
+export const config = defineWidgetConfig({
+ zone: "orders.detail.side",
+ id: "stripe-order-transfer",
+ permission: "payouts:view",
+})
+
+export default StripeOrderTransferWidget
diff --git a/packages/plugins/stripe-connector/src/admin/widgets/stripe-payout-account.tsx b/packages/plugins/stripe-connector/src/admin/widgets/stripe-payout-account.tsx
new file mode 100644
index 000000000..648a53b23
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/admin/widgets/stripe-payout-account.tsx
@@ -0,0 +1,118 @@
+import { defineWidgetConfig } from "@mercurjs/dashboard-sdk"
+import type { DetailWidgetProps } from "@medusajs/framework/types"
+import { Eye, EyeSlash, OpenRectArrowOut } from "@medusajs/icons"
+import { Badge, Container, Heading, StatusBadge, Text, toast } from "@medusajs/ui"
+import { ActionMenu, SectionRow } from "@mercurjs/dashboard-shared"
+
+import { useIgnoreStripeAccount, useStripeAccount } from "../hooks/api/stripe"
+import { isIgnored, type PayoutAccountRow } from "../lib/client"
+import { disabledReasonLabel, humanizeRequirement, stripeRequirementsOf } from "../lib/status"
+import { SettingsProviders } from "../providers/settings-providers"
+
+const Requirements = ({ items }: { items: string[] }) =>
+ items.length ? (
+ <div className="flex flex-wrap gap-1">
+ {items.map((item) => (
+ <Badge key={item} size="2xsmall" title={item}>
+ {humanizeRequirement(item)}
+ </Badge>
+ ))}
+ </div>
+ ) : (
+ "-"
+ )
+
+const StripeAccountSection = ({ account }: { account: PayoutAccountRow }) => {
+ const ignore = useIgnoreStripeAccount(account.id)
+
+ const ignored = isIgnored(account)
+ const requirements = stripeRequirementsOf(account.data)
+
+ const notify = (message: string) => ({
+ onSuccess: () => toast.success(message),
+ onError: (error: Error) => toast.error(error.message),
+ })
+
+ return (
+ <Container className="divide-y p-0" data-testid="stripe-payout-account-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading level="h2" data-testid="stripe-payout-account-heading">
+ Stripe
+ </Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ Connected account and what Stripe still needs from the store.
+ </Text>
+ </div>
+ <div className="flex items-center gap-x-2">
+ {ignored ? <StatusBadge color="grey">Ignored</StatusBadge> : null}
+ <ActionMenu
+ groups={[
+ {
+ actions: account.external_id
+ ? [
+ {
+ label: "Open in Stripe",
+ icon: <OpenRectArrowOut />,
+ onClick: () =>
+ window.open(`https://dashboard.stripe.com/connect/accounts/${account.external_id}`, "_blank"),
+ },
+ ]
+ : [],
+ },
+ {
+ actions: [
+ {
+ label: ignored ? "Stop ignoring" : "Ignore store",
+ icon: ignored ? <Eye /> : <EyeSlash />,
+ onClick: () =>
+ ignore.mutate(!ignored, notify(ignored ? "Store is no longer ignored" : "Store ignored")),
+ permission: "payouts:edit",
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ </div>
+ <SectionRow title="Account ID" value={account.external_id ?? "-"} />
+ <SectionRow
+ title="Stripe reason"
+ value={account.disabled_reason ? disabledReasonLabel(account.disabled_reason) : "-"}
+ />
+ <SectionRow title="Currently due" value={<Requirements items={requirements.currently_due} />} />
+ <SectionRow title="Past due" value={<Requirements items={requirements.past_due} />} />
+ <SectionRow title="Pending verification" value={<Requirements items={requirements.pending_verification} />} />
+ </Container>
+ )
+}
+
+const Body = ({ id }: { id: string }) => {
+ const { payout_account } = useStripeAccount(id)
+
+ if (!payout_account) {
+ return null
+ }
+
+ return <StripeAccountSection account={payout_account as PayoutAccountRow} />
+}
+
+const StripePayoutAccountWidget = ({ data }: DetailWidgetProps<{ id?: string }>) => {
+ if (!data?.id) {
+ return null
+ }
+
+ return (
+ <SettingsProviders>
+ <Body id={data.id} />
+ </SettingsProviders>
+ )
+}
+
+export const config = defineWidgetConfig({
+ zone: "payout_accounts.detail.side",
+ id: "stripe-payout-account",
+ permission: "payouts:view",
+})
+
+export default StripePayoutAccountWidget
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/accounts/[id]/ignore/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/accounts/[id]/ignore/route.ts
new file mode 100644
index 000000000..c8421a6a1
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/accounts/[id]/ignore/route.ts
@@ -0,0 +1,24 @@
+import { AuthenticatedMedusaRequest, MedusaResponse, refetchEntity } from "@medusajs/framework/http"
+
+import { AdminPayoutAccountResponse } from "../../../../../../types/http"
+import { ignorePayoutAccountWorkflow } from "../../../../../../workflows/accounts/workflows/ignore-payout-account"
+import { AdminIgnoreAccountType } from "../../../../validators"
+
+/** Ignored sellers keep their payout account, but the transfers job never pays their orders out. */
+export const POST = async (
+ req: AuthenticatedMedusaRequest<AdminIgnoreAccountType>,
+ res: MedusaResponse<AdminPayoutAccountResponse>
+) => {
+ await ignorePayoutAccountWorkflow(req.scope).run({
+ input: { id: req.params.id, ignored: req.validatedBody.ignored },
+ })
+
+ const payout_account = await refetchEntity({
+ entity: "payout_account",
+ idOrFilter: req.params.id,
+ scope: req.scope,
+ fields: req.queryConfig.fields,
+ })
+
+ res.json({ payout_account } as AdminPayoutAccountResponse)
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/accounts/query-config.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/accounts/query-config.ts
new file mode 100644
index 000000000..6ed047ecc
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/accounts/query-config.ts
@@ -0,0 +1,6 @@
+export const adminStripeAccountQueryConfig = {
+ retrieve: {
+ defaults: ["*", "seller.id", "seller.name", "seller.handle", "seller.metadata"],
+ isList: false,
+ },
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/adjustments/query-config.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/adjustments/query-config.ts
new file mode 100644
index 000000000..f15549e6d
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/adjustments/query-config.ts
@@ -0,0 +1,23 @@
+export const adminAdjustmentFields = [
+ "id",
+ "account_id",
+ "type",
+ "amount",
+ "currency_code",
+ "reason",
+ "created_by",
+ "status",
+ "status_reason",
+ "provider_transfer_id",
+ "created_at",
+ "updated_at",
+ "payout_account.id",
+ "payout_account.seller.id",
+ "payout_account.seller.name",
+ "payout_account.seller.handle",
+]
+
+export const adminAdjustmentQueryConfig = {
+ list: { defaults: adminAdjustmentFields, isList: true, defaultLimit: 20 },
+ retrieve: { defaults: adminAdjustmentFields, isList: false },
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/adjustments/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/adjustments/route.ts
new file mode 100644
index 000000000..4ede232be
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/adjustments/route.ts
@@ -0,0 +1,44 @@
+import { AuthenticatedMedusaRequest, MedusaResponse, refetchEntity } from "@medusajs/framework/http"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+import { AdjustmentDTO } from "../../../../types/common"
+import { AdminAdjustmentListResponse, AdminAdjustmentResponse } from "../../../../types/http"
+import { createAdjustmentsWorkflow } from "../../../../workflows/adjustments/workflows/create-adjustments"
+import { AdminCreateAdjustmentType, AdminGetAdjustmentsParamsType } from "../../validators"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest<unknown, AdminGetAdjustmentsParamsType>,
+ res: MedusaResponse<AdminAdjustmentListResponse>
+) => {
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+ const { data: adjustments, metadata } = await query.graph({
+ entity: "adjustment",
+ fields: req.queryConfig.fields,
+ filters: req.filterableFields,
+ pagination: req.queryConfig.pagination,
+ })
+ res.json({
+ adjustments: adjustments as unknown as AdjustmentDTO[],
+ count: metadata?.count ?? 0,
+ offset: metadata?.skip ?? 0,
+ limit: metadata?.take ?? 0,
+ })
+}
+
+export const POST = async (
+ req: AuthenticatedMedusaRequest<AdminCreateAdjustmentType>,
+ res: MedusaResponse<AdminAdjustmentResponse>
+) => {
+ const { result } = await createAdjustmentsWorkflow(req.scope).run({
+ input: { ...req.validatedBody, created_by: req.auth_context?.actor_id ?? null },
+ })
+
+ const adjustment = await refetchEntity({
+ entity: "adjustment",
+ idOrFilter: result[0].id,
+ scope: req.scope,
+ fields: req.queryConfig.fields,
+ })
+
+ res.status(201).json({ adjustment: adjustment as AdjustmentDTO })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/captures/[order_group_id]/cancel/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/captures/[order_group_id]/cancel/route.ts
new file mode 100644
index 000000000..6349871c3
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/captures/[order_group_id]/cancel/route.ts
@@ -0,0 +1,13 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+
+import { AdminStripeCaptureResponse } from "../../../../../../types/http"
+import { settleOrderGroupPaymentWorkflow } from "../../../../../../workflows/captures/workflows/settle-order-group-payment"
+import { refetchCapture } from "../../helpers"
+
+export const POST = async (req: AuthenticatedMedusaRequest, res: MedusaResponse<AdminStripeCaptureResponse>) => {
+ await settleOrderGroupPaymentWorkflow(req.scope).run({
+ input: { order_group_id: req.params.order_group_id, action: "cancel" },
+ })
+
+ res.json({ capture: await refetchCapture(req.scope, req.params.order_group_id, req.queryConfig.fields) })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/captures/[order_group_id]/capture/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/captures/[order_group_id]/capture/route.ts
new file mode 100644
index 000000000..ead694396
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/captures/[order_group_id]/capture/route.ts
@@ -0,0 +1,13 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+
+import { AdminStripeCaptureResponse } from "../../../../../../types/http"
+import { settleOrderGroupPaymentWorkflow } from "../../../../../../workflows/captures/workflows/settle-order-group-payment"
+import { refetchCapture } from "../../helpers"
+
+export const POST = async (req: AuthenticatedMedusaRequest, res: MedusaResponse<AdminStripeCaptureResponse>) => {
+ await settleOrderGroupPaymentWorkflow(req.scope).run({
+ input: { order_group_id: req.params.order_group_id, action: "capture" },
+ })
+
+ res.json({ capture: await refetchCapture(req.scope, req.params.order_group_id, req.queryConfig.fields) })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/captures/[order_group_id]/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/captures/[order_group_id]/route.ts
new file mode 100644
index 000000000..1b968682c
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/captures/[order_group_id]/route.ts
@@ -0,0 +1,8 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+
+import { AdminStripeCaptureResponse } from "../../../../../types/http"
+import { refetchCapture } from "../helpers"
+
+export const GET = async (req: AuthenticatedMedusaRequest, res: MedusaResponse<AdminStripeCaptureResponse>) => {
+ res.json({ capture: await refetchCapture(req.scope, req.params.order_group_id, req.queryConfig.fields) })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/captures/helpers.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/captures/helpers.ts
new file mode 100644
index 000000000..3e81f0eb5
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/captures/helpers.ts
@@ -0,0 +1,22 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+import { MedusaError } from "@medusajs/framework/utils"
+import { refetchEntity } from "@medusajs/framework/http"
+
+import { AdminStripeCapture } from "../../../../types/http"
+
+export async function refetchCapture(
+ container: MedusaContainer,
+ orderGroupId: string,
+ fields: string[]
+): Promise<AdminStripeCapture> {
+ const capture = await refetchEntity({
+ entity: "stripe_capture",
+ idOrFilter: { order_group_id: orderGroupId },
+ scope: container,
+ fields,
+ })
+ if (!capture) {
+ throw new MedusaError(MedusaError.Types.NOT_FOUND, `No capture for order group ${orderGroupId}`)
+ }
+ return capture as AdminStripeCapture
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/captures/query-config.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/captures/query-config.ts
new file mode 100644
index 000000000..7b7eae2be
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/captures/query-config.ts
@@ -0,0 +1,24 @@
+export const adminCaptureFields = [
+ "id",
+ "order_group_id",
+ "payment_collection_id",
+ "payment_id",
+ "currency_code",
+ "authorized_amount",
+ "capturable_amount",
+ "orders_total",
+ "orders_decided",
+ "status",
+ "status_reason",
+ "authorized_at",
+ "expires_at",
+ "created_at",
+ "updated_at",
+ "order_group.id",
+ "order_group.display_id",
+]
+
+export const adminCaptureQueryConfig = {
+ list: { defaults: adminCaptureFields, isList: true, defaultLimit: 20 },
+ retrieve: { defaults: adminCaptureFields, isList: false },
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/captures/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/captures/route.ts
new file mode 100644
index 000000000..4c33c41e6
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/captures/route.ts
@@ -0,0 +1,26 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+import { AdminStripeCaptureListResponse } from "../../../../types/http"
+import { AdminGetCapturesParamsType } from "../../validators"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest<unknown, AdminGetCapturesParamsType>,
+ res: MedusaResponse<AdminStripeCaptureListResponse>
+) => {
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const { data: captures, metadata } = await query.graph({
+ entity: "stripe_capture",
+ fields: req.queryConfig.fields,
+ filters: req.filterableFields,
+ pagination: req.queryConfig.pagination,
+ })
+
+ res.json({
+ captures: captures as unknown as AdminStripeCaptureListResponse["captures"],
+ count: metadata?.count ?? 0,
+ offset: metadata?.skip ?? 0,
+ limit: metadata?.take ?? 0,
+ })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/jobs/[job]/run/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/jobs/[job]/run/route.ts
new file mode 100644
index 000000000..028b81d5a
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/jobs/[job]/run/route.ts
@@ -0,0 +1,25 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { MedusaError } from "@medusajs/framework/utils"
+
+import { JobTrigger, PAYOUT_JOBS, PayoutJobName } from "../../../../../../types/common"
+import { AdminPayoutJobRunResponse } from "../../../../../../types/http"
+import { runJob } from "../../../../../../utils/run-job"
+import { JobScope, jobWorkflow } from "../../../../../../workflows/jobs"
+import { AdminRunJobType } from "../../../../validators"
+
+export const POST = async (
+ req: AuthenticatedMedusaRequest<AdminRunJobType>,
+ res: MedusaResponse<AdminPayoutJobRunResponse>
+) => {
+ const job = req.params.job as PayoutJobName
+ if (!PAYOUT_JOBS.includes(job)) {
+ throw new MedusaError(MedusaError.Types.NOT_FOUND, `Unknown payout job ${job}`)
+ }
+ const scope: JobScope = req.validatedBody ?? {}
+
+ const run = await runJob(req.scope, job, JobTrigger.MANUAL, jobWorkflow(job, req.scope, scope))
+ if (!run) {
+ throw new MedusaError(MedusaError.Types.CONFLICT, `${job} is already running`)
+ }
+ res.json({ run })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/jobs/[job]/runs/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/jobs/[job]/runs/route.ts
new file mode 100644
index 000000000..2f68016d7
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/jobs/[job]/runs/route.ts
@@ -0,0 +1,23 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { MedusaError } from "@medusajs/framework/utils"
+
+import { PAYOUT_JOBS, PayoutJobName } from "../../../../../../types/common"
+import { AdminPayoutJobRunListResponse } from "../../../../../../types/http"
+import { resolveConnector } from "../../../../../../utils/payout-module"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest<unknown, { offset?: number; limit?: number }>,
+ res: MedusaResponse<AdminPayoutJobRunListResponse>
+) => {
+ const job = req.params.job as PayoutJobName
+ if (!PAYOUT_JOBS.includes(job)) {
+ throw new MedusaError(MedusaError.Types.NOT_FOUND, `Unknown payout job ${job}`)
+ }
+ const offset = Number(req.query.offset ?? 0)
+ const limit = Math.min(Number(req.query.limit ?? 20), 200)
+ const [runs, count] = await resolveConnector(req.scope).listAndCountConnectorJobRuns(
+ { job },
+ { skip: offset, take: limit, order: { started_at: "DESC" } }
+ )
+ res.json({ runs, count, offset, limit })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/jobs/helpers.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/jobs/helpers.ts
new file mode 100644
index 000000000..fe83b2839
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/jobs/helpers.ts
@@ -0,0 +1,74 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+import { PayoutStatus } from "@mercurjs/types"
+
+import { CaptureStatus, PAYOUT_JOBS, PAYOUT_JOB_SCHEDULES, PayoutJobName } from "../../../../types/common"
+import { AdminPayoutJob } from "../../../../types/http"
+import { nextCronRun } from "../../../../utils/cron"
+import { resolveConnector, resolvePayoutModule } from "../../../../utils/payout-module"
+import { decodeCursor } from "../../../../workflows/common/utils/cursor"
+import { ONBOARDING_CHECKPOINT } from "../../../../workflows/onboarding/utils/onboarding-sellers"
+import { PAYOUTS_CHECKPOINT } from "../../../../workflows/payouts/utils/payout-orders"
+import { REVERSALS_CHECKPOINT } from "../../../../workflows/reversals/steps/select-reversal-orders"
+
+const COUNT_ONLY = { take: 1, select: ["id"] }
+
+export async function countFailed(container: MedusaContainer) {
+ const payoutModule = resolvePayoutModule(container)
+ const connector = resolveConnector(container)
+ const [[, captures], [, payouts], [, reversals], [, settlements], [, adjustments]] = await Promise.all([
+ connector.listAndCountStripeCaptures({ status: CaptureStatus.FAILED }, COUNT_ONLY),
+ payoutModule.listAndCountPayouts({ status: PayoutStatus.FAILED }, COUNT_ONLY),
+ payoutModule.listAndCountPayoutReversals({ status: PayoutStatus.FAILED }, COUNT_ONLY),
+ connector.listAndCountSettlements({ payout_status: PayoutStatus.FAILED }, COUNT_ONLY),
+ connector.listAndCountAdjustments({ status: PayoutStatus.FAILED }, COUNT_ONLY),
+ ])
+ return { captures, payouts, reversals, settlements, adjustments }
+}
+
+const CHECKPOINT_BY_JOB: Partial<Record<PayoutJobName, string>> = {
+ "payout-sync-onboarding": ONBOARDING_CHECKPOINT,
+ "payout-process-transfers": PAYOUTS_CHECKPOINT,
+ "payout-process-reversals": REVERSALS_CHECKPOINT,
+}
+
+// Cursor checkpoints keep the row id next to the date; the date is what is shown.
+const checkpointDate = (value: string | null) => decodeCursor(value)?.created_at ?? value
+
+export async function describeJobs(container: MedusaContainer): Promise<AdminPayoutJob[]> {
+ const connector = resolveConnector(container)
+ const options = connector.getOptions()
+
+ const enabled: Record<PayoutJobName, boolean> = {
+ "payout-sync-onboarding": options.onboarding.enabled,
+ "payout-validate-captures": true,
+ "payout-process-transfers": options.transfers.enabled,
+ "payout-process-reversals": options.reversals.enabled,
+ "payout-process-settlements": options.settlements.enabled,
+ "payout-alert-failed-operations": true,
+ "payout-monitor-kyc": options.kycMonitor.enabled,
+ }
+
+ const failed = await countFailed(container)
+ const failedByJob: Partial<Record<PayoutJobName, number>> = {
+ "payout-validate-captures": failed.captures,
+ "payout-process-transfers": failed.payouts,
+ "payout-process-reversals": failed.reversals,
+ "payout-process-settlements": failed.settlements + failed.adjustments,
+ }
+
+ return await Promise.all(
+ PAYOUT_JOBS.map(async (job) => {
+ const [lastRun] = await connector.listConnectorJobRuns({ job }, { take: 1, order: { started_at: "DESC" } })
+ const checkpointKey = CHECKPOINT_BY_JOB[job]
+ return {
+ job,
+ schedule: PAYOUT_JOB_SCHEDULES[job],
+ enabled: enabled[job],
+ checkpoint: checkpointKey ? checkpointDate(await connector.getCheckpoint(checkpointKey)) : null,
+ last_run: lastRun ?? null,
+ next_run_at: enabled[job] ? nextCronRun(PAYOUT_JOB_SCHEDULES[job], new Date()) : null,
+ failed_count: failedByJob[job] ?? 0,
+ }
+ })
+ )
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/jobs/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/jobs/route.ts
new file mode 100644
index 000000000..f2f6510fd
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/jobs/route.ts
@@ -0,0 +1,8 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+
+import { AdminPayoutJobListResponse } from "../../../../types/http"
+import { describeJobs } from "./helpers"
+
+export const GET = async (req: AuthenticatedMedusaRequest, res: MedusaResponse<AdminPayoutJobListResponse>) => {
+ res.json({ jobs: await describeJobs(req.scope) })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/notifications/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/notifications/route.ts
new file mode 100644
index 000000000..ced7ba6ec
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/notifications/route.ts
@@ -0,0 +1,32 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+
+import { AdminPayoutNotificationListResponse } from "../../../../types/http"
+import { resolveConnector } from "../../../../utils/payout-module"
+import { redactUrl } from "../../../../workflows/notifications/utils/notification-signature"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse<AdminPayoutNotificationListResponse>
+) => {
+ const offset = Number(req.query.offset ?? 0)
+ const limit = Math.min(Number(req.query.limit ?? 20), 200)
+ const [rows, count] = await resolveConnector(req.scope).listAndCountConnectorNotifications(
+ {},
+ { skip: offset, take: limit, order: { created_at: "DESC" } }
+ )
+ res.json({
+ notifications: rows.map((row) => ({
+ id: row.id,
+ type: row.type,
+ url: redactUrl(row.url) ?? "",
+ attempts: row.attempts,
+ response_status: row.response_status,
+ error: row.error,
+ delivered: row.delivered,
+ created_at: row.created_at,
+ })),
+ count,
+ offset,
+ limit,
+ })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/notifications/test/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/notifications/test/route.ts
new file mode 100644
index 000000000..0420d0703
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/notifications/test/route.ts
@@ -0,0 +1,10 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+
+import { notifyOperatorWorkflow } from "../../../../../workflows/notifications/workflows/notify-operator"
+
+export const POST = async (req: AuthenticatedMedusaRequest, res: MedusaResponse) => {
+ const { result } = await notifyOperatorWorkflow(req.scope).run({
+ input: { type: "test", payload: { sent_at: new Date().toISOString(), actor_id: req.auth_context?.actor_id ?? null } },
+ })
+ res.json({ notification: result })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/[id]/retry/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/[id]/retry/route.ts
new file mode 100644
index 000000000..bc6e07f7f
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/[id]/retry/route.ts
@@ -0,0 +1,10 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+
+import { AdminSettlementResponse } from "../../../../../../types/http"
+import { retrySettlementPayoutWorkflow } from "../../../../../../workflows/settlements/workflows/retry-settlement-payout"
+import { refetchSettlement } from "../../helpers"
+
+export const POST = async (req: AuthenticatedMedusaRequest, res: MedusaResponse<AdminSettlementResponse>) => {
+ await retrySettlementPayoutWorkflow(req.scope).run({ input: { id: req.params.id } })
+ res.json({ settlement: await refetchSettlement(req.params.id, req.scope, req.queryConfig.fields) })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/[id]/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/[id]/route.ts
new file mode 100644
index 000000000..9be7a6b66
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/[id]/route.ts
@@ -0,0 +1,8 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+
+import { AdminSettlementResponse } from "../../../../../types/http"
+import { refetchSettlement } from "../helpers"
+
+export const GET = async (req: AuthenticatedMedusaRequest, res: MedusaResponse<AdminSettlementResponse>) => {
+ res.json({ settlement: await refetchSettlement(req.params.id, req.scope, req.queryConfig.fields) })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/helpers.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/helpers.ts
new file mode 100644
index 000000000..8f57d671e
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/helpers.ts
@@ -0,0 +1,20 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys, MedusaError } from "@medusajs/framework/utils"
+
+import { AdminSettlement } from "../../../../types/http"
+
+export async function refetchSettlement(
+ id: string,
+ scope: MedusaContainer,
+ fields: string[],
+ filters: Record<string, unknown> = {}
+): Promise<AdminSettlement> {
+ const query = scope.resolve(ContainerRegistrationKeys.QUERY)
+ const {
+ data: [settlement],
+ } = await query.graph({ entity: "settlement", fields, filters: { ...filters, id } })
+ if (!settlement) {
+ throw new MedusaError(MedusaError.Types.NOT_FOUND, `Settlement ${id} was not found`)
+ }
+ return settlement as unknown as AdminSettlement
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/query-config.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/query-config.ts
new file mode 100644
index 000000000..5c8884c74
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/query-config.ts
@@ -0,0 +1,75 @@
+const settlementFields = [
+ "id",
+ "display_id",
+ "currency_code",
+ "period_start",
+ "period_end",
+ "payouts_total",
+ "reversals_total",
+ "adjustments_total",
+ "amount",
+ "payout_amount",
+ "payout_currency_code",
+ "status",
+ "payout_status",
+ "provider_payout_id",
+ "status_reason",
+ "created_at",
+ "updated_at",
+]
+
+const lineFields = [
+ "lines.id",
+ "lines.type",
+ "lines.amount",
+ "lines.payout_id",
+ "lines.payout_reversal_id",
+ "lines.adjustment_id",
+ "lines.payout.id",
+ "lines.payout.status",
+ "lines.payout.order_id",
+ "lines.payout.data",
+ "lines.payout.order.display_id",
+ "lines.payout_reversal.id",
+ "lines.payout_reversal.status",
+ "lines.payout_reversal.refund_id",
+ "lines.payout_reversal.data",
+ "lines.payout_reversal.payout.order_id",
+ "lines.payout_reversal.payout.order.display_id",
+ "lines.adjustment.id",
+ "lines.adjustment.type",
+ "lines.adjustment.amount",
+ "lines.adjustment.reason",
+ "lines.adjustment.status",
+ "lines.adjustment.provider_transfer_id",
+]
+
+const sellerFields = ["payout_account.id", "payout_account.seller.id", "payout_account.seller.name", "payout_account.seller.handle"]
+
+export const adminSettlementQueryConfig = {
+ list: {
+ defaults: [...settlementFields, "account_id", ...sellerFields],
+ isList: true,
+ defaultLimit: 20,
+ defaultOrder: { period_end: "DESC" },
+ },
+ retrieve: {
+ defaults: [...settlementFields, "account_id", "data", ...sellerFields, ...lineFields, "lines.adjustment.created_by"],
+ isList: false,
+ },
+}
+
+export const vendorSettlementQueryConfig = {
+ list: {
+ defaults: settlementFields,
+ allowed: settlementFields,
+ isList: true,
+ defaultLimit: 20,
+ defaultOrder: { period_end: "DESC" },
+ },
+ retrieve: {
+ defaults: [...settlementFields, ...lineFields],
+ allowed: [...settlementFields, ...lineFields],
+ isList: false,
+ },
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/route.ts
new file mode 100644
index 000000000..b5725aef2
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/settlements/route.ts
@@ -0,0 +1,25 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+import { AdminSettlement, AdminSettlementListResponse } from "../../../../types/http"
+import { AdminGetSettlementsParamsType } from "../../validators"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest<unknown, AdminGetSettlementsParamsType>,
+ res: MedusaResponse<AdminSettlementListResponse>
+) => {
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+ const { data: settlements, metadata } = await query.graph({
+ entity: "settlement",
+ fields: req.queryConfig.fields,
+ filters: req.filterableFields,
+ pagination: req.queryConfig.pagination,
+ })
+
+ res.json({
+ settlements: settlements as unknown as AdminSettlement[],
+ count: metadata?.count ?? 0,
+ offset: metadata?.skip ?? 0,
+ limit: metadata?.take ?? 0,
+ })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/stripe/status/route.ts b/packages/plugins/stripe-connector/src/api/admin/stripe/status/route.ts
new file mode 100644
index 000000000..ed69c8824
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/stripe/status/route.ts
@@ -0,0 +1,35 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+
+import { AdminPayoutStatusResponse } from "../../../../types/http"
+import { resolveConnector } from "../../../../utils/payout-module"
+import { redactUrl } from "../../../../workflows/notifications/utils/notification-signature"
+import { LAST_WEBHOOK_CHECKPOINT } from "../../../../workflows/webhooks/utils"
+import { countFailed, describeJobs } from "../jobs/helpers"
+
+export const GET = async (req: AuthenticatedMedusaRequest, res: MedusaResponse<AdminPayoutStatusResponse>) => {
+ const connector = resolveConnector(req.scope)
+ const { apiKey: _apiKey, webhookSecret: _webhookSecret, notifications, ...options } = connector.getOptions()
+ const { secret: _secret, url, ...notificationOptions } = notifications
+
+ const [jobs, failed, lastWebhook] = await Promise.all([
+ describeJobs(req.scope),
+ countFailed(req.scope),
+ connector.getCheckpoint(LAST_WEBHOOK_CHECKPOINT),
+ ])
+ const checkpointOf = (job: string) => jobs.find((row) => row.job === job)?.checkpoint ?? null
+
+ res.json({
+ configured: connector.isConfigured(),
+ options: {
+ ...options,
+ notifications: { ...notificationOptions, url: redactUrl(url) },
+ } as unknown as Record<string, unknown>,
+ checkpoints: {
+ onboarding: checkpointOf("payout-sync-onboarding"),
+ transfers: checkpointOf("payout-process-transfers"),
+ },
+ failed,
+ last_webhook_at: lastWebhook ? new Date(lastWebhook) : null,
+ jobs,
+ })
+}
diff --git a/packages/plugins/stripe-connector/src/api/admin/validators.ts b/packages/plugins/stripe-connector/src/api/admin/validators.ts
new file mode 100644
index 000000000..8686d8013
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/admin/validators.ts
@@ -0,0 +1,69 @@
+import { z } from "zod"
+import { createFindParams, createOperatorMap, createSelectParams } from "@medusajs/medusa/api/utils/validators"
+
+import { AdjustmentType } from "../../types/common"
+
+export type AdminRunJobType = z.infer<typeof AdminRunJob>
+export const AdminRunJob = z
+ .object({
+ seller_id: z.string().optional(),
+ order_id: z.string().optional(),
+ order_group_id: z.string().optional(),
+ })
+ .strict()
+
+export type AdminGetSelectParamsType = z.infer<typeof AdminGetSelectParams>
+export const AdminGetSelectParams = createSelectParams()
+
+export type AdminGetCaptureParamsType = z.infer<typeof AdminGetCaptureParams>
+export const AdminGetCaptureParams = createSelectParams()
+
+export type AdminGetCapturesParamsType = z.infer<typeof AdminGetCapturesParams>
+export const AdminGetCapturesParams = createFindParams({ offset: 0, limit: 20, order: "expires_at" }).merge(
+ z.object({
+ order_group_id: z.union([z.string(), z.array(z.string())]).optional(),
+ status: z.union([z.string(), z.array(z.string())]).optional(),
+ expires_at: createOperatorMap().optional(),
+ created_at: createOperatorMap().optional(),
+ })
+)
+
+export type AdminGetSettlementsParamsType = z.infer<typeof AdminGetSettlementsParams>
+export const AdminGetSettlementsParams = createFindParams({ offset: 0, limit: 20 }).merge(
+ z.object({
+ id: z.union([z.string(), z.array(z.string())]).optional(),
+ account_id: z.union([z.string(), z.array(z.string())]).optional(),
+ currency_code: z.union([z.string(), z.array(z.string())]).optional(),
+ status: z.union([z.string(), z.array(z.string())]).optional(),
+ payout_status: z.union([z.string(), z.array(z.string())]).optional(),
+ period_start: createOperatorMap().optional(),
+ period_end: createOperatorMap().optional(),
+ })
+)
+
+export type AdminGetAdjustmentsParamsType = z.infer<typeof AdminGetAdjustmentsParams>
+export const AdminGetAdjustmentsParams = createFindParams({ offset: 0, limit: 20 }).merge(
+ z.object({
+ account_id: z.union([z.string(), z.array(z.string())]).optional(),
+ type: z.union([z.string(), z.array(z.string())]).optional(),
+ status: z.union([z.string(), z.array(z.string())]).optional(),
+ })
+)
+
+export type AdminCreateAdjustmentType = z.infer<typeof AdminCreateAdjustment>
+export const AdminCreateAdjustment = z
+ .object({
+ account_id: z.string().optional(),
+ seller_id: z.string().optional(),
+ type: z.nativeEnum(AdjustmentType),
+ amount: z.number().positive(),
+ currency_code: z.string().min(3).max(3),
+ reason: z.string().max(1024).optional().nullable(),
+ })
+ .strict()
+ .refine((body) => !!body.account_id || !!body.seller_id, {
+ message: "account_id or seller_id is required",
+ })
+
+export type AdminIgnoreAccountType = z.infer<typeof AdminIgnoreAccount>
+export const AdminIgnoreAccount = z.object({ ignored: z.boolean() }).strict()
diff --git a/packages/plugins/stripe-connector/src/api/middlewares.ts b/packages/plugins/stripe-connector/src/api/middlewares.ts
new file mode 100644
index 000000000..1df2d218a
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/middlewares.ts
@@ -0,0 +1,104 @@
+import { validateAndTransformBody, validateAndTransformQuery } from "@medusajs/framework"
+import { MiddlewareRoute, defineMiddlewares } from "@medusajs/framework/http"
+import { requirePermission } from "@mercurjs/core/api/utils/index"
+
+import {
+ AdminCreateAdjustment,
+ AdminGetAdjustmentsParams,
+ AdminGetCaptureParams,
+ AdminGetCapturesParams,
+ AdminGetSelectParams,
+ AdminGetSettlementsParams,
+ AdminIgnoreAccount,
+ AdminRunJob,
+} from "./admin/validators"
+import { adminAdjustmentQueryConfig } from "./admin/stripe/adjustments/query-config"
+import { adminStripeAccountQueryConfig } from "./admin/stripe/accounts/query-config"
+import { adminCaptureQueryConfig } from "./admin/stripe/captures/query-config"
+import { adminSettlementQueryConfig, vendorSettlementQueryConfig } from "./admin/stripe/settlements/query-config"
+
+const view = requirePermission("payouts", "view")
+const edit = requirePermission("payouts", "edit")
+
+const routes: MiddlewareRoute[] = [
+ { method: ["GET"], matcher: "/admin/stripe/status", middlewares: [view] },
+ { method: ["GET"], matcher: "/admin/stripe/jobs", middlewares: [view] },
+ { method: ["GET"], matcher: "/admin/stripe/jobs/:job/runs", middlewares: [view] },
+ {
+ method: ["POST"],
+ matcher: "/admin/stripe/jobs/:job/run",
+ middlewares: [edit, validateAndTransformBody(AdminRunJob)],
+ },
+ { method: ["GET"], matcher: "/admin/stripe/notifications", middlewares: [view] },
+ { method: ["POST"], matcher: "/admin/stripe/notifications/test", middlewares: [edit] },
+ {
+ method: ["GET"],
+ matcher: "/admin/stripe/captures",
+ middlewares: [view, validateAndTransformQuery(AdminGetCapturesParams, adminCaptureQueryConfig.list)],
+ },
+ {
+ method: ["GET"],
+ matcher: "/admin/stripe/captures/:order_group_id",
+ middlewares: [view, validateAndTransformQuery(AdminGetCaptureParams, adminCaptureQueryConfig.retrieve)],
+ },
+ {
+ method: ["POST"],
+ matcher: "/admin/stripe/captures/:order_group_id/capture",
+ middlewares: [edit, validateAndTransformQuery(AdminGetCaptureParams, adminCaptureQueryConfig.retrieve)],
+ },
+ {
+ method: ["POST"],
+ matcher: "/admin/stripe/captures/:order_group_id/cancel",
+ middlewares: [edit, validateAndTransformQuery(AdminGetCaptureParams, adminCaptureQueryConfig.retrieve)],
+ },
+ {
+ method: ["GET"],
+ matcher: "/admin/stripe/settlements",
+ middlewares: [view, validateAndTransformQuery(AdminGetSettlementsParams, adminSettlementQueryConfig.list)],
+ },
+ {
+ method: ["GET"],
+ matcher: "/admin/stripe/settlements/:id",
+ middlewares: [view, validateAndTransformQuery(AdminGetSelectParams, adminSettlementQueryConfig.retrieve)],
+ },
+ {
+ method: ["POST"],
+ matcher: "/admin/stripe/settlements/:id/retry",
+ middlewares: [edit, validateAndTransformQuery(AdminGetSelectParams, adminSettlementQueryConfig.retrieve)],
+ },
+ {
+ method: ["GET"],
+ matcher: "/admin/stripe/adjustments",
+ middlewares: [view, validateAndTransformQuery(AdminGetAdjustmentsParams, adminAdjustmentQueryConfig.list)],
+ },
+ {
+ method: ["POST"],
+ matcher: "/admin/stripe/adjustments",
+ middlewares: [
+ edit,
+ validateAndTransformBody(AdminCreateAdjustment),
+ validateAndTransformQuery(AdminGetSelectParams, adminAdjustmentQueryConfig.retrieve),
+ ],
+ },
+ {
+ method: ["POST"],
+ matcher: "/admin/stripe/accounts/:id/ignore",
+ middlewares: [
+ edit,
+ validateAndTransformBody(AdminIgnoreAccount),
+ validateAndTransformQuery(AdminGetSelectParams, adminStripeAccountQueryConfig.retrieve),
+ ],
+ },
+ {
+ method: ["GET"],
+ matcher: "/vendor/stripe/settlements",
+ middlewares: [view, validateAndTransformQuery(AdminGetSettlementsParams, vendorSettlementQueryConfig.list)],
+ },
+ {
+ method: ["GET"],
+ matcher: "/vendor/stripe/settlements/:id",
+ middlewares: [view, validateAndTransformQuery(AdminGetSelectParams, vendorSettlementQueryConfig.retrieve)],
+ },
+]
+
+export default defineMiddlewares({ routes })
diff --git a/packages/plugins/stripe-connector/src/api/vendor-seller.ts b/packages/plugins/stripe-connector/src/api/vendor-seller.ts
new file mode 100644
index 000000000..bb1adff57
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/vendor-seller.ts
@@ -0,0 +1,12 @@
+import type { SellerContext } from "@mercurjs/core/types/seller-context"
+import { AuthenticatedMedusaRequest } from "@medusajs/framework/http"
+import { MedusaError } from "@medusajs/framework/utils"
+
+export function vendorSellerId(req: AuthenticatedMedusaRequest): string {
+ const context: SellerContext | undefined = req.seller_context
+ const sellerId = context?.seller_id
+ if (!sellerId) {
+ throw new MedusaError(MedusaError.Types.UNAUTHORIZED, "No seller in context")
+ }
+ return sellerId
+}
diff --git a/packages/plugins/stripe-connector/src/api/vendor/stripe/settlements/[id]/route.ts b/packages/plugins/stripe-connector/src/api/vendor/stripe/settlements/[id]/route.ts
new file mode 100644
index 000000000..ba017cefb
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/vendor/stripe/settlements/[id]/route.ts
@@ -0,0 +1,16 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+
+import { VendorSettlementResponse } from "../../../../../types/http"
+import { refetchSettlement } from "../../../../admin/stripe/settlements/helpers"
+import { vendorSellerId } from "../../../../vendor-seller"
+import { sellerAccountFilter } from "../helpers"
+
+export const GET = async (req: AuthenticatedMedusaRequest, res: MedusaResponse<VendorSettlementResponse>) => {
+ const settlement = await refetchSettlement(
+ req.params.id,
+ req.scope,
+ req.queryConfig.fields,
+ await sellerAccountFilter(req.scope, vendorSellerId(req))
+ )
+ res.json({ settlement })
+}
diff --git a/packages/plugins/stripe-connector/src/api/vendor/stripe/settlements/helpers.ts b/packages/plugins/stripe-connector/src/api/vendor/stripe/settlements/helpers.ts
new file mode 100644
index 000000000..f1dcda7d9
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/vendor/stripe/settlements/helpers.ts
@@ -0,0 +1,14 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+/** The payout accounts of a seller, never empty so a seller without one matches nothing. */
+export async function sellerAccountFilter(scope: MedusaContainer, sellerId: string) {
+ const query = scope.resolve(ContainerRegistrationKeys.QUERY)
+ const { data } = await query.graph({
+ entity: "seller_payout_account",
+ fields: ["payout_account_id"],
+ filters: { seller_id: sellerId },
+ })
+ const ids = data.map((link) => link.payout_account_id as string)
+ return { account_id: ids.length ? ids : ["none"] }
+}
diff --git a/packages/plugins/stripe-connector/src/api/vendor/stripe/settlements/route.ts b/packages/plugins/stripe-connector/src/api/vendor/stripe/settlements/route.ts
new file mode 100644
index 000000000..441182384
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/api/vendor/stripe/settlements/route.ts
@@ -0,0 +1,27 @@
+import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+import { VendorSettlement, VendorSettlementListResponse } from "../../../../types/http"
+import { vendorSellerId } from "../../../vendor-seller"
+import { AdminGetSettlementsParamsType } from "../../../admin/validators"
+import { sellerAccountFilter } from "./helpers"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest<unknown, AdminGetSettlementsParamsType>,
+ res: MedusaResponse<VendorSettlementListResponse>
+) => {
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+ const { data: settlements, metadata } = await query.graph({
+ entity: "settlement",
+ fields: req.queryConfig.fields,
+ filters: { ...req.filterableFields, ...(await sellerAccountFilter(req.scope, vendorSellerId(req))) },
+ pagination: req.queryConfig.pagination,
+ })
+
+ res.json({
+ settlements: settlements as unknown as VendorSettlement[],
+ count: metadata?.count ?? 0,
+ offset: metadata?.skip ?? 0,
+ limit: metadata?.take ?? 0,
+ })
+}
diff --git a/packages/plugins/stripe-connector/src/index.ts b/packages/plugins/stripe-connector/src/index.ts
new file mode 100644
index 000000000..eda8d4705
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/index.ts
@@ -0,0 +1,4 @@
+export * from "./types"
+export { StripeConnectPayoutProviderService } from "./providers/payout-stripe-connect/service"
+export { StripeConnectorPaymentProviderService } from "./providers/payment-stripe/service"
+export { StripeConnectorModuleService } from "./modules/stripe-connector"
diff --git a/packages/plugins/stripe-connector/src/jobs/payout-alert-failed-operations.ts b/packages/plugins/stripe-connector/src/jobs/payout-alert-failed-operations.ts
new file mode 100644
index 000000000..2840b82df
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/jobs/payout-alert-failed-operations.ts
@@ -0,0 +1,14 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+
+import { JobTrigger, PAYOUT_JOB_SCHEDULES } from "../types/common"
+import { runJob } from "../utils/run-job"
+import { jobWorkflow } from "../workflows/jobs"
+
+export default async function payoutAlertFailedOperationsJob(container: MedusaContainer) {
+ await runJob(container, "payout-alert-failed-operations", JobTrigger.SCHEDULE, jobWorkflow("payout-alert-failed-operations", container))
+}
+
+export const config = {
+ name: "payout-alert-failed-operations",
+ schedule: PAYOUT_JOB_SCHEDULES["payout-alert-failed-operations"],
+}
diff --git a/packages/plugins/stripe-connector/src/jobs/payout-monitor-kyc.ts b/packages/plugins/stripe-connector/src/jobs/payout-monitor-kyc.ts
new file mode 100644
index 000000000..3c65775ef
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/jobs/payout-monitor-kyc.ts
@@ -0,0 +1,14 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+
+import { JobTrigger, PAYOUT_JOB_SCHEDULES } from "../types/common"
+import { runJob } from "../utils/run-job"
+import { jobWorkflow } from "../workflows/jobs"
+
+export default async function payoutMonitorKycJob(container: MedusaContainer) {
+ await runJob(container, "payout-monitor-kyc", JobTrigger.SCHEDULE, jobWorkflow("payout-monitor-kyc", container))
+}
+
+export const config = {
+ name: "payout-monitor-kyc",
+ schedule: PAYOUT_JOB_SCHEDULES["payout-monitor-kyc"],
+}
diff --git a/packages/plugins/stripe-connector/src/jobs/payout-process-reversals.ts b/packages/plugins/stripe-connector/src/jobs/payout-process-reversals.ts
new file mode 100644
index 000000000..19233bd4c
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/jobs/payout-process-reversals.ts
@@ -0,0 +1,14 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+
+import { JobTrigger, PAYOUT_JOB_SCHEDULES } from "../types/common"
+import { runJob } from "../utils/run-job"
+import { jobWorkflow } from "../workflows/jobs"
+
+export default async function payoutProcessReversalsJob(container: MedusaContainer) {
+ await runJob(container, "payout-process-reversals", JobTrigger.SCHEDULE, jobWorkflow("payout-process-reversals", container))
+}
+
+export const config = {
+ name: "payout-process-reversals",
+ schedule: PAYOUT_JOB_SCHEDULES["payout-process-reversals"],
+}
diff --git a/packages/plugins/stripe-connector/src/jobs/payout-process-settlements.ts b/packages/plugins/stripe-connector/src/jobs/payout-process-settlements.ts
new file mode 100644
index 000000000..49ff018b3
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/jobs/payout-process-settlements.ts
@@ -0,0 +1,14 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+
+import { JobTrigger, PAYOUT_JOB_SCHEDULES } from "../types/common"
+import { runJob } from "../utils/run-job"
+import { jobWorkflow } from "../workflows/jobs"
+
+export default async function payoutProcessSettlementsJob(container: MedusaContainer) {
+ await runJob(container, "payout-process-settlements", JobTrigger.SCHEDULE, jobWorkflow("payout-process-settlements", container))
+}
+
+export const config = {
+ name: "payout-process-settlements",
+ schedule: PAYOUT_JOB_SCHEDULES["payout-process-settlements"],
+}
diff --git a/packages/plugins/stripe-connector/src/jobs/payout-process-transfers.ts b/packages/plugins/stripe-connector/src/jobs/payout-process-transfers.ts
new file mode 100644
index 000000000..cd4e8c9df
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/jobs/payout-process-transfers.ts
@@ -0,0 +1,14 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+
+import { JobTrigger, PAYOUT_JOB_SCHEDULES } from "../types/common"
+import { runJob } from "../utils/run-job"
+import { jobWorkflow } from "../workflows/jobs"
+
+export default async function payoutProcessTransfersJob(container: MedusaContainer) {
+ await runJob(container, "payout-process-transfers", JobTrigger.SCHEDULE, jobWorkflow("payout-process-transfers", container))
+}
+
+export const config = {
+ name: "payout-process-transfers",
+ schedule: PAYOUT_JOB_SCHEDULES["payout-process-transfers"],
+}
diff --git a/packages/plugins/stripe-connector/src/jobs/payout-sync-onboarding.ts b/packages/plugins/stripe-connector/src/jobs/payout-sync-onboarding.ts
new file mode 100644
index 000000000..fea2804ca
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/jobs/payout-sync-onboarding.ts
@@ -0,0 +1,14 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+
+import { JobTrigger, PAYOUT_JOB_SCHEDULES } from "../types/common"
+import { runJob } from "../utils/run-job"
+import { jobWorkflow } from "../workflows/jobs"
+
+export default async function payoutSyncOnboardingJob(container: MedusaContainer) {
+ await runJob(container, "payout-sync-onboarding", JobTrigger.SCHEDULE, jobWorkflow("payout-sync-onboarding", container))
+}
+
+export const config = {
+ name: "payout-sync-onboarding",
+ schedule: PAYOUT_JOB_SCHEDULES["payout-sync-onboarding"],
+}
diff --git a/packages/plugins/stripe-connector/src/jobs/payout-validate-captures.ts b/packages/plugins/stripe-connector/src/jobs/payout-validate-captures.ts
new file mode 100644
index 000000000..077df7c81
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/jobs/payout-validate-captures.ts
@@ -0,0 +1,14 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+
+import { JobTrigger, PAYOUT_JOB_SCHEDULES } from "../types/common"
+import { runJob } from "../utils/run-job"
+import { jobWorkflow } from "../workflows/jobs"
+
+export default async function payoutValidateCapturesJob(container: MedusaContainer) {
+ await runJob(container, "payout-validate-captures", JobTrigger.SCHEDULE, jobWorkflow("payout-validate-captures", container))
+}
+
+export const config = {
+ name: "payout-validate-captures",
+ schedule: PAYOUT_JOB_SCHEDULES["payout-validate-captures"],
+}
diff --git a/packages/plugins/stripe-connector/src/lib/amounts.ts b/packages/plugins/stripe-connector/src/lib/amounts.ts
new file mode 100644
index 000000000..90371e402
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/lib/amounts.ts
@@ -0,0 +1,36 @@
+import { BigNumberInput } from "@medusajs/framework/types"
+import { BigNumber, MathBN } from "@medusajs/framework/utils"
+
+function getCurrencyMultiplier(currency: string): number {
+ const multipliers: Record<number, string[]> = {
+ 0: ["BIF", "CLP", "DJF", "GNF", "JPY", "KMF", "KRW", "MGA", "PYG", "RWF", "UGX", "VND", "VUV", "XAF", "XOF", "XPF"],
+ 3: ["BHD", "IQD", "JOD", "KWD", "OMR", "TND"],
+ }
+ const code = currency.toUpperCase()
+ let power = 2
+ for (const [key, list] of Object.entries(multipliers)) {
+ if (list.includes(code)) {
+ power = parseInt(key, 10)
+ break
+ }
+ }
+ return Math.pow(10, power)
+}
+
+/** Converts a major-unit amount to Stripe's smallest unit (https://docs.stripe.com/currencies). */
+export function getSmallestUnit(amount: BigNumberInput, currency: string): number {
+ const multiplier = getCurrencyMultiplier(currency)
+ const rounded = Math.round(new BigNumber(MathBN.mult(amount, multiplier)).numeric) / multiplier
+ const smallest = new BigNumber(MathBN.mult(rounded, multiplier))
+ let numeric = smallest.numeric
+ if (multiplier === 1e3) {
+ numeric = Math.ceil(numeric / 10) * 10
+ }
+ return parseInt(numeric.toString().split(".").shift()!, 10)
+}
+
+/** Converts a smallest-unit amount back to the major unit. */
+export function getAmountFromSmallestUnit(amount: BigNumberInput, currency: string): number {
+ const multiplier = getCurrencyMultiplier(currency)
+ return new BigNumber(MathBN.div(amount, multiplier)).numeric
+}
diff --git a/packages/plugins/stripe-connector/src/lib/landed.ts b/packages/plugins/stripe-connector/src/lib/landed.ts
new file mode 100644
index 000000000..dce984bf8
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/lib/landed.ts
@@ -0,0 +1,77 @@
+import Stripe from "stripe"
+
+import { getAmountFromSmallestUnit } from "./amounts"
+
+/**
+ * What a movement added to or took from the connected balance. Stripe converts
+ * a transfer into a currency the account holds, so this can differ from the
+ * amount and currency that were sent.
+ */
+export type Landed = { landed_amount: number; landed_currency: string }
+
+type StripeRef<T> = string | T | null | undefined
+
+const idOf = <T extends { id: string }>(ref: StripeRef<T>) => (typeof ref === "string" ? ref : ref?.id ?? null)
+
+const fromBalanceTransaction = (transaction: StripeRef<Stripe.BalanceTransaction>): Landed | null =>
+ transaction && typeof transaction !== "string"
+ ? {
+ landed_amount: getAmountFromSmallestUnit(Math.abs(transaction.net), transaction.currency),
+ landed_currency: transaction.currency,
+ }
+ : null
+
+// The movement already happened, so a failed lookup only loses the landed
+// amount; the settlement then falls back to its own currency.
+const quietly = async (lookup: () => Promise<Landed | null>) => {
+ try {
+ return await lookup()
+ } catch {
+ return null
+ }
+}
+
+/** The connected account's side of a transfer it received. */
+export const landedOfTransfer = (stripe: Stripe, transfer: Stripe.Transfer, stripeAccount: string) => {
+ const paymentId = idOf(transfer.destination_payment)
+ if (!paymentId) {
+ return Promise.resolve(null)
+ }
+ return quietly(async () =>
+ fromBalanceTransaction(
+ (await stripe.charges.retrieve(paymentId, { expand: ["balance_transaction"] }, { stripeAccount })).balance_transaction
+ )
+ )
+}
+
+/** The connected account's side of a transfer reversal. */
+export const landedOfReversal = (stripe: Stripe, reversal: Stripe.TransferReversal, stripeAccount: string) => {
+ const refundId = idOf(reversal.destination_payment_refund)
+ if (!refundId) {
+ return Promise.resolve(null)
+ }
+ return quietly(async () =>
+ fromBalanceTransaction(
+ (await stripe.refunds.retrieve(refundId, { expand: ["balance_transaction"] }, { stripeAccount })).balance_transaction
+ )
+ )
+}
+
+/** A transfer the connected account sent, e.g. a debit back to the platform. */
+export const landedOfOutgoingTransfer = (stripe: Stripe, transfer: Stripe.Transfer, stripeAccount: string) => {
+ const transactionId = idOf(transfer.balance_transaction)
+ if (!transactionId) {
+ return Promise.resolve(null)
+ }
+ return quietly(async () =>
+ fromBalanceTransaction(await stripe.balanceTransactions.retrieve(transactionId, {}, { stripeAccount }))
+ )
+}
+
+/** The landed amount recorded on a payout, reversal or adjustment row. */
+export const landedOf = (data: Record<string, unknown> | null | undefined): Landed | null => {
+ const source = (data?.provider ?? data) as Partial<Landed> | null | undefined
+ return typeof source?.landed_amount === "number" && typeof source?.landed_currency === "string"
+ ? { landed_amount: source.landed_amount, landed_currency: source.landed_currency }
+ : null
+}
diff --git a/packages/plugins/stripe-connector/src/lib/provider-data.ts b/packages/plugins/stripe-connector/src/lib/provider-data.ts
new file mode 100644
index 000000000..39133ac60
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/lib/provider-data.ts
@@ -0,0 +1,4 @@
+export const providerIdOf = (data: Record<string, unknown> | null | undefined): string | null => {
+ const provider = data?.provider as { id?: unknown } | undefined
+ return typeof provider?.id === "string" ? provider.id : null
+}
diff --git a/packages/plugins/stripe-connector/src/lib/stripe-client.ts b/packages/plugins/stripe-connector/src/lib/stripe-client.ts
new file mode 100644
index 000000000..f6d75469f
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/lib/stripe-client.ts
@@ -0,0 +1,13 @@
+import Stripe from "stripe"
+
+const clients = new Map<string, Stripe>()
+
+/** One Stripe SDK instance per API key, shared by the payment and payout providers. */
+export function getStripeClient(apiKey: string): Stripe {
+ let client = clients.get(apiKey)
+ if (!client) {
+ client = new Stripe(apiKey, { appInfo: { name: "Mercur Stripe connector" } })
+ clients.set(apiKey, client)
+ }
+ return client
+}
diff --git a/packages/plugins/stripe-connector/src/lib/stripe-errors.ts b/packages/plugins/stripe-connector/src/lib/stripe-errors.ts
new file mode 100644
index 000000000..16933e6ca
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/lib/stripe-errors.ts
@@ -0,0 +1,51 @@
+import { PayoutProviderError, PayoutProviderErrorCode } from "@mercurjs/types"
+
+const DEFINITIVE_TYPES = ["StripeInvalidRequestError", "StripeCardError"]
+
+type StripeErrorShape = {
+ type?: unknown
+ code?: unknown
+ statusCode?: unknown
+}
+
+/**
+ * Whether Stripe refused the request for good. Anything else (connection
+ * errors, 5xx, rate limits, idempotency conflicts) may still have gone
+ * through, so it is retried with the same idempotency key.
+ */
+export const isDefinitiveStripeRefusal = (error: unknown): boolean => {
+ if (error instanceof PayoutProviderError) {
+ return error.code !== PayoutProviderErrorCode.UNKNOWN
+ }
+ if (!error || typeof error !== "object") {
+ return false
+ }
+ const { type, statusCode } = error as StripeErrorShape
+ if (statusCode === 409 || statusCode === 429) {
+ return false
+ }
+ if (typeof type === "string" && DEFINITIVE_TYPES.includes(type)) {
+ return true
+ }
+ return typeof statusCode === "number" && statusCode >= 400 && statusCode < 500
+}
+
+export class StripePayoutProviderError extends PayoutProviderError {
+ readonly type: string | null
+ readonly stripeCode: string | null
+ readonly statusCode: number | null
+
+ constructor(error: unknown) {
+ super(error instanceof Error ? error.message : String(error), {
+ code: isDefinitiveStripeRefusal(error) ? PayoutProviderErrorCode.REFUSED : PayoutProviderErrorCode.UNKNOWN,
+ })
+ const shape = (error && typeof error === "object" ? error : {}) as StripeErrorShape
+ this.name = "StripePayoutProviderError"
+ this.type = typeof shape.type === "string" ? shape.type : null
+ this.stripeCode = typeof shape.code === "string" ? shape.code : null
+ this.statusCode = typeof shape.statusCode === "number" ? shape.statusCode : null
+ }
+}
+
+export const toPayoutProviderError = (error: unknown): PayoutProviderError =>
+ error instanceof PayoutProviderError ? error : new StripePayoutProviderError(error)
diff --git a/packages/plugins/stripe-connector/src/links/adjustment-payout-account.ts b/packages/plugins/stripe-connector/src/links/adjustment-payout-account.ts
new file mode 100644
index 000000000..40e959162
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/links/adjustment-payout-account.ts
@@ -0,0 +1,10 @@
+import { defineLink } from "@medusajs/framework/utils"
+import PayoutModule from "@mercurjs/core/modules/payout"
+
+import StripeConnectorModule from "../modules/stripe-connector"
+
+export default defineLink(
+ { linkable: StripeConnectorModule.linkable.adjustment, field: "account_id" },
+ PayoutModule.linkable.payoutAccount,
+ { readOnly: true }
+)
diff --git a/packages/plugins/stripe-connector/src/links/capture-order-group.ts b/packages/plugins/stripe-connector/src/links/capture-order-group.ts
new file mode 100644
index 000000000..7fad5e1af
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/links/capture-order-group.ts
@@ -0,0 +1,10 @@
+import { defineLink } from "@medusajs/framework/utils"
+import SellerModule from "@mercurjs/core/modules/seller"
+
+import StripeConnectorModule from "../modules/stripe-connector"
+
+export default defineLink(
+ { linkable: StripeConnectorModule.linkable.stripeCapture, field: "order_group_id" },
+ SellerModule.linkable.orderGroup,
+ { readOnly: true }
+)
diff --git a/packages/plugins/stripe-connector/src/links/settlement-line-payout-reversal.ts b/packages/plugins/stripe-connector/src/links/settlement-line-payout-reversal.ts
new file mode 100644
index 000000000..bdac75b6b
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/links/settlement-line-payout-reversal.ts
@@ -0,0 +1,10 @@
+import { defineLink } from "@medusajs/framework/utils"
+import PayoutModule from "@mercurjs/core/modules/payout"
+
+import StripeConnectorModule from "../modules/stripe-connector"
+
+export default defineLink(
+ { linkable: StripeConnectorModule.linkable.settlementLine, field: "payout_reversal_id" },
+ PayoutModule.linkable.payoutReversal,
+ { readOnly: true }
+)
diff --git a/packages/plugins/stripe-connector/src/links/settlement-line-payout.ts b/packages/plugins/stripe-connector/src/links/settlement-line-payout.ts
new file mode 100644
index 000000000..73057e7ae
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/links/settlement-line-payout.ts
@@ -0,0 +1,10 @@
+import { defineLink } from "@medusajs/framework/utils"
+import PayoutModule from "@mercurjs/core/modules/payout"
+
+import StripeConnectorModule from "../modules/stripe-connector"
+
+export default defineLink(
+ { linkable: StripeConnectorModule.linkable.settlementLine, field: "payout_id" },
+ PayoutModule.linkable.payout,
+ { readOnly: true }
+)
diff --git a/packages/plugins/stripe-connector/src/links/settlement-payout-account.ts b/packages/plugins/stripe-connector/src/links/settlement-payout-account.ts
new file mode 100644
index 000000000..e4921a769
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/links/settlement-payout-account.ts
@@ -0,0 +1,10 @@
+import { defineLink } from "@medusajs/framework/utils"
+import PayoutModule from "@mercurjs/core/modules/payout"
+
+import StripeConnectorModule from "../modules/stripe-connector"
+
+export default defineLink(
+ { linkable: StripeConnectorModule.linkable.settlement, field: "account_id" },
+ PayoutModule.linkable.payoutAccount,
+ { readOnly: true }
+)
diff --git a/packages/plugins/stripe-connector/src/modules/stripe-connector/__tests__/service.unit.spec.ts b/packages/plugins/stripe-connector/src/modules/stripe-connector/__tests__/service.unit.spec.ts
new file mode 100644
index 000000000..459cb342d
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/modules/stripe-connector/__tests__/service.unit.spec.ts
@@ -0,0 +1,157 @@
+import { PayoutStatus } from "@mercurjs/types"
+
+import {
+ AdjustmentDTO,
+ AdjustmentType,
+ INSUFFICIENT_BALANCE_REASON,
+ SettlementDTO,
+ SettlementStatus,
+ resolveStripeConnectorOptions,
+} from "../../../types/common"
+import StripeConnectorModuleService from "../service"
+
+type Call = { method: string; args: unknown[] }
+
+type Internals = {
+ options_: ReturnType<typeof resolveStripeConnectorOptions>
+ stripe_: () => unknown
+ nextAttempt_: (status: PayoutStatus, providerId: string | null, data: Record<string, unknown> | null) => number | null
+ createSettlementPayoutFromProvider_: (settlement: SettlementDTO, account: string, attempt: number) => Promise<unknown>
+ processAdjustmentFromProvider_: (adjustment: AdjustmentDTO, account: string, attempt: number) => Promise<unknown>
+}
+
+const build = (available: { currency: string; amount: number }[], payouts: { create: (...args: unknown[]) => Promise<unknown> }) => {
+ const calls: Call[] = []
+ const service = Object.create(StripeConnectorModuleService.prototype) as Internals
+ service.options_ = resolveStripeConnectorOptions({ apiKey: "sk_test_x" })
+ const stripe = {
+ balance: {
+ retrieve: (...args: unknown[]) => {
+ calls.push({ method: "balance.retrieve", args })
+ return Promise.resolve({ available })
+ },
+ },
+ payouts: {
+ create: (...args: unknown[]) => {
+ calls.push({ method: "payouts.create", args })
+ return payouts.create(...args)
+ },
+ },
+ transfers: {
+ create: (...args: unknown[]) => {
+ calls.push({ method: "transfers.create", args })
+ return payouts.create(...args)
+ },
+ },
+ accounts: { retrieve: () => Promise.resolve({ id: "acct_platform" }) },
+ }
+ service.stripe_ = () => stripe
+ return { service, calls }
+}
+
+const settlement = {
+ id: "stl_1",
+ amount: 100,
+ currency_code: "EUR",
+ payout_status: PayoutStatus.PENDING,
+ status: SettlementStatus.OPEN,
+ provider_payout_id: null,
+ data: null,
+} as unknown as SettlementDTO
+
+const adjustment = {
+ id: "adj_1",
+ account_id: "pacc_1",
+ type: AdjustmentType.EXTRA_CREDIT,
+ amount: 10,
+ currency_code: "eur",
+ data: null,
+} as unknown as AdjustmentDTO
+
+const stripeError = (type: string, statusCode?: number) => Object.assign(new Error(type), { type, statusCode })
+
+describe("StripeConnectorModuleService", () => {
+ describe("bank payout of a settlement", () => {
+ it("pays out in the settlement currency when the balance covers it", async () => {
+ const { service, calls } = build([{ currency: "eur", amount: 20000 }], {
+ create: () => Promise.resolve({ id: "po_1", status: "pending" }),
+ })
+ const outcome = await service.createSettlementPayoutFromProvider_(settlement, "acct_1", 1)
+ expect(calls[1].args[0]).toMatchObject({ amount: 10000, currency: "eur" })
+ expect(calls[1].args[1]).toEqual({ idempotencyKey: "stl_1", stripeAccount: "acct_1" })
+ expect(outcome).toMatchObject({ status: PayoutStatus.PROCESSING, provider_id: "po_1" })
+ })
+
+ it("holds the payout when the settlement currency balance is short, whatever else is available", async () => {
+ const { service, calls } = build(
+ [
+ { currency: "eur", amount: 5000 },
+ { currency: "usd", amount: 900000 },
+ ],
+ { create: () => Promise.resolve({ id: "po_1", status: "pending" }) }
+ )
+ const outcome = await service.createSettlementPayoutFromProvider_(settlement, "acct_1", 1)
+ expect(calls.some((call) => call.method === "payouts.create")).toBe(false)
+ expect(outcome).toEqual({
+ status: PayoutStatus.ON_HOLD,
+ status_reason: INSUFFICIENT_BALANCE_REASON,
+ })
+ })
+
+ it("marks a definitive refusal failed and leaves an unknown outcome processing", async () => {
+ const refused = build([{ currency: "eur", amount: 20000 }], {
+ create: () => Promise.reject(stripeError("StripeInvalidRequestError", 400)),
+ })
+ expect(await refused.service.createSettlementPayoutFromProvider_(settlement, "acct_1", 1)).toMatchObject({
+ status: PayoutStatus.FAILED,
+ })
+
+ for (const error of [
+ stripeError("StripeConnectionError"),
+ stripeError("StripeAPIError", 500),
+ stripeError("StripeRateLimitError", 429),
+ stripeError("StripeInvalidRequestError", 409),
+ ]) {
+ const transient = build([{ currency: "eur", amount: 20000 }], { create: () => Promise.reject(error) })
+ expect(typeof (await transient.service.createSettlementPayoutFromProvider_(settlement, "acct_1", 1))).toBe(
+ "string"
+ )
+ }
+ })
+ })
+
+ describe("adjustments", () => {
+ it("sends the transfer under the attempt's idempotency key", async () => {
+ const { service, calls } = build([], { create: () => Promise.resolve({ id: "tr_1" }) })
+ const outcome = await service.processAdjustmentFromProvider_(adjustment, "acct_1", 3)
+ expect(calls[0].args[1]).toEqual({ idempotencyKey: "adj_1:3" })
+ expect(outcome).toMatchObject({ status: PayoutStatus.PAID, provider_id: "tr_1" })
+ })
+
+ it("keeps an unknown outcome processing", async () => {
+ const { service } = build([], { create: () => Promise.reject(stripeError("StripeAPIError", 502)) })
+ expect(typeof (await service.processAdjustmentFromProvider_(adjustment, "acct_1", 1))).toBe("string")
+ })
+ })
+
+ describe("idempotency key attempts", () => {
+ const { service } = build([], { create: () => Promise.resolve({}) })
+
+ it("resends a processing row with the same attempt", () => {
+ expect(service.nextAttempt_(PayoutStatus.PROCESSING, null, { attempts: 2 })).toBe(2)
+ expect(service.nextAttempt_(PayoutStatus.PROCESSING, null, null)).toBe(1)
+ })
+
+ it("moves to a new attempt after a refusal or a hold", () => {
+ expect(service.nextAttempt_(PayoutStatus.FAILED, null, { attempts: 2 })).toBe(3)
+ expect(service.nextAttempt_(PayoutStatus.ON_HOLD, null, { attempts: 1 })).toBe(2)
+ expect(service.nextAttempt_(PayoutStatus.PENDING, null, null)).toBe(1)
+ })
+
+ it("never resends what the provider accepted", () => {
+ expect(service.nextAttempt_(PayoutStatus.PROCESSING, "po_1", { attempts: 1 })).toBeNull()
+ expect(service.nextAttempt_(PayoutStatus.PAID, "po_1", { attempts: 1 })).toBeNull()
+ expect(service.nextAttempt_(PayoutStatus.ABORTED, null, null)).toBeNull()
+ })
+ })
+})
diff --git a/packages/plugins/stripe-connector/src/modules/stripe-connector/index.ts b/packages/plugins/stripe-connector/src/modules/stripe-connector/index.ts
new file mode 100644
index 000000000..0db55b529
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/modules/stripe-connector/index.ts
@@ -0,0 +1,10 @@
+import { Module } from "@medusajs/framework/utils"
+
+import { STRIPE_CONNECTOR_MODULE } from "../../types/common"
+import StripeConnectorModuleService from "./service"
+
+export { StripeConnectorModuleService }
+
+export default Module(STRIPE_CONNECTOR_MODULE, {
+ service: StripeConnectorModuleService,
+})
diff --git a/packages/plugins/stripe-connector/src/modules/stripe-connector/migrations/Migration20261028130000.ts b/packages/plugins/stripe-connector/src/modules/stripe-connector/migrations/Migration20261028130000.ts
new file mode 100644
index 000000000..2067d11e9
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/modules/stripe-connector/migrations/Migration20261028130000.ts
@@ -0,0 +1,87 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations"
+
+const PAYOUT_STATUSES = `'pending', 'on_hold', 'processing', 'paid', 'failed', 'aborted'`
+const TIMESTAMPS = `"created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null`
+
+const addConstraint = (table: string, name: string, definition: string) => `
+ DO $$
+ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = '${name}') THEN
+ ALTER TABLE "${table}" ADD CONSTRAINT "${name}" ${definition};
+ END IF;
+ END $$;`
+
+export class Migration20261028130000 extends Migration {
+ override async up(): Promise<void> {
+ this.addSql(`create table if not exists "connector_checkpoint" ("id" text not null, "key" text not null, "value" text null, ${TIMESTAMPS}, constraint "connector_checkpoint_pkey" primary key ("id"));`)
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_connector_checkpoint_key_unique" ON "connector_checkpoint" ("key") WHERE deleted_at IS NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_connector_checkpoint_deleted_at" ON "connector_checkpoint" ("deleted_at") WHERE deleted_at IS NULL;`)
+
+ this.addSql(`create table if not exists "connector_job_run" ("id" text not null, "job" text not null, "trigger" text check ("trigger" in ('schedule', 'manual', 'subscriber')) not null default 'schedule', "status" text check ("status" in ('running', 'succeeded', 'failed')) not null default 'running', "started_at" timestamptz not null, "finished_at" timestamptz null, "stats" jsonb null, "error" text null, ${TIMESTAMPS}, constraint "connector_job_run_pkey" primary key ("id"));`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_connector_job_run_job_started_at" ON "connector_job_run" ("job", "started_at") WHERE deleted_at IS NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_connector_job_run_deleted_at" ON "connector_job_run" ("deleted_at") WHERE deleted_at IS NULL;`)
+
+ this.addSql(`create table if not exists "connector_notification" ("id" text not null, "type" text not null, "url" text not null, "payload" jsonb not null, "attempts" integer not null default 0, "response_status" integer null, "error" text null, "delivered" boolean not null default false, ${TIMESTAMPS}, constraint "connector_notification_pkey" primary key ("id"));`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_connector_notification_created_at" ON "connector_notification" ("created_at") WHERE deleted_at IS NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_connector_notification_deleted_at" ON "connector_notification" ("deleted_at") WHERE deleted_at IS NULL;`)
+
+ this.addSql(`create table if not exists "stripe_capture" ("id" text not null, "order_group_id" text not null, "payment_collection_id" text not null, "payment_id" text not null, "currency_code" text not null, "authorized_amount" numeric not null, "raw_authorized_amount" jsonb not null, "capturable_amount" numeric not null, "raw_capturable_amount" jsonb not null, "orders_total" integer not null default 0, "orders_decided" integer not null default 0, "status" text check ("status" in ('pending', 'ready', 'cancelable', 'captured', 'canceled', 'expired', 'failed')) not null default 'pending', "status_reason" text null, "authorized_at" timestamptz null, "expires_at" timestamptz null, ${TIMESTAMPS}, constraint "stripe_capture_pkey" primary key ("id"));`)
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_stripe_capture_order_group_id" ON "stripe_capture" ("order_group_id") WHERE deleted_at IS NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_stripe_capture_status_expires_at" ON "stripe_capture" ("status", "expires_at") WHERE deleted_at IS NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_stripe_capture_deleted_at" ON "stripe_capture" ("deleted_at") WHERE deleted_at IS NULL;`)
+
+ this.addSql(`create table if not exists "stripe_adjustment" ("id" text not null, "account_id" text not null, "type" text check ("type" in ('subscription', 'extra_invoice', 'extra_credit')) not null, "amount" numeric not null, "raw_amount" jsonb not null, "currency_code" text not null, "reason" text null, "created_by" text null, "status" text check ("status" in (${PAYOUT_STATUSES})) not null default 'pending', "status_reason" text null, "provider_transfer_id" text null, "data" jsonb null, ${TIMESTAMPS}, constraint "stripe_adjustment_pkey" primary key ("id"));`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_stripe_adjustment_account_id_status" ON "stripe_adjustment" ("account_id", "status") WHERE deleted_at IS NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_stripe_adjustment_deleted_at" ON "stripe_adjustment" ("deleted_at") WHERE deleted_at IS NULL;`)
+
+ this.addSql(`create table if not exists "stripe_settlement" ("id" text not null, "display_id" serial, "account_id" text not null, "currency_code" text not null, "period_start" timestamptz not null, "period_end" timestamptz not null, "payouts_total" numeric not null, "raw_payouts_total" jsonb not null, "reversals_total" numeric not null, "raw_reversals_total" jsonb not null, "adjustments_total" numeric not null, "raw_adjustments_total" jsonb not null, "amount" numeric not null, "raw_amount" jsonb not null, "status" text check ("status" in ('open', 'paid_out', 'failed', 'aborted')) not null default 'open', "payout_status" text check ("payout_status" in (${PAYOUT_STATUSES})) null, "provider_payout_id" text null, "status_reason" text null, "data" jsonb null, ${TIMESTAMPS}, constraint "stripe_settlement_pkey" primary key ("id"));`)
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_stripe_settlement_account_currency_period_end" ON "stripe_settlement" ("account_id", "currency_code", "period_end") WHERE deleted_at IS NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_stripe_settlement_status" ON "stripe_settlement" ("status") WHERE deleted_at IS NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_stripe_settlement_provider_payout_id" ON "stripe_settlement" ("provider_payout_id") WHERE deleted_at IS NULL AND provider_payout_id IS NOT NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_stripe_settlement_deleted_at" ON "stripe_settlement" ("deleted_at") WHERE deleted_at IS NULL;`)
+
+ this.addSql(`create table if not exists "stripe_settlement_line" ("id" text not null, "type" text check ("type" in ('payout', 'reversal', 'adjustment_credit', 'adjustment_debit')) not null, "payout_id" text null, "payout_reversal_id" text null, "amount" numeric not null, "raw_amount" jsonb not null, "settlement_id" text not null, "adjustment_id" text null, ${TIMESTAMPS}, constraint "stripe_settlement_line_pkey" primary key ("id"));`)
+ // An early draft of this migration keyed every line on a single "source_id".
+ this.addSql(`alter table if exists "stripe_settlement_line" add column if not exists "payout_id" text null, add column if not exists "payout_reversal_id" text null, add column if not exists "adjustment_id" text null;`)
+ this.addSql(`
+ DO $$
+ BEGIN
+ IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'stripe_settlement_line' AND column_name = 'source_id') THEN
+ UPDATE "stripe_settlement_line" SET "payout_id" = "source_id" WHERE "type" = 'payout' AND "payout_id" IS NULL;
+ UPDATE "stripe_settlement_line" SET "payout_reversal_id" = "source_id" WHERE "type" = 'reversal' AND "payout_reversal_id" IS NULL;
+ UPDATE "stripe_settlement_line" SET "adjustment_id" = "source_id" WHERE "type" IN ('adjustment_credit', 'adjustment_debit') AND "adjustment_id" IS NULL;
+ ALTER TABLE "stripe_settlement_line" DROP COLUMN "source_id";
+ END IF;
+ END $$;`)
+ this.addSql(`DROP INDEX IF EXISTS "IDX_stripe_settlement_line_source_id";`)
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_stripe_settlement_line_payout_id" ON "stripe_settlement_line" ("payout_id") WHERE deleted_at IS NULL AND payout_id IS NOT NULL;`)
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_stripe_settlement_line_payout_reversal_id" ON "stripe_settlement_line" ("payout_reversal_id") WHERE deleted_at IS NULL AND payout_reversal_id IS NOT NULL;`)
+ this.addSql(`CREATE UNIQUE INDEX IF NOT EXISTS "IDX_stripe_settlement_line_adjustment_id" ON "stripe_settlement_line" ("adjustment_id") WHERE deleted_at IS NULL AND adjustment_id IS NOT NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_stripe_settlement_line_settlement_id" ON "stripe_settlement_line" ("settlement_id") WHERE deleted_at IS NULL;`)
+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_stripe_settlement_line_deleted_at" ON "stripe_settlement_line" ("deleted_at") WHERE deleted_at IS NULL;`)
+ this.addSql(
+ addConstraint(
+ "stripe_settlement_line",
+ "stripe_settlement_line_settlement_id_foreign",
+ `foreign key ("settlement_id") references "stripe_settlement" ("id") on update cascade on delete cascade`
+ )
+ )
+ this.addSql(
+ addConstraint(
+ "stripe_settlement_line",
+ "stripe_settlement_line_adjustment_id_foreign",
+ `foreign key ("adjustment_id") references "stripe_adjustment" ("id") on update cascade on delete set null`
+ )
+ )
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(`drop table if exists "stripe_settlement_line" cascade;`)
+ this.addSql(`drop table if exists "stripe_settlement" cascade;`)
+ this.addSql(`drop table if exists "stripe_adjustment" cascade;`)
+ this.addSql(`drop table if exists "stripe_capture" cascade;`)
+ this.addSql(`drop table if exists "connector_notification" cascade;`)
+ this.addSql(`drop table if exists "connector_job_run" cascade;`)
+ this.addSql(`drop table if exists "connector_checkpoint" cascade;`)
+ }
+}
diff --git a/packages/plugins/stripe-connector/src/modules/stripe-connector/migrations/Migration20261028160000.ts b/packages/plugins/stripe-connector/src/modules/stripe-connector/migrations/Migration20261028160000.ts
new file mode 100644
index 000000000..93cdfc7bf
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/modules/stripe-connector/migrations/Migration20261028160000.ts
@@ -0,0 +1,15 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations"
+
+export class Migration20261028160000 extends Migration {
+ override async up(): Promise<void> {
+ this.addSql(
+ `alter table if exists "stripe_settlement" add column if not exists "payout_amount" numeric null, add column if not exists "raw_payout_amount" jsonb null, add column if not exists "payout_currency_code" text null;`
+ )
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(
+ `alter table if exists "stripe_settlement" drop column if exists "payout_amount", drop column if exists "raw_payout_amount", drop column if exists "payout_currency_code";`
+ )
+ }
+}
diff --git a/packages/plugins/stripe-connector/src/modules/stripe-connector/models/adjustment.ts b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/adjustment.ts
new file mode 100644
index 000000000..87a4fcef5
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/adjustment.ts
@@ -0,0 +1,30 @@
+import { model } from "@medusajs/framework/utils"
+import { PayoutStatus } from "@mercurjs/types"
+
+import { AdjustmentType } from "../../../types/common"
+import { SettlementLine } from "./settlement-line"
+
+export const Adjustment = model
+ .define({ name: "adjustment", tableName: "stripe_adjustment" }, {
+ id: model.id({ prefix: "adj" }).primaryKey(),
+ account_id: model.text(),
+ type: model.enum(AdjustmentType),
+ amount: model.bigNumber(),
+ currency_code: model.text(),
+ reason: model.text().nullable(),
+ created_by: model.text().nullable(),
+ status: model.enum(PayoutStatus).default(PayoutStatus.PENDING),
+ status_reason: model.text().nullable(),
+ provider_transfer_id: model.text().nullable(),
+ data: model.json().nullable(),
+ settlement_lines: model.hasMany(() => SettlementLine, {
+ mappedBy: "adjustment",
+ }),
+ })
+ .indexes([
+ {
+ name: "IDX_stripe_adjustment_account_id_status",
+ on: ["account_id", "status"],
+ where: "deleted_at IS NULL",
+ },
+ ])
diff --git a/packages/plugins/stripe-connector/src/modules/stripe-connector/models/capture.ts b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/capture.ts
new file mode 100644
index 000000000..4b31bb97c
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/capture.ts
@@ -0,0 +1,33 @@
+import { model } from "@medusajs/framework/utils"
+
+import { CaptureStatus } from "../../../types/common"
+
+export const StripeCapture = model
+ .define({ name: "stripe_capture", tableName: "stripe_capture" }, {
+ id: model.id({ prefix: "scap" }).primaryKey(),
+ order_group_id: model.text(),
+ payment_collection_id: model.text(),
+ payment_id: model.text(),
+ currency_code: model.text(),
+ authorized_amount: model.bigNumber(),
+ capturable_amount: model.bigNumber(),
+ orders_total: model.number().default(0),
+ orders_decided: model.number().default(0),
+ status: model.enum(CaptureStatus).default(CaptureStatus.PENDING),
+ status_reason: model.text().nullable(),
+ authorized_at: model.dateTime().nullable(),
+ expires_at: model.dateTime().nullable(),
+ })
+ .indexes([
+ {
+ name: "IDX_stripe_capture_order_group_id",
+ on: ["order_group_id"],
+ unique: true,
+ where: "deleted_at IS NULL",
+ },
+ {
+ name: "IDX_stripe_capture_status_expires_at",
+ on: ["status", "expires_at"],
+ where: "deleted_at IS NULL",
+ },
+ ])
diff --git a/packages/plugins/stripe-connector/src/modules/stripe-connector/models/connector-checkpoint.ts b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/connector-checkpoint.ts
new file mode 100644
index 000000000..abe3116a5
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/connector-checkpoint.ts
@@ -0,0 +1,7 @@
+import { model } from "@medusajs/framework/utils"
+
+export const ConnectorCheckpoint = model.define("connector_checkpoint", {
+ id: model.id({ prefix: "cchk" }).primaryKey(),
+ key: model.text().unique(),
+ value: model.text().nullable(),
+})
diff --git a/packages/plugins/stripe-connector/src/modules/stripe-connector/models/connector-job-run.ts b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/connector-job-run.ts
new file mode 100644
index 000000000..1f1e8d2e2
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/connector-job-run.ts
@@ -0,0 +1,22 @@
+import { model } from "@medusajs/framework/utils"
+
+import { JobRunStatus, JobTrigger } from "../../../types/common"
+
+export const ConnectorJobRun = model
+ .define("connector_job_run", {
+ id: model.id({ prefix: "cjrun" }).primaryKey(),
+ job: model.text(),
+ trigger: model.enum(JobTrigger).default(JobTrigger.SCHEDULE),
+ status: model.enum(JobRunStatus).default(JobRunStatus.RUNNING),
+ started_at: model.dateTime(),
+ finished_at: model.dateTime().nullable(),
+ stats: model.json().nullable(),
+ error: model.text().nullable(),
+ })
+ .indexes([
+ {
+ name: "IDX_connector_job_run_job_started_at",
+ on: ["job", "started_at"],
+ where: "deleted_at IS NULL",
+ },
+ ])
diff --git a/packages/plugins/stripe-connector/src/modules/stripe-connector/models/connector-notification.ts b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/connector-notification.ts
new file mode 100644
index 000000000..a3723c483
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/connector-notification.ts
@@ -0,0 +1,20 @@
+import { model } from "@medusajs/framework/utils"
+
+export const ConnectorNotification = model
+ .define("connector_notification", {
+ id: model.id({ prefix: "cnotif" }).primaryKey(),
+ type: model.text(),
+ url: model.text(),
+ payload: model.json(),
+ attempts: model.number().default(0),
+ response_status: model.number().nullable(),
+ error: model.text().nullable(),
+ delivered: model.boolean().default(false),
+ })
+ .indexes([
+ {
+ name: "IDX_connector_notification_created_at",
+ on: ["created_at"],
+ where: "deleted_at IS NULL",
+ },
+ ])
diff --git a/packages/plugins/stripe-connector/src/modules/stripe-connector/models/index.ts b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/index.ts
new file mode 100644
index 000000000..06cb4d80d
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/index.ts
@@ -0,0 +1,7 @@
+export { Adjustment } from "./adjustment"
+export { StripeCapture } from "./capture"
+export { ConnectorCheckpoint } from "./connector-checkpoint"
+export { ConnectorJobRun } from "./connector-job-run"
+export { ConnectorNotification } from "./connector-notification"
+export { Settlement } from "./settlement"
+export { SettlementLine } from "./settlement-line"
diff --git a/packages/plugins/stripe-connector/src/modules/stripe-connector/models/settlement-line.ts b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/settlement-line.ts
new file mode 100644
index 000000000..305ed4ffd
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/settlement-line.ts
@@ -0,0 +1,42 @@
+import { model } from "@medusajs/framework/utils"
+
+import { SettlementLineType } from "../../../types/common"
+import { Adjustment } from "./adjustment"
+import { Settlement } from "./settlement"
+
+export const SettlementLine = model
+ .define({ name: "settlement_line", tableName: "stripe_settlement_line" }, {
+ id: model.id({ prefix: "stlln" }).primaryKey(),
+ type: model.enum(SettlementLineType),
+ payout_id: model.text().nullable(),
+ payout_reversal_id: model.text().nullable(),
+ amount: model.bigNumber(),
+ settlement: model.belongsTo(() => Settlement, {
+ mappedBy: "lines",
+ }),
+ adjustment: model
+ .belongsTo(() => Adjustment, {
+ mappedBy: "settlement_lines",
+ })
+ .nullable(),
+ })
+ .indexes([
+ {
+ name: "IDX_stripe_settlement_line_payout_id",
+ on: ["payout_id"],
+ unique: true,
+ where: "deleted_at IS NULL AND payout_id IS NOT NULL",
+ },
+ {
+ name: "IDX_stripe_settlement_line_payout_reversal_id",
+ on: ["payout_reversal_id"],
+ unique: true,
+ where: "deleted_at IS NULL AND payout_reversal_id IS NOT NULL",
+ },
+ {
+ name: "IDX_stripe_settlement_line_adjustment_id",
+ on: ["adjustment_id"],
+ unique: true,
+ where: "deleted_at IS NULL AND adjustment_id IS NOT NULL",
+ },
+ ])
diff --git a/packages/plugins/stripe-connector/src/modules/stripe-connector/models/settlement.ts b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/settlement.ts
new file mode 100644
index 000000000..c7e858294
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/modules/stripe-connector/models/settlement.ts
@@ -0,0 +1,50 @@
+import { model } from "@medusajs/framework/utils"
+import { PayoutStatus } from "@mercurjs/types"
+
+import { SettlementStatus } from "../../../types/common"
+import { SettlementLine } from "./settlement-line"
+
+export const Settlement = model
+ .define({ name: "settlement", tableName: "stripe_settlement" }, {
+ id: model.id({ prefix: "stl" }).primaryKey(),
+ display_id: model.autoincrement(),
+ account_id: model.text(),
+ currency_code: model.text(),
+ period_start: model.dateTime(),
+ period_end: model.dateTime(),
+ payouts_total: model.bigNumber(),
+ reversals_total: model.bigNumber(),
+ adjustments_total: model.bigNumber(),
+ amount: model.bigNumber(),
+ payout_amount: model.bigNumber().nullable(),
+ payout_currency_code: model.text().nullable(),
+ status: model.enum(SettlementStatus).default(SettlementStatus.OPEN),
+ payout_status: model.enum(PayoutStatus).nullable(),
+ provider_payout_id: model.text().nullable(),
+ status_reason: model.text().nullable(),
+ data: model.json().nullable(),
+ lines: model.hasMany(() => SettlementLine, {
+ mappedBy: "settlement",
+ }),
+ })
+ .cascades({
+ delete: ["lines"],
+ })
+ .indexes([
+ {
+ name: "IDX_stripe_settlement_account_currency_period_end",
+ on: ["account_id", "currency_code", "period_end"],
+ unique: true,
+ where: "deleted_at IS NULL",
+ },
+ {
+ name: "IDX_stripe_settlement_status",
+ on: ["status"],
+ where: "deleted_at IS NULL",
+ },
+ {
+ name: "IDX_stripe_settlement_provider_payout_id",
+ on: ["provider_payout_id"],
+ where: "deleted_at IS NULL AND provider_payout_id IS NOT NULL",
+ },
+ ])
diff --git a/packages/plugins/stripe-connector/src/modules/stripe-connector/service.ts b/packages/plugins/stripe-connector/src/modules/stripe-connector/service.ts
new file mode 100644
index 000000000..2d665b88e
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/modules/stripe-connector/service.ts
@@ -0,0 +1,555 @@
+import { BigNumberInput, Context, DAL } from "@medusajs/framework/types"
+import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"
+import {
+ InjectManager,
+ InjectTransactionManager,
+ MedusaContext,
+ MedusaError,
+ MedusaService,
+} from "@medusajs/framework/utils"
+import { PayoutStatus } from "@mercurjs/types"
+import Stripe from "stripe"
+
+import { getSmallestUnit } from "../../lib/amounts"
+import { landedOfOutgoingTransfer, landedOfTransfer } from "../../lib/landed"
+import { getStripeClient } from "../../lib/stripe-client"
+import { isDefinitiveStripeRefusal } from "../../lib/stripe-errors"
+import {
+ AdjustmentDTO,
+ AdjustmentType,
+ CaptureDTO,
+ ConnectorCheckpointDTO,
+ INSUFFICIENT_BALANCE_REASON,
+ ConnectorNotificationDTO,
+ JobRunDTO,
+ JobRunStatus,
+ JobTrigger,
+ ResolvedStripeConnectorOptions,
+ SettlementDTO,
+ SettlementLineDTO,
+ SettlementStatus,
+ StripeConnectorPluginOptions,
+ resolveStripeConnectorOptions,
+} from "../../types/common"
+import {
+ Adjustment,
+ StripeCapture,
+ ConnectorCheckpoint,
+ ConnectorJobRun,
+ ConnectorNotification,
+ Settlement,
+ SettlementLine,
+} from "./models"
+
+type InjectedDependencies = {
+ baseRepository: DAL.RepositoryService
+}
+
+export type CreateSettlementWithLinesDTO = Omit<
+ SettlementDTO,
+ "id" | "display_id" | "provider_payout_id" | "data" | "created_at" | "updated_at"
+> & {
+ lines: Pick<SettlementLineDTO, "type" | "amount" | "payout_id" | "payout_reversal_id" | "adjustment_id">[]
+}
+
+type ProviderOutcome = {
+ status: PayoutStatus
+ status_reason: string | null
+ provider_id?: string
+ data?: Record<string, unknown>
+}
+
+type Attempt<T> = { row: T; attempt: number | null }
+
+export default class StripeConnectorModuleService extends MedusaService<{
+ Adjustment: { dto: AdjustmentDTO }
+ StripeCapture: { dto: CaptureDTO }
+ ConnectorCheckpoint: { dto: ConnectorCheckpointDTO }
+ ConnectorJobRun: { dto: JobRunDTO }
+ ConnectorNotification: { dto: ConnectorNotificationDTO }
+ Settlement: { dto: SettlementDTO }
+ SettlementLine: { dto: SettlementLineDTO }
+}>({
+ Adjustment,
+ StripeCapture,
+ ConnectorCheckpoint,
+ ConnectorJobRun,
+ ConnectorNotification,
+ Settlement,
+ SettlementLine,
+}) {
+ protected static readonly STATUS_REASON_MAX_LENGTH = 1024
+ protected static readonly PROCESSABLE_STATUSES = [PayoutStatus.PENDING, PayoutStatus.FAILED, PayoutStatus.ON_HOLD]
+
+ protected readonly baseRepository_: DAL.RepositoryService
+ protected readonly options_: ResolvedStripeConnectorOptions
+
+ constructor({ baseRepository }: InjectedDependencies, options: StripeConnectorPluginOptions) {
+ // @ts-ignore
+ super(...arguments)
+ this.baseRepository_ = baseRepository
+ this.options_ = resolveStripeConnectorOptions(options)
+ }
+
+ getOptions(): ResolvedStripeConnectorOptions {
+ return this.options_
+ }
+
+ isConfigured(): boolean {
+ return !!this.options_.apiKey
+ }
+
+ protected stripe_(): Stripe {
+ if (!this.options_.apiKey) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ "The Stripe connector plugin has no apiKey configured"
+ )
+ }
+ return getStripeClient(this.options_.apiKey)
+ }
+
+ /**
+ * Verifies a Connect webhook with the plugin's signing secret. Returns null
+ * when the plugin has no secret configured.
+ */
+ constructWebhookEvent(rawData: string | Buffer, signature: string): Stripe.Event | null {
+ if (!this.options_.apiKey || !this.options_.webhookSecret) {
+ return null
+ }
+ return this.stripe_().webhooks.constructEvent(rawData, signature, this.options_.webhookSecret)
+ }
+
+ @InjectManager()
+ async getCheckpoint(
+ key: string,
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
+ ): Promise<string | null> {
+ const [row] = await this.listConnectorCheckpoints({ key }, {}, sharedContext)
+ return row?.value ?? null
+ }
+
+ @InjectManager()
+ async setCheckpoint(
+ key: string,
+ value: string | null,
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
+ ): Promise<void> {
+ const [row] = await this.listConnectorCheckpoints({ key }, {}, sharedContext)
+ if (row) {
+ await this.updateConnectorCheckpoints({ id: row.id, value }, sharedContext)
+ } else {
+ await this.createConnectorCheckpoints({ key, value }, sharedContext)
+ }
+ }
+
+ @InjectManager()
+ async startJobRun(
+ input: { job: string; trigger: JobTrigger },
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
+ ): Promise<JobRunDTO> {
+ return await this.createConnectorJobRuns(
+ {
+ job: input.job,
+ trigger: input.trigger,
+ status: JobRunStatus.RUNNING,
+ started_at: new Date(),
+ },
+ sharedContext
+ )
+ }
+
+ @InjectManager()
+ async finishJobRun(
+ runId: string,
+ result: { stats?: Record<string, unknown>; error?: string },
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
+ ): Promise<JobRunDTO> {
+ return await this.updateConnectorJobRuns(
+ {
+ id: runId,
+ status: result.error ? JobRunStatus.FAILED : JobRunStatus.SUCCEEDED,
+ finished_at: new Date(),
+ stats: result.stats ?? null,
+ error: result.error ? this.reason_(result.error) : null,
+ },
+ sharedContext
+ )
+ }
+
+ /**
+ * Creates each settlement together with its lines, so a settlement never
+ * exists without the lines it nets.
+ */
+ @InjectManager()
+ async createSettlementsWithLines(
+ data: CreateSettlementWithLinesDTO[],
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
+ ): Promise<SettlementDTO[]> {
+ if (!data.length) {
+ return []
+ }
+ const ids = await this.createSettlementsWithLines_(data, sharedContext)
+ return await this.listSettlements({ id: ids }, { take: null }, sharedContext)
+ }
+
+ /**
+ * Captures part of an authorized PaymentIntent. Medusa's Stripe provider
+ * always captures the whole intent, which would charge the customer for
+ * orders canceled before the capture.
+ */
+ async capturePaymentIntent(
+ captureId: string,
+ paymentIntentId: string,
+ amount: BigNumberInput,
+ currencyCode: string
+ ): Promise<void> {
+ const amountToCapture = getSmallestUnit(amount, currencyCode)
+ try {
+ // The amount is in the key: Stripe refuses a key reused with other parameters.
+ await this.stripe_().paymentIntents.capture(
+ paymentIntentId,
+ { amount_to_capture: amountToCapture },
+ { idempotencyKey: `capture-${captureId}-${amountToCapture}` }
+ )
+ } catch (error) {
+ const stripeError = error as Stripe.errors.StripeError
+ if (stripeError.code === "payment_intent_unexpected_state" && stripeError.payment_intent?.status === "succeeded") {
+ return
+ }
+ throw error
+ }
+ }
+
+ /**
+ * Moves an adjustment between the platform and the connected account: a
+ * credit is a transfer to the seller, an invoice or subscription is a
+ * transfer from the seller's balance back to the platform.
+ */
+ @InjectManager()
+ async processAdjustment(
+ adjustmentId: string,
+ stripeAccountId: string,
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
+ ): Promise<AdjustmentDTO> {
+ const { row, attempt } = await this.processAdjustment_(adjustmentId, sharedContext)
+
+ if (attempt) {
+ const outcome = await this.processAdjustmentFromProvider_(row, stripeAccountId, attempt)
+ await this.recordAdjustmentOutcome_(adjustmentId, outcome, sharedContext)
+ }
+
+ return await this.retrieveAdjustment(adjustmentId, {}, sharedContext)
+ }
+
+ /** Pays the settlement out from the connected balance to the seller's bank. */
+ @InjectManager()
+ async createSettlementPayout(
+ settlementId: string,
+ stripeAccountId: string,
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
+ ): Promise<SettlementDTO> {
+ const { row, attempt } = await this.processSettlementPayout_(settlementId, sharedContext)
+
+ if (attempt) {
+ const outcome = await this.createSettlementPayoutFromProvider_(row, stripeAccountId, attempt)
+ await this.recordSettlementPayoutOutcome_(settlementId, outcome, sharedContext)
+ }
+
+ return await this.retrieveSettlement(settlementId, {}, sharedContext)
+ }
+
+ @InjectManager()
+ async applySettlementPayoutEvent(
+ providerPayoutId: string,
+ status: Stripe.Payout["status"],
+ reason: string | null,
+ @MedusaContext() sharedContext?: Context<SqlEntityManager>
+ ): Promise<SettlementDTO | null> {
+ const [settlement] = await this.listSettlements(
+ { provider_payout_id: providerPayoutId },
+ {},
+ sharedContext
+ )
+ if (!settlement) {
+ return null
+ }
+
+ const payoutStatus = this.payoutStatusFromStripe_(status)
+ return await this.updateSettlements(
+ {
+ id: settlement.id,
+ payout_status: payoutStatus,
+ status: this.settlementStatusFor_(payoutStatus),
+ status_reason: payoutStatus === PayoutStatus.FAILED ? reason : null,
+ },
+ sharedContext
+ )
+ }
+
+ @InjectTransactionManager()
+ protected async createSettlementsWithLines_(
+ data: CreateSettlementWithLinesDTO[],
+ @MedusaContext() sharedContext: Context<SqlEntityManager> = {}
+ ): Promise<string[]> {
+ const settlements = await this.createSettlements(
+ data.map(({ lines: _lines, ...settlement }) => settlement),
+ sharedContext
+ )
+ await this.createSettlementLines(
+ settlements.flatMap((settlement, index) =>
+ data[index].lines.map((line) => ({ ...line, settlement_id: settlement.id }))
+ ),
+ sharedContext
+ )
+ return settlements.map((settlement) => settlement.id)
+ }
+
+ @InjectTransactionManager()
+ protected async processAdjustment_(
+ adjustmentId: string,
+ @MedusaContext() sharedContext: Context<SqlEntityManager> = {}
+ ): Promise<Attempt<AdjustmentDTO>> {
+ await this.lockRow_("stripe_adjustment", adjustmentId, sharedContext)
+ const adjustment = await this.retrieveAdjustment(adjustmentId, {}, sharedContext)
+
+ const attempt = this.nextAttempt_(adjustment.status, adjustment.provider_transfer_id, adjustment.data)
+ if (attempt && adjustment.status !== PayoutStatus.PROCESSING) {
+ await this.updateAdjustments(
+ {
+ id: adjustment.id,
+ status: PayoutStatus.PROCESSING,
+ data: { ...(adjustment.data ?? {}), attempts: attempt },
+ },
+ sharedContext
+ )
+ }
+
+ return { row: adjustment, attempt }
+ }
+
+ @InjectTransactionManager()
+ protected async processSettlementPayout_(
+ settlementId: string,
+ @MedusaContext() sharedContext: Context<SqlEntityManager> = {}
+ ): Promise<Attempt<SettlementDTO>> {
+ await this.lockRow_("stripe_settlement", settlementId, sharedContext)
+ const settlement = await this.retrieveSettlement(settlementId, {}, sharedContext)
+
+ const attempt = settlement.payout_status
+ ? this.nextAttempt_(settlement.payout_status, settlement.provider_payout_id, settlement.data)
+ : null
+ if (attempt && settlement.payout_status !== PayoutStatus.PROCESSING) {
+ await this.updateSettlements(
+ {
+ id: settlement.id,
+ payout_status: PayoutStatus.PROCESSING,
+ status: SettlementStatus.OPEN,
+ data: { ...(settlement.data ?? {}), attempts: attempt },
+ },
+ sharedContext
+ )
+ }
+
+ return { row: settlement, attempt }
+ }
+
+ @InjectTransactionManager()
+ protected async recordAdjustmentOutcome_(
+ adjustmentId: string,
+ outcome: ProviderOutcome | string,
+ @MedusaContext() sharedContext: Context<SqlEntityManager> = {}
+ ): Promise<void> {
+ await this.lockRow_("stripe_adjustment", adjustmentId, sharedContext)
+ const adjustment = await this.retrieveAdjustment(adjustmentId, {}, sharedContext)
+ if (adjustment.status !== PayoutStatus.PROCESSING) {
+ return
+ }
+
+ if (typeof outcome === "string") {
+ await this.updateAdjustments({ id: adjustmentId, status_reason: outcome }, sharedContext)
+ return
+ }
+
+ await this.updateAdjustments(
+ {
+ id: adjustmentId,
+ status: outcome.status,
+ status_reason: outcome.status_reason,
+ ...(outcome.provider_id ? { provider_transfer_id: outcome.provider_id } : {}),
+ ...(outcome.data ? { data: { ...(adjustment.data ?? {}), ...outcome.data } } : {}),
+ },
+ sharedContext
+ )
+ }
+
+ @InjectTransactionManager()
+ protected async recordSettlementPayoutOutcome_(
+ settlementId: string,
+ outcome: ProviderOutcome | string,
+ @MedusaContext() sharedContext: Context<SqlEntityManager> = {}
+ ): Promise<void> {
+ await this.lockRow_("stripe_settlement", settlementId, sharedContext)
+ const settlement = await this.retrieveSettlement(settlementId, {}, sharedContext)
+ if (settlement.payout_status !== PayoutStatus.PROCESSING || settlement.provider_payout_id) {
+ return
+ }
+
+ if (typeof outcome === "string") {
+ await this.updateSettlements({ id: settlementId, status_reason: outcome }, sharedContext)
+ return
+ }
+
+ await this.updateSettlements(
+ {
+ id: settlementId,
+ payout_status: outcome.status,
+ status: this.settlementStatusFor_(outcome.status),
+ status_reason: outcome.status_reason,
+ ...(outcome.provider_id ? { provider_payout_id: outcome.provider_id } : {}),
+ ...(outcome.data ? { data: { ...(settlement.data ?? {}), provider: outcome.data } } : {}),
+ },
+ sharedContext
+ )
+ }
+
+ // Runs outside the transaction so the row lock is never held across the Stripe call.
+ // A string result is a transient error: the row stays processing and the next
+ // run resends with the same idempotency key.
+ protected async processAdjustmentFromProvider_(
+ adjustment: AdjustmentDTO,
+ stripeAccountId: string,
+ attempt: number
+ ): Promise<ProviderOutcome | string> {
+ const amount = getSmallestUnit(adjustment.amount, adjustment.currency_code)
+ const metadata = { adjustment_id: adjustment.id, account_id: adjustment.account_id }
+ const idempotencyKey = this.idempotencyKey_(adjustment.id, attempt)
+
+ try {
+ const stripe = this.stripe_()
+ let transfer: Stripe.Transfer
+ if (adjustment.type === AdjustmentType.EXTRA_CREDIT) {
+ transfer = await stripe.transfers.create(
+ { amount, currency: adjustment.currency_code, destination: stripeAccountId, metadata },
+ { idempotencyKey }
+ )
+ } else {
+ const platform = await stripe.accounts.retrieve()
+ transfer = await stripe.transfers.create(
+ { amount, currency: adjustment.currency_code, destination: platform.id, metadata },
+ { idempotencyKey, stripeAccount: stripeAccountId }
+ )
+ }
+ const landed =
+ adjustment.type === AdjustmentType.EXTRA_CREDIT
+ ? await landedOfTransfer(stripe, transfer, stripeAccountId)
+ : await landedOfOutgoingTransfer(stripe, transfer, stripeAccountId)
+ return { status: PayoutStatus.PAID, status_reason: null, provider_id: transfer.id, ...(landed ? { data: landed } : {}) }
+ } catch (error) {
+ return this.outcomeFromError_(error)
+ }
+ }
+
+ protected async createSettlementPayoutFromProvider_(
+ settlement: SettlementDTO,
+ stripeAccountId: string,
+ attempt: number
+ ): Promise<ProviderOutcome | string> {
+ const currency = (settlement.payout_currency_code ?? settlement.currency_code).toLowerCase()
+
+ try {
+ const stripe = this.stripe_()
+ const requested = getSmallestUnit(settlement.payout_amount ?? settlement.amount, currency)
+ const balance = await stripe.balance.retrieve({}, { stripeAccount: stripeAccountId })
+ const available = balance.available.find((entry) => entry.currency === currency)?.amount ?? 0
+
+ if (available < requested) {
+ return {
+ status: PayoutStatus.ON_HOLD,
+ status_reason: INSUFFICIENT_BALANCE_REASON,
+ }
+ }
+
+ const payout = await stripe.payouts.create(
+ { amount: requested, currency, metadata: { settlement_id: settlement.id } },
+ { idempotencyKey: this.idempotencyKey_(settlement.id, attempt), stripeAccount: stripeAccountId }
+ )
+
+ return {
+ status: this.payoutStatusFromStripe_(payout.status),
+ status_reason: null,
+ provider_id: payout.id,
+ data: { ...payout },
+ }
+ } catch (error) {
+ return this.outcomeFromError_(error)
+ }
+ }
+
+ protected outcomeFromError_(error: unknown): ProviderOutcome | string {
+ const reason = this.reason_(error instanceof Error ? error.message : String(error))
+ return isDefinitiveStripeRefusal(error) ? { status: PayoutStatus.FAILED, status_reason: reason } : reason
+ }
+
+ // A processing row without a provider id was sent but its outcome is unknown,
+ // so it is resent with the key of that attempt. Any other retry follows a
+ // definitive refusal, which Stripe caches against the key, so it needs a new one.
+ protected nextAttempt_(
+ status: PayoutStatus,
+ providerId: string | null,
+ data: Record<string, unknown> | null
+ ): number | null {
+ const attempts = Number(data?.attempts ?? 0)
+ if (status === PayoutStatus.PROCESSING) {
+ return providerId ? null : Math.max(attempts, 1)
+ }
+ return StripeConnectorModuleService.PROCESSABLE_STATUSES.includes(status) ? attempts + 1 : null
+ }
+
+ protected async lockRow_(table: string, id: string, sharedContext: Context<SqlEntityManager>) {
+ // A FOR UPDATE on a pooled (autocommit) connection would release the lock
+ // immediately, so require the transaction context.
+ const knex = sharedContext.transactionManager?.getTransactionContext()
+ if (!knex) {
+ throw new MedusaError(
+ MedusaError.Types.UNEXPECTED_STATE,
+ `Processing ${table} ${id} must run inside a transaction.`
+ )
+ }
+
+ await knex.raw("SET LOCAL lock_timeout = '3s'")
+ await knex(table).where("id", id).forUpdate().select("id")
+ }
+
+ protected idempotencyKey_(id: string, attempt: number) {
+ return attempt === 1 ? id : `${id}:${attempt}`
+ }
+
+ protected reason_(message: string) {
+ return message.slice(0, StripeConnectorModuleService.STATUS_REASON_MAX_LENGTH)
+ }
+
+ protected settlementStatusFor_(payoutStatus: PayoutStatus): SettlementStatus {
+ switch (payoutStatus) {
+ case PayoutStatus.PAID:
+ return SettlementStatus.PAID_OUT
+ case PayoutStatus.FAILED:
+ case PayoutStatus.ON_HOLD:
+ return SettlementStatus.FAILED
+ default:
+ return SettlementStatus.OPEN
+ }
+ }
+
+ protected payoutStatusFromStripe_(status: Stripe.Payout["status"]): PayoutStatus {
+ switch (status) {
+ case "paid":
+ return PayoutStatus.PAID
+ case "failed":
+ case "canceled":
+ return PayoutStatus.FAILED
+ default:
+ return PayoutStatus.PROCESSING
+ }
+ }
+}
diff --git a/packages/plugins/stripe-connector/src/providers/payment-stripe/index.ts b/packages/plugins/stripe-connector/src/providers/payment-stripe/index.ts
new file mode 100644
index 000000000..f6f190b29
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/providers/payment-stripe/index.ts
@@ -0,0 +1,9 @@
+import { ModuleProvider, Modules } from "@medusajs/framework/utils"
+
+import { StripeConnectorPaymentProviderService } from "./service"
+
+export { StripeConnectorPaymentProviderService }
+
+export default ModuleProvider(Modules.PAYMENT, {
+ services: [StripeConnectorPaymentProviderService],
+})
diff --git a/packages/plugins/stripe-connector/src/providers/payment-stripe/service.ts b/packages/plugins/stripe-connector/src/providers/payment-stripe/service.ts
new file mode 100644
index 000000000..69294b967
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/providers/payment-stripe/service.ts
@@ -0,0 +1,92 @@
+import {
+ InitiatePaymentInput,
+ InitiatePaymentOutput,
+ ProviderWebhookPayload,
+ RetrievePaymentInput,
+ RetrievePaymentOutput,
+ WebhookActionResult,
+} from "@medusajs/framework/types"
+import { PaymentActions } from "@medusajs/framework/utils"
+import StripeBase from "@medusajs/payment-stripe/dist/core/stripe-base"
+import type { PaymentIntentOptions, StripeOptions } from "@medusajs/payment-stripe/dist/types"
+import Stripe from "stripe"
+
+import { ORDER_GROUP_METADATA_KEY, StripeConnectorPaymentProviderOptions } from "../../types"
+
+/**
+ * Aggregate payment model: the platform account charges the
+ * whole cart once, authorized only, and the payout module captures it when
+ * the order group is decided. The PaymentIntent carries the order group so
+ * transfers can be grouped and reconciled on Stripe's side.
+ */
+export class StripeConnectorPaymentProviderService extends StripeBase {
+ static identifier = "stripe-connector"
+
+ protected readonly connectorOptions_: StripeConnectorPaymentProviderOptions
+
+ constructor(cradle: Record<string, unknown>, options: StripeConnectorPaymentProviderOptions) {
+ super(cradle, { ...options, capture: false } as unknown as StripeOptions)
+ this.connectorOptions_ = options
+ }
+
+ static validateOptions(options: StripeOptions): void {
+ if (!options.apiKey) {
+ throw new Error("Stripe connector payment provider: apiKey is required")
+ }
+ if (!options.webhookSecret) {
+ throw new Error("Stripe connector payment provider: webhookSecret is required")
+ }
+ }
+
+ get paymentIntentOptions(): PaymentIntentOptions {
+ return { capture_method: "manual" }
+ }
+
+ protected orderGroupKey(): string {
+ return this.connectorOptions_.orderGroupMetadataKey ?? ORDER_GROUP_METADATA_KEY
+ }
+
+ async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
+ const cartId = (input.data?.cart_id as string | undefined) ?? (input.context as { cart_id?: string } | undefined)?.cart_id
+ const orderGroupId = input.data?.order_group_id as string | undefined
+ const metadata = {
+ ...((input.data?.metadata as Record<string, string> | undefined) ?? {}),
+ ...(cartId ? { mercur_cart_id: cartId } : {}),
+ ...(orderGroupId ? { [this.orderGroupKey()]: orderGroupId } : {}),
+ }
+
+ return await super.initiatePayment({
+ ...input,
+ data: {
+ ...input.data,
+ capture_method: "manual",
+ metadata,
+ ...(cartId ? { transfer_group: cartId } : {}),
+ },
+ })
+ }
+
+ /**
+ * Adds `latest_charge` to the payment data so the payout provider can use
+ * the charge as `source_transaction` without a second round trip.
+ */
+ async retrievePayment(input: RetrievePaymentInput): Promise<RetrievePaymentOutput> {
+ const result = await super.retrievePayment(input)
+ const intent = result.data as unknown as Stripe.PaymentIntent | undefined
+ if (intent && typeof intent.latest_charge === "object" && intent.latest_charge) {
+ return { data: { ...(intent as unknown as Record<string, unknown>), latest_charge: intent.latest_charge.id } }
+ }
+ return result
+ }
+
+ async getWebhookActionAndData(payload: ProviderWebhookPayload["payload"]): Promise<WebhookActionResult> {
+ const event = this.constructWebhookEvent(payload)
+
+ // Charge events from connected accounts are not the platform's payments.
+ if (event.account) {
+ return { action: PaymentActions.NOT_SUPPORTED }
+ }
+
+ return await super.getWebhookActionAndData(payload)
+ }
+}
diff --git a/packages/plugins/stripe-connector/src/providers/payout-stripe-connect/__tests__/service.unit.spec.ts b/packages/plugins/stripe-connector/src/providers/payout-stripe-connect/__tests__/service.unit.spec.ts
new file mode 100644
index 000000000..cd883e16f
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/providers/payout-stripe-connect/__tests__/service.unit.spec.ts
@@ -0,0 +1,267 @@
+import { PayoutAccountStatus, PayoutProviderError, PayoutProviderErrorCode, PayoutStatus } from "@mercurjs/types"
+
+import { StripeConnectPayoutProviderService } from "../service"
+
+type Call = { method: string; args: unknown[] }
+
+const makeStripe = (calls: Call[]) => {
+ const record =
+ (method: string, result: unknown) =>
+ (...args: unknown[]) => {
+ calls.push({ method, args })
+ return Promise.resolve(result)
+ }
+ return {
+ accounts: {
+ create: record("accounts.create", { id: "acct_new", details_submitted: false, charges_enabled: false, payouts_enabled: false, requirements: { currently_due: ["x"], past_due: [], pending_verification: [] } }),
+ update: record("accounts.update", { id: "acct_seller" }),
+ retrieve: record("accounts.retrieve", { id: "acct_platform", details_submitted: true, charges_enabled: true, payouts_enabled: true, requirements: {} }),
+ list: record("accounts.list", { data: [], has_more: false }),
+ createLoginLink: record("accounts.createLoginLink", { url: "https://connect.stripe.com/express/login" }),
+ del: record("accounts.del", { id: "acct_seller", deleted: true }),
+ },
+ accountLinks: { create: record("accountLinks.create", { url: "https://connect.stripe.com/setup", expires_at: 1_700_000_000 }) },
+ transfers: {
+ create: record("transfers.create", { id: "tr_1" }),
+ createReversal: record("transfers.createReversal", { id: "trr_1" }),
+ retrieve: record("transfers.retrieve", { id: "tr_1", amount: 16200, amount_reversed: 0 }),
+ listReversals: (...args: unknown[]) => {
+ calls.push({ method: "transfers.listReversals", args })
+ return (async function* (): AsyncGenerator<{ id: string; metadata: Record<string, string> }> {})()
+ },
+ },
+ payouts: { create: record("payouts.create", { id: "po_1", status: "pending" }) },
+ refunds: { retrieve: record("refunds.retrieve", { id: "pyr_1", balance_transaction: { currency: "pln", net: -6900 } }) },
+ charges: { retrieve: record("charges.retrieve", { id: "ch_1", amount: 25800, currency: "eur", balance_transaction: { currency: "eur", amount: 25800 } }) },
+ balance: { retrieve: record("balance.retrieve", { available: [{ currency: "eur", amount: 100000 }] }) },
+ paymentIntents: { retrieve: record("paymentIntents.retrieve", { id: "pi_1", status: "succeeded", latest_charge: "ch_from_pi" }) },
+ webhooks: { constructEvent: (raw: string) => JSON.parse(raw) },
+ }
+}
+
+const build = (options: { manualPayouts?: boolean } = {}) => {
+ const calls: Call[] = []
+ const service = new StripeConnectPayoutProviderService({}, { apiKey: "sk_test_x", webhookSecret: "whsec_x", ...options })
+ ;(service as unknown as { stripe_: unknown }).stripe_ = makeStripe(calls)
+ return { service, calls }
+}
+
+const account = { id: "acct_seller", data: {} }
+
+describe("StripeConnectPayoutProviderService", () => {
+ it("refuses to start without an api key or webhook secret", () => {
+ expect(() => new StripeConnectPayoutProviderService({}, { apiKey: "", webhookSecret: "x" })).toThrow()
+ expect(() => new StripeConnectPayoutProviderService({}, { apiKey: "x", webhookSecret: "" })).toThrow()
+ })
+
+ it("creates an express account with a manual payout schedule when asked", async () => {
+ const { service, calls } = build({ manualPayouts: true })
+ const out = await service.createAccount({
+ country: "DE",
+ business_type: "company",
+ metadata: { seller_id: "sel_1" },
+ context: { idempotency_key: "pacc_1" },
+ })
+ expect(calls[0].method).toBe("accounts.create")
+ expect(calls[0].args[0]).toMatchObject({ type: "express", country: "DE", business_type: "company", capabilities: { card_payments: { requested: true }, transfers: { requested: true } }, settings: { payouts: { debit_negative_balances: false, schedule: { interval: "manual" } } } })
+ expect(calls[0].args[1]).toEqual({ idempotencyKey: "pacc_1" })
+ expect(out.status).toBe(PayoutAccountStatus.PENDING)
+ expect(out.requirements.currently_due).toEqual(["x"])
+ })
+
+ it("creates onboarding and login links", async () => {
+ const { service, calls } = build()
+ const link = await service.createOnboarding({ account, refresh_url: "https://api/refresh", return_url: "https://vendor/stripe" })
+ expect(calls[0].method).toBe("accounts.update")
+ expect(calls[0].args[1]).toEqual({ capabilities: { card_payments: { requested: true }, transfers: { requested: true } } })
+ expect(calls[1].args[0]).toMatchObject({ account: "acct_seller", refresh_url: "https://api/refresh", return_url: "https://vendor/stripe", type: "account_onboarding" })
+ expect(link.url).toContain("setup")
+ calls.length = 0
+ await service.createOnboarding({ account: { id: "acct_seller", data: { capabilities: { transfers: "active" } } }, refresh_url: "r", return_url: "u" })
+ expect(calls[0].method).toBe("accountLinks.create")
+ const login = await service.createLoginLink({ account })
+ expect(calls[1].method).toBe("accounts.createLoginLink")
+ expect(login.url).toContain("login")
+ })
+
+ it("pays out as a transfer with the charge as source_transaction, resolving a PaymentIntent when needed", async () => {
+ const { service, calls } = build()
+ const payout = await service.createPayout({
+ account,
+ amount: 162,
+ currency_code: "eur",
+ source_payment: { id: "pay_1", data: { id: "pi_1", latest_charge: "ch_1" } },
+ group: "order_1",
+ metadata: { payout_id: "pout_1" },
+ context: { idempotency_key: "pout_1" },
+ })
+ expect(payout.status).toBe(PayoutStatus.PAID)
+ expect(calls[0].method).toBe("charges.retrieve")
+ expect(calls[1].method).toBe("transfers.create")
+ expect(calls[1].args[0]).toMatchObject({ amount: 16200, currency: "eur", destination: "acct_seller", source_transaction: "ch_1" })
+ expect(calls[1].args[0]).not.toHaveProperty("transfer_group")
+
+ calls.length = 0
+ await service.createPayout({
+ account,
+ amount: 10,
+ currency_code: "eur",
+ source_payment: { id: "pay_2", data: { id: "pi_1" } },
+ })
+ expect(calls[0].method).toBe("paymentIntents.retrieve")
+ expect(calls[2].args[0]).toMatchObject({ source_transaction: "ch_from_pi" })
+ })
+
+ it("records what the transfer and its reversal moved on the connected balance", async () => {
+ const { service, calls } = build()
+ const stripe = (service as unknown as { stripe_: ReturnType<typeof makeStripe> }).stripe_
+ stripe.transfers.create = (...args: unknown[]) => {
+ calls.push({ method: "transfers.create", args })
+ return Promise.resolve({ id: "tr_1", destination_payment: "py_1" })
+ }
+ stripe.charges.retrieve = (...args: unknown[]) => {
+ calls.push({ method: "charges.retrieve", args })
+ return Promise.resolve(
+ args[0] === "py_1"
+ ? { id: "py_1", balance_transaction: { currency: "pln", net: 69400 } }
+ : { id: "ch_1", amount: 16200, currency: "eur", balance_transaction: { currency: "eur", amount: 16200 } }
+ )
+ }
+ const payout = await service.createPayout({
+ account,
+ amount: 162,
+ currency_code: "eur",
+ source_payment: { id: "pay_1", data: { id: "pi_1", latest_charge: "ch_1" } },
+ })
+ expect(payout.data).toMatchObject({ landed_amount: 694, landed_currency: "pln" })
+ expect(calls.find((c) => c.args[0] === "py_1")?.args[2]).toEqual({ stripeAccount: "acct_seller" })
+
+ stripe.transfers.retrieve = () => Promise.resolve({ id: "tr_1", amount: 16200, amount_reversed: 0, destination: "acct_seller" })
+ stripe.transfers.createReversal = () => Promise.resolve({ id: "trr_1", destination_payment_refund: "pyr_1" })
+ const reversal = await service.reversePayout({ payout: { id: "tr_1", data: {} }, amount: 16.2, currency_code: "eur" })
+ expect(reversal.data).toMatchObject({ landed_amount: 69, landed_currency: "pln" })
+ })
+
+ it("converts a cross-currency payout at the captured amount's rate", async () => {
+ const { service, calls } = build()
+ const stripe = (service as unknown as { stripe_: ReturnType<typeof makeStripe> }).stripe_
+ stripe.charges.retrieve = (...args: unknown[]) => {
+ calls.push({ method: "charges.retrieve", args })
+ return Promise.resolve({ id: "ch_1", amount: 20000, amount_captured: 10000, currency: "eur", balance_transaction: { currency: "usd", amount: 11000 } })
+ }
+ await service.createPayout({
+ account,
+ amount: 80,
+ currency_code: "eur",
+ source_payment: { id: "pay_1", data: { id: "pi_1", latest_charge: "ch_1" } },
+ })
+ expect(calls[1].args[0]).toMatchObject({ amount: 8800, currency: "usd" })
+ })
+
+ it("reverses a payout on its transfer", async () => {
+ const { service, calls } = build()
+ const reversal = await service.reversePayout({ payout: { id: "tr_1", data: {} }, amount: 54, currency_code: "eur", context: { idempotency_key: "pourev_1" } })
+ const create = calls.find((call) => call.method === "transfers.createReversal")
+ expect(create?.args[0]).toBe("tr_1")
+ expect(create?.args[1]).toMatchObject({ amount: 5400 })
+ expect(create?.args[2]).toEqual({ idempotencyKey: "pourev_1" })
+ expect(reversal.status).toBe(PayoutStatus.PAID)
+ })
+
+ it("caps a reversal at what is left on the transfer", async () => {
+ const { service, calls } = build()
+ const stripe = (service as unknown as { stripe_: ReturnType<typeof makeStripe> }).stripe_
+ stripe.transfers.retrieve = () => Promise.resolve({ id: "tr_1", amount: 10000, amount_reversed: 9950 })
+ await service.reversePayout({ payout: { id: "tr_1", data: {} }, amount: 1, currency_code: "eur" })
+ const create = calls.find((call) => call.method === "transfers.createReversal")
+ expect(create?.args[1]).toMatchObject({ amount: 50 })
+ })
+
+ it("refuses to reverse a transfer that is already fully reversed", async () => {
+ const { service, calls } = build()
+ const stripe = (service as unknown as { stripe_: ReturnType<typeof makeStripe> }).stripe_
+ stripe.transfers.retrieve = () => Promise.resolve({ id: "tr_1", amount: 10000, amount_reversed: 10000 })
+ const error = await service
+ .reversePayout({ payout: { id: "tr_1", data: {} }, amount: 1, currency_code: "eur" })
+ .catch((e: unknown) => e)
+ expect(error).toBeInstanceOf(PayoutProviderError)
+ expect((error as PayoutProviderError).final).toBe(true)
+ expect(calls.some((call) => call.method === "transfers.createReversal")).toBe(false)
+ })
+
+ it("returns the reversal a previous attempt already created", async () => {
+ const { service, calls } = build()
+ const stripe = (service as unknown as { stripe_: ReturnType<typeof makeStripe> }).stripe_
+ stripe.transfers.listReversals = () =>
+ (async function* () {
+ yield { id: "trr_other", metadata: { payout_reversal_id: "pourev_0" } }
+ yield { id: "trr_done", metadata: { payout_reversal_id: "pourev_1" } }
+ })()
+ const reversal = await service.reversePayout({
+ payout: { id: "tr_1", data: {} },
+ amount: 54,
+ currency_code: "eur",
+ metadata: { payout_id: "pout_1", payout_reversal_id: "pourev_1" },
+ })
+ expect(reversal.id).toBe("trr_done")
+ expect(calls.some((call) => call.method === "transfers.createReversal")).toBe(false)
+ })
+
+ it("tells a definitive Stripe refusal from an unknown outcome", async () => {
+ const { service } = build()
+ const stripe = (service as unknown as { stripe_: ReturnType<typeof makeStripe> }).stripe_
+ const fail = (error: Record<string, unknown>) => {
+ stripe.transfers.create = () => Promise.reject(Object.assign(new Error("stripe"), error))
+ return service
+ .createPayout({ account, amount: 10, currency_code: "eur" })
+ .then(() => {
+ throw new Error("expected a refusal")
+ })
+ .catch((e: unknown) => e as PayoutProviderError & { type: string })
+ }
+
+ const refused = await fail({ type: "StripeInvalidRequestError", statusCode: 400, code: "balance_insufficient" })
+ expect(refused.code).toBe(PayoutProviderErrorCode.REFUSED)
+ expect(refused.type).toBe("StripeInvalidRequestError")
+
+ expect((await fail({ type: "StripeConnectionError" })).code).toBe(PayoutProviderErrorCode.UNKNOWN)
+ expect((await fail({ type: "StripeAPIError", statusCode: 500 })).code).toBe(PayoutProviderErrorCode.UNKNOWN)
+ expect((await fail({ type: "StripeRateLimitError", statusCode: 429 })).code).toBe(PayoutProviderErrorCode.UNKNOWN)
+ expect((await fail({ type: "StripeInvalidRequestError", statusCode: 409 })).code).toBe(PayoutProviderErrorCode.UNKNOWN)
+ })
+
+ it("deletes a connected account", async () => {
+ const { service, calls } = build()
+ await service.deleteAccount({ account })
+ expect(calls[0]).toEqual({ method: "accounts.del", args: ["acct_seller"] })
+ })
+
+ it("normalizes account and transfer webhooks", async () => {
+ const { service } = build()
+ const hook = (event: unknown) => service.getWebhookActionAndData({ data: {}, rawData: JSON.stringify(event), headers: { "stripe-signature": "sig" } })
+
+ const rejected = await hook({ type: "account.updated", data: { object: { id: "acct_1", details_submitted: true, requirements: { disabled_reason: "rejected.fraud" } } } })
+ expect(rejected).toEqual({ action: "account.rejected", data: { id: "acct_1" } })
+
+ const active = await hook({ type: "account.updated", data: { object: { id: "acct_2", details_submitted: true, charges_enabled: true, payouts_enabled: true, requirements: {} } } })
+ expect(active.action).toBe("account.activated")
+
+ const restricted = await hook({ type: "account.updated", data: { object: { id: "acct_3", details_submitted: true, charges_enabled: true, payouts_enabled: false, requirements: { currently_due: ["doc"] } } } })
+ expect(restricted.action).toBe("account.restricted")
+
+ const paid = await hook({ type: "transfer.created", data: { object: { id: "tr_1" } } })
+ expect(paid).toEqual({ action: "payout.paid", data: { id: "tr_1" } })
+
+ const reversed = await hook({ type: "transfer.reversed", data: { object: { id: "tr_1" } } })
+ expect(reversed).toEqual({ action: "payout.reversed", data: { id: "tr_1" } })
+
+ const foreign = await hook({ type: "transfer.created", account: "acct_other", data: { object: { id: "tr_9", metadata: { payout_id: "pout_1" } } } })
+ expect(foreign.action).toBe("not_supported")
+
+ const bank = await hook({ type: "payout.failed", data: { object: { id: "po_1" } } })
+ expect(bank.action).toBe("not_supported")
+
+ const other = await hook({ type: "charge.succeeded", data: { object: {} } })
+ expect(other.action).toBe("not_supported")
+ })
+})
diff --git a/packages/plugins/stripe-connector/src/providers/payout-stripe-connect/index.ts b/packages/plugins/stripe-connector/src/providers/payout-stripe-connect/index.ts
new file mode 100644
index 000000000..2da5733e5
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/providers/payout-stripe-connect/index.ts
@@ -0,0 +1,10 @@
+import { ModuleProvider } from "@medusajs/framework/utils"
+import { MercurModules } from "@mercurjs/types"
+
+import { StripeConnectPayoutProviderService } from "./service"
+
+export { StripeConnectPayoutProviderService }
+
+export default ModuleProvider(MercurModules.PAYOUT, {
+ services: [StripeConnectPayoutProviderService],
+})
diff --git a/packages/plugins/stripe-connector/src/providers/payout-stripe-connect/service.ts b/packages/plugins/stripe-connector/src/providers/payout-stripe-connect/service.ts
new file mode 100644
index 000000000..3666ee35b
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/providers/payout-stripe-connect/service.ts
@@ -0,0 +1,406 @@
+import { BigNumberInput } from "@medusajs/framework/types"
+import { MedusaError } from "@medusajs/framework/utils"
+import {
+ AccountOutput,
+ CreateAccountInput,
+ CreateLoginLinkInput,
+ CreateOnboardingInput,
+ CreatePayoutInput,
+ DeleteAccountInput,
+ IPayoutProvider,
+ LinkOutput,
+ ListAccountsInput,
+ ListAccountsOutput,
+ PayoutAccountStatus,
+ PayoutOutput,
+ PayoutProviderError,
+ PayoutStatus,
+ PayoutWebhookActionInput,
+ PayoutWebhookResult,
+ RetrieveAccountInput,
+ ReversePayoutInput,
+} from "@mercurjs/types"
+import Stripe from "stripe"
+
+import { getAmountFromSmallestUnit, getSmallestUnit } from "../../lib/amounts"
+import { landedOfReversal, landedOfTransfer } from "../../lib/landed"
+import { getStripeClient } from "../../lib/stripe-client"
+import { toPayoutProviderError } from "../../lib/stripe-errors"
+import { StripeConnectPayoutProviderOptions } from "../../types"
+
+const DEFAULT_ACCOUNT_VALIDATION = {
+ detailsSubmitted: true,
+ chargesEnabled: true,
+ payoutsEnabled: true,
+ noOutstandingRequirements: true,
+ requiredCapabilities: [] as string[],
+}
+
+const asRecord = (value: unknown) => value as unknown as Record<string, unknown>
+
+// Requested explicitly so onboarding links work for any country, not only
+// those enabled in the platform's Express settings. Stripe refuses
+// `transfers` on its own for US accounts, so both are requested together.
+const EXPRESS_CAPABILITIES: Stripe.AccountCreateParams["capabilities"] = {
+ card_payments: { requested: true },
+ transfers: { requested: true },
+}
+
+const hasRequestedCapabilities = (data: Record<string, unknown> | null | undefined) => {
+ const capabilities = (data?.capabilities ?? null) as Record<string, string> | null
+ return !!capabilities && "transfers" in capabilities
+}
+
+/**
+ * Stripe Connect adapter for the payout module. A payout is a Stripe transfer
+ * to the seller's connected account; when and how much to pay out is decided
+ * by the caller.
+ */
+export class StripeConnectPayoutProviderService implements IPayoutProvider {
+ static identifier = "stripe-connect"
+ static _isPayoutProvider = true
+
+ protected readonly stripe_: Stripe
+ protected readonly options_: StripeConnectPayoutProviderOptions
+
+ constructor(_cradle: Record<string, unknown>, options: StripeConnectPayoutProviderOptions) {
+ StripeConnectPayoutProviderService.validateOptions(options)
+ this.options_ = options
+ this.stripe_ = getStripeClient(options.apiKey)
+ }
+
+ static validateOptions(options: Partial<StripeConnectPayoutProviderOptions>): void {
+ if (!options.apiKey) {
+ throw new MedusaError(MedusaError.Types.INVALID_DATA, "Stripe Connect payout provider: apiKey is required")
+ }
+ if (!options.webhookSecret) {
+ throw new MedusaError(MedusaError.Types.INVALID_DATA, "Stripe Connect payout provider: webhookSecret is required")
+ }
+ }
+
+ protected normalizeAccount(account: Stripe.Account): AccountOutput {
+ const validation = { ...DEFAULT_ACCOUNT_VALIDATION, ...this.options_.accountValidation }
+ const requirements = account.requirements
+ const disabledReason = requirements?.disabled_reason ?? null
+ const outstanding = {
+ currently_due: requirements?.currently_due ?? [],
+ past_due: requirements?.past_due ?? [],
+ pending_verification: requirements?.pending_verification ?? [],
+ }
+ const hasOutstanding =
+ outstanding.currently_due.length > 0 ||
+ outstanding.past_due.length > 0 ||
+ outstanding.pending_verification.length > 0
+ const inactiveCapability = (validation.requiredCapabilities ?? []).some(
+ (capability) => account.capabilities?.[capability as keyof Stripe.Account.Capabilities] !== "active"
+ )
+
+ let status: PayoutAccountStatus
+ if (disabledReason?.startsWith("rejected")) {
+ status = PayoutAccountStatus.REJECTED
+ } else if (
+ (!validation.detailsSubmitted || account.details_submitted) &&
+ (!validation.chargesEnabled || account.charges_enabled) &&
+ (!validation.payoutsEnabled || account.payouts_enabled) &&
+ (!validation.noOutstandingRequirements || !hasOutstanding) &&
+ !inactiveCapability
+ ) {
+ status = PayoutAccountStatus.ACTIVE
+ } else if (!account.details_submitted) {
+ status = PayoutAccountStatus.PENDING
+ } else {
+ status = PayoutAccountStatus.RESTRICTED
+ }
+
+ return {
+ id: account.id,
+ status,
+ payouts_enabled: !!account.payouts_enabled,
+ charges_enabled: !!account.charges_enabled,
+ details_submitted: !!account.details_submitted,
+ disabled_reason: disabledReason,
+ requirements: outstanding,
+ data: asRecord(account),
+ }
+ }
+
+ async createAccount(input: CreateAccountInput): Promise<AccountOutput> {
+ const params: Stripe.AccountCreateParams = {
+ type: "express",
+ country: input.country,
+ metadata: input.metadata,
+ capabilities: EXPRESS_CAPABILITIES,
+ ...(input.business_type ? { business_type: input.business_type } : {}),
+ ...(input.business_profile
+ ? {
+ business_profile: {
+ name: input.business_profile.name ?? undefined,
+ url: input.business_profile.url ?? undefined,
+ support_email: input.business_profile.support_email ?? undefined,
+ support_phone: input.business_profile.support_phone ?? undefined,
+ },
+ }
+ : {}),
+ settings: {
+ payouts: {
+ debit_negative_balances: false,
+ ...(this.options_.manualPayouts ? { schedule: { interval: "manual" } } : {}),
+ },
+ },
+ }
+
+ const account = await this.stripe_.accounts.create(params, {
+ idempotencyKey: input.context?.idempotency_key,
+ })
+
+ return this.normalizeAccount(account)
+ }
+
+ async retrieveAccount(input: RetrieveAccountInput): Promise<AccountOutput> {
+ const account = await this.stripe_.accounts.retrieve(input.account.id)
+ return this.normalizeAccount(account)
+ }
+
+ async listAccounts(input: ListAccountsInput): Promise<ListAccountsOutput> {
+ const page = await this.stripe_.accounts.list({
+ limit: input.limit ?? 100,
+ starting_after: input.starting_after,
+ })
+ return {
+ accounts: page.data.map((account) => this.normalizeAccount(account)),
+ has_more: page.has_more,
+ }
+ }
+
+ async createOnboarding(input: CreateOnboardingInput): Promise<LinkOutput> {
+ if (!hasRequestedCapabilities(input.account.data)) {
+ await this.stripe_.accounts.update(input.account.id, { capabilities: EXPRESS_CAPABILITIES })
+ }
+
+ const link = await this.stripe_.accountLinks.create({
+ account: input.account.id,
+ refresh_url: input.refresh_url,
+ return_url: input.return_url,
+ type: "account_onboarding",
+ })
+ return {
+ url: link.url,
+ expires_at: link.expires_at ? new Date(link.expires_at * 1000) : null,
+ data: asRecord(link),
+ }
+ }
+
+ async createLoginLink(input: CreateLoginLinkInput): Promise<LinkOutput> {
+ const link = await this.stripe_.accounts.createLoginLink(input.account.id)
+ return { url: link.url, data: asRecord(link) }
+ }
+
+ protected sourceTransactionFrom(source: CreatePayoutInput["source_payment"]): string | undefined {
+ if (!source) {
+ return undefined
+ }
+ const data = source.data ?? {}
+ const latestCharge = data.latest_charge
+ if (typeof latestCharge === "string" && latestCharge.startsWith("ch_")) {
+ return latestCharge
+ }
+ if (latestCharge && typeof latestCharge === "object" && typeof (latestCharge as { id?: string }).id === "string") {
+ return (latestCharge as { id: string }).id
+ }
+ const id = data.id
+ if (typeof id === "string" && (id.startsWith("ch_") || id.startsWith("py_"))) {
+ return id
+ }
+ if (typeof id === "string" && id.startsWith("pi_")) {
+ return undefined
+ }
+ throw new PayoutProviderError(`Payment ${source.id} is not a Stripe charge or PaymentIntent`, { final: true })
+ }
+
+ protected async resolveSourceTransaction(source: CreatePayoutInput["source_payment"]): Promise<string | undefined> {
+ const direct = this.sourceTransactionFrom(source)
+ if (direct || !source) {
+ return direct
+ }
+ const intent = await this.stripe_.paymentIntents.retrieve(source.data.id as string)
+ const charge = intent.latest_charge
+ if (!charge) {
+ throw new PayoutProviderError(`PaymentIntent ${intent.id} has no charge yet (status ${intent.status})`)
+ }
+ return typeof charge === "string" ? charge : charge.id
+ }
+
+ /**
+ * A platform whose balance currency differs from the order currency settles
+ * the charge in the balance currency, and a transfer sourced on that charge
+ * must use it. The requested amount is converted at the charge's own rate.
+ */
+ protected async settleAmount(
+ sourceTransaction: string | undefined,
+ amount: BigNumberInput,
+ currency: string
+ ): Promise<{ amount: number; currency: string; rate: number | null }> {
+ const requested = getSmallestUnit(amount, currency)
+ if (!sourceTransaction) {
+ return { amount: requested, currency, rate: null }
+ }
+
+ const charge = await this.stripe_.charges.retrieve(sourceTransaction, { expand: ["balance_transaction"] })
+ const balanceTransaction = charge.balance_transaction as Stripe.BalanceTransaction | null
+ if (!balanceTransaction || balanceTransaction.currency === currency.toLowerCase()) {
+ return { amount: requested, currency, rate: null }
+ }
+
+ const rate = balanceTransaction.amount / (charge.amount_captured || charge.amount)
+ return {
+ amount: Math.round(requested * rate),
+ currency: balanceTransaction.currency,
+ rate,
+ }
+ }
+
+ async createPayout(input: CreatePayoutInput): Promise<PayoutOutput> {
+ try {
+ const sourceTransaction = await this.resolveSourceTransaction(input.source_payment)
+ const settled = await this.settleAmount(sourceTransaction, input.amount, input.currency_code)
+
+ const transfer = await this.stripe_.transfers.create(
+ {
+ amount: settled.amount,
+ currency: settled.currency,
+ destination: input.account.id,
+ source_transaction: sourceTransaction,
+ // Stripe takes the group from the source charge and refuses a
+ // second one, so it is only set when there is no charge.
+ ...(sourceTransaction ? {} : { transfer_group: input.group ?? undefined }),
+ metadata: {
+ ...input.metadata,
+ requested_amount: String(input.amount),
+ requested_currency: input.currency_code,
+ },
+ },
+ { idempotencyKey: input.context?.idempotency_key }
+ )
+ const landed = await landedOfTransfer(this.stripe_, transfer, input.account.id)
+
+ return {
+ id: transfer.id,
+ status: PayoutStatus.PAID,
+ data: {
+ ...asRecord(transfer),
+ requested_amount: String(input.amount),
+ requested_currency: input.currency_code,
+ settled_rate: settled.rate,
+ ...landed,
+ },
+ }
+ } catch (error) {
+ throw toPayoutProviderError(error)
+ }
+ }
+
+ // Reversals are denominated in the transfer's currency; scale the share of
+ // the original request when the transfer settled in another currency.
+ protected reversalAmount(input: ReversePayoutInput): number {
+ const transfer = input.payout.data ?? {}
+ const requestedAmount = Number(transfer.requested_amount ?? NaN)
+ const settledAmount = Number(transfer.amount ?? NaN)
+ return Number.isFinite(requestedAmount) &&
+ Number.isFinite(settledAmount) &&
+ requestedAmount > 0 &&
+ String(transfer.currency ?? "").toLowerCase() !== input.currency_code.toLowerCase()
+ ? Math.round((settledAmount * Number(input.amount)) / requestedAmount)
+ : getSmallestUnit(input.amount, input.currency_code)
+ }
+
+ protected async findReversal(
+ transferId: string,
+ reversalId: string | undefined
+ ): Promise<Stripe.TransferReversal | null> {
+ if (!reversalId) {
+ return null
+ }
+ for await (const reversal of this.stripe_.transfers.listReversals(transferId, { limit: 100 })) {
+ if (reversal.metadata?.payout_reversal_id === reversalId) {
+ return reversal
+ }
+ }
+ return null
+ }
+
+ async reversePayout(input: ReversePayoutInput): Promise<PayoutOutput> {
+ try {
+ const transfer = await this.stripe_.transfers.retrieve(input.payout.id)
+ const landedOnSeller = (reversal: Stripe.TransferReversal) =>
+ typeof transfer.destination === "string" ? landedOfReversal(this.stripe_, reversal, transfer.destination) : null
+
+ // A retry of a reversal that went through would see a smaller remainder
+ // and resend different parameters under the same idempotency key.
+ const existing = await this.findReversal(input.payout.id, input.metadata?.payout_reversal_id)
+ if (existing) {
+ return { id: existing.id, status: PayoutStatus.PAID, data: { ...asRecord(existing), ...(await landedOnSeller(existing)) } }
+ }
+
+ const remaining = transfer.amount - transfer.amount_reversed
+ if (remaining <= 0) {
+ throw new PayoutProviderError(`Transfer ${transfer.id} is already fully reversed`, { final: true })
+ }
+
+ const reversal = await this.stripe_.transfers.createReversal(
+ input.payout.id,
+ {
+ amount: Math.min(this.reversalAmount(input), remaining),
+ metadata: input.metadata,
+ },
+ { idempotencyKey: input.context?.idempotency_key }
+ )
+ return { id: reversal.id, status: PayoutStatus.PAID, data: { ...asRecord(reversal), ...(await landedOnSeller(reversal)) } }
+ } catch (error) {
+ throw toPayoutProviderError(error)
+ }
+ }
+
+ async deleteAccount(input: DeleteAccountInput): Promise<void> {
+ await this.stripe_.accounts.del(input.account.id)
+ }
+
+ 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.options_.webhookSecret
+ )
+
+ switch (event.type) {
+ case "account.updated": {
+ const account = this.normalizeAccount(event.data.object as Stripe.Account)
+ const action =
+ account.status === PayoutAccountStatus.REJECTED
+ ? "account.rejected"
+ : account.status === PayoutAccountStatus.ACTIVE
+ ? "account.activated"
+ : account.details_submitted
+ ? "account.restricted"
+ : "account.updated"
+ return { action, data: { id: account.id } }
+ }
+ case "transfer.created":
+ case "transfer.reversed": {
+ if (event.account) {
+ return { action: "not_supported" }
+ }
+ const transfer = event.data.object as Stripe.Transfer
+ return {
+ action: event.type === "transfer.created" ? "payout.paid" : "payout.reversed",
+ data: { id: transfer.id, payout_id: transfer.metadata?.payout_id },
+ }
+ }
+ default:
+ return { action: "not_supported" }
+ }
+ }
+}
+
+export { getAmountFromSmallestUnit, getSmallestUnit }
diff --git a/packages/plugins/stripe-connector/src/subscribers/operator-notification.ts b/packages/plugins/stripe-connector/src/subscribers/operator-notification.ts
new file mode 100644
index 000000000..2329e6126
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/subscribers/operator-notification.ts
@@ -0,0 +1,32 @@
+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
+import { PayoutModuleEvents } from "@mercurjs/types"
+
+import { StripeConnectorEvents } from "../types/common"
+import { resolveConnector } from "../utils/payout-module"
+import {
+ FailedOperation,
+ notifyOperationFailedWorkflow,
+} from "../workflows/notifications/workflows/notify-operation-failed"
+
+const OPERATION_BY_EVENT: Record<string, FailedOperation> = {
+ [PayoutModuleEvents.PAYOUT_FAILED]: "payout",
+ [PayoutModuleEvents.PAYOUT_REVERSAL_FAILED]: "payout_reversal",
+ [StripeConnectorEvents.SETTLEMENT_PAYOUT_FAILED]: "settlement",
+}
+
+export default async function stripeOperatorNotificationHandler({
+ event,
+ container,
+}: SubscriberArgs<{ id: string }>) {
+ const operation = OPERATION_BY_EVENT[event.name]
+ if (!operation || !event.data?.id || !resolveConnector(container).getOptions().notifications.url) {
+ return
+ }
+
+ await notifyOperationFailedWorkflow(container).run({ input: { operation, id: event.data.id } })
+}
+
+export const config: SubscriberConfig = {
+ event: Object.keys(OPERATION_BY_EVENT),
+ context: { subscriberId: "stripe-connector-operator-notification" },
+}
diff --git a/packages/plugins/stripe-connector/src/subscribers/order-group-created.ts b/packages/plugins/stripe-connector/src/subscribers/order-group-created.ts
new file mode 100644
index 000000000..f186995f9
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/subscribers/order-group-created.ts
@@ -0,0 +1,16 @@
+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
+import { OrderGroupWorkflowEvents } from "@mercurjs/core/workflows"
+
+import { syncCapturesWorkflow } from "../workflows/captures/workflows/sync-captures"
+
+export default async function stripeOrderGroupCreatedHandler({
+ event,
+ container,
+}: SubscriberArgs<{ id: string }>) {
+ await syncCapturesWorkflow(container).run({ input: { order_group_ids: [event.data.id] } })
+}
+
+export const config: SubscriberConfig = {
+ event: OrderGroupWorkflowEvents.CREATED,
+ context: { subscriberId: "stripe-connector-order-group-created" },
+}
diff --git a/packages/plugins/stripe-connector/src/subscribers/payout-account-updated.ts b/packages/plugins/stripe-connector/src/subscribers/payout-account-updated.ts
new file mode 100644
index 000000000..b1ad56309
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/subscribers/payout-account-updated.ts
@@ -0,0 +1,16 @@
+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
+import { PayoutModuleEvents } from "@mercurjs/types"
+
+import { queueAwaitingAccountPayoutsWorkflow } from "../workflows/payouts/workflows/queue-awaiting-account-payouts"
+
+export default async function stripePayoutAccountUpdatedHandler({
+ event,
+ container,
+}: SubscriberArgs<{ id: string }>) {
+ await queueAwaitingAccountPayoutsWorkflow(container).run({ input: { id: event.data.id } })
+}
+
+export const config: SubscriberConfig = {
+ event: PayoutModuleEvents.ACCOUNT_UPDATED,
+ context: { subscriberId: "stripe-connector-payout-account-updated" },
+}
diff --git a/packages/plugins/stripe-connector/src/subscribers/payout-order-changed.ts b/packages/plugins/stripe-connector/src/subscribers/payout-order-changed.ts
new file mode 100644
index 000000000..b4b7a4403
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/subscribers/payout-order-changed.ts
@@ -0,0 +1,26 @@
+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
+import { OrderWorkflowEvents } from "@medusajs/framework/utils"
+
+import { JobTrigger } from "../types/common"
+import { runJob } from "../utils/run-job"
+import { processOrderChangedPayoutsWorkflow } from "../workflows/payouts/workflows/process-order-changed-payouts"
+
+export default async function payoutOrderChangedHandler({
+ event,
+ container,
+}: SubscriberArgs<{ id: string; order_id?: string }>) {
+ const orderId = event.data.order_id ?? event.data.id
+ if (!orderId) {
+ return
+ }
+
+ await runJob(container, "payout-process-transfers", JobTrigger.SUBSCRIBER, async () => {
+ const { result } = await processOrderChangedPayoutsWorkflow(container).run({ input: { order_id: orderId } })
+ return result
+ })
+}
+
+export const config: SubscriberConfig = {
+ event: [OrderWorkflowEvents.FULFILLMENT_CREATED, OrderWorkflowEvents.CANCELED],
+ context: { subscriberId: "stripe-connector-payout-order-changed" },
+}
diff --git a/packages/plugins/stripe-connector/src/subscribers/payout-payment-captured.ts b/packages/plugins/stripe-connector/src/subscribers/payout-payment-captured.ts
new file mode 100644
index 000000000..9c45846ed
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/subscribers/payout-payment-captured.ts
@@ -0,0 +1,20 @@
+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
+import { PaymentEvents } from "@medusajs/framework/utils"
+
+import { JobTrigger } from "../types/common"
+import { runJob } from "../utils/run-job"
+import { processPaymentCapturedPayoutsWorkflow } from "../workflows/payouts/workflows/process-payment-captured-payouts"
+
+export default async function payoutPaymentCapturedHandler({ event, container }: SubscriberArgs<{ id: string }>) {
+ await runJob(container, "payout-process-transfers", JobTrigger.SUBSCRIBER, async () => {
+ const { result } = await processPaymentCapturedPayoutsWorkflow(container).run({
+ input: { payment_id: event.data.id },
+ })
+ return result
+ })
+}
+
+export const config: SubscriberConfig = {
+ event: PaymentEvents.CAPTURED,
+ context: { subscriberId: "stripe-connector-payout-payment-captured" },
+}
diff --git a/packages/plugins/stripe-connector/src/subscribers/payout-webhook-received.ts b/packages/plugins/stripe-connector/src/subscribers/payout-webhook-received.ts
new file mode 100644
index 000000000..ce585092b
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/subscribers/payout-webhook-received.ts
@@ -0,0 +1,55 @@
+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
+import { ProviderWebhookPayload } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { PayoutModuleEvents } from "@mercurjs/types"
+import Stripe from "stripe"
+
+import { resolveConnector } from "../utils/payout-module"
+import { reviveRawData } from "../utils/webhook-raw-data"
+import { processStripeBankPayoutWebhookWorkflow } from "../workflows/webhooks/workflows/process-stripe-bank-payout-webhook"
+
+export default async function stripeConnectorWebhookHandler({
+ event,
+ container,
+}: SubscriberArgs<ProviderWebhookPayload["payload"]>) {
+ const rawData = reviveRawData(event.data?.rawData)
+ const signature = (event.data?.headers as Record<string, unknown> | undefined)?.["stripe-signature"]
+ if (!rawData || typeof signature !== "string") {
+ return
+ }
+
+ let stripeEvent: Stripe.Event | null
+ try {
+ stripeEvent = resolveConnector(container).constructWebhookEvent(rawData, signature)
+ } catch (error) {
+ container
+ .resolve(ContainerRegistrationKeys.LOGGER)
+ .warn(`Stripe connector could not verify a webhook: ${(error as Error).message}`)
+ return
+ }
+ if (!stripeEvent) {
+ return
+ }
+
+ const payout = stripeEvent.type.startsWith("payout.") ? (stripeEvent.data.object as Stripe.Payout) : null
+
+ await processStripeBankPayoutWebhookWorkflow(container).run({
+ input: {
+ type: stripeEvent.type,
+ received_at: new Date().toISOString(),
+ payout: payout
+ ? {
+ id: payout.id,
+ status: payout.status,
+ failure_code: payout.failure_code,
+ failure_message: payout.failure_message,
+ }
+ : null,
+ },
+ })
+}
+
+export const config: SubscriberConfig = {
+ event: PayoutModuleEvents.WEBHOOK_RECEIVED,
+ context: { subscriberId: "stripe-connector-webhook-handler" },
+}
diff --git a/packages/plugins/stripe-connector/src/types/common.ts b/packages/plugins/stripe-connector/src/types/common.ts
new file mode 100644
index 000000000..290188beb
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/types/common.ts
@@ -0,0 +1,271 @@
+import type { BigNumberInput, FulfillmentStatus } from "@medusajs/framework/types"
+import type { PayoutStatus } from "@mercurjs/types"
+
+export const STRIPE_CONNECTOR_MODULE = "stripe_connector"
+
+export enum SettlementStatus {
+ OPEN = "open",
+ PAID_OUT = "paid_out",
+ FAILED = "failed",
+ ABORTED = "aborted",
+}
+
+export enum SettlementLineType {
+ PAYOUT = "payout",
+ REVERSAL = "reversal",
+ ADJUSTMENT_CREDIT = "adjustment_credit",
+ ADJUSTMENT_DEBIT = "adjustment_debit",
+}
+
+export enum AdjustmentType {
+ SUBSCRIPTION = "subscription",
+ EXTRA_INVOICE = "extra_invoice",
+ EXTRA_CREDIT = "extra_credit",
+}
+
+export enum JobRunStatus {
+ RUNNING = "running",
+ SUCCEEDED = "succeeded",
+ FAILED = "failed",
+}
+
+export enum JobTrigger {
+ SCHEDULE = "schedule",
+ MANUAL = "manual",
+ SUBSCRIBER = "subscriber",
+}
+
+export const PAYOUT_JOBS = [
+ "payout-sync-onboarding",
+ "payout-validate-captures",
+ "payout-process-transfers",
+ "payout-process-reversals",
+ "payout-process-settlements",
+ "payout-alert-failed-operations",
+ "payout-monitor-kyc",
+] as const
+
+export type PayoutJobName = (typeof PAYOUT_JOBS)[number]
+
+export const PAYOUT_JOB_SCHEDULES: Record<PayoutJobName, string> = {
+ "payout-sync-onboarding": "* * * * *",
+ "payout-validate-captures": "0-59/5 * * * *",
+ "payout-process-transfers": "1-59/5 * * * *",
+ "payout-process-reversals": "2-59/5 * * * *",
+ "payout-process-settlements": "3 1 * * *",
+ "payout-alert-failed-operations": "4 8 * * *",
+ "payout-monitor-kyc": "0 */6 * * *",
+}
+
+export const StripeConnectorEvents = {
+ SETTLEMENT_CREATED: "stripe_connector.settlement_created",
+ SETTLEMENT_PAYOUT_FAILED: "stripe_connector.settlement_payout_failed",
+} as const
+
+export const PAYOUT_IGNORED_KEY = "payout_ignored"
+
+export const INSUFFICIENT_BALANCE_REASON = "insufficient_available_balance"
+
+export enum CaptureStatus {
+ /** Some orders of the group are not decided yet. */
+ PENDING = "pending",
+ /** Every order is decided, or the authorization is about to expire: capture now. */
+ READY = "ready",
+ /** Every order was canceled: release the authorization. */
+ CANCELABLE = "cancelable",
+ CAPTURED = "captured",
+ CANCELED = "canceled",
+ EXPIRED = "expired",
+ FAILED = "failed",
+}
+
+export const OPEN_CAPTURE_STATUSES = [
+ CaptureStatus.PENDING,
+ CaptureStatus.READY,
+ CaptureStatus.CANCELABLE,
+ CaptureStatus.FAILED,
+]
+
+export interface StripeConnectorPluginOptions {
+ /** Platform secret key, used for settlement bank payouts and adjustments. */
+ apiKey?: string
+ /** Signing secret of the Connect webhook endpoint (`/hooks/payout`). */
+ webhookSecret?: string
+ onboarding?: { enabled?: boolean }
+ capture?: {
+ captureBeforeAcceptance?: boolean
+ authorizationWindowMs?: number
+ safetyBufferMs?: number
+ }
+ transfers?: {
+ enabled?: boolean
+ requiredFulfillmentStatus?: FulfillmentStatus
+ }
+ reversals?: { enabled?: boolean }
+ settlements?: {
+ enabled?: boolean
+ /**
+ * `plugin` nets each window and sends the bank payout itself (connected
+ * accounts on a manual payout schedule); `provider` leaves bank payouts to
+ * Stripe's automatic schedule and only records the settlement.
+ */
+ mode?: "plugin" | "provider"
+ }
+ notifications?: {
+ url?: string
+ /** Signs each notification body with HMAC-SHA256 in the `x-mercur-signature` header. */
+ secret?: string
+ mailOnEndpointDown?: boolean
+ endpointDownCooldownMinutes?: number
+ }
+ alerting?: { technicalEmail?: string; from?: string }
+ kycMonitor?: { enabled?: boolean }
+}
+
+export type ResolvedStripeConnectorOptions = {
+ apiKey?: string
+ webhookSecret?: string
+ onboarding: { enabled: boolean }
+ capture: {
+ captureBeforeAcceptance: boolean
+ authorizationWindowMs: number
+ safetyBufferMs: number
+ }
+ transfers: { enabled: boolean; requiredFulfillmentStatus: FulfillmentStatus }
+ reversals: { enabled: boolean }
+ settlements: { enabled: boolean; mode: "plugin" | "provider" }
+ notifications: {
+ url?: string
+ secret?: string
+ mailOnEndpointDown: boolean
+ endpointDownCooldownMinutes: number
+ }
+ alerting: { technicalEmail?: string; from?: string }
+ kycMonitor: { enabled: boolean }
+}
+
+export function resolveStripeConnectorOptions(
+ options?: StripeConnectorPluginOptions | null
+): ResolvedStripeConnectorOptions {
+ const o = options ?? {}
+ return {
+ apiKey: o.apiKey,
+ webhookSecret: o.webhookSecret,
+ onboarding: { enabled: true, ...(o.onboarding ?? {}) },
+ capture: {
+ captureBeforeAcceptance: false,
+ authorizationWindowMs: 7 * 24 * 60 * 60 * 1000,
+ safetyBufferMs: 24 * 60 * 60 * 1000,
+ ...(o.capture ?? {}),
+ },
+ transfers: { enabled: true, requiredFulfillmentStatus: "fulfilled", ...(o.transfers ?? {}) },
+ reversals: { enabled: true, ...(o.reversals ?? {}) },
+ settlements: { enabled: true, mode: "plugin", ...(o.settlements ?? {}) },
+ notifications: {
+ mailOnEndpointDown: true,
+ endpointDownCooldownMinutes: 10,
+ ...(o.notifications ?? {}),
+ },
+ alerting: { ...(o.alerting ?? {}) },
+ kycMonitor: { enabled: false, ...(o.kycMonitor ?? {}) },
+ }
+}
+
+export interface SettlementDTO {
+ id: string
+ display_id: number
+ account_id: string
+ currency_code: string
+ period_start: Date
+ period_end: Date
+ payouts_total: BigNumberInput
+ reversals_total: BigNumberInput
+ adjustments_total: BigNumberInput
+ amount: BigNumberInput
+ /** The bank payout in what actually landed on the connected balance; null pays `amount` in `currency_code`. */
+ payout_amount: BigNumberInput | null
+ payout_currency_code: string | null
+ status: SettlementStatus
+ payout_status: PayoutStatus | null
+ provider_payout_id: string | null
+ status_reason: string | null
+ data: Record<string, unknown> | null
+ created_at: Date
+ updated_at: Date
+}
+
+export interface SettlementLineDTO {
+ id: string
+ settlement_id: string
+ type: SettlementLineType
+ payout_id: string | null
+ payout_reversal_id: string | null
+ adjustment_id: string | null
+ amount: BigNumberInput
+ created_at: Date
+}
+
+export interface CaptureDTO {
+ id: string
+ order_group_id: string
+ payment_collection_id: string
+ payment_id: string
+ currency_code: string
+ authorized_amount: BigNumberInput
+ capturable_amount: BigNumberInput
+ orders_total: number
+ orders_decided: number
+ status: CaptureStatus
+ status_reason: string | null
+ authorized_at: Date | null
+ expires_at: Date | null
+ created_at: Date
+ updated_at: Date
+}
+
+export interface AdjustmentDTO {
+ id: string
+ account_id: string
+ type: AdjustmentType
+ amount: BigNumberInput
+ currency_code: string
+ reason: string | null
+ created_by: string | null
+ status: PayoutStatus
+ status_reason: string | null
+ provider_transfer_id: string | null
+ data: Record<string, unknown> | null
+ created_at: Date
+ updated_at: Date
+}
+
+export interface JobRunDTO {
+ id: string
+ job: string
+ trigger: JobTrigger
+ status: JobRunStatus
+ started_at: Date
+ finished_at: Date | null
+ stats: Record<string, unknown> | null
+ error: string | null
+}
+
+export interface ConnectorCheckpointDTO {
+ id: string
+ key: string
+ value: string | null
+ created_at: Date
+ updated_at: Date
+}
+
+export interface ConnectorNotificationDTO {
+ id: string
+ type: string
+ url: string
+ payload: Record<string, unknown>
+ attempts: number
+ response_status: number | null
+ error: string | null
+ delivered: boolean
+ created_at: Date
+}
diff --git a/packages/plugins/stripe-connector/src/types/http.ts b/packages/plugins/stripe-connector/src/types/http.ts
new file mode 100644
index 000000000..806a4f07f
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/types/http.ts
@@ -0,0 +1,149 @@
+import type { BigNumberInput, PaginatedResponse } from "@medusajs/types"
+import type { HttpTypes, PayoutStatus } from "@mercurjs/types"
+
+import type {
+ AdjustmentDTO,
+ AdjustmentType,
+ CaptureDTO,
+ JobRunDTO,
+ PayoutJobName,
+ SettlementDTO,
+ SettlementLineType,
+} from "./common"
+
+export type AdminPayoutAccountListResponse = HttpTypes.AdminPayoutAccountListResponse
+export type AdminPayoutAccountResponse = HttpTypes.AdminPayoutAccountResponse
+export type AdminPayoutListResponse = HttpTypes.AdminPayoutListResponse
+export type AdminPayoutResponse = HttpTypes.AdminPayoutResponse
+export type VendorPayoutAccountMeResponse = HttpTypes.VendorPayoutAccountMeResponse
+export type VendorPayoutListResponse = HttpTypes.VendorPayoutListResponse
+
+export interface SettlementSeller {
+ id: string
+ name: string
+ handle: string
+}
+
+type SettlementOrderRef = { order_id: string | null; order?: { display_id: number } | null }
+
+export interface SettlementLineDetail {
+ id: string
+ type: SettlementLineType
+ amount: BigNumberInput
+ payout_id: string | null
+ payout_reversal_id: string | null
+ adjustment_id: string | null
+ payout?: (SettlementOrderRef & { id: string; status: PayoutStatus; data: Record<string, unknown> | null }) | null
+ payout_reversal?: {
+ id: string
+ status: PayoutStatus
+ refund_id: string | null
+ data: Record<string, unknown> | null
+ payout?: SettlementOrderRef | null
+ } | null
+ adjustment?: {
+ id: string
+ type: AdjustmentType
+ amount: BigNumberInput
+ reason: string | null
+ created_by?: string | null
+ status: PayoutStatus
+ provider_transfer_id: string | null
+ } | null
+}
+
+export interface AdminSettlement extends Omit<SettlementDTO, "data"> {
+ data?: Record<string, unknown> | null
+ payout_account?: { id: string; seller?: SettlementSeller | null } | null
+ lines?: SettlementLineDetail[]
+}
+
+export type VendorSettlement = Omit<AdminSettlement, "account_id" | "data" | "payout_account">
+
+export type AdminSettlementListResponse = PaginatedResponse<{
+ settlements: AdminSettlement[]
+}>
+
+export interface AdminSettlementResponse {
+ settlement: AdminSettlement
+}
+
+export type VendorSettlementListResponse = PaginatedResponse<{
+ settlements: VendorSettlement[]
+}>
+
+export interface VendorSettlementResponse {
+ settlement: VendorSettlement
+}
+
+export interface AdminAdjustmentResponse {
+ adjustment: AdjustmentDTO
+}
+
+export type AdminAdjustmentListResponse = PaginatedResponse<{
+ adjustments: AdjustmentDTO[]
+}>
+
+export interface AdminPayoutJob {
+ job: PayoutJobName
+ schedule: string
+ enabled: boolean
+ checkpoint: string | null
+ last_run: JobRunDTO | null
+ next_run_at: Date | null
+ failed_count: number
+}
+
+export interface AdminPayoutJobListResponse {
+ jobs: AdminPayoutJob[]
+}
+
+export type AdminPayoutJobRunListResponse = PaginatedResponse<{
+ runs: JobRunDTO[]
+}>
+
+export interface AdminPayoutJobRunResponse {
+ run: JobRunDTO
+}
+
+export interface AdminPayoutStatusResponse {
+ configured: boolean
+ options: Record<string, unknown>
+ checkpoints: Record<string, string | null>
+ failed: {
+ captures: number
+ payouts: number
+ reversals: number
+ settlements: number
+ adjustments: number
+ }
+ last_webhook_at: Date | null
+ jobs: AdminPayoutJob[]
+}
+
+export interface AdminStripeCapture extends CaptureDTO {
+ order_group: { id: string; display_id: number | null } | null
+}
+
+export type AdminStripeCaptureResponse = {
+ capture: AdminStripeCapture
+}
+
+export type AdminStripeCaptureListResponse = PaginatedResponse<{
+ captures: AdminStripeCapture[]
+}>
+
+export interface AdminPayoutNotification {
+ id: string
+ type: string
+ url: string
+ attempts: number
+ response_status: number | null
+ error: string | null
+ delivered: boolean
+ created_at: Date
+}
+
+export type AdminPayoutNotificationListResponse = PaginatedResponse<{
+ notifications: AdminPayoutNotification[]
+}>
diff --git a/packages/plugins/stripe-connector/src/types/index.ts b/packages/plugins/stripe-connector/src/types/index.ts
new file mode 100644
index 000000000..fdadb7a8c
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/types/index.ts
@@ -0,0 +1,33 @@
+export interface StripeConnectorAccountValidationOptions {
+ detailsSubmitted?: boolean
+ chargesEnabled?: boolean
+ payoutsEnabled?: boolean
+ noOutstandingRequirements?: boolean
+ requiredCapabilities?: string[]
+}
+
+export interface StripeConnectPayoutProviderOptions {
+ apiKey: string
+ webhookSecret: string
+ accountValidation?: StripeConnectorAccountValidationOptions
+ /**
+ * Put new connected accounts on a manual payout schedule. Turn it on when
+ * the plugin's settlements run in `plugin` mode, so bank payouts only
+ * leave through a settlement.
+ */
+ manualPayouts?: boolean
+}
+
+export interface StripeConnectorPaymentProviderOptions {
+ apiKey: string
+ webhookSecret: string
+ automaticPaymentMethods?: boolean
+ paymentDescription?: string
+ /** Metadata key carrying the order group id on the PaymentIntent. */
+ orderGroupMetadataKey?: string
+}
+
+export const ORDER_GROUP_METADATA_KEY = "mercur_order_group_id"
+
+export * from "./common"
+export * from "./http"
diff --git a/packages/plugins/stripe-connector/src/utils/__tests__/cron.unit.spec.ts b/packages/plugins/stripe-connector/src/utils/__tests__/cron.unit.spec.ts
new file mode 100644
index 000000000..5b778922e
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/utils/__tests__/cron.unit.spec.ts
@@ -0,0 +1,18 @@
+import { nextCronRun } from "../cron"
+
+describe("nextCronRun", () => {
+ it("finds the next minute of a stepped schedule", () => {
+ const next = nextCronRun("1-59/5 * * * *", new Date("2026-10-22T10:03:30Z"))
+ expect(next?.toISOString()).toBe("2026-10-22T10:06:00.000Z")
+ })
+
+ it("finds the daily 01:03 run on the next day", () => {
+ const next = nextCronRun("3 1 * * *", new Date("2026-10-22T10:00:00Z"))
+ expect(next?.toISOString()).toBe("2026-10-23T01:03:00.000Z")
+ })
+
+ it("handles every six hours", () => {
+ const next = nextCronRun("0 */6 * * *", new Date("2026-10-22T07:00:00Z"))
+ expect(next?.toISOString()).toBe("2026-10-22T12:00:00.000Z")
+ })
+})
diff --git a/packages/plugins/stripe-connector/src/utils/cron.ts b/packages/plugins/stripe-connector/src/utils/cron.ts
new file mode 100644
index 000000000..8468480f0
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/utils/cron.ts
@@ -0,0 +1,50 @@
+/**
+ * Next match for a five-field cron expression (minute hour dom month dow),
+ * supporting `*`, lists, ranges and steps. Enough for the job schedules;
+ * not a general cron parser.
+ */
+export function nextCronRun(expression: string, from: Date): Date | null {
+ const fields = expression.trim().split(/\s+/)
+ if (fields.length !== 5) return null
+
+ const parse = (field: string, min: number, max: number): Set<number> => {
+ const out = new Set<number>()
+ for (const part of field.split(",")) {
+ const [rangePart, stepPart] = part.split("/")
+ const step = stepPart ? parseInt(stepPart, 10) : 1
+ let lo = min
+ let hi = max
+ if (rangePart !== "*") {
+ const [a, b] = rangePart.split("-").map((v) => parseInt(v, 10))
+ lo = a
+ hi = b ?? (stepPart ? max : a)
+ }
+ for (let v = lo; v <= hi; v += step) out.add(v)
+ }
+ return out
+ }
+
+ const minutes = parse(fields[0], 0, 59)
+ const hours = parse(fields[1], 0, 23)
+ const doms = parse(fields[2], 1, 31)
+ const months = parse(fields[3], 1, 12)
+ const dows = parse(fields[4], 0, 6)
+
+ const candidate = new Date(from.getTime())
+ candidate.setUTCSeconds(0, 0)
+ candidate.setUTCMinutes(candidate.getUTCMinutes() + 1)
+
+ for (let i = 0; i < 366 * 24 * 60; i++) {
+ if (
+ months.has(candidate.getUTCMonth() + 1) &&
+ doms.has(candidate.getUTCDate()) &&
+ dows.has(candidate.getUTCDay()) &&
+ hours.has(candidate.getUTCHours()) &&
+ minutes.has(candidate.getUTCMinutes())
+ ) {
+ return candidate
+ }
+ candidate.setUTCMinutes(candidate.getUTCMinutes() + 1)
+ }
+ return null
+}
diff --git a/packages/plugins/stripe-connector/src/utils/payout-module.ts b/packages/plugins/stripe-connector/src/utils/payout-module.ts
new file mode 100644
index 000000000..495547104
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/utils/payout-module.ts
@@ -0,0 +1,11 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+import { IPayoutModuleService, MercurModules } from "@mercurjs/types"
+
+import StripeConnectorModuleService from "../modules/stripe-connector/service"
+import { STRIPE_CONNECTOR_MODULE } from "../types/common"
+
+export const resolvePayoutModule = (container: MedusaContainer) =>
+ container.resolve<IPayoutModuleService>(MercurModules.PAYOUT)
+
+export const resolveConnector = (container: MedusaContainer) =>
+ container.resolve<StripeConnectorModuleService>(STRIPE_CONNECTOR_MODULE)
diff --git a/packages/plugins/stripe-connector/src/utils/run-job.ts b/packages/plugins/stripe-connector/src/utils/run-job.ts
new file mode 100644
index 000000000..a7713d0d9
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/utils/run-job.ts
@@ -0,0 +1,67 @@
+import { randomUUID } from "crypto"
+
+import { Logger, MedusaContainer } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+
+import { JobRunDTO, JobTrigger, PayoutJobName } from "../types/common"
+import { resolveConnector } from "./payout-module"
+
+export type JobStats = Record<string, number | string | null>
+
+type Locking = {
+ acquire: (key: string, args: { expire: number; ownerId: string }) => Promise<unknown>
+ release: (key: string, args: { ownerId: string }) => Promise<unknown>
+}
+
+const LOCK_EXPIRE_SECONDS = 15 * 60
+
+/**
+ * One lock per job so overlapping runs skip, and one job run row per
+ * execution with the stats the job collected.
+ */
+export async function runJob(
+ container: MedusaContainer,
+ job: PayoutJobName,
+ trigger: JobTrigger,
+ run: () => Promise<JobStats>
+): Promise<JobRunDTO | null> {
+ const logger = container.resolve<Logger>(ContainerRegistrationKeys.LOGGER)
+ const connector = resolveConnector(container)
+ const lockKey = `payout:${job}`
+ const ownerId = `${job}:${randomUUID()}`
+
+ let locking: Locking | null = null
+ try {
+ locking = container.resolve<Locking>(Modules.LOCKING)
+ } catch {
+ locking = null
+ }
+
+ if (locking) {
+ try {
+ await locking.acquire(lockKey, { expire: LOCK_EXPIRE_SECONDS, ownerId })
+ } catch {
+ logger.info(`[${job}] skipped, a run is already in progress`)
+ return null
+ }
+ }
+
+ const jobRun = await connector.startJobRun({ job, trigger })
+ logger.info(`[${job}] starting`)
+
+ try {
+ const stats = await run()
+ logger.info(`[${job}] job succeeded`)
+ return await connector.finishJobRun(jobRun.id, { stats })
+ } catch (error) {
+ // Workflow errors arrive serialized, as plain objects with a message.
+ const raw = (error as { message?: unknown } | null)?.message
+ const message = typeof raw === "string" ? raw : String(error)
+ logger.error(`[${job}] failed: ${message}`)
+ return await connector.finishJobRun(jobRun.id, { error: message })
+ } finally {
+ if (locking) {
+ await locking.release(lockKey, { ownerId }).catch(() => null)
+ }
+ }
+}
diff --git a/packages/plugins/stripe-connector/src/utils/webhook-raw-data.ts b/packages/plugins/stripe-connector/src/utils/webhook-raw-data.ts
new file mode 100644
index 000000000..5b1729dee
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/utils/webhook-raw-data.ts
@@ -0,0 +1,14 @@
+type SerializedBuffer = { type: "Buffer"; data: number[] | ArrayBuffer }
+
+// The event bus serializes a Buffer to `{ type: "Buffer", data }`, and the
+// signature has to be checked against the original bytes.
+export function reviveRawData(rawData: unknown): string | Buffer | null {
+ if ((rawData as SerializedBuffer | null)?.type === "Buffer") {
+ const { data } = rawData as SerializedBuffer
+ return Buffer.from(data instanceof ArrayBuffer ? new Uint8Array(data) : data)
+ }
+ if (typeof rawData === "string" || Buffer.isBuffer(rawData)) {
+ return rawData
+ }
+ return null
+}
diff --git a/packages/plugins/stripe-connector/src/vendor/_layouts.ts b/packages/plugins/stripe-connector/src/vendor/_layouts.ts
new file mode 100644
index 000000000..ba663e175
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/vendor/_layouts.ts
@@ -0,0 +1,7 @@
+import { defineLayoutPreferences } from "@mercurjs/dashboard-sdk"
+
+export default defineLayoutPreferences({
+ "nav.main": {
+ groups: [{ id: "integrations", label: "Integrations", rank: 5 }],
+ },
+})
diff --git a/packages/plugins/stripe-connector/src/vendor/components/stripe-icon.tsx b/packages/plugins/stripe-connector/src/vendor/components/stripe-icon.tsx
new file mode 100644
index 000000000..e3959021f
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/vendor/components/stripe-icon.tsx
@@ -0,0 +1,25 @@
+import type { ComponentProps } from "react"
+
+// Brand mark: the Stripe purple and glyph are fixed by Stripe, not theme tokens.
+export const StripeIcon = (props: ComponentProps<"svg">) => (
+ <svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>
+ <rect width="15" height="15" fill="#635BFF" />
+ <rect width="15" height="15" fill="url(#stripe_icon_gradient)" fillOpacity="0.2" />
+ <g clipPath="url(#stripe_icon_clip)">
+ <path
+ transform="translate(3 3) scale(0.375)"
+ fill="white"
+ d="M13.976 9.15c-2.172-.806-3.356-1.426-3.356-2.409 0-.831.683-1.305 1.901-1.305 2.227 0 4.515.858 6.09 1.631l.89-5.494C18.252.975 15.697 0 12.165 0 9.667 0 7.589.654 6.104 1.872 4.56 3.147 3.757 4.992 3.757 7.218c0 4.039 2.467 5.76 6.476 7.219 2.585.92 3.445 1.574 3.445 2.583 0 .98-.84 1.545-2.354 1.545-1.875 0-4.965-.921-6.99-2.109l-.9 5.555C5.175 22.99 8.385 24 11.714 24c2.641 0 4.843-.624 6.328-1.813 1.664-1.305 2.525-3.236 2.525-5.732 0-4.128-2.524-5.851-6.594-7.305h.003z"
+ />
+ </g>
+ <defs>
+ <linearGradient id="stripe_icon_gradient" x1="7.5" y1="0" x2="7.5" y2="15" gradientUnits="userSpaceOnUse">
+ <stop stopColor="white" />
+ <stop offset="1" stopColor="white" stopOpacity="0" />
+ </linearGradient>
+ <clipPath id="stripe_icon_clip">
+ <rect width="9" height="9" fill="white" transform="translate(3 3)" />
+ </clipPath>
+ </defs>
+ </svg>
+)
diff --git a/packages/plugins/stripe-connector/src/vendor/hooks/api/stripe.tsx b/packages/plugins/stripe-connector/src/vendor/hooks/api/stripe.tsx
new file mode 100644
index 000000000..966f5cb85
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/vendor/hooks/api/stripe.tsx
@@ -0,0 +1,65 @@
+import type { ClientError } from "@mercurjs/client"
+import { queryKeysFactory } from "@mercurjs/dashboard-shared"
+import {
+ UseMutationOptions,
+ UseQueryOptions,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query"
+
+import { client, type VendorAccount } from "../../lib/client"
+import type {
+ VendorPayoutAccountMeResponse,
+ VendorSettlementListResponse,
+} from "../../../types/http"
+
+export const vendorStripeKeys = queryKeysFactory("vendor_stripe")
+const payoutAccountsQueryKeys = queryKeysFactory("payout_accounts")
+
+export const useMyStripeAccount = (
+ options?: Omit<
+ UseQueryOptions<VendorPayoutAccountMeResponse, ClientError, VendorPayoutAccountMeResponse>,
+ "queryKey" | "queryFn"
+ >
+) => {
+ const { data, ...rest } = useQuery({
+ queryKey: vendorStripeKeys.detail("me"),
+ queryFn: () => client.vendor["payout-accounts"].me.query({}),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
+
+export const useMySettlements = (
+ query: Record<string, unknown> = {},
+ options?: Omit<
+ UseQueryOptions<VendorSettlementListResponse, ClientError, VendorSettlementListResponse>,
+ "queryKey" | "queryFn"
+ >
+) => {
+ const { data, ...rest } = useQuery({
+ queryKey: vendorStripeKeys.list({ kind: "settlements", ...query }),
+ queryFn: () => client.vendor.stripe.settlements.query(query),
+ ...options,
+ })
+
+ return { ...data, ...rest }
+}
+
+export const useCreateMyAccount = (
+ options?: UseMutationOptions<{ payout_account: VendorAccount }, ClientError, Record<string, unknown>>
+) => {
+ const queryClient = useQueryClient()
+
+ return useMutation({
+ ...options,
+ mutationFn: (data) => client.vendor["payout-accounts"].mutate({ data, context: {} }),
+ onSuccess: (data, variables, context) => {
+ queryClient.invalidateQueries({ queryKey: vendorStripeKeys.all })
+ queryClient.invalidateQueries({ queryKey: payoutAccountsQueryKeys.all })
+ options?.onSuccess?.(data, variables, context)
+ },
+ })
+}
diff --git a/packages/plugins/stripe-connector/src/vendor/lib/client.ts b/packages/plugins/stripe-connector/src/vendor/lib/client.ts
new file mode 100644
index 000000000..dbc6c8dbf
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/vendor/lib/client.ts
@@ -0,0 +1,37 @@
+import { createClient, vendorAuth, type InferClient } from "@mercurjs/client"
+import type { MedusaResponse } from "@medusajs/framework"
+import type {
+ VendorPayoutAccountMeResponse,
+ VendorPayoutListResponse,
+ VendorSettlementListResponse,
+ VendorSettlementResponse,
+} from "../../types/http"
+
+type ListQuery = Record<string, unknown> & { limit?: number; offset?: number }
+type Route<Input, Output> = (req: { validatedBody: Input }, res: MedusaResponse<Output>) => Promise<void>
+type Empty = { fields?: string }
+
+export type VendorAccount = NonNullable<VendorPayoutAccountMeResponse["payout_account"]>
+export type VendorSettlementRow = VendorSettlementListResponse["settlements"][number]
+
+type Routes = {
+ vendor: {
+ "payout-accounts": {
+ POST: Route<{ data?: Record<string, unknown>; context?: Record<string, unknown> }, { payout_account: VendorAccount }>
+ me: { GET: Route<Empty, VendorPayoutAccountMeResponse> }
+ }
+ payouts: { GET: Route<ListQuery, VendorPayoutListResponse> }
+ stripe: {
+ settlements: {
+ GET: Route<ListQuery, VendorSettlementListResponse>
+ $id: { GET: Route<Empty, VendorSettlementResponse> }
+ }
+ }
+ }
+}
+
+export const client: InferClient<Routes> = createClient({
+ baseUrl: import.meta.env.VITE_MERCUR_BACKEND_URL || "http://localhost:9000",
+ fetchOptions: { credentials: "omit" },
+ auth: vendorAuth(),
+})
diff --git a/packages/plugins/stripe-connector/src/vendor/lib/status.ts b/packages/plugins/stripe-connector/src/vendor/lib/status.ts
new file mode 100644
index 000000000..f3a72ac25
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/vendor/lib/status.ts
@@ -0,0 +1,55 @@
+type BadgeColor = "green" | "red" | "orange" | "grey" | "blue" | "purple"
+
+export const PAYOUT_STATUS_COLOR: Record<string, BadgeColor> = {
+ pending: "blue",
+ processing: "blue",
+ paid: "green",
+ failed: "red",
+ on_hold: "orange",
+ aborted: "grey",
+}
+
+export const PAYOUT_STATUS_LABEL: Record<string, string> = {
+ pending: "Pending",
+ processing: "Processing",
+ paid: "Paid",
+ failed: "Failed",
+ on_hold: "On hold",
+ aborted: "Aborted",
+}
+
+export const SETTLEMENT_STATUS_COLOR: Record<string, BadgeColor> = {
+ open: "blue",
+ paid_out: "green",
+ failed: "red",
+ aborted: "grey",
+}
+
+export const SETTLEMENT_STATUS_LABEL: Record<string, string> = {
+ open: "Open",
+ paid_out: "Paid out",
+ failed: "Failed",
+ aborted: "Aborted",
+}
+
+type StripeRequirements = {
+ currently_due: string[]
+ past_due: string[]
+ pending_verification: string[]
+}
+
+/** The connected account Stripe returned, kept on the payout account as `data`. */
+export const stripeRequirementsOf = (data: Record<string, unknown> | null | undefined): StripeRequirements => {
+ const requirements = data?.requirements as Partial<StripeRequirements> | undefined
+ return {
+ currently_due: requirements?.currently_due ?? [],
+ past_due: requirements?.past_due ?? [],
+ pending_verification: requirements?.pending_verification ?? [],
+ }
+}
+
+// Requirement entries are field paths such as `individual.verification.document`.
+export const humanizeRequirement = (requirement: string) => {
+ const text = requirement.split(".").join(" › ").replace(/_/g, " ")
+ return text.charAt(0).toUpperCase() + text.slice(1)
+}
diff --git a/packages/plugins/stripe-connector/src/vendor/providers/settings-providers.tsx b/packages/plugins/stripe-connector/src/vendor/providers/settings-providers.tsx
new file mode 100644
index 000000000..eaecb2571
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/vendor/providers/settings-providers.tsx
@@ -0,0 +1,11 @@
+import { TooltipProvider } from "@medusajs/ui"
+import { queryClient } from "@mercurjs/dashboard-shared"
+import { QueryClientProvider } from "@tanstack/react-query"
+import type { ReactNode } from "react"
+
+/** Settings routes mount outside the host dashboard's React providers, so each one supplies its own. */
+export const SettingsProviders = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>
+ <TooltipProvider>{children}</TooltipProvider>
+ </QueryClientProvider>
+)
diff --git a/packages/plugins/stripe-connector/src/vendor/routes/stripe/components/settlements-section.tsx b/packages/plugins/stripe-connector/src/vendor/routes/stripe/components/settlements-section.tsx
new file mode 100644
index 000000000..bfb5f0fc6
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/vendor/routes/stripe/components/settlements-section.tsx
@@ -0,0 +1,124 @@
+import { Container, Heading, Text } from "@medusajs/ui"
+import {
+ DateCell,
+ MoneyAmountCell,
+ StatusCell,
+ TextCell,
+ TextHeader,
+ _DataTable,
+ useDataTable,
+ useQueryParams,
+} from "@mercurjs/dashboard-shared"
+import { keepPreviousData } from "@tanstack/react-query"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+
+import { useMySettlements } from "../../../hooks/api/stripe"
+import type { VendorSettlementRow } from "../../../lib/client"
+import {
+ PAYOUT_STATUS_COLOR,
+ PAYOUT_STATUS_LABEL,
+ SETTLEMENT_STATUS_COLOR,
+ SETTLEMENT_STATUS_LABEL,
+} from "../../../lib/status"
+
+const PAGE_SIZE = 10
+const PREFIX = "stmt"
+
+const columnHelper = createColumnHelper<VendorSettlementRow>()
+
+const useColumns = () =>
+ useMemo(
+ () => [
+ columnHelper.accessor("display_id", {
+ header: () => <TextHeader text="Settlement" />,
+ cell: ({ getValue }) => <TextCell text={`#${getValue()}`} />,
+ }),
+ columnHelper.accessor("period_start", {
+ header: () => <TextHeader text="From" />,
+ cell: ({ getValue }) => <DateCell date={getValue()} />,
+ }),
+ columnHelper.accessor("period_end", {
+ header: () => <TextHeader text="To" />,
+ cell: ({ getValue }) => <DateCell date={getValue()} />,
+ }),
+ columnHelper.accessor("status", {
+ header: () => <TextHeader text="Status" />,
+ cell: ({ getValue }) => (
+ <StatusCell color={SETTLEMENT_STATUS_COLOR[getValue()] ?? "grey"}>
+ {SETTLEMENT_STATUS_LABEL[getValue()] ?? getValue()}
+ </StatusCell>
+ ),
+ }),
+ columnHelper.accessor("payout_status", {
+ header: () => <TextHeader text="Bank payout" />,
+ cell: ({ getValue }) => {
+ const status = getValue()
+ return status ? (
+ <StatusCell color={PAYOUT_STATUS_COLOR[status] ?? "grey"}>{PAYOUT_STATUS_LABEL[status] ?? status}</StatusCell>
+ ) : (
+ <TextCell text="-" />
+ )
+ },
+ }),
+ columnHelper.accessor("amount", {
+ header: () => (
+ <div className="flex h-full w-full items-center justify-end">
+ <span className="truncate">Amount</span>
+ </div>
+ ),
+ cell: ({ row }) => (
+ <MoneyAmountCell amount={Number(row.original.amount)} currencyCode={row.original.currency_code} align="right" />
+ ),
+ }),
+ ],
+ []
+ )
+
+export const SettlementsSection = () => {
+ const raw = useQueryParams(["offset"], PREFIX)
+ const query = { limit: PAGE_SIZE, offset: raw.offset ? Number(raw.offset) : 0 }
+
+ const { settlements, count, isPending, isError, error } = useMySettlements(query, {
+ placeholderData: keepPreviousData,
+ })
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: settlements ?? [],
+ columns,
+ count: count ?? 0,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0" data-testid="stripe-settlements-section">
+ <div className="px-6 py-4">
+ <Heading level="h2" data-testid="stripe-settlements-heading">
+ Settlements
+ </Heading>
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ Your payouts and refunds netted per period, and the bank payout that paid them.
+ </Text>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count ?? 0}
+ pageSize={PAGE_SIZE}
+ isLoading={isPending}
+ queryObject={raw}
+ prefix={PREFIX}
+ pagination
+ noRecords={{ message: "Settlements appear once your first payouts are settled." }}
+ />
+ </Container>
+ )
+}
diff --git a/packages/plugins/stripe-connector/src/vendor/routes/stripe/components/setup-form.tsx b/packages/plugins/stripe-connector/src/vendor/routes/stripe/components/setup-form.tsx
new file mode 100644
index 000000000..75038ee2a
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/vendor/routes/stripe/components/setup-form.tsx
@@ -0,0 +1,150 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Container, Heading, Input, Select, Text, toast } from "@medusajs/ui"
+import { Form, KeyboundForm, countries, useDocumentDirection } from "@mercurjs/dashboard-shared"
+import { useForm } from "react-hook-form"
+import * as zod from "zod"
+
+import { useCreateMyAccount } from "../../../hooks/api/stripe"
+
+const STRIPE_COUNTRIES = ["us", "gb", "de", "fr", "es", "it", "nl", "be", "pl", "se", "dk", "no", "fi", "ie", "at", "ch", "pt", "cz", "ca", "au"]
+
+const COUNTRY_OPTIONS = countries
+ .filter((country) => STRIPE_COUNTRIES.includes(country.iso_2))
+ .sort((a, b) => a.display_name.localeCompare(b.display_name))
+
+const SetupSchema = zod.object({
+ country: zod.string().min(1, "Choose a country"),
+ business_type: zod.enum(["individual", "company"]),
+ business_name: zod.string().optional(),
+ website: zod.union([zod.literal(""), zod.url("Enter a valid URL")]).optional(),
+ support_email: zod.union([zod.literal(""), zod.email("Enter a valid email")]).optional(),
+ support_phone: zod.string().optional(),
+})
+
+type SetupSchemaType = zod.infer<typeof SetupSchema>
+
+const OPTIONAL_FIELDS = [
+ { name: "business_name", label: "Business name", type: "text" },
+ { name: "website", label: "Website", type: "url" },
+ { name: "support_email", label: "Support email", type: "email" },
+ { name: "support_phone", label: "Support phone", type: "tel" },
+] as const
+
+export const SetupForm = () => {
+ const direction = useDocumentDirection()
+
+ const form = useForm<SetupSchemaType>({
+ defaultValues: {
+ country: "",
+ business_type: "individual",
+ business_name: "",
+ website: "",
+ support_email: "",
+ support_phone: "",
+ },
+ resolver: zodResolver(SetupSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateMyAccount()
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const data = Object.fromEntries(Object.entries(values).filter(([, value]) => !!value))
+
+ await mutateAsync(data, {
+ onSuccess: () => toast.success("Account created", { description: "Continue on Stripe to finish onboarding." }),
+ onError: (error) => toast.error(error.message),
+ })
+ })
+
+ return (
+ <Container className="divide-y p-0" data-testid="stripe-setup-form">
+ <div className="px-6 py-4">
+ <Heading data-testid="stripe-setup-heading">Set up payouts with Stripe</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ Tell us where your business is registered. Stripe asks for the rest.
+ </Text>
+ </div>
+ <Form {...form}>
+ <KeyboundForm onSubmit={handleSubmit} className="divide-y">
+ <div className="flex flex-col gap-y-4 px-6 py-4">
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="country"
+ render={({ field: { ref, onChange, ...field } }) => (
+ <Form.Item>
+ <Form.Label>Country</Form.Label>
+ <Form.Control>
+ <Select dir={direction} onValueChange={onChange} {...field}>
+ <Select.Trigger ref={ref} data-testid="stripe-setup-country">
+ <Select.Value placeholder="Choose a country" />
+ </Select.Trigger>
+ <Select.Content>
+ {COUNTRY_OPTIONS.map((country) => (
+ <Select.Item key={country.iso_2} value={country.iso_2.toUpperCase()}>
+ {country.display_name}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="business_type"
+ render={({ field: { ref, onChange, ...field } }) => (
+ <Form.Item>
+ <Form.Label>Business type</Form.Label>
+ <Form.Control>
+ <Select dir={direction} onValueChange={onChange} {...field}>
+ <Select.Trigger ref={ref} data-testid="stripe-setup-business-type">
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Item value="individual">Individual</Select.Item>
+ <Select.Item value="company">Company</Select.Item>
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ </div>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ {OPTIONAL_FIELDS.map(({ name, label, type }) => (
+ <Form.Field
+ key={name}
+ control={form.control}
+ name={name}
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Label optional>{label}</Form.Label>
+ <Form.Control>
+ <Input
+ type={type}
+ autoComplete="off"
+ data-testid={`stripe-setup-${name.replace(/_/g, "-")}`}
+ {...field}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ ))}
+ </div>
+ </div>
+ <div className="flex justify-end px-6 py-4">
+ <Button size="small" type="submit" isLoading={isPending} data-testid="stripe-setup-submit">
+ Create Stripe account
+ </Button>
+ </div>
+ </KeyboundForm>
+ </Form>
+ </Container>
+ )
+}
diff --git a/packages/plugins/stripe-connector/src/vendor/routes/stripe/components/stripe-account-section.tsx b/packages/plugins/stripe-connector/src/vendor/routes/stripe/components/stripe-account-section.tsx
new file mode 100644
index 000000000..bc6cb581d
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/vendor/routes/stripe/components/stripe-account-section.tsx
@@ -0,0 +1,41 @@
+import { Badge, Container, Heading, Text } from "@medusajs/ui"
+import { SectionRow } from "@mercurjs/dashboard-shared"
+
+import type { VendorAccount } from "../../../lib/client"
+import { humanizeRequirement, stripeRequirementsOf } from "../../../lib/status"
+
+const Requirements = ({ items }: { items: string[] }) =>
+ items.length ? (
+ <div className="flex flex-wrap gap-1">
+ {items.map((item) => (
+ <Badge key={item} size="2xsmall" title={item}>
+ {humanizeRequirement(item)}
+ </Badge>
+ ))}
+ </div>
+ ) : (
+ "-"
+ )
+
+export const StripeAccountSection = ({ account }: { account: VendorAccount }) => {
+ const requirements = stripeRequirementsOf(account.data)
+
+ return (
+ <Container className="divide-y p-0" data-testid="stripe-account-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading level="h2" data-testid="stripe-account-heading">
+ Stripe account
+ </Heading>
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ The connected account your payouts land on, and what Stripe still needs from you.
+ </Text>
+ </div>
+ </div>
+ <SectionRow title="Card payments" value={account.charges_enabled ? "Enabled" : "Not enabled yet"} />
+ <SectionRow title="Currently due" value={<Requirements items={requirements.currently_due} />} />
+ <SectionRow title="Past due" value={<Requirements items={requirements.past_due} />} />
+ <SectionRow title="Pending verification" value={<Requirements items={requirements.pending_verification} />} />
+ </Container>
+ )
+}
diff --git a/packages/plugins/stripe-connector/src/vendor/routes/stripe/page.tsx b/packages/plugins/stripe-connector/src/vendor/routes/stripe/page.tsx
new file mode 100644
index 000000000..90a5460ec
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/vendor/routes/stripe/page.tsx
@@ -0,0 +1,50 @@
+import { SingleColumnPage, SingleColumnPageSkeleton, WidgetZone } from "@mercurjs/dashboard-shared"
+import { defineRouteConfig } from "@mercurjs/dashboard-sdk"
+
+import { StripeIcon } from "../../components/stripe-icon"
+import { useMyStripeAccount } from "../../hooks/api/stripe"
+import { SettingsProviders } from "../../providers/settings-providers"
+import { SetupForm } from "./components/setup-form"
+import { SettlementsSection } from "./components/settlements-section"
+import { StripeAccountSection } from "./components/stripe-account-section"
+
+const StripeVendor = () => {
+ const { payout_account, isPending, isError, error } = useMyStripeAccount()
+ if (isError) throw error
+
+ if (isPending) {
+ return <SingleColumnPageSkeleton sections={2} />
+ }
+
+ if (!payout_account) {
+ return <SetupForm />
+ }
+
+ return (
+ <>
+ <StripeAccountSection account={payout_account} />
+ <SettlementsSection />
+ </>
+ )
+}
+
+const StripeVendorPage = () => (
+ <SettingsProviders>
+ <SingleColumnPage data-testid="vendor-stripe-page">
+ <WidgetZone id="stripe.vendor">
+ <StripeVendor />
+ </WidgetZone>
+ </SingleColumnPage>
+ </SettingsProviders>
+)
+
+export const config = defineRouteConfig({
+ label: "Stripe",
+ icon: StripeIcon,
+ group: "integrations",
+ permissions: ["payouts:view"],
+})
+
+export const handle = { breadcrumb: () => "Stripe", permissions: "payouts:view" }
+
+export default StripeVendorPage
diff --git a/packages/plugins/stripe-connector/src/vendor/tsconfig.json b/packages/plugins/stripe-connector/src/vendor/tsconfig.json
new file mode 100644
index 000000000..89f49d8ea
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/vendor/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ES2021",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "jsx": "react-jsx",
+ "lib": ["ES2021", "DOM"],
+ "strict": true,
+ "strictNullChecks": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "noEmit": true,
+ "resolveJsonModule": true
+ },
+ "include": ["./**/*", "./vite-env.d.ts"],
+ "exclude": ["node_modules"]
+}
diff --git a/packages/plugins/stripe-connector/src/vendor/vite-env.d.ts b/packages/plugins/stripe-connector/src/vendor/vite-env.d.ts
new file mode 100644
index 000000000..a7707bed6
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/vendor/vite-env.d.ts
@@ -0,0 +1,7 @@
+interface ImportMetaEnv {
+ readonly VITE_MERCUR_BACKEND_URL?: string
+}
+
+interface ImportMeta {
+ readonly env: ImportMetaEnv
+}
diff --git a/packages/plugins/stripe-connector/src/workflows/accounts/steps/index.ts b/packages/plugins/stripe-connector/src/workflows/accounts/steps/index.ts
new file mode 100644
index 000000000..0152648b8
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/accounts/steps/index.ts
@@ -0,0 +1 @@
+export * from "./validate-account-seller"
diff --git a/packages/plugins/stripe-connector/src/workflows/accounts/steps/validate-account-seller.ts b/packages/plugins/stripe-connector/src/workflows/accounts/steps/validate-account-seller.ts
new file mode 100644
index 000000000..f9399c01f
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/accounts/steps/validate-account-seller.ts
@@ -0,0 +1,14 @@
+import { MedusaError } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+export const validateAccountSellerStepId = "validate-stripe-account-seller"
+
+export const validateAccountSellerStep = createStep(
+ validateAccountSellerStepId,
+ async (input: { id: string; seller_id: string | null }) => {
+ if (!input.seller_id) {
+ throw new MedusaError(MedusaError.Types.NOT_FOUND, `Payout account ${input.id} has no seller`)
+ }
+ return new StepResponse(void 0)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/accounts/workflows/ignore-payout-account.ts b/packages/plugins/stripe-connector/src/workflows/accounts/workflows/ignore-payout-account.ts
new file mode 100644
index 000000000..5cac692e0
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/accounts/workflows/ignore-payout-account.ts
@@ -0,0 +1,48 @@
+import { WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { updateSellersWorkflow } from "@mercurjs/core/workflows"
+
+import { PAYOUT_IGNORED_KEY } from "../../../types/common"
+import { validateAccountSellerStep } from "../steps"
+
+export type IgnorePayoutAccountWorkflowInput = {
+ id: string
+ ignored: boolean
+}
+
+type AccountSeller = { seller?: { id: string; metadata?: Record<string, unknown> | null } | null }
+
+export const ignorePayoutAccountWorkflowId = "ignore-stripe-payout-account"
+
+/**
+ * Flags the account's seller so the transfers job leaves their orders alone,
+ * or lifts the flag. The account itself is untouched.
+ */
+export const ignorePayoutAccountWorkflow = createWorkflow(
+ ignorePayoutAccountWorkflowId,
+ function (input: IgnorePayoutAccountWorkflowInput) {
+ const { data: account } = useQueryGraphStep({
+ entity: "payout_account",
+ fields: ["id", "seller.id", "seller.metadata"],
+ filters: { id: input.id },
+ options: { isList: false, throwIfKeyNotFound: true },
+ }).config({ name: "ignore-account-query" })
+
+ const seller = transform({ account }, ({ account }) => (account as AccountSeller).seller ?? null)
+
+ validateAccountSellerStep(
+ transform({ input, seller }, ({ input, seller }) => ({ id: input.id, seller_id: seller?.id ?? null }))
+ )
+
+ updateSellersWorkflow.runAsStep({
+ input: transform({ input, seller }, ({ input, seller }) => ({
+ selector: { id: seller?.id },
+ update: {
+ metadata: { ...(seller?.metadata ?? {}), [PAYOUT_IGNORED_KEY]: String(input.ignored) },
+ },
+ })),
+ })
+
+ return new WorkflowResponse(void 0)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/accounts/workflows/index.ts b/packages/plugins/stripe-connector/src/workflows/accounts/workflows/index.ts
new file mode 100644
index 000000000..5c5a971a2
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/accounts/workflows/index.ts
@@ -0,0 +1 @@
+export * from "./ignore-payout-account"
diff --git a/packages/plugins/stripe-connector/src/workflows/adjustments/steps/create-adjustments.ts b/packages/plugins/stripe-connector/src/workflows/adjustments/steps/create-adjustments.ts
new file mode 100644
index 000000000..feae739fd
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/adjustments/steps/create-adjustments.ts
@@ -0,0 +1,32 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+import { AdjustmentDTO, AdjustmentType } from "../../../types/common"
+import { resolveConnector } from "../../../utils/payout-module"
+
+export type CreateAdjustmentsStepInput = {
+ account_id: string
+ type: AdjustmentType
+ amount: number
+ currency_code: string
+ reason: string | null
+ created_by: string | null
+}[]
+
+export const createAdjustmentsStepId = "create-stripe-adjustments"
+
+export const createAdjustmentsStep = createStep(
+ createAdjustmentsStepId,
+ async (input: CreateAdjustmentsStepInput, { container }) => {
+ const adjustments = await resolveConnector(container).createAdjustments(input)
+ return new StepResponse<AdjustmentDTO[], string[]>(
+ adjustments,
+ adjustments.map((adjustment) => adjustment.id)
+ )
+ },
+ async (ids, { container }) => {
+ if (!ids?.length) {
+ return
+ }
+ await resolveConnector(container).deleteAdjustments(ids)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/adjustments/steps/index.ts b/packages/plugins/stripe-connector/src/workflows/adjustments/steps/index.ts
new file mode 100644
index 000000000..44d256660
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/adjustments/steps/index.ts
@@ -0,0 +1,2 @@
+export * from "./create-adjustments"
+export * from "./validate-adjustment-account"
diff --git a/packages/plugins/stripe-connector/src/workflows/adjustments/steps/validate-adjustment-account.ts b/packages/plugins/stripe-connector/src/workflows/adjustments/steps/validate-adjustment-account.ts
new file mode 100644
index 000000000..9f651733b
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/adjustments/steps/validate-adjustment-account.ts
@@ -0,0 +1,14 @@
+import { MedusaError } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+export const validateAdjustmentAccountStepId = "validate-stripe-adjustment-account"
+
+export const validateAdjustmentAccountStep = createStep(
+ validateAdjustmentAccountStepId,
+ async (input: { account_id: string | null; seller_id?: string }) => {
+ if (!input.account_id) {
+ throw new MedusaError(MedusaError.Types.NOT_FOUND, `Seller ${input.seller_id} has no payout account`)
+ }
+ return new StepResponse(void 0)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/adjustments/workflows/create-adjustments.ts b/packages/plugins/stripe-connector/src/workflows/adjustments/workflows/create-adjustments.ts
new file mode 100644
index 000000000..af18920bc
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/adjustments/workflows/create-adjustments.ts
@@ -0,0 +1,63 @@
+import { WorkflowResponse, createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+import { AdjustmentType } from "../../../types/common"
+import { createAdjustmentsStep, validateAdjustmentAccountStep } from "../steps"
+
+export type CreateAdjustmentsWorkflowInput = {
+ account_id?: string
+ seller_id?: string
+ type: AdjustmentType
+ amount: number
+ currency_code: string
+ reason?: string | null
+ created_by?: string | null
+}
+
+export const createAdjustmentsWorkflowId = "create-stripe-adjustments"
+
+/**
+ * Books an operator adjustment on a payout account, given directly or as the
+ * seller's account. The next settlement run sends it.
+ */
+export const createAdjustmentsWorkflow = createWorkflow(
+ createAdjustmentsWorkflowId,
+ function (input: CreateAdjustmentsWorkflowInput) {
+ const sellerLinks = when(
+ "adjustment-for-seller",
+ { input },
+ ({ input }) => !input.account_id && !!input.seller_id
+ ).then(() => {
+ const { data } = useQueryGraphStep({
+ entity: "seller_payout_account",
+ fields: ["payout_account_id"],
+ filters: { seller_id: input.seller_id },
+ }).config({ name: "adjustment-seller-account-query" })
+ return data
+ })
+
+ const accountId = transform(
+ { input, sellerLinks },
+ ({ input, sellerLinks }) => input.account_id ?? (sellerLinks?.[0]?.payout_account_id as string | undefined) ?? null
+ )
+
+ validateAdjustmentAccountStep(
+ transform({ input, accountId }, ({ input, accountId }) => ({ account_id: accountId, seller_id: input.seller_id }))
+ )
+
+ const adjustments = createAdjustmentsStep(
+ transform({ input, accountId }, ({ input, accountId }) => [
+ {
+ account_id: accountId as string,
+ type: input.type,
+ amount: input.amount,
+ currency_code: input.currency_code.toLowerCase(),
+ reason: input.reason ?? null,
+ created_by: input.created_by ?? null,
+ },
+ ])
+ )
+
+ return new WorkflowResponse(adjustments)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/adjustments/workflows/index.ts b/packages/plugins/stripe-connector/src/workflows/adjustments/workflows/index.ts
new file mode 100644
index 000000000..3f33d9ab8
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/adjustments/workflows/index.ts
@@ -0,0 +1 @@
+export * from "./create-adjustments"
diff --git a/packages/plugins/stripe-connector/src/workflows/alerts/utils/failed-operations.ts b/packages/plugins/stripe-connector/src/workflows/alerts/utils/failed-operations.ts
new file mode 100644
index 000000000..32631fb06
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/alerts/utils/failed-operations.ts
@@ -0,0 +1,46 @@
+import { BigNumberInput } from "@medusajs/framework/types"
+
+export type FailedOperations = {
+ captures: { order_group_id: string; payment_id: string; error: string | null }[]
+ payouts: { id: string; order_id: string | null; amount: BigNumberInput; currency_code: string; status_reason: string | null }[]
+ reversals: { id: string; payout_id: string; refund_id: string | null; amount: BigNumberInput; status_reason: string | null }[]
+ settlements: { id: string; account_id: string; amount: BigNumberInput; currency_code: string; status_reason: string | null }[]
+ adjustments: { id: string; account_id: string; amount: BigNumberInput; currency_code: string; status_reason: string | null }[]
+}
+
+export type Alerting = { email: string | null; from: string | null }
+
+const section = (label: string, rows: Record<string, unknown>[]) =>
+ rows.length
+ ? `${label} (${rows.length}):\n` +
+ rows.map((row) => ` - ${Object.entries(row).map(([k, v]) => `${k}=${String(v ?? "")}`).join(" ")}`).join("\n")
+ : `${label}: none`
+
+export const countFailedOperations = (failed: FailedOperations) =>
+ Object.values(failed).reduce((sum, rows) => sum + rows.length, 0)
+
+export function failedOperationsNotifications(failed: FailedOperations, alerting: Alerting) {
+ const total = countFailedOperations(failed)
+ if (!total || !alerting.email) {
+ return []
+ }
+ return [
+ {
+ to: alerting.email,
+ from: alerting.from,
+ channel: "email",
+ template: "payout-operations-failed",
+ data: { ...failed },
+ content: {
+ subject: `[Payouts] ${total} failed operation(s) need attention`,
+ text: [
+ section("Payments that failed capturing or canceling", failed.captures),
+ section("Payouts that failed", failed.payouts),
+ section("Reversals that failed", failed.reversals),
+ section("Settlement bank payouts that failed", failed.settlements),
+ section("Adjustments that failed", failed.adjustments),
+ ].join("\n\n"),
+ },
+ },
+ ]
+}
diff --git a/packages/plugins/stripe-connector/src/workflows/alerts/utils/index.ts b/packages/plugins/stripe-connector/src/workflows/alerts/utils/index.ts
new file mode 100644
index 000000000..a307a95ce
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/alerts/utils/index.ts
@@ -0,0 +1 @@
+export * from "./failed-operations"
diff --git a/packages/plugins/stripe-connector/src/workflows/alerts/workflows/alert-failed-operations.ts b/packages/plugins/stripe-connector/src/workflows/alerts/workflows/alert-failed-operations.ts
new file mode 100644
index 000000000..f78b61598
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/alerts/workflows/alert-failed-operations.ts
@@ -0,0 +1,76 @@
+import { WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { PayoutStatus } from "@mercurjs/types"
+
+import { CaptureStatus } from "../../../types/common"
+import { JobStats } from "../../../utils/run-job"
+import { resolveAlertingStep, sendOperatorEmailsStep } from "../../common/steps"
+import { FailedOperations, countFailedOperations, failedOperationsNotifications } from "../utils/failed-operations"
+
+export const alertFailedOperationsWorkflowId = "alert-stripe-failed-operations"
+
+/** Mails the operator the daily digest of captures, payouts, reversals, settlements and adjustments that failed. */
+export const alertFailedOperationsWorkflow = createWorkflow(alertFailedOperationsWorkflowId, function () {
+ const { data: captures } = useQueryGraphStep({
+ entity: "stripe_capture",
+ fields: ["order_group_id", "payment_id", "status_reason"],
+ filters: { status: CaptureStatus.FAILED },
+ }).config({ name: "failed-captures-query" })
+
+ const { data: payouts } = useQueryGraphStep({
+ entity: "payout",
+ fields: ["id", "order_id", "amount", "currency_code", "status_reason"],
+ filters: { status: PayoutStatus.FAILED },
+ }).config({ name: "failed-payouts-query" })
+
+ const { data: reversals } = useQueryGraphStep({
+ entity: "payout_reversal",
+ fields: ["id", "payout_id", "refund_id", "amount", "status_reason"],
+ filters: { status: PayoutStatus.FAILED },
+ }).config({ name: "failed-reversals-query" })
+
+ const { data: settlements } = useQueryGraphStep({
+ entity: "settlement",
+ fields: ["id", "account_id", "amount", "currency_code", "status_reason"],
+ filters: { payout_status: PayoutStatus.FAILED },
+ }).config({ name: "failed-settlements-query" })
+
+ const { data: adjustments } = useQueryGraphStep({
+ entity: "adjustment",
+ fields: ["id", "account_id", "amount", "currency_code", "status_reason"],
+ filters: { status: PayoutStatus.FAILED },
+ }).config({ name: "failed-adjustments-query" })
+
+ const alerting = resolveAlertingStep()
+
+ const failed = transform(
+ { captures, payouts, reversals, settlements, adjustments },
+ ({ captures, ...rest }) =>
+ ({
+ ...rest,
+ captures: captures.map((row) => ({
+ order_group_id: row.order_group_id,
+ payment_id: row.payment_id,
+ error: row.status_reason,
+ })),
+ }) as unknown as FailedOperations
+ )
+
+ const notifications = transform({ failed, alerting }, ({ failed, alerting }) =>
+ failedOperationsNotifications(failed, alerting)
+ )
+
+ const sent = sendOperatorEmailsStep(notifications)
+
+ const stats = transform({ failed, sent }, ({ failed, sent }): JobStats => ({
+ captures: failed.captures.length,
+ payouts: failed.payouts.length,
+ reversals: failed.reversals.length,
+ settlements: failed.settlements.length,
+ adjustments: failed.adjustments.length,
+ total: countFailedOperations(failed),
+ sent,
+ }))
+
+ return new WorkflowResponse(stats)
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/alerts/workflows/index.ts b/packages/plugins/stripe-connector/src/workflows/alerts/workflows/index.ts
new file mode 100644
index 000000000..62df34285
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/alerts/workflows/index.ts
@@ -0,0 +1 @@
+export * from "./alert-failed-operations"
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/steps/capture-stripe-payment-intent.ts b/packages/plugins/stripe-connector/src/workflows/captures/steps/capture-stripe-payment-intent.ts
new file mode 100644
index 000000000..df582d1d8
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/steps/capture-stripe-payment-intent.ts
@@ -0,0 +1,31 @@
+import { BigNumberInput } from "@medusajs/framework/types"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+import { resolveConnector } from "../../../utils/payout-module"
+
+export type CaptureStripePaymentIntentStepInput = {
+ capture_id: string
+ payment_intent_id: string
+ currency_code: string
+ capturable_amount: BigNumberInput
+}
+
+export const captureStripePaymentIntentStepId = "capture-stripe-payment-intent"
+
+/**
+ * Captures only the decided part of the cart payment at Stripe; Medusa's
+ * provider then finds the intent captured and records it as it is.
+ */
+export const captureStripePaymentIntentStep = createStep(
+ captureStripePaymentIntentStepId,
+ async (input: CaptureStripePaymentIntentStepInput, { container }) => {
+ await resolveConnector(container).capturePaymentIntent(
+ input.capture_id,
+ input.payment_intent_id,
+ input.capturable_amount,
+ input.currency_code
+ )
+ return new StepResponse(void 0)
+ }
+ // No compensation: captured funds have been taken from the customer.
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/steps/create-stripe-captures.ts b/packages/plugins/stripe-connector/src/workflows/captures/steps/create-stripe-captures.ts
new file mode 100644
index 000000000..c96206301
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/steps/create-stripe-captures.ts
@@ -0,0 +1,34 @@
+import { MathBN } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+import { CaptureDTO } from "../../../types/common"
+import { resolveConnector } from "../../../utils/payout-module"
+import { CaptureRowInput } from "../utils/capture-rows"
+
+export const createStripeCapturesStepId = "create-stripe-captures"
+
+export const createStripeCapturesStep = createStep(
+ createStripeCapturesStepId,
+ async (input: CaptureRowInput[], { container }) => {
+ if (!input.length) {
+ return new StepResponse<CaptureDTO[], string[]>([], [])
+ }
+ const created = await resolveConnector(container).createStripeCaptures(
+ input.map((row) => ({
+ ...row,
+ authorized_amount: MathBN.convert(row.authorized_amount).toNumber(),
+ capturable_amount: MathBN.convert(row.capturable_amount).toNumber(),
+ }))
+ )
+ return new StepResponse(
+ created,
+ created.map((row) => row.id)
+ )
+ },
+ async (ids, { container }) => {
+ if (!ids?.length) {
+ return
+ }
+ await resolveConnector(container).deleteStripeCaptures(ids)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/steps/index.ts b/packages/plugins/stripe-connector/src/workflows/captures/steps/index.ts
new file mode 100644
index 000000000..7f6cf67bf
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/steps/index.ts
@@ -0,0 +1,5 @@
+export * from "./capture-stripe-payment-intent"
+export * from "./create-stripe-captures"
+export * from "./load-capture-sources"
+export * from "./update-stripe-captures"
+export * from "./validate-capture-settleable"
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/steps/load-capture-sources.ts b/packages/plugins/stripe-connector/src/workflows/captures/steps/load-capture-sources.ts
new file mode 100644
index 000000000..87af25318
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/steps/load-capture-sources.ts
@@ -0,0 +1,112 @@
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { ORDER_FULFILLMENT_FIELDS } from "@mercurjs/core/workflows/payout/utils/fulfillment-status"
+
+import { resolveConnector } from "../../../utils/payout-module"
+import { CaptureDecisionOptions, CaptureSources } from "../utils/capture-rows"
+
+export type LoadCaptureSourcesStepInput = {
+ order_group_ids?: string[]
+ payment_collection_ids?: string[]
+}
+
+export type LoadCaptureSourcesStepOutput = {
+ sources: CaptureSources
+ options: CaptureDecisionOptions
+}
+
+const empty = (): CaptureSources => ({ collections: [], cart_links: [], groups: [], orders: [] })
+
+export const loadCaptureSourcesStepId = "load-stripe-capture-sources"
+
+/**
+ * The cart payments of the given order groups, or every authorized cart
+ * payment plus the given open ones (so a payment captured or canceled
+ * elsewhere closes its row), with the orders that decide them. Each hop keys
+ * on the previous one's results, which a fixed graph query cannot follow
+ * through the cart links.
+ */
+export const loadCaptureSourcesStep = createStep(
+ loadCaptureSourcesStepId,
+ async (input: LoadCaptureSourcesStepInput, { container }) => {
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+ const { capture, transfers } = resolveConnector(container).getOptions()
+ const options = { capture, transfers }
+ const done = (sources: CaptureSources) => new StepResponse<LoadCaptureSourcesStepOutput>({ sources, options })
+
+ let collectionIds: string[]
+ if (input.order_group_ids) {
+ if (!input.order_group_ids.length) return done(empty())
+ const { data: groups } = await query.graph({
+ entity: "order_group",
+ fields: ["cart_id"],
+ filters: { id: input.order_group_ids },
+ })
+ const cartIds = groups.map((group) => group.cart_id).filter((id): id is string => !!id)
+ if (!cartIds.length) return done(empty())
+ const { data: links } = await query.graph({
+ entity: "cart_payment_collection",
+ fields: ["payment_collection_id"],
+ filters: { cart_id: cartIds },
+ })
+ collectionIds = links.map((link) => link.payment_collection_id)
+ } else {
+ const { data: authorized } = await query.graph({
+ entity: "payment_collection",
+ fields: ["id"],
+ filters: { status: "authorized" },
+ })
+ collectionIds = Array.from(new Set([...authorized.map((c) => c.id), ...(input.payment_collection_ids ?? [])]))
+ }
+
+ if (!collectionIds.length) return done(empty())
+
+ const { data: collections } = await query.graph({
+ entity: "payment_collection",
+ fields: [
+ "id",
+ "currency_code",
+ "payments.id",
+ "payments.amount",
+ "payments.raw_amount",
+ "payments.captured_at",
+ "payments.canceled_at",
+ "payments.created_at",
+ "payments.captures.amount",
+ "payments.captures.raw_amount",
+ ],
+ filters: { id: collectionIds },
+ })
+
+ const { data: cartLinks } = await query.graph({
+ entity: "cart_payment_collection",
+ fields: ["cart_id", "payment_collection_id"],
+ filters: { payment_collection_id: collectionIds },
+ })
+ const cartIds = Array.from(new Set(cartLinks.map((link) => link.cart_id)))
+ if (!cartIds.length) return done(empty())
+
+ const { data: groups } = await query.graph({
+ entity: "order_group",
+ fields: ["id", "cart_id", "orders.id"],
+ filters: { cart_id: cartIds },
+ })
+
+ // fulfillment_status only resolves with orders at the root of the query.
+ const orderIds = groups.flatMap((group) => (group.orders ?? []).map((order) => order.id))
+ const { data: orders } = orderIds.length
+ ? await query.graph({
+ entity: "order",
+ fields: ["id", "status", "canceled_at", "total", "metadata", ...ORDER_FULFILLMENT_FIELDS],
+ filters: { id: orderIds },
+ })
+ : { data: [] }
+
+ return done({
+ collections: collections as unknown as CaptureSources["collections"],
+ cart_links: cartLinks,
+ groups: groups as unknown as CaptureSources["groups"],
+ orders: orders as unknown as CaptureSources["orders"],
+ })
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/steps/update-stripe-captures.ts b/packages/plugins/stripe-connector/src/workflows/captures/steps/update-stripe-captures.ts
new file mode 100644
index 000000000..55e5d9e2b
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/steps/update-stripe-captures.ts
@@ -0,0 +1,56 @@
+import { MathBN } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+import { CaptureDTO } from "../../../types/common"
+import { resolveConnector } from "../../../utils/payout-module"
+
+export type UpdateStripeCapturesStepInput = (Partial<Omit<CaptureDTO, "id">> & { id: string })[]
+
+const UPDATABLE = [
+ "status",
+ "status_reason",
+ "capturable_amount",
+ "authorized_amount",
+ "orders_total",
+ "orders_decided",
+ "authorized_at",
+ "expires_at",
+] as const
+
+const toWrite = (row: UpdateStripeCapturesStepInput[number]) => ({
+ ...row,
+ ...(row.capturable_amount !== undefined
+ ? { capturable_amount: MathBN.convert(row.capturable_amount).toNumber() }
+ : {}),
+ ...(row.authorized_amount !== undefined
+ ? { authorized_amount: MathBN.convert(row.authorized_amount).toNumber() }
+ : {}),
+})
+
+export const updateStripeCapturesStepId = "update-stripe-captures"
+
+export const updateStripeCapturesStep = createStep(
+ updateStripeCapturesStepId,
+ async (input: UpdateStripeCapturesStepInput, { container }) => {
+ if (!input.length) {
+ return new StepResponse<CaptureDTO[], UpdateStripeCapturesStepInput>([], [])
+ }
+ const connector = resolveConnector(container)
+ const previous = await connector.listStripeCaptures({ id: input.map((row) => row.id) }, { take: null })
+ const updated = await connector.updateStripeCaptures(input.map(toWrite))
+
+ return new StepResponse(
+ updated,
+ previous.map((row) => ({
+ id: row.id,
+ ...Object.fromEntries(UPDATABLE.map((field) => [field, row[field]])),
+ }))
+ )
+ },
+ async (previous, { container }) => {
+ if (!previous?.length) {
+ return
+ }
+ await resolveConnector(container).updateStripeCaptures(previous.map(toWrite))
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/steps/validate-capture-settleable.ts b/packages/plugins/stripe-connector/src/workflows/captures/steps/validate-capture-settleable.ts
new file mode 100644
index 000000000..a145af823
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/steps/validate-capture-settleable.ts
@@ -0,0 +1,29 @@
+import { MathBN, MedusaError } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+import { CaptureStatus, OPEN_CAPTURE_STATUSES } from "../../../types/common"
+import { CaptureAction } from "../utils/capture-action"
+
+export type ValidateCaptureSettleableStepInput = {
+ order_group_id: string
+ action: CaptureAction
+ capture: { status: CaptureStatus; capturable_amount: number | string } | null | undefined
+}
+
+export const validateCaptureSettleableStepId = "validate-stripe-capture-settleable"
+
+export const validateCaptureSettleableStep = createStep(
+ validateCaptureSettleableStepId,
+ async (input: ValidateCaptureSettleableStepInput) => {
+ if (!input.capture || !OPEN_CAPTURE_STATUSES.includes(input.capture.status)) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_FOUND,
+ `Order group ${input.order_group_id} has no payment waiting to be captured`
+ )
+ }
+ if (input.action === "capture" && !MathBN.gt(input.capture.capturable_amount, 0)) {
+ throw new MedusaError(MedusaError.Types.NOT_ALLOWED, "Nothing is left to capture")
+ }
+ return new StepResponse(void 0)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/utils/__tests__/capture-action.unit.spec.ts b/packages/plugins/stripe-connector/src/workflows/captures/utils/__tests__/capture-action.unit.spec.ts
new file mode 100644
index 000000000..a8988c933
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/utils/__tests__/capture-action.unit.spec.ts
@@ -0,0 +1,38 @@
+import { CaptureDTO, CaptureStatus } from "../../../../types/common"
+import { actionFor } from "../capture-action"
+
+const row = (status: CaptureStatus, capturable_amount = 100): CaptureDTO => ({
+ id: "scap_1",
+ order_group_id: "ogrp_1",
+ payment_collection_id: "pay_col_1",
+ payment_id: "pay_1",
+ currency_code: "eur",
+ authorized_amount: 100,
+ capturable_amount,
+ orders_total: 1,
+ orders_decided: 1,
+ status,
+ status_reason: null,
+ authorized_at: null,
+ expires_at: null,
+ created_at: new Date(),
+ updated_at: new Date(),
+})
+
+describe("actionFor", () => {
+ it("captures ready rows and releases cancelable ones", () => {
+ expect(actionFor(row(CaptureStatus.READY))).toBe("capture")
+ expect(actionFor(row(CaptureStatus.CANCELABLE))).toBe("cancel")
+ })
+
+ it("retries a failed row the way its capturable amount points", () => {
+ expect(actionFor(row(CaptureStatus.FAILED, 40))).toBe("capture")
+ expect(actionFor(row(CaptureStatus.FAILED, 0))).toBe("cancel")
+ })
+
+ it("leaves pending, expired and settled rows alone", () => {
+ for (const status of [CaptureStatus.PENDING, CaptureStatus.EXPIRED, CaptureStatus.CAPTURED, CaptureStatus.CANCELED]) {
+ expect(actionFor(row(status))).toBeNull()
+ }
+ })
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/utils/__tests__/capture-decision.unit.spec.ts b/packages/plugins/stripe-connector/src/workflows/captures/utils/__tests__/capture-decision.unit.spec.ts
new file mode 100644
index 000000000..59a794af1
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/utils/__tests__/capture-decision.unit.spec.ts
@@ -0,0 +1,75 @@
+import { decideCapture } from "../capture-decision"
+
+const DAY = 24 * 3600 * 1000
+const now = new Date("2026-10-22T10:00:00Z")
+
+const base = {
+ authorized_amount: 280,
+ authorized_at: new Date(now.getTime() - DAY),
+ now,
+ capture_before_acceptance: false,
+ required_fulfillment_status: "fulfilled" as const,
+ authorization_window_ms: 7 * DAY,
+ safety_buffer_ms: DAY,
+}
+
+const order = (id: string, fulfillment_status: string, status = "pending") => ({
+ id,
+ status,
+ canceled_at: status === "canceled" ? now : null,
+ fulfillment_status,
+ total: id === "a" ? 180 : 100,
+})
+
+describe("decideCapture", () => {
+ it("waits while an order is undecided", () => {
+ const decision = decideCapture({ ...base, orders: [order("a", "fulfilled"), order("b", "not_fulfilled")] })
+ expect(decision.action).toBe("wait")
+ expect(decision.orders_decided).toBe(1)
+ })
+
+ it("captures the full amount once every order is fulfilled", () => {
+ const decision = decideCapture({ ...base, orders: [order("a", "fulfilled"), order("b", "shipped")] })
+ expect(decision.action).toBe("capture")
+ expect(Number(decision.capturable_amount)).toBe(280)
+ })
+
+ it("deducts canceled orders from the capture", () => {
+ const decision = decideCapture({ ...base, orders: [order("a", "fulfilled"), order("b", "not_fulfilled", "canceled")] })
+ expect(decision.action).toBe("capture")
+ expect(Number(decision.capturable_amount)).toBe(180)
+ })
+
+ it("cancels when every order is canceled", () => {
+ const decision = decideCapture({ ...base, orders: [order("a", "not_fulfilled", "canceled"), order("b", "not_fulfilled", "canceled")] })
+ expect(decision.action).toBe("cancel")
+ })
+
+ it("captures on acceptance alone when configured", () => {
+ const decision = decideCapture({
+ ...base,
+ capture_before_acceptance: true,
+ orders: [{ ...order("a", "not_fulfilled"), accepted: true }, { ...order("b", "not_fulfilled"), accepted: null }],
+ })
+ expect(decision.action).toBe("capture")
+ })
+
+ it("captures what is decided once inside the safety buffer", () => {
+ const decision = decideCapture({
+ ...base,
+ authorized_at: new Date(now.getTime() - 6.5 * DAY),
+ orders: [order("a", "fulfilled"), order("b", "not_fulfilled")],
+ })
+ expect(decision.action).toBe("capture")
+ expect(decision.past_safety_buffer).toBe(true)
+ })
+
+ it("reports an expired authorization", () => {
+ const decision = decideCapture({
+ ...base,
+ authorized_at: new Date(now.getTime() - 8 * DAY),
+ orders: [order("a", "fulfilled")],
+ })
+ expect(decision.action).toBe("expired")
+ })
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/utils/__tests__/capture-rows.unit.spec.ts b/packages/plugins/stripe-connector/src/workflows/captures/utils/__tests__/capture-rows.unit.spec.ts
new file mode 100644
index 000000000..ad591f3e9
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/utils/__tests__/capture-rows.unit.spec.ts
@@ -0,0 +1,66 @@
+import { CaptureDTO, CaptureStatus } from "../../../../types/common"
+import { CaptureDecision } from "../capture-decision"
+import { captureStatusFor, planCaptureSync } from "../capture-rows"
+
+const payment = {
+ id: "pay_1",
+ amount: 100,
+ captured_at: null,
+ canceled_at: null,
+ created_at: new Date("2026-10-20T10:00:00Z"),
+ captures: [],
+}
+
+const decision = (action: CaptureDecision["action"]): CaptureDecision => ({
+ action,
+ capturable_amount: 100,
+ orders_decided: 1,
+ orders_total: 2,
+ expires_at: null,
+ past_safety_buffer: false,
+})
+
+describe("captureStatusFor", () => {
+ it("follows the decision while the payment is only authorized", () => {
+ expect(captureStatusFor(payment, decision("wait"))).toBe(CaptureStatus.PENDING)
+ expect(captureStatusFor(payment, decision("capture"))).toBe(CaptureStatus.READY)
+ expect(captureStatusFor(payment, decision("cancel"))).toBe(CaptureStatus.CANCELABLE)
+ expect(captureStatusFor(payment, decision("expired"))).toBe(CaptureStatus.EXPIRED)
+ })
+
+ it("closes the row once the payment is captured or canceled, whatever the decision", () => {
+ expect(captureStatusFor({ ...payment, captured_at: new Date() }, decision("wait"))).toBe(CaptureStatus.CAPTURED)
+ expect(captureStatusFor({ ...payment, captures: [{ amount: 40 }] }, decision("wait"))).toBe(CaptureStatus.CAPTURED)
+ expect(captureStatusFor({ ...payment, canceled_at: new Date() }, decision("capture"))).toBe(CaptureStatus.CANCELED)
+ })
+})
+
+describe("planCaptureSync", () => {
+ const row = (order_group_id: string, status: CaptureStatus) => ({
+ order_group_id,
+ payment_collection_id: `pc_${order_group_id}`,
+ payment_id: `pay_${order_group_id}`,
+ currency_code: "eur",
+ authorized_amount: 100,
+ capturable_amount: 100,
+ orders_total: 1,
+ orders_decided: 1,
+ status,
+ authorized_at: null,
+ expires_at: null,
+ })
+ const existing = (order_group_id: string, status: CaptureStatus, status_reason: string | null = null) =>
+ ({ ...row(order_group_id, status), id: `scap_${order_group_id}`, status_reason }) as unknown as CaptureDTO
+
+ it("creates unseen groups and refreshes known ones, keeping a failure visible", () => {
+ const plan = planCaptureSync(
+ [row("og_new", CaptureStatus.PENDING), row("og_failed", CaptureStatus.READY), row("og_ok", CaptureStatus.CAPTURED)],
+ [existing("og_failed", CaptureStatus.FAILED, "card_declined"), existing("og_ok", CaptureStatus.READY)]
+ )
+ expect(plan.create.map((r) => r.order_group_id)).toEqual(["og_new"])
+ expect(plan.update).toEqual([
+ expect.objectContaining({ id: "scap_og_failed", status: CaptureStatus.FAILED, status_reason: "card_declined" }),
+ expect.objectContaining({ id: "scap_og_ok", status: CaptureStatus.CAPTURED, status_reason: null }),
+ ])
+ })
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/utils/capture-action.ts b/packages/plugins/stripe-connector/src/workflows/captures/utils/capture-action.ts
new file mode 100644
index 000000000..3ff129c49
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/utils/capture-action.ts
@@ -0,0 +1,19 @@
+import { MathBN } from "@medusajs/framework/utils"
+
+import { CaptureDTO, CaptureStatus } from "../../../types/common"
+
+export type CaptureAction = "capture" | "cancel"
+
+// A failed row has lost its decision; what is left to capture tells which way it went.
+export const actionFor = (row: CaptureDTO): CaptureAction | null => {
+ switch (row.status) {
+ case CaptureStatus.READY:
+ return "capture"
+ case CaptureStatus.CANCELABLE:
+ return "cancel"
+ case CaptureStatus.FAILED:
+ return MathBN.gt(row.capturable_amount, 0) ? "capture" : "cancel"
+ default:
+ return null
+ }
+}
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/utils/capture-decision.ts b/packages/plugins/stripe-connector/src/workflows/captures/utils/capture-decision.ts
new file mode 100644
index 000000000..12d4648a4
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/utils/capture-decision.ts
@@ -0,0 +1,97 @@
+import { BigNumberInput, FulfillmentStatus } from "@medusajs/framework/types"
+import { MathBN } from "@medusajs/framework/utils"
+
+import { fulfillmentReached } from "@mercurjs/core/workflows/payout/utils/fulfillment-status"
+
+export type CaptureOrderState = {
+ id: string
+ status: string
+ canceled_at?: Date | string | null
+ fulfillment_status: string | null
+ total: BigNumberInput
+ /** Seller acceptance, when the marketplace tracks it; `null` means not tracked. */
+ accepted?: boolean | null
+}
+
+export type CaptureDecisionInput = {
+ orders: CaptureOrderState[]
+ authorized_amount: BigNumberInput
+ authorized_at: Date | string | null
+ now: Date
+ capture_before_acceptance: boolean
+ required_fulfillment_status: FulfillmentStatus
+ authorization_window_ms: number
+ safety_buffer_ms: number
+}
+
+export type CaptureDecision = {
+ action: "wait" | "capture" | "cancel" | "expired"
+ capturable_amount: BigNumberInput
+ orders_decided: number
+ orders_total: number
+ expires_at: Date | null
+ past_safety_buffer: boolean
+}
+
+const isCanceled = (order: CaptureOrderState) =>
+ order.status === "canceled" || !!order.canceled_at
+
+/**
+ * A group is decided when
+ * every order is canceled or ready; the capture amount deducts canceled
+ * orders; nothing left means cancel.
+ */
+export function decideCapture(input: CaptureDecisionInput): CaptureDecision {
+ const authorizedAt = input.authorized_at ? new Date(input.authorized_at) : null
+ const expiresAt = authorizedAt
+ ? new Date(authorizedAt.getTime() + input.authorization_window_ms)
+ : null
+ const pastSafety = expiresAt
+ ? input.now.getTime() >= expiresAt.getTime() - input.safety_buffer_ms
+ : false
+ const expired = expiresAt ? input.now.getTime() >= expiresAt.getTime() : false
+
+ let canceledTotal: BigNumberInput = 0
+ let decided = 0
+
+ for (const order of input.orders) {
+ if (isCanceled(order)) {
+ canceledTotal = MathBN.add(canceledTotal, order.total)
+ decided += 1
+ continue
+ }
+
+ const ready = input.capture_before_acceptance
+ ? order.accepted !== false
+ : fulfillmentReached(order.fulfillment_status, input.required_fulfillment_status)
+
+ if (ready) {
+ decided += 1
+ }
+ }
+
+ const capturable = MathBN.sub(input.authorized_amount, canceledTotal)
+ const base = {
+ capturable_amount: MathBN.gt(capturable, 0) ? capturable : 0,
+ orders_decided: decided,
+ orders_total: input.orders.length,
+ expires_at: expiresAt,
+ past_safety_buffer: pastSafety,
+ }
+
+ if (expired) {
+ return { ...base, action: "expired" }
+ }
+
+ const allDecided = input.orders.length > 0 && decided === input.orders.length
+
+ if (!allDecided && !pastSafety) {
+ return { ...base, action: "wait" }
+ }
+
+ if (MathBN.lte(capturable, 0)) {
+ return { ...base, action: "cancel" }
+ }
+
+ return { ...base, action: "capture" }
+}
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/utils/capture-rows.ts b/packages/plugins/stripe-connector/src/workflows/captures/utils/capture-rows.ts
new file mode 100644
index 000000000..68d7a8889
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/utils/capture-rows.ts
@@ -0,0 +1,176 @@
+import { BigNumberInput } from "@medusajs/framework/types"
+import { MathBN } from "@medusajs/framework/utils"
+import {
+ FulfillableOrder,
+ deriveFulfillmentStatus,
+} from "@mercurjs/core/workflows/payout/utils/fulfillment-status"
+
+import { CaptureDTO, CaptureStatus, ResolvedStripeConnectorOptions } from "../../../types/common"
+import { CaptureDecision, decideCapture } from "./capture-decision"
+
+type PaymentRow = {
+ id: string
+ amount: BigNumberInput
+ raw_amount?: BigNumberInput | null
+ captured_at: Date | string | null
+ canceled_at: Date | string | null
+ created_at: Date | string
+ captures?: { amount: BigNumberInput; raw_amount?: BigNumberInput | null }[] | null
+}
+
+type CollectionRow = {
+ id: string
+ currency_code: string
+ payments: PaymentRow[] | null
+}
+
+export type CaptureRowInput = {
+ order_group_id: string
+ payment_collection_id: string
+ payment_id: string
+ currency_code: string
+ authorized_amount: BigNumberInput
+ capturable_amount: BigNumberInput
+ orders_total: number
+ orders_decided: number
+ status: CaptureStatus
+ authorized_at: Date | null
+ expires_at: Date | null
+}
+
+const isCaptured = (payment: PaymentRow) =>
+ !!payment.captured_at ||
+ (payment.captures ?? []).some((capture) => MathBN.gt(capture.raw_amount ?? capture.amount, 0))
+
+export function captureStatusFor(payment: PaymentRow, decision: CaptureDecision): CaptureStatus {
+ if (payment.canceled_at) {
+ return CaptureStatus.CANCELED
+ }
+ if (isCaptured(payment)) {
+ return CaptureStatus.CAPTURED
+ }
+ switch (decision.action) {
+ case "expired":
+ return CaptureStatus.EXPIRED
+ case "capture":
+ return CaptureStatus.READY
+ case "cancel":
+ return CaptureStatus.CANCELABLE
+ default:
+ return CaptureStatus.PENDING
+ }
+}
+
+export type CaptureOrderRow = FulfillableOrder & {
+ id: string
+ status: string
+ canceled_at?: Date | string | null
+ total: BigNumberInput
+ metadata?: Record<string, unknown> | null
+}
+
+export type CaptureSources = {
+ collections: CollectionRow[]
+ cart_links: { cart_id: string; payment_collection_id: string }[]
+ groups: { id: string; cart_id: string | null; orders?: { id: string }[] | null }[]
+ orders: CaptureOrderRow[]
+}
+
+export type CaptureDecisionOptions = Pick<ResolvedStripeConnectorOptions, "capture" | "transfers">
+
+/**
+ * The capture state of each order group's cart payment, decided the way the
+ * capture job acts on it.
+ */
+export function buildCaptureRows(
+ sources: CaptureSources,
+ options: CaptureDecisionOptions,
+ now: Date
+): CaptureRowInput[] {
+ const cartByCollection = new Map(sources.cart_links.map((link) => [link.payment_collection_id, link.cart_id]))
+ const orderById = new Map(sources.orders.map((order) => [order.id, order]))
+ const groupByCart = new Map(sources.groups.map((group) => [group.cart_id, group]))
+
+ const rows: CaptureRowInput[] = []
+
+ for (const collection of sources.collections) {
+ const group = groupByCart.get(cartByCollection.get(collection.id) ?? "")
+ const payments = collection.payments ?? []
+ const payment = payments.find((p) => !p.canceled_at && !isCaptured(p)) ?? payments[0]
+ if (!group || !payment) {
+ continue
+ }
+
+ const groupOrders = (group.orders ?? [])
+ .map((ref) => orderById.get(ref.id))
+ .filter((order): order is CaptureOrderRow => !!order)
+ .map((order) => ({
+ id: order.id,
+ status: order.status,
+ canceled_at: order.canceled_at ?? null,
+ fulfillment_status: deriveFulfillmentStatus(order),
+ total: order.total,
+ accepted: order.metadata && "accepted" in order.metadata ? !!order.metadata.accepted : null,
+ }))
+
+ const authorizedAmount = payment.raw_amount ?? payment.amount
+ const decision = decideCapture({
+ orders: groupOrders,
+ authorized_amount: authorizedAmount,
+ authorized_at: payment.created_at,
+ now,
+ capture_before_acceptance: options.capture.captureBeforeAcceptance,
+ required_fulfillment_status: options.transfers.requiredFulfillmentStatus,
+ authorization_window_ms: options.capture.authorizationWindowMs,
+ safety_buffer_ms: options.capture.safetyBufferMs,
+ })
+
+ rows.push({
+ order_group_id: group.id,
+ payment_collection_id: collection.id,
+ payment_id: payment.id,
+ currency_code: collection.currency_code,
+ authorized_amount: authorizedAmount,
+ capturable_amount: decision.capturable_amount,
+ orders_total: decision.orders_total,
+ orders_decided: decision.orders_decided,
+ status: captureStatusFor(payment, decision),
+ authorized_at: payment.created_at ? new Date(payment.created_at) : null,
+ expires_at: decision.expires_at,
+ })
+ }
+
+ return rows
+}
+
+export type CaptureSyncPlan = {
+ create: CaptureRowInput[]
+ update: (CaptureRowInput & { id: string; status_reason: string | null })[]
+}
+
+// A failed attempt stays visible until the payment is captured or canceled,
+// even while the decision still says capture or cancel.
+const keepFailed = (existing: CaptureDTO, next: CaptureStatus) =>
+ existing.status === CaptureStatus.FAILED && (next === CaptureStatus.READY || next === CaptureStatus.CANCELABLE)
+
+export function planCaptureSync(rows: CaptureRowInput[], existing: CaptureDTO[]): CaptureSyncPlan {
+ const byGroup = new Map(existing.map((row) => [row.order_group_id, row]))
+ const plan: CaptureSyncPlan = { create: [], update: [] }
+
+ for (const row of rows) {
+ const current = byGroup.get(row.order_group_id)
+ if (!current) {
+ plan.create.push(row)
+ continue
+ }
+ const status = keepFailed(current, row.status) ? CaptureStatus.FAILED : row.status
+ plan.update.push({
+ ...row,
+ id: current.id,
+ status,
+ status_reason: status === CaptureStatus.FAILED ? current.status_reason : null,
+ })
+ }
+
+ return plan
+}
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/workflows/fail-stripe-capture.ts b/packages/plugins/stripe-connector/src/workflows/captures/workflows/fail-stripe-capture.ts
new file mode 100644
index 000000000..1179c82fb
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/workflows/fail-stripe-capture.ts
@@ -0,0 +1,24 @@
+import { WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
+
+import { CaptureStatus } from "../../../types/common"
+import { updateStripeCapturesStep } from "../steps"
+
+export type FailStripeCaptureWorkflowInput = {
+ id: string
+ status_reason: string
+}
+
+export const failStripeCaptureWorkflowId = "fail-stripe-capture"
+
+/** Marks a capture failed so the next run retries it and the daily digest reports it. */
+export const failStripeCaptureWorkflow = createWorkflow(
+ failStripeCaptureWorkflowId,
+ function (input: FailStripeCaptureWorkflowInput) {
+ const updated = updateStripeCapturesStep(
+ transform({ input }, ({ input }) => [
+ { id: input.id, status: CaptureStatus.FAILED, status_reason: input.status_reason.slice(0, 1024) },
+ ])
+ )
+ return new WorkflowResponse(transform({ updated }, ({ updated }) => updated[0]))
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/workflows/index.ts b/packages/plugins/stripe-connector/src/workflows/captures/workflows/index.ts
new file mode 100644
index 000000000..1803e0c34
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/workflows/index.ts
@@ -0,0 +1,5 @@
+export * from "./fail-stripe-capture"
+export * from "./process-captures"
+export * from "./settle-order-group-payment"
+export * from "./settle-stripe-capture"
+export * from "./sync-captures"
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/workflows/process-captures.ts b/packages/plugins/stripe-connector/src/workflows/captures/workflows/process-captures.ts
new file mode 100644
index 000000000..960cfa3a5
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/workflows/process-captures.ts
@@ -0,0 +1,49 @@
+import { WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
+
+import { CaptureDTO, CaptureStatus } from "../../../types/common"
+import { CaptureAction, actionFor } from "../utils/capture-action"
+import { syncCapturesWorkflow } from "./sync-captures"
+
+export type ProcessCapturesWorkflowInput = {
+ order_group_id?: string
+}
+
+export type ProcessCapturesWorkflowOutput = {
+ settle: { order_group_id: string; capture_id: string; action: CaptureAction }[]
+ stats: { synced: number; pending: number; expired: number }
+}
+
+export const processCapturesWorkflowId = "process-stripe-captures"
+
+/**
+ * Refreshes every open capture and returns the order groups whose cart
+ * payment is due: captured once its orders are all decided (or the
+ * authorization is about to expire), released once they were all canceled.
+ */
+export const processCapturesWorkflow = createWorkflow(
+ processCapturesWorkflowId,
+ function (input: ProcessCapturesWorkflowInput) {
+ const synced = syncCapturesWorkflow.runAsStep({
+ input: transform({ input }, ({ input }) => ({
+ order_group_ids: input.order_group_id ? [input.order_group_id] : undefined,
+ })),
+ })
+
+ return new WorkflowResponse(
+ transform({ synced }, ({ synced }): ProcessCapturesWorkflowOutput => {
+ const rows = synced as CaptureDTO[]
+ return {
+ settle: rows.flatMap((row) => {
+ const action = actionFor(row)
+ return action ? [{ order_group_id: row.order_group_id, capture_id: row.id, action }] : []
+ }),
+ stats: {
+ synced: rows.length,
+ pending: rows.filter((row) => row.status === CaptureStatus.PENDING).length,
+ expired: rows.filter((row) => row.status === CaptureStatus.EXPIRED).length,
+ },
+ }
+ })
+ )
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/workflows/settle-order-group-payment.ts b/packages/plugins/stripe-connector/src/workflows/captures/workflows/settle-order-group-payment.ts
new file mode 100644
index 000000000..90020b76a
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/workflows/settle-order-group-payment.ts
@@ -0,0 +1,26 @@
+import { WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
+
+import { CaptureAction } from "../utils/capture-action"
+import { settleStripeCaptureWorkflow } from "./settle-stripe-capture"
+import { syncCapturesWorkflow } from "./sync-captures"
+
+export type SettleOrderGroupPaymentWorkflowInput = {
+ order_group_id: string
+ action: CaptureAction
+}
+
+export const settleOrderGroupPaymentWorkflowId = "settle-stripe-order-group-payment"
+
+/** Captures or releases one order group's cart payment now, on the operator's call. */
+export const settleOrderGroupPaymentWorkflow = createWorkflow(
+ settleOrderGroupPaymentWorkflowId,
+ function (input: SettleOrderGroupPaymentWorkflowInput) {
+ syncCapturesWorkflow.runAsStep({
+ input: transform({ input }, ({ input }) => ({ order_group_ids: [input.order_group_id] })),
+ })
+
+ const settled = settleStripeCaptureWorkflow.runAsStep({ input })
+
+ return new WorkflowResponse(settled)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/workflows/settle-stripe-capture.ts b/packages/plugins/stripe-connector/src/workflows/captures/workflows/settle-stripe-capture.ts
new file mode 100644
index 000000000..e29cf7c6d
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/workflows/settle-stripe-capture.ts
@@ -0,0 +1,105 @@
+import { BigNumberInput } from "@medusajs/framework/types"
+import { MathBN } from "@medusajs/framework/utils"
+import { WorkflowResponse, createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+import { cancelPaymentStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { capturePaymentWorkflow } from "@mercurjs/core/workflows"
+
+import { CaptureDTO, CaptureStatus } from "../../../types/common"
+import { captureStripePaymentIntentStep, updateStripeCapturesStep, validateCaptureSettleableStep } from "../steps"
+import { CaptureAction } from "../utils/capture-action"
+
+export type SettleStripeCaptureWorkflowInput = {
+ order_group_id: string
+ action: CaptureAction
+}
+
+export const settleStripeCaptureWorkflowId = "settle-stripe-capture"
+
+/** Captures the decided amount of an order group's cart payment, or releases it. */
+export const settleStripeCaptureWorkflow = createWorkflow(
+ settleStripeCaptureWorkflowId,
+ function (input: SettleStripeCaptureWorkflowInput) {
+ const { data: captures } = useQueryGraphStep({
+ entity: "stripe_capture",
+ fields: ["id", "status", "payment_id", "authorized_amount", "capturable_amount"],
+ filters: { order_group_id: input.order_group_id },
+ }).config({ name: "settle-capture-query" })
+
+ const capture = transform({ captures }, ({ captures }) => captures[0] as unknown as CaptureDTO | undefined)
+
+ validateCaptureSettleableStep(
+ transform({ input, capture }, ({ input, capture }) => ({
+ order_group_id: input.order_group_id,
+ action: input.action,
+ capture: capture ? { status: capture.status, capturable_amount: Number(capture.capturable_amount) } : null,
+ }))
+ )
+
+ const paymentFilter = transform({ capture }, ({ capture }) => ({ id: capture!.payment_id }))
+
+ const { data: payment } = useQueryGraphStep({
+ entity: "payment",
+ fields: ["id", "currency_code", "data"],
+ filters: paymentFilter,
+ options: { isList: false, throwIfKeyNotFound: true },
+ }).config({ name: "settle-capture-payment-query" })
+
+ const partial = transform(
+ { input, capture },
+ ({ input, capture }) => input.action === "capture" && MathBN.lt(capture!.capturable_amount, capture!.authorized_amount)
+ )
+
+ when("capture-stripe-payment-intent", { partial }, ({ partial }) => partial).then(() => {
+ captureStripePaymentIntentStep(
+ transform({ capture, payment }, ({ capture, payment }) => ({
+ capture_id: capture!.id,
+ payment_intent_id: (payment.data as { id: string }).id,
+ currency_code: payment.currency_code,
+ capturable_amount: capture!.capturable_amount,
+ }))
+ )
+ })
+
+ // Read after the Stripe capture: its payment_intent.succeeded webhook may have recorded it already.
+ const { data: recordedPayment } = useQueryGraphStep({
+ entity: "payment",
+ fields: ["id", "captures.amount", "captures.raw_amount"],
+ filters: paymentFilter,
+ options: { isList: false, throwIfKeyNotFound: true },
+ }).config({ name: "settle-capture-recorded-query" })
+
+ const recorded = transform({ recordedPayment }, ({ recordedPayment }) =>
+ ((recordedPayment.captures ?? []) as { amount: BigNumberInput; raw_amount?: BigNumberInput | null }[]).reduce<BigNumberInput>(
+ (sum, row) => MathBN.add(sum, row.raw_amount ?? row.amount),
+ 0
+ )
+ )
+
+ when("record-cart-payment-capture", { input, capture, recorded }, ({ input, capture, recorded }) =>
+ input.action === "capture" && MathBN.lt(recorded, capture!.capturable_amount)
+ ).then(() => {
+ capturePaymentWorkflow.runAsStep({
+ input: transform({ capture }, ({ capture }) => ({
+ payment_id: capture!.payment_id,
+ amount: capture!.capturable_amount,
+ })),
+ })
+ })
+
+ when("cancel-cart-payment", { input }, ({ input }) => input.action === "cancel").then(() => {
+ cancelPaymentStep({ paymentIds: transform({ capture }, ({ capture }) => capture!.payment_id) })
+ })
+
+ const updated = updateStripeCapturesStep(
+ transform({ input, capture }, ({ input, capture }) => [
+ {
+ id: capture!.id,
+ status: input.action === "capture" ? CaptureStatus.CAPTURED : CaptureStatus.CANCELED,
+ status_reason: null,
+ },
+ ])
+ )
+
+ return new WorkflowResponse(transform({ updated }, ({ updated }) => updated[0]))
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/captures/workflows/sync-captures.ts b/packages/plugins/stripe-connector/src/workflows/captures/workflows/sync-captures.ts
new file mode 100644
index 000000000..e8f966ee7
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/captures/workflows/sync-captures.ts
@@ -0,0 +1,59 @@
+import { WorkflowResponse, createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+import { CaptureDTO, OPEN_CAPTURE_STATUSES } from "../../../types/common"
+import { createStripeCapturesStep, loadCaptureSourcesStep, updateStripeCapturesStep } from "../steps"
+import { buildCaptureRows, planCaptureSync } from "../utils/capture-rows"
+
+export type SyncCapturesWorkflowInput = {
+ order_group_ids?: string[]
+}
+
+export const syncCapturesWorkflowId = "sync-stripe-captures"
+
+/**
+ * Writes the capture state of each order group's cart payment: the given
+ * groups, or every open capture and authorized cart payment.
+ */
+export const syncCapturesWorkflow = createWorkflow(
+ syncCapturesWorkflowId,
+ function (input: SyncCapturesWorkflowInput) {
+ const open = when("sync-every-open-capture", { input }, ({ input }) => !input.order_group_ids).then(() => {
+ const { data } = useQueryGraphStep({
+ entity: "stripe_capture",
+ fields: ["payment_collection_id"],
+ filters: { status: OPEN_CAPTURE_STATUSES },
+ }).config({ name: "open-captures-query" })
+ return data
+ })
+
+ const loaded = loadCaptureSourcesStep(
+ transform({ input, open }, ({ input, open }) => ({
+ order_group_ids: input.order_group_ids,
+ payment_collection_ids: (open ?? []).map((row) => row.payment_collection_id as string),
+ }))
+ )
+
+ const rows = transform({ loaded }, ({ loaded }) => buildCaptureRows(loaded.sources, loaded.options, new Date()))
+
+ const existing = when("captures-to-sync", { rows }, ({ rows }) => rows.length > 0).then(() => {
+ const { data } = useQueryGraphStep({
+ entity: "stripe_capture",
+ fields: ["*"],
+ filters: transform({ rows }, ({ rows }) => ({ order_group_id: rows.map((row) => row.order_group_id) })),
+ }).config({ name: "existing-captures-query" })
+ return data
+ })
+
+ const plan = transform({ rows, existing }, ({ rows, existing }) =>
+ planCaptureSync(rows, (existing ?? []) as unknown as CaptureDTO[])
+ )
+
+ const created = createStripeCapturesStep(plan.create)
+ const updated = updateStripeCapturesStep(plan.update)
+
+ return new WorkflowResponse(
+ transform({ created, updated }, ({ created, updated }) => [...created, ...updated])
+ )
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/common/steps/index.ts b/packages/plugins/stripe-connector/src/workflows/common/steps/index.ts
new file mode 100644
index 000000000..08817952e
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/common/steps/index.ts
@@ -0,0 +1,3 @@
+export * from "./resolve-alerting"
+export * from "./set-checkpoints"
+export * from "./send-operator-emails"
diff --git a/packages/plugins/stripe-connector/src/workflows/common/steps/resolve-alerting.ts b/packages/plugins/stripe-connector/src/workflows/common/steps/resolve-alerting.ts
new file mode 100644
index 000000000..9a8ecd924
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/common/steps/resolve-alerting.ts
@@ -0,0 +1,10 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+import { resolveConnector } from "../../../utils/payout-module"
+
+export const resolveAlertingStepId = "resolve-stripe-alerting"
+
+export const resolveAlertingStep = createStep(resolveAlertingStepId, async (_, { container }) => {
+ const { alerting } = resolveConnector(container).getOptions()
+ return new StepResponse({ email: alerting.technicalEmail ?? null, from: alerting.from ?? null })
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/common/steps/send-operator-emails.ts b/packages/plugins/stripe-connector/src/workflows/common/steps/send-operator-emails.ts
new file mode 100644
index 000000000..c321ee2e2
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/common/steps/send-operator-emails.ts
@@ -0,0 +1,27 @@
+import { CreateNotificationDTO, INotificationModuleService } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+export const sendOperatorEmailsStepId = "send-stripe-operator-emails"
+
+/**
+ * Operator mail is best effort: a project without an email notification
+ * provider still runs the job. Responds with the number of mails sent.
+ */
+export const sendOperatorEmailsStep = createStep(
+ sendOperatorEmailsStepId,
+ async (notifications: CreateNotificationDTO[], { container }) => {
+ if (!notifications.length) {
+ return new StepResponse(0)
+ }
+ try {
+ await container.resolve<INotificationModuleService>(Modules.NOTIFICATION).createNotifications(notifications)
+ return new StepResponse(notifications.length)
+ } catch (error) {
+ container
+ .resolve(ContainerRegistrationKeys.LOGGER)
+ .warn(`Stripe connector could not mail the operator: ${(error as Error).message}`)
+ return new StepResponse(0)
+ }
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/common/steps/set-checkpoints.ts b/packages/plugins/stripe-connector/src/workflows/common/steps/set-checkpoints.ts
new file mode 100644
index 000000000..3a2f35d09
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/common/steps/set-checkpoints.ts
@@ -0,0 +1,35 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+import { resolveConnector } from "../../../utils/payout-module"
+
+export type SetCheckpointsStepInput = { key: string; value: string | null }[]
+
+export const setCheckpointsStepId = "set-stripe-connector-checkpoints"
+
+export const setCheckpointsStep = createStep(
+ setCheckpointsStepId,
+ async (input: SetCheckpointsStepInput, { container }) => {
+ const connector = resolveConnector(container)
+ const previous: SetCheckpointsStepInput = []
+
+ for (const checkpoint of input) {
+ const current = await connector.getCheckpoint(checkpoint.key)
+ if (current === checkpoint.value) {
+ continue
+ }
+ previous.push({ key: checkpoint.key, value: current })
+ await connector.setCheckpoint(checkpoint.key, checkpoint.value)
+ }
+
+ return new StepResponse(void 0, previous)
+ },
+ async (previous, { container }) => {
+ if (!previous?.length) {
+ return
+ }
+ const connector = resolveConnector(container)
+ for (const checkpoint of previous) {
+ await connector.setCheckpoint(checkpoint.key, checkpoint.value)
+ }
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/common/utils/__tests__/cursor.unit.spec.ts b/packages/plugins/stripe-connector/src/workflows/common/utils/__tests__/cursor.unit.spec.ts
new file mode 100644
index 000000000..75fa73337
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/common/utils/__tests__/cursor.unit.spec.ts
@@ -0,0 +1,46 @@
+import { advanceCursor, afterCursor, decodeCursor, encodeCursor, wrapCursor } from "../cursor"
+
+const at = "2026-10-20T10:00:00.000Z"
+
+// Applies a cursor filter the way Postgres would, for rows of the same shape.
+const matches = (filter: Record<string, unknown>, row: { id: string; created_at: string }) => {
+ const clauses = (filter.$or ?? []) as { created_at: Date | { $gt: Date }; id?: { $gt: string } }[]
+ if (!clauses.length) return true
+ return clauses.some((clause) => {
+ const time = new Date(row.created_at).getTime()
+ const createdOk =
+ clause.created_at instanceof Date
+ ? time === clause.created_at.getTime()
+ : time > clause.created_at.$gt.getTime()
+ return createdOk && (!clause.id || row.id > clause.id.$gt)
+ })
+}
+
+describe("cursor", () => {
+ it("round-trips the created_at and id of the last row", () => {
+ expect(decodeCursor(encodeCursor({ id: "order_2", created_at: new Date(at) }))).toEqual({ created_at: at, id: "order_2" })
+ })
+
+ it("reads a plain date stored by an earlier version", () => {
+ expect(decodeCursor(at)).toEqual({ created_at: at, id: "" })
+ expect(decodeCursor(null)).toBeNull()
+ expect(decodeCursor("garbage")).toBeNull()
+ })
+
+ it("does not skip rows that share the boundary timestamp", () => {
+ const rows = Array.from({ length: 5 }, (_, i) => ({ id: `order_${i}`, created_at: at }))
+ const filter = afterCursor(decodeCursor(encodeCursor(rows[1])))
+ expect(rows.filter((row) => matches(filter, row)).map((row) => row.id)).toEqual(["order_2", "order_3", "order_4"])
+ })
+
+ it("moves a forward scan past the last row, or keeps it when nothing came", () => {
+ expect(advanceCursor([{ id: "order_9", created_at: at }], "prev")).toBe(`${at}|order_9`)
+ expect(advanceCursor([], "prev")).toBe("prev")
+ })
+
+ it("wraps a backlog scan to the start once a page comes back short", () => {
+ const full = [{ id: "pout_1", created_at: at }, { id: "pout_2", created_at: at }]
+ expect(wrapCursor(full, 2)).toBe(`${at}|pout_2`)
+ expect(wrapCursor(full.slice(0, 1), 2)).toBeNull()
+ })
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/common/utils/cursor.ts b/packages/plugins/stripe-connector/src/workflows/common/utils/cursor.ts
new file mode 100644
index 000000000..007275f3a
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/common/utils/cursor.ts
@@ -0,0 +1,39 @@
+export type Cursor = { created_at: string; id: string }
+
+export type CursorRow = { id: string; created_at: Date | string }
+
+const SEPARATOR = "|"
+
+export const encodeCursor = (row: CursorRow): string =>
+ `${new Date(row.created_at).toISOString()}${SEPARATOR}${row.id}`
+
+/** Also reads the plain ISO dates earlier versions stored. */
+export const decodeCursor = (value: string | null | undefined): Cursor | null => {
+ if (!value) {
+ return null
+ }
+ const [createdAt, id = ""] = value.split(SEPARATOR)
+ const date = new Date(createdAt)
+ return Number.isNaN(date.getTime()) ? null : { created_at: date.toISOString(), id }
+}
+
+// created_at carries microseconds while the cursor keeps milliseconds, so rows
+// in the cursor's own millisecond come back once more instead of being skipped.
+export const afterCursor = (cursor: Cursor | null): Record<string, unknown> =>
+ cursor
+ ? {
+ $or: [
+ { created_at: { $gt: new Date(cursor.created_at) } },
+ { created_at: new Date(cursor.created_at), id: { $gt: cursor.id } },
+ ],
+ }
+ : {}
+
+export const CURSOR_ORDER = { created_at: "ASC", id: "ASC" } as const
+
+export const advanceCursor = (rows: CursorRow[], previous: string | null): string | null =>
+ rows.length ? encodeCursor(rows[rows.length - 1]) : previous
+
+/** A scan that wraps: past the last row, or back to the start once a page comes back short. */
+export const wrapCursor = (rows: CursorRow[], pageSize: number): string | null =>
+ rows.length < pageSize ? null : encodeCursor(rows[rows.length - 1])
diff --git a/packages/plugins/stripe-connector/src/workflows/common/utils/index.ts b/packages/plugins/stripe-connector/src/workflows/common/utils/index.ts
new file mode 100644
index 000000000..c10f1d56c
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/common/utils/index.ts
@@ -0,0 +1 @@
+export * from "./cursor"
diff --git a/packages/plugins/stripe-connector/src/workflows/common/workflows/index.ts b/packages/plugins/stripe-connector/src/workflows/common/workflows/index.ts
new file mode 100644
index 000000000..05335b4cf
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/common/workflows/index.ts
@@ -0,0 +1 @@
+export * from "./set-checkpoints"
diff --git a/packages/plugins/stripe-connector/src/workflows/common/workflows/set-checkpoints.ts b/packages/plugins/stripe-connector/src/workflows/common/workflows/set-checkpoints.ts
new file mode 100644
index 000000000..e39e6acf8
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/common/workflows/set-checkpoints.ts
@@ -0,0 +1,13 @@
+import { WorkflowResponse, createWorkflow } from "@medusajs/framework/workflows-sdk"
+
+import { SetCheckpointsStepInput, setCheckpointsStep } from "../steps/set-checkpoints"
+
+export const setStripeCheckpointsWorkflowId = "set-stripe-connector-checkpoints"
+
+export const setStripeCheckpointsWorkflow = createWorkflow(
+ setStripeCheckpointsWorkflowId,
+ function (input: { checkpoints: SetCheckpointsStepInput }) {
+ setCheckpointsStep(input.checkpoints)
+ return new WorkflowResponse(void 0)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/hooks/payment-refunded.ts b/packages/plugins/stripe-connector/src/workflows/hooks/payment-refunded.ts
new file mode 100644
index 000000000..f717f785d
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/hooks/payment-refunded.ts
@@ -0,0 +1,18 @@
+import { refundPaymentWorkflow } from "@mercurjs/core/workflows"
+
+import { JobTrigger } from "../../types/common"
+import { runJob } from "../../utils/run-job"
+import { jobWorkflow } from "../jobs"
+
+refundPaymentWorkflow.hooks.paymentRefunded(async ({ order_id, is_replay }, { container }) => {
+ if (!order_id || is_replay) {
+ return
+ }
+
+ await runJob(
+ container,
+ "payout-process-reversals",
+ JobTrigger.SUBSCRIBER,
+ jobWorkflow("payout-process-reversals", container, { order_id })
+ )
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/jobs.ts b/packages/plugins/stripe-connector/src/workflows/jobs.ts
new file mode 100644
index 000000000..61718034c
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/jobs.ts
@@ -0,0 +1,145 @@
+import { Logger, MedusaContainer } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { createOrRefreshSellerPayoutAccountWorkflow, syncPayoutAccountWorkflow } from "@mercurjs/core/workflows"
+
+import { CaptureStatus, PayoutJobName } from "../types/common"
+import { resolveConnector } from "../utils/payout-module"
+import { JobStats } from "../utils/run-job"
+import { alertFailedOperationsWorkflow } from "./alerts/workflows/alert-failed-operations"
+import { failStripeCaptureWorkflow } from "./captures/workflows/fail-stripe-capture"
+import { processCapturesWorkflow } from "./captures/workflows/process-captures"
+import { settleStripeCaptureWorkflow } from "./captures/workflows/settle-stripe-capture"
+import { setStripeCheckpointsWorkflow } from "./common/workflows/set-checkpoints"
+import { notifyKycAttentionWorkflow } from "./kyc/workflows/notify-kyc-attention"
+import { ONBOARDING_CHECKPOINT } from "./onboarding/utils/onboarding-sellers"
+import { selectOnboardingSellersWorkflow } from "./onboarding/workflows/select-onboarding-sellers"
+import { processPayoutsWorkflow } from "./payouts/workflows/process-payouts"
+import { processReversalsWorkflow } from "./reversals/workflows/process-reversals"
+import { processSettlementsWorkflow } from "./settlements/workflows/process-settlements"
+
+export type JobScope = { seller_id?: string; order_id?: string; order_group_id?: string }
+
+const errorMessage = (errors: { error?: { message?: string } | null }[] | undefined) =>
+ errors?.[0]?.error?.message ?? "unknown error"
+
+// Jobs that act on many sellers, accounts or payments run one workflow per
+// item, so one failing item is recorded and the rest still go through.
+async function syncOnboarding(container: MedusaContainer, scope: JobScope): Promise<JobStats> {
+ if (!resolveConnector(container).getOptions().onboarding.enabled) {
+ return { skipped: "onboarding disabled" }
+ }
+ const logger = container.resolve<Logger>(ContainerRegistrationKeys.LOGGER)
+
+ const { result: selection } = await selectOnboardingSellersWorkflow(container).run({
+ input: { seller_ids: scope.seller_id ? [scope.seller_id] : undefined },
+ })
+
+ let processed = 0
+ let failed = 0
+ for (const sellerId of selection.seller_ids) {
+ const { errors } = await createOrRefreshSellerPayoutAccountWorkflow(container).run({
+ input: { seller_id: sellerId },
+ throwOnError: false,
+ })
+ if (errors?.length) {
+ failed += 1
+ logger.error(`Could not prepare payout account for seller ${sellerId}: ${errorMessage(errors)}`)
+ } else {
+ processed += 1
+ }
+ }
+
+ if (selection.checkpoint) {
+ await setStripeCheckpointsWorkflow(container).run({
+ input: { checkpoints: [{ key: ONBOARDING_CHECKPOINT, value: selection.checkpoint }] },
+ })
+ }
+
+ return {
+ sellers: selection.seller_ids.length,
+ processed,
+ failed,
+ ...(selection.checkpoint ? { checkpoint: selection.checkpoint } : {}),
+ }
+}
+
+async function validateCaptures(container: MedusaContainer, scope: JobScope): Promise<JobStats> {
+ const logger = container.resolve<Logger>(ContainerRegistrationKeys.LOGGER)
+ const { result } = await processCapturesWorkflow(container).run({ input: { order_group_id: scope.order_group_id } })
+
+ const settled: Record<string, number> = { captured: 0, canceled: 0, failed: 0 }
+ for (const row of result.settle) {
+ const { errors } = await settleStripeCaptureWorkflow(container).run({
+ input: { order_group_id: row.order_group_id, action: row.action },
+ throwOnError: false,
+ })
+ if (errors?.length) {
+ const reason = errorMessage(errors)
+ logger.error(`Could not ${row.action} the payment of order group ${row.order_group_id}: ${reason}`)
+ await failStripeCaptureWorkflow(container).run({ input: { id: row.capture_id, status_reason: reason } })
+ settled.failed += 1
+ } else {
+ settled[row.action === "capture" ? CaptureStatus.CAPTURED : CaptureStatus.CANCELED] += 1
+ }
+ }
+
+ return { ...result.stats, ...settled }
+}
+
+async function monitorKyc(container: MedusaContainer): Promise<JobStats> {
+ if (!resolveConnector(container).getOptions().kycMonitor.enabled) {
+ return { skipped: "kyc monitor disabled" }
+ }
+ const logger = container.resolve<Logger>(ContainerRegistrationKeys.LOGGER)
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+
+ const { data: accounts } = await query.graph({
+ entity: "payout_account",
+ fields: ["id"],
+ filters: { external_id: { $ne: null } },
+ })
+
+ const synced: string[] = []
+ for (const account of accounts) {
+ const { errors } = await syncPayoutAccountWorkflow(container).run({
+ input: { id: account.id },
+ throwOnError: false,
+ })
+ if (errors?.length) {
+ logger.error(`Could not sync payout account ${account.id}: ${errorMessage(errors)}`)
+ } else {
+ synced.push(account.id)
+ }
+ }
+
+ const { result } = await notifyKycAttentionWorkflow(container).run({ input: { account_ids: synced } })
+ return { accounts: accounts.length, synced: synced.length, ...result }
+}
+
+export const jobWorkflow = (
+ job: PayoutJobName,
+ container: MedusaContainer,
+ scope: JobScope = {}
+): (() => Promise<JobStats>) => {
+ const workflows: Record<PayoutJobName, () => Promise<JobStats>> = {
+ "payout-sync-onboarding": () => syncOnboarding(container, scope),
+ "payout-validate-captures": () => validateCaptures(container, scope),
+ "payout-process-transfers": async () =>
+ (
+ await processPayoutsWorkflow(container).run({
+ input: { order_ids: scope.order_id ? [scope.order_id] : undefined },
+ })
+ ).result,
+ "payout-process-reversals": async () =>
+ (
+ await processReversalsWorkflow(container).run({
+ input: { order_ids: scope.order_id ? [scope.order_id] : undefined },
+ })
+ ).result,
+ "payout-process-settlements": async () =>
+ (await processSettlementsWorkflow(container).run({ input: { seller_id: scope.seller_id } })).result,
+ "payout-alert-failed-operations": async () => (await alertFailedOperationsWorkflow(container).run()).result,
+ "payout-monitor-kyc": () => monitorKyc(container),
+ }
+ return workflows[job]
+}
diff --git a/packages/plugins/stripe-connector/src/workflows/kyc/utils/index.ts b/packages/plugins/stripe-connector/src/workflows/kyc/utils/index.ts
new file mode 100644
index 000000000..b9512d804
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/kyc/utils/index.ts
@@ -0,0 +1 @@
+export * from "./kyc-attention"
diff --git a/packages/plugins/stripe-connector/src/workflows/kyc/utils/kyc-attention.ts b/packages/plugins/stripe-connector/src/workflows/kyc/utils/kyc-attention.ts
new file mode 100644
index 000000000..ab1cccb96
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/kyc/utils/kyc-attention.ts
@@ -0,0 +1,27 @@
+import { PayoutKycStatus } from "@mercurjs/types"
+
+export type KycAttention = { account_id: string; kyc_status: string | null; disabled_reason: string | null }
+
+export const needsKycAttention = (account: { kyc_status: string | null }) =>
+ !!account.kyc_status && account.kyc_status !== PayoutKycStatus.APPROVED
+
+export function kycAttentionNotifications(attention: KycAttention[], alerting: { email: string | null; from: string | null }) {
+ if (!attention.length || !alerting.email) {
+ return []
+ }
+ return [
+ {
+ to: alerting.email,
+ from: alerting.from,
+ channel: "email",
+ template: "payout-kyc-required",
+ data: { accounts: attention },
+ content: {
+ subject: `[Payouts] ${attention.length} account(s) need KYC attention`,
+ text: attention
+ .map((row) => `- ${row.account_id}: ${row.kyc_status}${row.disabled_reason ? ` (${row.disabled_reason})` : ""}`)
+ .join("\n"),
+ },
+ },
+ ]
+}
diff --git a/packages/plugins/stripe-connector/src/workflows/kyc/workflows/index.ts b/packages/plugins/stripe-connector/src/workflows/kyc/workflows/index.ts
new file mode 100644
index 000000000..029bc0cac
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/kyc/workflows/index.ts
@@ -0,0 +1 @@
+export * from "./notify-kyc-attention"
diff --git a/packages/plugins/stripe-connector/src/workflows/kyc/workflows/notify-kyc-attention.ts b/packages/plugins/stripe-connector/src/workflows/kyc/workflows/notify-kyc-attention.ts
new file mode 100644
index 000000000..74c4b8345
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/kyc/workflows/notify-kyc-attention.ts
@@ -0,0 +1,51 @@
+import { WorkflowResponse, createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+import { resolveAlertingStep, sendOperatorEmailsStep } from "../../common/steps"
+import { KycAttention, kycAttentionNotifications, needsKycAttention } from "../utils/kyc-attention"
+
+export type NotifyKycAttentionWorkflowInput = {
+ account_ids: string[]
+}
+
+export const notifyKycAttentionWorkflowId = "notify-stripe-kyc-attention"
+
+/** Mails the technical contact the given payout accounts whose KYC is not approved. */
+export const notifyKycAttentionWorkflow = createWorkflow(
+ notifyKycAttentionWorkflowId,
+ function (input: NotifyKycAttentionWorkflowInput) {
+ const accounts = when("kyc-accounts-to-check", { input }, ({ input }) => input.account_ids.length > 0).then(() => {
+ const { data } = useQueryGraphStep({
+ entity: "payout_account",
+ fields: ["id", "kyc_status", "disabled_reason"],
+ filters: { id: input.account_ids },
+ }).config({ name: "kyc-attention-accounts-query" })
+ return data
+ })
+
+ const alerting = resolveAlertingStep()
+
+ const attention = transform({ accounts }, ({ accounts }): KycAttention[] =>
+ ((accounts ?? []) as { id: string; kyc_status: string | null; disabled_reason: string | null }[])
+ .filter(needsKycAttention)
+ .map((account) => ({
+ account_id: account.id,
+ kyc_status: account.kyc_status,
+ disabled_reason: account.disabled_reason,
+ }))
+ )
+
+ const notifications = transform({ attention, alerting }, ({ attention, alerting }) =>
+ kycAttentionNotifications(attention, alerting)
+ )
+
+ const sent = sendOperatorEmailsStep(notifications)
+
+ return new WorkflowResponse(
+ transform({ attention, sent }, ({ attention, sent }) => ({
+ attention: attention.length,
+ sent,
+ }))
+ )
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/notifications/steps/claim-operator-notification.ts b/packages/plugins/stripe-connector/src/workflows/notifications/steps/claim-operator-notification.ts
new file mode 100644
index 000000000..a4e262045
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/notifications/steps/claim-operator-notification.ts
@@ -0,0 +1,27 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+import { resolveConnector } from "../../../utils/payout-module"
+
+export const claimOperatorNotificationStepId = "claim-stripe-operator-notification"
+
+/**
+ * Retried payouts fail again on every run; the operator hears about each
+ * failure once, so the key is claimed in the checkpoints before sending.
+ */
+export const claimOperatorNotificationStep = createStep(
+ claimOperatorNotificationStepId,
+ async (input: { key: string }, { container }) => {
+ const connector = resolveConnector(container)
+ if (await connector.getCheckpoint(input.key)) {
+ return new StepResponse(false, null)
+ }
+ await connector.setCheckpoint(input.key, new Date().toISOString())
+ return new StepResponse(true, input.key)
+ },
+ async (key, { container }) => {
+ if (!key) {
+ return
+ }
+ await resolveConnector(container).setCheckpoint(key, null)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/notifications/steps/index.ts b/packages/plugins/stripe-connector/src/workflows/notifications/steps/index.ts
new file mode 100644
index 000000000..684810185
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/notifications/steps/index.ts
@@ -0,0 +1,3 @@
+export * from "./resolve-endpoint-down-mail"
+export * from "./post-operator-notification"
+export * from "./claim-operator-notification"
diff --git a/packages/plugins/stripe-connector/src/workflows/notifications/steps/post-operator-notification.ts b/packages/plugins/stripe-connector/src/workflows/notifications/steps/post-operator-notification.ts
new file mode 100644
index 000000000..829498c71
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/notifications/steps/post-operator-notification.ts
@@ -0,0 +1,89 @@
+import { Logger } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+import { ConnectorNotificationDTO } from "../../../types/common"
+import { resolveConnector } from "../../../utils/payout-module"
+import { notificationHeaders, redactUrl } from "../utils/notification-signature"
+
+export type PostOperatorNotificationStepInput = {
+ type: string
+ payload: Record<string, unknown>
+}
+
+export type PostOperatorNotificationStepOutput = {
+ notification: ConnectorNotificationDTO | null
+ delivered: boolean
+ error: string | null
+}
+
+const RETRY_DELAYS_MS = [1000, 5000, 25000]
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
+
+export const postOperatorNotificationStepId = "post-stripe-operator-notification"
+
+/**
+ * POSTs the notification to the operator's endpoint, retrying with backoff,
+ * and logs each delivery. Nothing is undone: the endpoint already got it.
+ */
+export const postOperatorNotificationStep = createStep(
+ postOperatorNotificationStepId,
+ async (input: PostOperatorNotificationStepInput, { container }) => {
+ const connector = resolveConnector(container)
+ const logger = container.resolve<Logger>(ContainerRegistrationKeys.LOGGER)
+ const { url, secret } = connector.getOptions().notifications
+
+ if (!url) {
+ return new StepResponse<PostOperatorNotificationStepOutput>({ notification: null, delivered: false, error: null })
+ }
+
+ const body = JSON.stringify({ type: input.type, payload: input.payload })
+ const record = await connector.createConnectorNotifications({
+ type: input.type,
+ url: redactUrl(url) ?? "",
+ payload: { type: input.type, payload: input.payload },
+ })
+
+ let attempts = 0
+ let responseStatus: number | null = null
+ let error: string | null = null
+ let delivered = false
+
+ for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt++) {
+ attempts += 1
+ try {
+ const response = await fetch(url, { method: "POST", headers: notificationHeaders(body, secret), body })
+ responseStatus = response.status
+ if (response.ok) {
+ delivered = true
+ error = null
+ break
+ }
+ error = `Operator endpoint answered ${response.status}`
+ } catch (err) {
+ error = err instanceof Error ? err.message : String(err)
+ }
+
+ if (attempt < RETRY_DELAYS_MS.length) {
+ await sleep(RETRY_DELAYS_MS[attempt])
+ }
+ }
+
+ const notification = await connector.updateConnectorNotifications({
+ id: record.id,
+ attempts,
+ response_status: responseStatus,
+ error,
+ delivered,
+ })
+
+ if (delivered) {
+ logger.info(`Notification ${input.type} sent to operator (${responseStatus})`)
+ } else {
+ logger.error(`Error while notifying the operator at ${redactUrl(url)}: ${error}`)
+ }
+
+ return new StepResponse<PostOperatorNotificationStepOutput>({ notification, delivered, error })
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/notifications/steps/resolve-endpoint-down-mail.ts b/packages/plugins/stripe-connector/src/workflows/notifications/steps/resolve-endpoint-down-mail.ts
new file mode 100644
index 000000000..8a126356c
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/notifications/steps/resolve-endpoint-down-mail.ts
@@ -0,0 +1,44 @@
+import { CreateNotificationDTO } from "@medusajs/framework/types"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+import { resolveConnector } from "../../../utils/payout-module"
+import { redactUrl } from "../utils/notification-signature"
+
+export const ENDPOINT_DOWN_CHECKPOINT = "notification_endpoint_down_mailed_at"
+
+export const resolveEndpointDownMailStepId = "resolve-stripe-endpoint-down-mail"
+
+/** The mail telling the operator their notification endpoint is down, unless it is off or cooling down. */
+export const resolveEndpointDownMailStep = createStep(
+ resolveEndpointDownMailStepId,
+ async (input: { down: boolean; error: string | null }, { container }) => {
+ const connector = resolveConnector(container)
+ const { notifications, alerting } = connector.getOptions()
+ const email = alerting.technicalEmail
+ if (!input.down || !notifications.mailOnEndpointDown || !email) {
+ return new StepResponse<CreateNotificationDTO[]>([])
+ }
+
+ const cooldownMs = notifications.endpointDownCooldownMinutes * 60 * 1000
+ const last = await connector.getCheckpoint(ENDPOINT_DOWN_CHECKPOINT)
+ if (cooldownMs > 0 && last && Date.now() - new Date(last).getTime() < cooldownMs) {
+ return new StepResponse<CreateNotificationDTO[]>([])
+ }
+
+ const url = redactUrl(notifications.url)
+ const error = input.error ?? "unknown"
+ return new StepResponse<CreateNotificationDTO[]>([
+ {
+ to: email,
+ from: alerting.from,
+ channel: "email",
+ template: "payout-notification-endpoint-down",
+ data: { url, error },
+ content: {
+ subject: "[Payouts] Operator notification endpoint is down",
+ text: `POST ${url} failed after retries: ${error}`,
+ },
+ },
+ ])
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/notifications/utils/__tests__/failed-operation.unit.spec.ts b/packages/plugins/stripe-connector/src/workflows/notifications/utils/__tests__/failed-operation.unit.spec.ts
new file mode 100644
index 000000000..5f6edbf83
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/notifications/utils/__tests__/failed-operation.unit.spec.ts
@@ -0,0 +1,115 @@
+import { failedOperationNotification, failedOperationNotificationKey } from "../failed-operation"
+
+describe("failed operation notifications", () => {
+ it("describes a failed payout with its order, seller and Stripe's message", () => {
+ const notification = failedOperationNotification("payout", {
+ id: "pout_1",
+ display_id: 7,
+ order_id: "order_1",
+ amount: 4200,
+ currency_code: "eur",
+ status: "failed",
+ status_reason: "provider_error",
+ data: { status_detail: "Insufficient funds in Stripe account" },
+ account: { id: "pacc_1", seller: { id: "sel_1" } },
+ })
+
+ expect(notification).toEqual({
+ type: "payout.failed",
+ payload: {
+ id: "pout_1",
+ display_id: 7,
+ order_id: "order_1",
+ account_id: "pacc_1",
+ seller_id: "sel_1",
+ amount: 4200,
+ currency_code: "eur",
+ status_reason: "provider_error",
+ status_detail: "Insufficient funds in Stripe account",
+ },
+ })
+ })
+
+ it("takes a reversal's order, currency and seller from its payout", () => {
+ const notification = failedOperationNotification("payout_reversal", {
+ id: "prev_1",
+ payout_id: "pout_1",
+ refund_id: "ref_1",
+ amount: 500,
+ status: "failed",
+ status_reason: "provider_error",
+ data: null,
+ payout: { order_id: "order_1", currency_code: "eur", account: { id: "pacc_1", seller: { id: "sel_1" } } },
+ })
+
+ expect(notification?.type).toBe("payout_reversal.failed")
+ expect(notification?.payload).toMatchObject({
+ order_id: "order_1",
+ currency_code: "eur",
+ seller_id: "sel_1",
+ status_detail: null,
+ })
+ })
+
+ it("reads a settlement's bank payout status, not the settlement status", () => {
+ const row = {
+ id: "stl_1",
+ display_id: 3,
+ account_id: "pacc_1",
+ amount: 9000,
+ currency_code: "eur",
+ status: "failed",
+ payout_status: "failed",
+ provider_payout_id: "po_1",
+ status_reason: "account_closed: The bank account has been closed",
+ payout_account: { seller: { id: "sel_1" } },
+ }
+
+ expect(failedOperationNotification("settlement", row)?.type).toBe("settlement.payout_failed")
+ expect(
+ failedOperationNotification("settlement", { ...row, status: "open", payout_status: "on_hold", status_reason: "account_not_ready" })
+ ).toBeNull()
+ })
+
+ it("notifies a settlement held because the connected balance cannot cover it", () => {
+ const row = {
+ id: "stl_2",
+ display_id: 4,
+ account_id: "pacc_1",
+ amount: 9000,
+ currency_code: "eur",
+ status: "failed",
+ payout_status: "on_hold",
+ provider_payout_id: null,
+ status_reason: "insufficient_available_balance",
+ payout_account: { seller: { id: "sel_1" } },
+ }
+
+ expect(failedOperationNotification("settlement", row)?.payload).toMatchObject({
+ id: "stl_2",
+ status_reason: "insufficient_available_balance",
+ })
+ })
+
+ it("skips records that are gone or no longer failed", () => {
+ expect(failedOperationNotification("payout", null)).toBeNull()
+ expect(failedOperationNotification("payout", { id: "pout_1", status: "paid" })).toBeNull()
+ })
+
+ it("keys a settlement failure by its bank payout, so a later failure of a retried payout is new", () => {
+ const first = failedOperationNotificationKey({
+ type: "settlement.payout_failed",
+ payload: { id: "stl_1", provider_payout_id: "po_1" },
+ })
+ const refused = failedOperationNotificationKey({
+ type: "settlement.payout_failed",
+ payload: { id: "stl_1", provider_payout_id: null },
+ })
+
+ expect(first).toBe("notified:settlement.payout_failed:stl_1:po_1")
+ expect(refused).toBe("notified:settlement.payout_failed:stl_1")
+ expect(failedOperationNotificationKey({ type: "payout.failed", payload: { id: "pout_1" } })).toBe(
+ "notified:payout.failed:pout_1"
+ )
+ })
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/notifications/utils/__tests__/notification-signature.unit.spec.ts b/packages/plugins/stripe-connector/src/workflows/notifications/utils/__tests__/notification-signature.unit.spec.ts
new file mode 100644
index 000000000..ff2be02b3
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/notifications/utils/__tests__/notification-signature.unit.spec.ts
@@ -0,0 +1,24 @@
+import { createHmac } from "crypto"
+
+import { NOTIFICATION_SIGNATURE_HEADER, notificationHeaders, redactUrl } from "../notification-signature"
+
+describe("operator notifications", () => {
+ it("signs the body with HMAC-SHA256 when a secret is configured", () => {
+ const body = JSON.stringify({ type: "test", payload: {} })
+ const headers = notificationHeaders(body, "s3cret")
+ const expected = createHmac("sha256", "s3cret").update(body).digest("hex")
+ expect(headers[NOTIFICATION_SIGNATURE_HEADER]).toBe(`sha256=${expected}`)
+ expect(headers["content-type"]).toBe("application/json")
+ })
+
+ it("sends no signature without a secret", () => {
+ expect(notificationHeaders("{}", undefined)).toEqual({ "content-type": "application/json" })
+ })
+
+ it("redacts the webhook secret in the path, query and credentials", () => {
+ expect(redactUrl("https://hooks.slack.com/services/T000/B000/XXXX")).toBe("https://hooks.slack.com")
+ expect(redactUrl("https://user:[email protected]:8443/hook?token=abc")).toBe("https://ops.example.com:8443")
+ expect(redactUrl("not a url")).toBe("[invalid url]")
+ expect(redactUrl(undefined)).toBeNull()
+ })
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/notifications/utils/failed-operation.ts b/packages/plugins/stripe-connector/src/workflows/notifications/utils/failed-operation.ts
new file mode 100644
index 000000000..c13070127
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/notifications/utils/failed-operation.ts
@@ -0,0 +1,102 @@
+import { PayoutStatus } from "@mercurjs/types"
+
+import { INSUFFICIENT_BALANCE_REASON } from "../../../types/common"
+import type { NotifyOperatorWorkflowInput } from "../workflows/notify-operator"
+
+type Row = Record<string, unknown> & {
+ id: string
+ data?: Record<string, unknown> | null
+ account?: { id?: string; seller?: { id: string } | null } | null
+ payout?: {
+ order_id?: string | null
+ currency_code?: string
+ account?: { id?: string; seller?: { id: string } | null } | null
+ } | null
+ payout_account?: { seller?: { id: string } | null } | null
+}
+
+export const FAILED_OPERATION_TYPE = {
+ payout: "payout.failed",
+ payout_reversal: "payout_reversal.failed",
+ settlement: "settlement.payout_failed",
+} as const
+
+/** A settlement's bank payout can fail again after a retry Stripe accepted, which is a new failure. */
+export const failedOperationNotificationKey = (notification: NotifyOperatorWorkflowInput) =>
+ ["notified", notification.type, notification.payload.id, notification.payload.provider_payout_id]
+ .filter((part) => part !== undefined && part !== null)
+ .join(":")
+
+const statusDetail = (data: Record<string, unknown> | null | undefined) =>
+ typeof data?.status_detail === "string" ? data.status_detail : null
+
+/** The operator notification for a failed record, or null when it is gone or no longer failed. */
+export function failedOperationNotification(
+ operation: keyof typeof FAILED_OPERATION_TYPE,
+ row: Row | null
+): NotifyOperatorWorkflowInput | null {
+ if (!row) {
+ return null
+ }
+
+ if (operation === "settlement") {
+ // Held for an account that is not ready yet is expected; held because the
+ // connected balance cannot cover the bank payout is not.
+ const shortBalance = row.payout_status === PayoutStatus.ON_HOLD && row.status_reason === INSUFFICIENT_BALANCE_REASON
+ if (row.payout_status !== PayoutStatus.FAILED && !shortBalance) {
+ return null
+ }
+ return {
+ type: FAILED_OPERATION_TYPE.settlement,
+ payload: {
+ id: row.id,
+ display_id: row.display_id,
+ account_id: row.account_id,
+ seller_id: row.payout_account?.seller?.id ?? null,
+ amount: row.amount,
+ currency_code: row.currency_code,
+ period_start: row.period_start,
+ period_end: row.period_end,
+ provider_payout_id: row.provider_payout_id,
+ status_reason: row.status_reason,
+ },
+ }
+ }
+
+ if (row.status !== PayoutStatus.FAILED) {
+ return null
+ }
+
+ if (operation === "payout_reversal") {
+ return {
+ type: FAILED_OPERATION_TYPE.payout_reversal,
+ payload: {
+ id: row.id,
+ payout_id: row.payout_id,
+ refund_id: row.refund_id,
+ order_id: row.payout?.order_id ?? null,
+ account_id: row.payout?.account?.id ?? null,
+ seller_id: row.payout?.account?.seller?.id ?? null,
+ amount: row.amount,
+ currency_code: row.payout?.currency_code ?? null,
+ status_reason: row.status_reason,
+ status_detail: statusDetail(row.data),
+ },
+ }
+ }
+
+ return {
+ type: FAILED_OPERATION_TYPE.payout,
+ payload: {
+ id: row.id,
+ display_id: row.display_id,
+ order_id: row.order_id,
+ account_id: row.account?.id ?? null,
+ seller_id: row.account?.seller?.id ?? null,
+ amount: row.amount,
+ currency_code: row.currency_code,
+ status_reason: row.status_reason,
+ status_detail: statusDetail(row.data),
+ },
+ }
+}
diff --git a/packages/plugins/stripe-connector/src/workflows/notifications/utils/index.ts b/packages/plugins/stripe-connector/src/workflows/notifications/utils/index.ts
new file mode 100644
index 000000000..066e48095
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/notifications/utils/index.ts
@@ -0,0 +1,2 @@
+export * from "./notification-signature"
+export * from "./failed-operation"
diff --git a/packages/plugins/stripe-connector/src/workflows/notifications/utils/notification-signature.ts b/packages/plugins/stripe-connector/src/workflows/notifications/utils/notification-signature.ts
new file mode 100644
index 000000000..4f1c49cc5
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/notifications/utils/notification-signature.ts
@@ -0,0 +1,28 @@
+import { createHmac } from "crypto"
+
+export const NOTIFICATION_SIGNATURE_HEADER = "x-mercur-signature"
+
+export const signNotification = (body: string, secret: string) =>
+ `sha256=${createHmac("sha256", secret).update(body).digest("hex")}`
+
+export function notificationHeaders(body: string, secret: string | undefined): Record<string, string> {
+ return {
+ "content-type": "application/json",
+ ...(secret ? { [NOTIFICATION_SIGNATURE_HEADER]: signNotification(body, secret) } : {}),
+ }
+}
+
+/**
+ * The endpoint without its path, query or credentials. Chat webhook URLs
+ * (Slack, Teams) carry their secret in the path.
+ */
+export function redactUrl(url: string | null | undefined): string | null {
+ if (!url) {
+ return null
+ }
+ try {
+ return new URL(url).origin
+ } catch {
+ return "[invalid url]"
+ }
+}
diff --git a/packages/plugins/stripe-connector/src/workflows/notifications/workflows/index.ts b/packages/plugins/stripe-connector/src/workflows/notifications/workflows/index.ts
new file mode 100644
index 000000000..12f4ba062
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/notifications/workflows/index.ts
@@ -0,0 +1,2 @@
+export * from "./notify-operator"
+export * from "./notify-operation-failed"
diff --git a/packages/plugins/stripe-connector/src/workflows/notifications/workflows/notify-operation-failed.ts b/packages/plugins/stripe-connector/src/workflows/notifications/workflows/notify-operation-failed.ts
new file mode 100644
index 000000000..c2a765b7d
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/notifications/workflows/notify-operation-failed.ts
@@ -0,0 +1,108 @@
+import { WorkflowResponse, createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+import { claimOperatorNotificationStep } from "../steps"
+import { failedOperationNotification, failedOperationNotificationKey } from "../utils/failed-operation"
+import { notifyOperatorWorkflow } from "./notify-operator"
+
+export type FailedOperation = "payout" | "payout_reversal" | "settlement"
+
+export type NotifyOperationFailedWorkflowInput = {
+ operation: FailedOperation
+ id: string
+}
+
+export const notifyOperationFailedWorkflowId = "notify-stripe-operation-failed"
+
+/** Posts a failed payout, reversal or settlement bank payout to the operator's notification endpoint. */
+export const notifyOperationFailedWorkflow = createWorkflow(
+ notifyOperationFailedWorkflowId,
+ function (input: NotifyOperationFailedWorkflowInput) {
+ const payouts = when("failed-payout", { input }, ({ input }) => input.operation === "payout").then(() => {
+ const { data } = useQueryGraphStep({
+ entity: "payout",
+ fields: [
+ "id",
+ "display_id",
+ "order_id",
+ "amount",
+ "currency_code",
+ "status",
+ "status_reason",
+ "data",
+ "account.id",
+ "account.seller.id",
+ ],
+ filters: { id: input.id },
+ }).config({ name: "failed-payout-query" })
+ return data
+ })
+
+ const reversals = when("failed-payout-reversal", { input }, ({ input }) => input.operation === "payout_reversal").then(
+ () => {
+ const { data } = useQueryGraphStep({
+ entity: "payout_reversal",
+ fields: [
+ "id",
+ "payout_id",
+ "refund_id",
+ "amount",
+ "status",
+ "status_reason",
+ "data",
+ "payout.order_id",
+ "payout.currency_code",
+ "payout.account.id",
+ "payout.account.seller.id",
+ ],
+ filters: { id: input.id },
+ }).config({ name: "failed-payout-reversal-query" })
+ return data
+ }
+ )
+
+ const settlements = when("failed-settlement", { input }, ({ input }) => input.operation === "settlement").then(() => {
+ const { data } = useQueryGraphStep({
+ entity: "settlement",
+ fields: [
+ "id",
+ "display_id",
+ "account_id",
+ "amount",
+ "currency_code",
+ "period_start",
+ "period_end",
+ "status",
+ "payout_status",
+ "provider_payout_id",
+ "status_reason",
+ "payout_account.seller.id",
+ ],
+ filters: { id: input.id },
+ }).config({ name: "failed-settlement-query" })
+ return data
+ })
+
+ const notification = transform(
+ { input, payouts, reversals, settlements },
+ ({ input, payouts, reversals, settlements }) =>
+ failedOperationNotification(input.operation, payouts?.[0] ?? reversals?.[0] ?? settlements?.[0] ?? null)
+ )
+
+ const claimed = when("failed-operation-found", { notification }, ({ notification }) => !!notification).then(() =>
+ claimOperatorNotificationStep(
+ transform({ notification }, ({ notification }) => ({
+ key: failedOperationNotificationKey(notification as NonNullable<typeof notification>),
+ }))
+ )
+ )
+
+ const sent = when("failed-operation-claimed", { claimed }, ({ claimed }) => !!claimed).then(() =>
+ notifyOperatorWorkflow.runAsStep({
+ input: transform({ notification }, ({ notification }) => notification as NonNullable<typeof notification>),
+ })
+ )
+
+ return new WorkflowResponse(transform({ sent }, ({ sent }) => sent ?? null))
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/notifications/workflows/notify-operator.ts b/packages/plugins/stripe-connector/src/workflows/notifications/workflows/notify-operator.ts
new file mode 100644
index 000000000..d1cc48702
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/notifications/workflows/notify-operator.ts
@@ -0,0 +1,35 @@
+import { WorkflowResponse, createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+
+import { sendOperatorEmailsStep, setCheckpointsStep } from "../../common/steps"
+import { ENDPOINT_DOWN_CHECKPOINT, postOperatorNotificationStep, resolveEndpointDownMailStep } from "../steps"
+
+export type NotifyOperatorWorkflowInput = {
+ type: string
+ payload: Record<string, unknown>
+}
+
+export const notifyOperatorWorkflowId = "notify-stripe-operator"
+
+/** Sends the operator a notification, and mails the technical contact when the endpoint stays down. */
+export const notifyOperatorWorkflow = createWorkflow(
+ notifyOperatorWorkflowId,
+ function (input: NotifyOperatorWorkflowInput) {
+ const posted = postOperatorNotificationStep(input)
+
+ const mail = resolveEndpointDownMailStep(
+ transform({ posted }, ({ posted }) => ({
+ down: !!posted.notification && !posted.delivered,
+ error: posted.error,
+ }))
+ )
+ const sent = sendOperatorEmailsStep(mail)
+
+ when("endpoint-down-mailed", { sent }, ({ sent }) => sent > 0).then(() => {
+ setCheckpointsStep(
+ transform({ sent }, () => [{ key: ENDPOINT_DOWN_CHECKPOINT, value: new Date().toISOString() }])
+ )
+ })
+
+ return new WorkflowResponse(posted.notification)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/onboarding/utils/index.ts b/packages/plugins/stripe-connector/src/workflows/onboarding/utils/index.ts
new file mode 100644
index 000000000..eab9dfd47
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/onboarding/utils/index.ts
@@ -0,0 +1 @@
+export * from "./onboarding-sellers"
diff --git a/packages/plugins/stripe-connector/src/workflows/onboarding/utils/onboarding-sellers.ts b/packages/plugins/stripe-connector/src/workflows/onboarding/utils/onboarding-sellers.ts
new file mode 100644
index 000000000..3b765b0d0
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/onboarding/utils/onboarding-sellers.ts
@@ -0,0 +1,10 @@
+import { SellerStatus } from "@mercurjs/types"
+
+export const ONBOARDING_CHECKPOINT = "onboarding"
+export const ONBOARDING_PAGE = 100
+
+export const onboardingSellerFilters = (sellerIds: string[] | undefined, checkpoint: string | null) => ({
+ status: [SellerStatus.OPEN, SellerStatus.PENDING_APPROVAL],
+ ...(sellerIds ? { id: sellerIds } : {}),
+ ...(!sellerIds && checkpoint ? { updated_at: { $gt: new Date(checkpoint) } } : {}),
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/onboarding/workflows/index.ts b/packages/plugins/stripe-connector/src/workflows/onboarding/workflows/index.ts
new file mode 100644
index 000000000..f3339623f
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/onboarding/workflows/index.ts
@@ -0,0 +1 @@
+export * from "./select-onboarding-sellers"
diff --git a/packages/plugins/stripe-connector/src/workflows/onboarding/workflows/select-onboarding-sellers.ts b/packages/plugins/stripe-connector/src/workflows/onboarding/workflows/select-onboarding-sellers.ts
new file mode 100644
index 000000000..e87b143a4
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/onboarding/workflows/select-onboarding-sellers.ts
@@ -0,0 +1,46 @@
+import { WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+import { ONBOARDING_CHECKPOINT, ONBOARDING_PAGE, onboardingSellerFilters } from "../utils/onboarding-sellers"
+
+export type SelectOnboardingSellersWorkflowInput = {
+ seller_ids?: string[]
+}
+
+export type SelectOnboardingSellersWorkflowOutput = {
+ seller_ids: string[]
+ checkpoint: string | null
+}
+
+export const selectOnboardingSellersWorkflowId = "select-stripe-onboarding-sellers"
+
+/** The given sellers, or the next page of sellers touched since the onboarding checkpoint. */
+export const selectOnboardingSellersWorkflow = createWorkflow(
+ selectOnboardingSellersWorkflowId,
+ function (input: SelectOnboardingSellersWorkflowInput) {
+ const { data: checkpoints } = useQueryGraphStep({
+ entity: "connector_checkpoint",
+ fields: ["value"],
+ filters: { key: ONBOARDING_CHECKPOINT },
+ }).config({ name: "onboarding-checkpoint-query" })
+
+ const { data: sellers } = useQueryGraphStep({
+ entity: "seller",
+ fields: ["id", "updated_at"],
+ filters: transform({ input, checkpoints }, ({ input, checkpoints }) =>
+ onboardingSellerFilters(input.seller_ids, (checkpoints[0]?.value as string | null | undefined) ?? null)
+ ),
+ pagination: { take: ONBOARDING_PAGE, order: { updated_at: "ASC" } },
+ }).config({ name: "onboarding-sellers-query" })
+
+ return new WorkflowResponse(
+ transform({ input, sellers }, ({ input, sellers }): SelectOnboardingSellersWorkflowOutput => ({
+ seller_ids: sellers.map((seller) => seller.id as string),
+ checkpoint:
+ !input.seller_ids && sellers.length
+ ? new Date(sellers[sellers.length - 1].updated_at as Date | string).toISOString()
+ : null,
+ }))
+ )
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/payouts/steps/index.ts b/packages/plugins/stripe-connector/src/workflows/payouts/steps/index.ts
new file mode 100644
index 000000000..06bd75298
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/payouts/steps/index.ts
@@ -0,0 +1,2 @@
+export * from "./resolve-required-fulfillment"
+export * from "./select-payout-orders"
diff --git a/packages/plugins/stripe-connector/src/workflows/payouts/steps/resolve-required-fulfillment.ts b/packages/plugins/stripe-connector/src/workflows/payouts/steps/resolve-required-fulfillment.ts
new file mode 100644
index 000000000..aaa9914b1
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/payouts/steps/resolve-required-fulfillment.ts
@@ -0,0 +1,11 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+import { resolveConnector } from "../../../utils/payout-module"
+
+export const resolveRequiredFulfillmentStepId = "resolve-stripe-required-fulfillment"
+
+export const resolveRequiredFulfillmentStep = createStep(
+ resolveRequiredFulfillmentStepId,
+ async (_, { container }) =>
+ new StepResponse(resolveConnector(container).getOptions().transfers.requiredFulfillmentStatus)
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/payouts/steps/select-payout-orders.ts b/packages/plugins/stripe-connector/src/workflows/payouts/steps/select-payout-orders.ts
new file mode 100644
index 000000000..10ccd3ba6
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/payouts/steps/select-payout-orders.ts
@@ -0,0 +1,125 @@
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { PayoutStatus } from "@mercurjs/types"
+
+import { resolveConnector, resolvePayoutModule } from "../../../utils/payout-module"
+import { SetCheckpointsStepInput } from "../../common/steps/set-checkpoints"
+import { CURSOR_ORDER, advanceCursor, afterCursor, decodeCursor, wrapCursor } from "../../common/utils/cursor"
+import {
+ AWAITING_ACCOUNT_CHECKPOINT_PREFIX,
+ PAYOUTS_BACKLOG_CHECKPOINT,
+ PAYOUTS_CHECKPOINT,
+ PayoutOrderRow,
+ eligiblePayoutOrders,
+ ordersWithoutPayout,
+} from "../utils/payout-orders"
+
+const PAGE = 100
+const ORDER_FIELDS = ["id", "created_at", "seller.metadata"]
+
+export type SelectPayoutOrdersStepOutput = {
+ order_ids: string[]
+ checkpoints: SetCheckpointsStepInput
+ stats: Record<string, number | string>
+}
+
+export const selectPayoutOrdersStepId = "select-stripe-payout-orders"
+
+/**
+ * The orders to pay out this run: the given ones, or the next page of held
+ * or failed payouts, the orders created since the last run, and the orders a
+ * seller placed before their payout account was ready. Each source pages by
+ * its own checkpoint, which a graph query step cannot carry.
+ */
+export const selectPayoutOrdersStep = createStep(
+ selectPayoutOrdersStepId,
+ async (input: { order_ids?: string[] }, { container }) => {
+ const connector = resolveConnector(container)
+ const payoutModule = resolvePayoutModule(container)
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+ const stats: Record<string, number | string> = {}
+ const checkpoints: SetCheckpointsStepInput = []
+
+ if (!connector.getOptions().transfers.enabled) {
+ stats.skipped = "transfers disabled"
+ return new StepResponse<SelectPayoutOrdersStepOutput>({ order_ids: [], checkpoints, stats })
+ }
+
+ const loadOrders = async (ids: string[]): Promise<PayoutOrderRow[]> => {
+ if (!ids.length) {
+ return []
+ }
+ const { data } = await query.graph({ entity: "order", fields: ORDER_FIELDS, filters: { id: ids } })
+ const byId = new Map((data as PayoutOrderRow[]).map((order) => [order.id, order]))
+ return ids.flatMap((id) => byId.get(id) ?? [])
+ }
+
+ if (input.order_ids?.length) {
+ const selection = eligiblePayoutOrders(await loadOrders(input.order_ids))
+ if (selection.ignored) stats.ignored = selection.ignored
+ return new StepResponse<SelectPayoutOrdersStepOutput>({ order_ids: selection.order_ids, checkpoints, stats })
+ }
+
+ const backlogCheckpoint = await connector.getCheckpoint(PAYOUTS_BACKLOG_CHECKPOINT)
+ const { data: backlogRows } = await query.graph({
+ entity: "payout",
+ fields: ["id", "order_id", "created_at"],
+ filters: {
+ status: [PayoutStatus.FAILED, PayoutStatus.ON_HOLD],
+ order_id: { $ne: null },
+ ...afterCursor(decodeCursor(backlogCheckpoint)),
+ },
+ pagination: { take: PAGE, order: CURSOR_ORDER },
+ })
+ const backlog = backlogRows as { id: string; order_id: string; created_at: Date | string }[]
+ stats.backlog = backlog.length
+ checkpoints.push({ key: PAYOUTS_BACKLOG_CHECKPOINT, value: wrapCursor(backlog, PAGE) })
+
+ const freshCheckpoint = await connector.getCheckpoint(PAYOUTS_CHECKPOINT)
+ const { data: fresh } = await query.graph({
+ entity: "order",
+ fields: ORDER_FIELDS,
+ filters: afterCursor(decodeCursor(freshCheckpoint)),
+ pagination: { take: PAGE, order: CURSOR_ORDER },
+ })
+ stats.new_orders = fresh.length
+ const freshCursor = advanceCursor(fresh as PayoutOrderRow[], freshCheckpoint)
+ if (freshCursor !== freshCheckpoint) {
+ checkpoints.push({ key: PAYOUTS_CHECKPOINT, value: freshCursor })
+ }
+
+ let awaitingIds: string[] = []
+ const [queued] = await connector.listConnectorCheckpoints(
+ { key: { $like: `${AWAITING_ACCOUNT_CHECKPOINT_PREFIX}%` }, value: { $ne: null } },
+ { take: 1, order: { updated_at: "ASC" } }
+ )
+ if (queued) {
+ const sellerId = queued.key.slice(AWAITING_ACCOUNT_CHECKPOINT_PREFIX.length)
+ const { data: links } = await query.graph({
+ entity: "order_seller",
+ fields: ["order_id"],
+ filters: { seller_id: sellerId, ...(queued.value ? { order_id: { $gt: queued.value } } : {}) },
+ pagination: { take: PAGE, order: { order_id: "ASC" } },
+ })
+ const orderIds = links.map((link) => link.order_id as string)
+ const paid = orderIds.length
+ ? await payoutModule.listPayouts({ order_id: orderIds }, { take: null, select: ["order_id"] })
+ : []
+ awaitingIds = ordersWithoutPayout(orderIds, paid.map((payout) => payout.order_id))
+ stats.awaiting_account = awaitingIds.length
+ checkpoints.push({
+ key: queued.key,
+ value: orderIds.length < PAGE ? null : orderIds[orderIds.length - 1],
+ })
+ }
+
+ const selection = eligiblePayoutOrders(
+ await loadOrders(backlog.map((payout) => payout.order_id)),
+ fresh as PayoutOrderRow[],
+ await loadOrders(awaitingIds)
+ )
+ if (selection.ignored) stats.ignored = selection.ignored
+
+ return new StepResponse<SelectPayoutOrdersStepOutput>({ order_ids: selection.order_ids, checkpoints, stats })
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/payouts/utils/__tests__/payout-orders.unit.spec.ts b/packages/plugins/stripe-connector/src/workflows/payouts/utils/__tests__/payout-orders.unit.spec.ts
new file mode 100644
index 000000000..d2f2e99ac
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/payouts/utils/__tests__/payout-orders.unit.spec.ts
@@ -0,0 +1,24 @@
+import { awaitingAccountCheckpoint, eligiblePayoutOrders, ordersWithoutPayout } from "../payout-orders"
+
+const order = (id: string, ignored = false) => ({
+ id,
+ created_at: "2026-10-20T10:00:00.000Z",
+ seller: { metadata: ignored ? { payout_ignored: "true" } : {} },
+})
+
+describe("payout order selection", () => {
+ it("keeps each order once, in source order, without ignored sellers", () => {
+ expect(eligiblePayoutOrders([order("a"), order("b")], [order("b"), order("c", true)], [order("d")])).toEqual({
+ order_ids: ["a", "b", "d"],
+ ignored: 1,
+ })
+ })
+
+ it("picks the seller's orders that have no payout yet", () => {
+ expect(ordersWithoutPayout(["o1", "o2", "o3"], ["o2", null])).toEqual(["o1", "o3"])
+ })
+
+ it("keys the awaiting-account queue per seller", () => {
+ expect(awaitingAccountCheckpoint("sel_1")).toBe("transfers_awaiting_account:sel_1")
+ })
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/payouts/utils/index.ts b/packages/plugins/stripe-connector/src/workflows/payouts/utils/index.ts
new file mode 100644
index 000000000..dcf8a8fd4
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/payouts/utils/index.ts
@@ -0,0 +1 @@
+export * from "./payout-orders"
diff --git a/packages/plugins/stripe-connector/src/workflows/payouts/utils/payout-orders.ts b/packages/plugins/stripe-connector/src/workflows/payouts/utils/payout-orders.ts
new file mode 100644
index 000000000..83794690c
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/payouts/utils/payout-orders.ts
@@ -0,0 +1,28 @@
+import { PAYOUT_IGNORED_KEY } from "../../../types/common"
+
+export const PAYOUTS_CHECKPOINT = "transfers"
+export const PAYOUTS_BACKLOG_CHECKPOINT = "transfers_backlog"
+export const AWAITING_ACCOUNT_CHECKPOINT_PREFIX = "transfers_awaiting_account:"
+
+export const awaitingAccountCheckpoint = (sellerId: string) => `${AWAITING_ACCOUNT_CHECKPOINT_PREFIX}${sellerId}`
+
+export type PayoutOrderRow = {
+ id: string
+ created_at: Date | string
+ seller?: { metadata?: Record<string, unknown> | null } | null
+}
+
+export const isIgnoredSeller = (order: PayoutOrderRow) =>
+ String(order.seller?.metadata?.[PAYOUT_IGNORED_KEY] ?? "") === "true"
+
+export function eligiblePayoutOrders(...groups: PayoutOrderRow[][]): { order_ids: string[]; ignored: number } {
+ const seen = new Set<string>()
+ const unique = groups.flat().filter((order) => !seen.has(order.id) && !!seen.add(order.id))
+ const eligible = unique.filter((order) => !isIgnoredSeller(order))
+ return { order_ids: eligible.map((order) => order.id), ignored: unique.length - eligible.length }
+}
+
+export const ordersWithoutPayout = (orderIds: string[], paidOrderIds: (string | null)[]) => {
+ const paid = new Set(paidOrderIds)
+ return orderIds.filter((id) => !paid.has(id))
+}
diff --git a/packages/plugins/stripe-connector/src/workflows/payouts/workflows/index.ts b/packages/plugins/stripe-connector/src/workflows/payouts/workflows/index.ts
new file mode 100644
index 000000000..62fa538a4
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/payouts/workflows/index.ts
@@ -0,0 +1,4 @@
+export * from "./process-order-changed-payouts"
+export * from "./process-payment-captured-payouts"
+export * from "./process-payouts"
+export * from "./queue-awaiting-account-payouts"
diff --git a/packages/plugins/stripe-connector/src/workflows/payouts/workflows/process-order-changed-payouts.ts b/packages/plugins/stripe-connector/src/workflows/payouts/workflows/process-order-changed-payouts.ts
new file mode 100644
index 000000000..ff22facdc
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/payouts/workflows/process-order-changed-payouts.ts
@@ -0,0 +1,39 @@
+import { WorkflowResponse, createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+import { syncCapturesWorkflow } from "../../captures/workflows/sync-captures"
+import { processPayoutsWorkflow } from "./process-payouts"
+
+export type ProcessOrderChangedPayoutsWorkflowInput = {
+ order_id: string
+}
+
+export const processOrderChangedPayoutsWorkflowId = "process-stripe-order-changed-payouts"
+
+/** A fulfilled or canceled order refreshes its group's capture and re-decides its payout. */
+export const processOrderChangedPayoutsWorkflow = createWorkflow(
+ processOrderChangedPayoutsWorkflowId,
+ function (input: ProcessOrderChangedPayoutsWorkflowInput) {
+ const { data: orders } = useQueryGraphStep({
+ entity: "order",
+ fields: ["id", "order_group.id"],
+ filters: { id: input.order_id },
+ }).config({ name: "changed-order-query" })
+
+ const orderGroupId = transform({ orders }, ({ orders }) =>
+ ((orders[0] as { order_group?: { id: string } | null } | undefined)?.order_group?.id ?? null)
+ )
+
+ when("changed-order-in-group", { orderGroupId }, ({ orderGroupId }) => !!orderGroupId).then(() => {
+ syncCapturesWorkflow.runAsStep({
+ input: transform({ orderGroupId }, ({ orderGroupId }) => ({ order_group_ids: [orderGroupId as string] })),
+ })
+ })
+
+ const stats = processPayoutsWorkflow.runAsStep({
+ input: transform({ input }, ({ input }) => ({ order_ids: [input.order_id] })),
+ })
+
+ return new WorkflowResponse(stats)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/payouts/workflows/process-payment-captured-payouts.ts b/packages/plugins/stripe-connector/src/workflows/payouts/workflows/process-payment-captured-payouts.ts
new file mode 100644
index 000000000..0b0fe3047
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/payouts/workflows/process-payment-captured-payouts.ts
@@ -0,0 +1,55 @@
+import { WorkflowResponse, createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+import { JobStats } from "../../../utils/run-job"
+import { syncCapturesWorkflow } from "../../captures/workflows/sync-captures"
+import { processPayoutsWorkflow } from "./process-payouts"
+
+export type ProcessPaymentCapturedPayoutsWorkflowInput = {
+ payment_id: string
+}
+
+type CapturedPayment = { payment_collection_id: string; payment_collection?: { order?: { id: string } | null } | null }
+
+export const processPaymentCapturedPayoutsWorkflowId = "process-stripe-payment-captured-payouts"
+
+/** A captured payment closes its order group's capture and lets its order be paid out. */
+export const processPaymentCapturedPayoutsWorkflow = createWorkflow(
+ processPaymentCapturedPayoutsWorkflowId,
+ function (input: ProcessPaymentCapturedPayoutsWorkflowInput) {
+ const { data: payments } = useQueryGraphStep({
+ entity: "payment",
+ fields: ["id", "payment_collection_id", "payment_collection.order.id"],
+ filters: { id: input.payment_id },
+ }).config({ name: "captured-payment-query" })
+
+ const payment = transform({ payments }, ({ payments }) => (payments[0] as CapturedPayment | undefined) ?? null)
+
+ const captures = when("captured-payment-found", { payment }, ({ payment }) => !!payment).then(() => {
+ const { data } = useQueryGraphStep({
+ entity: "stripe_capture",
+ fields: ["order_group_id"],
+ filters: transform({ payment }, ({ payment }) => ({ payment_collection_id: payment?.payment_collection_id })),
+ }).config({ name: "captured-payment-capture-query" })
+ return data
+ })
+
+ when("captured-payment-has-capture", { captures }, ({ captures }) => !!captures?.length).then(() => {
+ syncCapturesWorkflow.runAsStep({
+ input: transform({ captures }, ({ captures }) => ({
+ order_group_ids: (captures ?? []).map((row) => row.order_group_id as string),
+ })),
+ })
+ })
+
+ const orderId = transform({ payment }, ({ payment }) => payment?.payment_collection?.order?.id ?? null)
+
+ const stats = when("captured-payment-has-order", { orderId }, ({ orderId }) => !!orderId).then(() =>
+ processPayoutsWorkflow.runAsStep({
+ input: transform({ orderId }, ({ orderId }) => ({ order_ids: [orderId as string] })),
+ })
+ )
+
+ return new WorkflowResponse(transform({ stats }, ({ stats }) => (stats ?? {}) as JobStats))
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/payouts/workflows/process-payouts.ts b/packages/plugins/stripe-connector/src/workflows/payouts/workflows/process-payouts.ts
new file mode 100644
index 000000000..8d24a0982
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/payouts/workflows/process-payouts.ts
@@ -0,0 +1,42 @@
+import { WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
+import { createOrderPayoutsWorkflow } from "@mercurjs/core/workflows"
+
+import { JobStats } from "../../../utils/run-job"
+import { setCheckpointsStep } from "../../common/steps"
+import { resolveRequiredFulfillmentStep, selectPayoutOrdersStep } from "../steps"
+
+export type ProcessPayoutsWorkflowInput = {
+ order_ids?: string[]
+}
+
+export const processPayoutsWorkflowId = "process-stripe-payouts"
+
+/**
+ * Pays sellers through core's payout workflow: a page of the held and failed
+ * backlog, the orders created since the last run, and the orders of sellers
+ * whose payout account just became ready.
+ */
+export const processPayoutsWorkflow = createWorkflow(
+ processPayoutsWorkflowId,
+ function (input: ProcessPayoutsWorkflowInput) {
+ const selection = selectPayoutOrdersStep(input)
+ const requiredFulfillmentStatus = resolveRequiredFulfillmentStep()
+
+ const payouts = createOrderPayoutsWorkflow.runAsStep({
+ input: transform({ selection, requiredFulfillmentStatus }, ({ selection, requiredFulfillmentStatus }) => ({
+ order_ids: selection.order_ids,
+ required_fulfillment_status: requiredFulfillmentStatus,
+ })),
+ })
+
+ setCheckpointsStep(selection.checkpoints)
+
+ const stats = transform({ selection, payouts }, ({ selection, payouts }): JobStats => ({
+ ...selection.stats,
+ ...payouts.counts,
+ processed: payouts.payouts.length,
+ }))
+
+ return new WorkflowResponse(stats)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/payouts/workflows/queue-awaiting-account-payouts.ts b/packages/plugins/stripe-connector/src/workflows/payouts/workflows/queue-awaiting-account-payouts.ts
new file mode 100644
index 000000000..e876f6448
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/payouts/workflows/queue-awaiting-account-payouts.ts
@@ -0,0 +1,41 @@
+import { WorkflowResponse, createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
+import { PayoutAccountStatus } from "@mercurjs/types"
+
+import { setCheckpointsStep } from "../../common/steps"
+import { awaitingAccountCheckpoint } from "../utils/payout-orders"
+
+export type QueueAwaitingAccountPayoutsWorkflowInput = {
+ id: string
+}
+
+export const queueAwaitingAccountPayoutsWorkflowId = "queue-stripe-awaiting-account-payouts"
+
+/**
+ * Core creates no payout for an order whose seller has no payout account yet.
+ * Once the account is active, the seller's orders are queued so the transfers
+ * job pays the ones that still have no payout.
+ */
+export const queueAwaitingAccountPayoutsWorkflow = createWorkflow(
+ queueAwaitingAccountPayoutsWorkflowId,
+ function (input: QueueAwaitingAccountPayoutsWorkflowInput) {
+ const { data: accounts } = useQueryGraphStep({
+ entity: "payout_account",
+ fields: ["id", "status", "seller.id"],
+ filters: { id: input.id },
+ }).config({ name: "awaiting-account-query" })
+
+ const sellerId = transform({ accounts }, ({ accounts }) => {
+ const account = accounts[0] as { status?: string; seller?: { id: string } | null } | undefined
+ return account?.status === PayoutAccountStatus.ACTIVE ? account.seller?.id ?? null : null
+ })
+
+ when("account-ready-for-payouts", { sellerId }, ({ sellerId }) => !!sellerId).then(() => {
+ setCheckpointsStep(
+ transform({ sellerId }, ({ sellerId }) => [{ key: awaitingAccountCheckpoint(sellerId ?? ""), value: "" }])
+ )
+ })
+
+ return new WorkflowResponse(sellerId)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/reversals/steps/index.ts b/packages/plugins/stripe-connector/src/workflows/reversals/steps/index.ts
new file mode 100644
index 000000000..445b0628a
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/reversals/steps/index.ts
@@ -0,0 +1 @@
+export * from "./select-reversal-orders"
diff --git a/packages/plugins/stripe-connector/src/workflows/reversals/steps/select-reversal-orders.ts b/packages/plugins/stripe-connector/src/workflows/reversals/steps/select-reversal-orders.ts
new file mode 100644
index 000000000..8d223bb9c
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/reversals/steps/select-reversal-orders.ts
@@ -0,0 +1,88 @@
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { PayoutStatus } from "@mercurjs/types"
+
+import { resolveConnector } from "../../../utils/payout-module"
+import { SetCheckpointsStepInput } from "../../common/steps/set-checkpoints"
+import { CURSOR_ORDER, CursorRow, advanceCursor, afterCursor, decodeCursor, wrapCursor } from "../../common/utils/cursor"
+
+export const REVERSALS_CHECKPOINT = "reversals"
+export const REVERSALS_BACKLOG_CHECKPOINT = "reversals_backlog"
+
+const PAGE = 100
+
+type RefundRow = CursorRow & { payment?: { payment_collection?: { order?: { id: string } | null } | null } | null }
+type ReversalRow = CursorRow & { payout?: { order_id: string | null } | null }
+
+export type SelectReversalOrdersStepOutput = {
+ order_ids: string[]
+ checkpoints: SetCheckpointsStepInput
+ stats: Record<string, number | string>
+}
+
+export const selectReversalOrdersStepId = "select-stripe-reversal-orders"
+
+/**
+ * The orders to reverse payouts for this run: the given ones, or the orders
+ * of refunds created since the last run plus a page of failed or held
+ * reversals. Each source pages by its own checkpoint, which a graph query
+ * step cannot carry.
+ */
+export const selectReversalOrdersStep = createStep(
+ selectReversalOrdersStepId,
+ async (input: { order_ids?: string[] }, { container }) => {
+ const connector = resolveConnector(container)
+ const stats: Record<string, number | string> = {}
+ const checkpoints: SetCheckpointsStepInput = []
+
+ if (!connector.getOptions().reversals.enabled) {
+ stats.skipped = "reversals disabled"
+ return new StepResponse<SelectReversalOrdersStepOutput>({ order_ids: [], checkpoints, stats })
+ }
+
+ if (input.order_ids?.length) {
+ return new StepResponse<SelectReversalOrdersStepOutput>({ order_ids: input.order_ids, checkpoints, stats })
+ }
+
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+
+ const refundCheckpoint = await connector.getCheckpoint(REVERSALS_CHECKPOINT)
+ const { data: refunds } = await query.graph({
+ entity: "refund",
+ fields: ["id", "created_at", "payment.payment_collection.order.id"],
+ filters: afterCursor(decodeCursor(refundCheckpoint)),
+ pagination: { take: PAGE, order: CURSOR_ORDER },
+ })
+ const refundRows = refunds as unknown as RefundRow[]
+ stats.refunds = refundRows.length
+ const refundCursor = advanceCursor(refundRows, refundCheckpoint)
+ if (refundCursor !== refundCheckpoint) {
+ checkpoints.push({ key: REVERSALS_CHECKPOINT, value: refundCursor })
+ }
+
+ const backlogCheckpoint = await connector.getCheckpoint(REVERSALS_BACKLOG_CHECKPOINT)
+ const { data: backlog } = await query.graph({
+ entity: "payout_reversal",
+ fields: ["id", "created_at", "payout.order_id"],
+ filters: {
+ status: [PayoutStatus.FAILED, PayoutStatus.ON_HOLD],
+ ...afterCursor(decodeCursor(backlogCheckpoint)),
+ },
+ pagination: { take: PAGE, order: CURSOR_ORDER },
+ })
+ const backlogRows = backlog as unknown as ReversalRow[]
+ stats.backlog = backlogRows.length
+ checkpoints.push({ key: REVERSALS_BACKLOG_CHECKPOINT, value: wrapCursor(backlogRows, PAGE) })
+
+ const orderIds = [
+ ...refundRows.map((refund) => refund.payment?.payment_collection?.order?.id),
+ ...backlogRows.map((reversal) => reversal.payout?.order_id),
+ ].filter((id): id is string => !!id)
+
+ return new StepResponse<SelectReversalOrdersStepOutput>({
+ order_ids: Array.from(new Set(orderIds)),
+ checkpoints,
+ stats,
+ })
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/reversals/workflows/index.ts b/packages/plugins/stripe-connector/src/workflows/reversals/workflows/index.ts
new file mode 100644
index 000000000..e6e6ad71a
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/reversals/workflows/index.ts
@@ -0,0 +1 @@
+export * from "./process-reversals"
diff --git a/packages/plugins/stripe-connector/src/workflows/reversals/workflows/process-reversals.ts b/packages/plugins/stripe-connector/src/workflows/reversals/workflows/process-reversals.ts
new file mode 100644
index 000000000..cfbce2a53
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/reversals/workflows/process-reversals.ts
@@ -0,0 +1,35 @@
+import { WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
+import { createPayoutReversalsWorkflow } from "@mercurjs/core/workflows"
+
+import { JobStats } from "../../../utils/run-job"
+import { setCheckpointsStep } from "../../common/steps"
+import { selectReversalOrdersStep } from "../steps"
+
+export type ProcessReversalsWorkflowInput = {
+ order_ids?: string[]
+}
+
+export const processReversalsWorkflowId = "process-stripe-reversals"
+
+/** Takes refunded shares back from sellers through core's reversal workflow. */
+export const processReversalsWorkflow = createWorkflow(
+ processReversalsWorkflowId,
+ function (input: ProcessReversalsWorkflowInput) {
+ const selection = selectReversalOrdersStep(input)
+
+ const reversals = createPayoutReversalsWorkflow.runAsStep({
+ input: transform({ selection }, ({ selection }) => ({ order_ids: selection.order_ids })),
+ })
+
+ setCheckpointsStep(selection.checkpoints)
+
+ const stats = transform({ selection, reversals }, ({ selection, reversals }): JobStats => ({
+ ...selection.stats,
+ ...reversals.counts,
+ orders: selection.order_ids.length,
+ processed: reversals.reversals.length,
+ }))
+
+ return new WorkflowResponse(stats)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/steps/create-settlement-payout.ts b/packages/plugins/stripe-connector/src/workflows/settlements/steps/create-settlement-payout.ts
new file mode 100644
index 000000000..08aef00b7
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/steps/create-settlement-payout.ts
@@ -0,0 +1,17 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+
+import { resolveConnector } from "../../../utils/payout-module"
+
+export const createSettlementPayoutStepId = "create-stripe-settlement-payout"
+
+export const createSettlementPayoutStep = createStep(
+ createSettlementPayoutStepId,
+ async (input: { settlement_id: string; stripe_account_id: string }, { container }) => {
+ const settlement = await resolveConnector(container).createSettlementPayout(
+ input.settlement_id,
+ input.stripe_account_id
+ )
+ // A bank payout Stripe accepted cannot be pulled back, so there is no compensation.
+ return new StepResponse(settlement)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/steps/create-settlements.ts b/packages/plugins/stripe-connector/src/workflows/settlements/steps/create-settlements.ts
new file mode 100644
index 000000000..102cceebd
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/steps/create-settlements.ts
@@ -0,0 +1,59 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { PayoutStatus } from "@mercurjs/types"
+
+import { SettlementStatus } from "../../../types/common"
+import { resolveConnector } from "../../../utils/payout-module"
+import { PlannedSettlement } from "../utils/plan-settlements"
+
+export type CreatedSettlement = {
+ id: string
+ account_id: string
+ external_id: string | null
+ seller_id: string | null
+ currency_code: string
+ amount: number
+ status: SettlementStatus
+ payout_status: PayoutStatus | null
+}
+
+export const createSettlementsStepId = "create-stripe-settlements"
+
+export const createSettlementsStep = createStep(
+ createSettlementsStepId,
+ async (input: PlannedSettlement[], { container }) => {
+ const connector = resolveConnector(container)
+ const settlements = await connector.createSettlementsWithLines(
+ input.map(({ external_id: _external, seller_id: _seller, ...settlement }) => settlement)
+ )
+ const byKey = new Map(settlements.map((s) => [`${s.account_id}:${s.currency_code}`, s]))
+
+ const created: CreatedSettlement[] = input.flatMap((planned) => {
+ const settlement = byKey.get(`${planned.account_id}:${planned.currency_code}`)
+ return settlement
+ ? [
+ {
+ id: settlement.id,
+ account_id: planned.account_id,
+ external_id: planned.external_id,
+ seller_id: planned.seller_id,
+ currency_code: planned.currency_code,
+ amount: planned.amount,
+ status: planned.status,
+ payout_status: planned.payout_status,
+ },
+ ]
+ : []
+ })
+
+ return new StepResponse(
+ created,
+ created.map((settlement) => settlement.id)
+ )
+ },
+ async (ids, { container }) => {
+ if (!ids?.length) {
+ return
+ }
+ await resolveConnector(container).deleteSettlements(ids)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/steps/index.ts b/packages/plugins/stripe-connector/src/workflows/settlements/steps/index.ts
new file mode 100644
index 000000000..dc93f0076
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/steps/index.ts
@@ -0,0 +1,7 @@
+export * from "./create-settlements"
+export * from "./load-settlement-sources"
+export * from "./process-adjustments"
+export * from "./process-settlement-payouts"
+export * from "./retry-settlement-payouts"
+export * from "./create-settlement-payout"
+export * from "./validate-settlement-payout-retry"
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/steps/load-settlement-sources.ts b/packages/plugins/stripe-connector/src/workflows/settlements/steps/load-settlement-sources.ts
new file mode 100644
index 000000000..b2c102a3b
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/steps/load-settlement-sources.ts
@@ -0,0 +1,144 @@
+import { BigNumberInput } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { PayoutStatus } from "@mercurjs/types"
+
+import { landedOf } from "../../../lib/landed"
+import { AdjustmentType, SettlementLineType } from "../../../types/common"
+import { resolveConnector, resolvePayoutModule } from "../../../utils/payout-module"
+import { SettlementSource, UnsettledLine, unsettledSince } from "../utils/plan-settlements"
+
+const SETTLED_CHECK_CHUNK = 1000
+
+type ReversalRow = {
+ id: string
+ amount: BigNumberInput
+ data: Record<string, unknown> | null
+ updated_at: Date | string
+ payout?: { currency_code: string } | null
+}
+
+export type LoadSettlementSourcesStepInput = {
+ accounts: {
+ id: string
+ external_id: string | null
+ payouts_enabled: boolean
+ created_at: Date | string
+ seller?: { id: string } | null
+ }[]
+}
+
+const chunk = <T>(values: T[], size: number): T[][] =>
+ Array.from({ length: Math.ceil(values.length / size) }, (_, i) => values.slice(i * size, (i + 1) * size))
+
+export const loadSettlementSourcesStepId = "load-stripe-settlement-sources"
+
+/**
+ * The previous settlements of each account and the paid payouts, reversals
+ * and adjustments no settlement holds yet. Each account is read with its own
+ * window, which a single graph query cannot express.
+ */
+export const loadSettlementSourcesStep = createStep(
+ loadSettlementSourcesStepId,
+ async (input: LoadSettlementSourcesStepInput, { container }) => {
+ const connector = resolveConnector(container)
+ const payoutModule = resolvePayoutModule(container)
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+ const { enabled, mode } = connector.getOptions().settlements
+ const sources: SettlementSource[] = []
+
+ if (!enabled) {
+ return new StepResponse({ sources, mode })
+ }
+
+ for (const account of input.accounts) {
+ const previous = await connector.listSettlements(
+ { account_id: account.id },
+ {
+ take: null,
+ select: ["currency_code", "period_start", "period_end", "status", "payout_status", "provider_payout_id"],
+ }
+ )
+ const since = unsettledSince(previous)
+ const window = since ? { updated_at: { $gt: since.toISOString() } } : {}
+
+ const [payouts, reversals, adjustments] = await Promise.all([
+ payoutModule.listPayouts(
+ { account_id: account.id, status: PayoutStatus.PAID, ...window },
+ { take: null, select: ["id", "amount", "currency_code", "data", "updated_at"] }
+ ),
+ query
+ .graph({
+ entity: "payout_reversal",
+ fields: ["id", "amount", "data", "updated_at", "payout.currency_code"],
+ filters: { status: PayoutStatus.PAID, payout: { account_id: account.id }, ...window },
+ })
+ .then(({ data }) => data as unknown as ReversalRow[]),
+ connector.listAdjustments({ account_id: account.id, status: PayoutStatus.PAID, ...window }, { take: null }),
+ ])
+
+ const candidates: UnsettledLine[] = [
+ ...payouts.map((p) => ({
+ id: p.id,
+ type: SettlementLineType.PAYOUT,
+ amount: p.amount,
+ paid_at: p.updated_at,
+ currency_code: p.currency_code,
+ ...landedOf(p.data),
+ })),
+ ...reversals.flatMap((r) =>
+ r.payout
+ ? [
+ {
+ id: r.id,
+ type: SettlementLineType.REVERSAL,
+ amount: r.amount,
+ paid_at: r.updated_at,
+ currency_code: r.payout.currency_code,
+ ...landedOf(r.data),
+ },
+ ]
+ : []
+ ),
+ ...adjustments.map((a) => ({
+ id: a.id,
+ type:
+ a.type === AdjustmentType.EXTRA_CREDIT
+ ? SettlementLineType.ADJUSTMENT_CREDIT
+ : SettlementLineType.ADJUSTMENT_DEBIT,
+ amount: a.amount,
+ paid_at: a.updated_at,
+ currency_code: a.currency_code,
+ ...landedOf(a.data),
+ })),
+ ]
+
+ const settled = new Set<string>()
+ for (const ids of chunk(candidates.map((line) => line.id), SETTLED_CHECK_CHUNK)) {
+ const lines = await connector.listSettlementLines(
+ { $or: [{ payout_id: ids }, { payout_reversal_id: ids }, { adjustment_id: ids }] },
+ { take: null, select: ["payout_id", "payout_reversal_id", "adjustment_id"] }
+ )
+ for (const line of lines) {
+ for (const id of [line.payout_id, line.payout_reversal_id, line.adjustment_id]) {
+ if (id) settled.add(id)
+ }
+ }
+ }
+
+ sources.push({
+ account: {
+ id: account.id,
+ external_id: account.external_id,
+ payouts_enabled: account.payouts_enabled,
+ created_at: account.created_at,
+ },
+ seller_id: account.seller?.id ?? null,
+ previous,
+ lines: candidates.filter((line) => !settled.has(line.id)),
+ })
+ }
+
+ return new StepResponse({ sources, mode })
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/steps/process-adjustments.ts b/packages/plugins/stripe-connector/src/workflows/settlements/steps/process-adjustments.ts
new file mode 100644
index 000000000..8ba24f436
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/steps/process-adjustments.ts
@@ -0,0 +1,46 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { PayoutStatus } from "@mercurjs/types"
+
+import { resolveConnector, resolvePayoutModule } from "../../../utils/payout-module"
+import { isPayoutReady } from "../utils/account-ready"
+
+const PROCESSABLE = [PayoutStatus.PENDING, PayoutStatus.FAILED, PayoutStatus.ON_HOLD, PayoutStatus.PROCESSING]
+
+export const processAdjustmentsStepId = "process-stripe-adjustments"
+
+/**
+ * Sends pending adjustments, retries failed or held ones whose account is
+ * ready, and resends the ones a previous run left without an outcome.
+ */
+export const processAdjustmentsStep = createStep(processAdjustmentsStepId, async (_, { container }) => {
+ const connector = resolveConnector(container)
+ if (!connector.getOptions().settlements.enabled) {
+ return new StepResponse(0)
+ }
+ const adjustments = await connector.listAdjustments({ status: PROCESSABLE }, { take: null })
+ const accountIds = Array.from(new Set(adjustments.map((a) => a.account_id)))
+ const accounts = accountIds.length
+ ? await resolvePayoutModule(container).listPayoutAccounts({ id: accountIds }, { take: null })
+ : []
+ const accountById = new Map(accounts.map((account) => [account.id, account]))
+
+ let processed = 0
+ for (const adjustment of adjustments) {
+ const account = accountById.get(adjustment.account_id)
+ if (!isPayoutReady(account)) {
+ if (adjustment.status === PayoutStatus.PENDING || adjustment.status === PayoutStatus.FAILED) {
+ await connector.updateAdjustments({
+ id: adjustment.id,
+ status: PayoutStatus.ON_HOLD,
+ status_reason: "Payout account is not ready",
+ })
+ }
+ continue
+ }
+ await connector.processAdjustment(adjustment.id, account.external_id as string)
+ processed += 1
+ }
+
+ // Money that left through Stripe cannot be pulled back, so there is no compensation.
+ return new StepResponse(processed)
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/steps/process-settlement-payouts.ts b/packages/plugins/stripe-connector/src/workflows/settlements/steps/process-settlement-payouts.ts
new file mode 100644
index 000000000..2b7e9e04f
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/steps/process-settlement-payouts.ts
@@ -0,0 +1,31 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { PayoutStatus } from "@mercurjs/types"
+
+import { SettlementStatus } from "../../../types/common"
+import { resolveConnector } from "../../../utils/payout-module"
+import { isSettlementPayoutUnpaid } from "../utils/settlement-payout"
+import { CreatedSettlement } from "./create-settlements"
+
+export const processSettlementPayoutsStepId = "process-stripe-settlement-payouts"
+
+export const processSettlementPayoutsStep = createStep(
+ processSettlementPayoutsStepId,
+ async (input: { settlements: CreatedSettlement[] }, { container }) => {
+ const connector = resolveConnector(container)
+ const ready = input.settlements.filter(
+ (settlement) =>
+ settlement.status === SettlementStatus.OPEN &&
+ settlement.payout_status === PayoutStatus.PENDING &&
+ !!settlement.external_id
+ )
+ const failedIds: string[] = []
+ for (const settlement of ready) {
+ const updated = await connector.createSettlementPayout(settlement.id, settlement.external_id as string)
+ if (isSettlementPayoutUnpaid(updated)) {
+ failedIds.push(updated.id)
+ }
+ }
+ // A bank payout Stripe accepted cannot be pulled back, so there is no compensation.
+ return new StepResponse({ sent: ready.length, failed_ids: failedIds })
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/steps/retry-settlement-payouts.ts b/packages/plugins/stripe-connector/src/workflows/settlements/steps/retry-settlement-payouts.ts
new file mode 100644
index 000000000..24de44656
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/steps/retry-settlement-payouts.ts
@@ -0,0 +1,58 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { PayoutStatus } from "@mercurjs/types"
+
+import { resolveConnector, resolvePayoutModule } from "../../../utils/payout-module"
+import { isPayoutReady } from "../utils/account-ready"
+import { isSettlementPayoutUnpaid } from "../utils/settlement-payout"
+
+export const retrySettlementPayoutsStepId = "retry-stripe-settlement-payouts"
+
+/**
+ * Sends the bank payouts of settlements that failed, were held (account not
+ * ready, balance short), or were left without an outcome, once their account
+ * is ready.
+ */
+export const retrySettlementPayoutsStep = createStep(
+ retrySettlementPayoutsStepId,
+ async (input: { account_ids: string[] | null }, { container }) => {
+ const connector = resolveConnector(container)
+ const { settlements } = connector.getOptions()
+ if (!settlements.enabled || settlements.mode !== "plugin") {
+ return new StepResponse({ sent: 0, failed_ids: [] as string[] })
+ }
+
+ const scope = input.account_ids ? { account_id: input.account_ids } : {}
+ const backlog = await connector.listSettlements(
+ {
+ $or: [
+ { payout_status: [PayoutStatus.FAILED, PayoutStatus.ON_HOLD] },
+ { payout_status: PayoutStatus.PROCESSING, provider_payout_id: null },
+ ],
+ ...scope,
+ },
+ { take: null }
+ )
+ const accountIds = Array.from(new Set(backlog.map((s) => s.account_id)))
+ const accounts = accountIds.length
+ ? await resolvePayoutModule(container).listPayoutAccounts({ id: accountIds }, { take: null })
+ : []
+ const accountById = new Map(accounts.map((account) => [account.id, account]))
+
+ let retried = 0
+ const failedIds: string[] = []
+ for (const settlement of backlog) {
+ const account = accountById.get(settlement.account_id)
+ if (!isPayoutReady(account)) {
+ continue
+ }
+ const updated = await connector.createSettlementPayout(settlement.id, account.external_id as string)
+ retried += 1
+ if (isSettlementPayoutUnpaid(updated)) {
+ failedIds.push(updated.id)
+ }
+ }
+
+ // A bank payout Stripe accepted cannot be pulled back, so there is no compensation.
+ return new StepResponse({ sent: retried, failed_ids: failedIds })
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/steps/validate-settlement-payout-retry.ts b/packages/plugins/stripe-connector/src/workflows/settlements/steps/validate-settlement-payout-retry.ts
new file mode 100644
index 000000000..586649eb4
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/steps/validate-settlement-payout-retry.ts
@@ -0,0 +1,42 @@
+import { MedusaError } from "@medusajs/framework/utils"
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { PayoutStatus } from "@mercurjs/types"
+
+export type ValidateSettlementPayoutRetryStepInput = {
+ settlement: {
+ id: string
+ payout_status: PayoutStatus | null
+ provider_payout_id: string | null
+ payout_account?: { id: string; external_id: string | null; payouts_enabled: boolean } | null
+ }
+}
+
+const RETRIABLE = [PayoutStatus.PENDING, PayoutStatus.FAILED, PayoutStatus.ON_HOLD]
+
+export const validateSettlementPayoutRetryStepId = "validate-stripe-settlement-payout-retry"
+
+export const validateSettlementPayoutRetryStep = createStep(
+ validateSettlementPayoutRetryStepId,
+ async ({ settlement }: ValidateSettlementPayoutRetryStepInput) => {
+ const status = settlement.payout_status
+ const retriable =
+ !!status &&
+ (RETRIABLE.includes(status) || (status === PayoutStatus.PROCESSING && !settlement.provider_payout_id))
+ if (!retriable) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_ALLOWED,
+ `Settlement ${settlement.id} has no failed or held payout to retry`
+ )
+ }
+
+ const account = settlement.payout_account
+ if (!account?.payouts_enabled || !account.external_id) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_ALLOWED,
+ `Payout account ${account?.id ?? "unknown"} cannot receive payouts yet`
+ )
+ }
+
+ return new StepResponse(void 0)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/utils/__tests__/plan-settlements.unit.spec.ts b/packages/plugins/stripe-connector/src/workflows/settlements/utils/__tests__/plan-settlements.unit.spec.ts
new file mode 100644
index 000000000..f783e8660
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/utils/__tests__/plan-settlements.unit.spec.ts
@@ -0,0 +1,72 @@
+import { PayoutStatus } from "@mercurjs/types"
+
+import { SettlementLineType, SettlementStatus } from "../../../../types/common"
+import { PreviousSettlement, SettlementSource, planSettlements, unsettledSince } from "../plan-settlements"
+
+const now = new Date("2026-10-28T01:00:00.000Z")
+
+const source = (overrides: Partial<SettlementSource> = {}): SettlementSource => ({
+ account: { id: "pacc_1", external_id: "acct_1", payouts_enabled: true, created_at: "2026-10-01T00:00:00.000Z" },
+ seller_id: "sel_1",
+ previous: [],
+ lines: [
+ { id: "pout_1", type: SettlementLineType.PAYOUT, amount: 100, paid_at: "2026-10-27T10:00:00.000Z", currency_code: "eur" },
+ { id: "adj_1", type: SettlementLineType.ADJUSTMENT_DEBIT, amount: 10, paid_at: "2026-10-27T11:00:00.000Z", currency_code: "eur" },
+ ],
+ ...overrides,
+})
+
+const previous = (overrides: Partial<PreviousSettlement>): PreviousSettlement => ({
+ currency_code: "eur",
+ period_start: "2026-10-26T01:00:00.000Z",
+ period_end: "2026-10-27T01:00:00.000Z",
+ status: SettlementStatus.PAID_OUT,
+ payout_status: PayoutStatus.PAID,
+ provider_payout_id: "po_1",
+ ...overrides,
+})
+
+describe("planSettlements", () => {
+ it("nets an account's lines per currency from the previous period end", () => {
+ const plan = planSettlements([source({ previous: [previous({})] })], now, "plugin")
+ expect(plan.settlements).toHaveLength(1)
+ expect(plan.settlements[0]).toMatchObject({
+ currency_code: "eur",
+ period_start: new Date("2026-10-27T01:00:00.000Z"),
+ amount: 90,
+ status: SettlementStatus.OPEN,
+ payout_status: PayoutStatus.PENDING,
+ })
+ expect(plan.settlements[0].lines).toEqual([
+ { type: SettlementLineType.PAYOUT, amount: 100, payout_id: "pout_1", payout_reversal_id: null, adjustment_id: null },
+ { type: SettlementLineType.ADJUSTMENT_DEBIT, amount: 10, payout_id: null, payout_reversal_id: null, adjustment_id: "adj_1" },
+ ])
+ })
+
+ it("blocks a currency whose previous bank payout has no outcome yet", () => {
+ const unanswered = previous({ status: SettlementStatus.OPEN, payout_status: PayoutStatus.PROCESSING, provider_payout_id: null })
+ expect(planSettlements([source({ previous: [unanswered] })], now, "plugin").counts.blocked).toBe(1)
+
+ const accepted = previous({ status: SettlementStatus.OPEN, payout_status: PayoutStatus.PROCESSING })
+ expect(planSettlements([source({ previous: [accepted] })], now, "plugin").settlements).toHaveLength(1)
+
+ const failed = previous({ status: SettlementStatus.FAILED, payout_status: PayoutStatus.ON_HOLD, provider_payout_id: null })
+ expect(planSettlements([source({ previous: [failed] })], now, "plugin").counts.blocked).toBe(1)
+ })
+
+ it("records provider-mode settlements as paid out", () => {
+ const [settlement] = planSettlements([source()], now, "provider").settlements
+ expect(settlement).toMatchObject({ status: SettlementStatus.PAID_OUT, payout_status: PayoutStatus.PAID })
+ })
+
+ it("looks for unsettled lines from the oldest latest window across currencies", () => {
+ expect(unsettledSince([])).toBeNull()
+ expect(
+ unsettledSince([
+ previous({ period_start: "2026-10-26T01:00:00.000Z", period_end: "2026-10-27T01:00:00.000Z" }),
+ previous({ period_start: "2026-10-25T01:00:00.000Z", period_end: "2026-10-26T01:00:00.000Z" }),
+ previous({ currency_code: "usd", period_start: "2026-10-20T01:00:00.000Z", period_end: "2026-10-21T01:00:00.000Z" }),
+ ])
+ ).toEqual(new Date("2026-10-20T01:00:00.000Z"))
+ })
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/utils/__tests__/settlement-builder.unit.spec.ts b/packages/plugins/stripe-connector/src/workflows/settlements/utils/__tests__/settlement-builder.unit.spec.ts
new file mode 100644
index 000000000..4511e9521
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/utils/__tests__/settlement-builder.unit.spec.ts
@@ -0,0 +1,94 @@
+import { PayoutStatus } from "@mercurjs/types"
+
+import { SettlementLineType, SettlementStatus } from "../../../../types/common"
+import { buildSettlement } from "../settlement-builder"
+
+const periodEnd = new Date("2026-10-22T01:03:00Z")
+const inside = new Date("2026-10-21T14:12:00Z")
+const line = (id: string, type: SettlementLineType, amount: number, paid_at: Date = inside) => ({
+ id,
+ type,
+ amount,
+ paid_at,
+})
+const account = { payouts_enabled: true, seller_id: "sel_1" }
+
+describe("buildSettlement", () => {
+ it("nets payouts, reversals and adjustments paid up to the window end", () => {
+ const totals = buildSettlement(
+ [
+ line("p1", SettlementLineType.PAYOUT, 162),
+ line("r1", SettlementLineType.REVERSAL, 54),
+ line("a1", SettlementLineType.ADJUSTMENT_DEBIT, 29),
+ line("a2", SettlementLineType.ADJUSTMENT_CREDIT, 5),
+ line("p2", SettlementLineType.PAYOUT, 999, new Date("2026-10-23T00:00:00Z")),
+ ],
+ periodEnd,
+ account
+ )
+ expect(Number(totals.payouts_total)).toBe(162)
+ expect(Number(totals.reversals_total)).toBe(54)
+ expect(Number(totals.adjustments_total)).toBe(-24)
+ expect(Number(totals.amount)).toBe(84)
+ expect(totals.lines.map((l) => l.id)).toEqual(["p1", "r1", "a1", "a2"])
+ expect(totals.status).toBe(SettlementStatus.OPEN)
+ expect(totals.payout_status).toBe(PayoutStatus.PENDING)
+ })
+
+ it("pays out what the lines landed on the connected balance", () => {
+ const landed = (l: ReturnType<typeof line>, landed_amount: number, landed_currency = "pln") => ({ ...l, landed_amount, landed_currency })
+ const totals = buildSettlement(
+ [
+ landed(line("p1", SettlementLineType.PAYOUT, 162), 694.2),
+ landed(line("r1", SettlementLineType.REVERSAL, 54), 231.4),
+ landed(line("a1", SettlementLineType.ADJUSTMENT_DEBIT, 29), 124.3),
+ landed(line("a2", SettlementLineType.ADJUSTMENT_CREDIT, 5), 21.4),
+ ],
+ periodEnd,
+ account
+ )
+ expect(Number(totals.amount)).toBe(84)
+ expect(totals.payout_currency_code).toBe("pln")
+ expect(Number(totals.payout_amount)).toBeCloseTo(359.9, 6)
+ })
+
+ it("pays out in the settlement currency when a line has no landed amount or they differ", () => {
+ const missing = buildSettlement(
+ [{ ...line("p1", SettlementLineType.PAYOUT, 162), landed_amount: 694.2, landed_currency: "pln" }, line("p2", SettlementLineType.PAYOUT, 10)],
+ periodEnd,
+ account
+ )
+ expect(missing.payout_currency_code).toBeNull()
+ expect(missing.payout_amount).toBeNull()
+
+ const mixed = buildSettlement(
+ [
+ { ...line("p1", SettlementLineType.PAYOUT, 162), landed_amount: 694.2, landed_currency: "pln" },
+ { ...line("p2", SettlementLineType.PAYOUT, 10), landed_amount: 10.8, landed_currency: "usd" },
+ ],
+ periodEnd,
+ account
+ )
+ expect(mixed.payout_currency_code).toBeNull()
+ })
+
+ it("aborts a non-positive window", () => {
+ const totals = buildSettlement(
+ [line("p1", SettlementLineType.PAYOUT, 10), line("r1", SettlementLineType.REVERSAL, 10)],
+ periodEnd,
+ account
+ )
+ expect(totals.status).toBe(SettlementStatus.ABORTED)
+ expect(totals.payout_status).toBeNull()
+ expect(totals.payout_reason).toBe("invalid_amount")
+ })
+
+ it("holds the payout when payouts are disabled", () => {
+ const totals = buildSettlement([line("p1", SettlementLineType.PAYOUT, 10)], periodEnd, {
+ ...account,
+ payouts_enabled: false,
+ })
+ expect(totals.payout_status).toBe(PayoutStatus.ON_HOLD)
+ expect(totals.payout_reason).toBe("account_payouts_disabled")
+ })
+})
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/utils/account-ready.ts b/packages/plugins/stripe-connector/src/workflows/settlements/utils/account-ready.ts
new file mode 100644
index 000000000..514217246
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/utils/account-ready.ts
@@ -0,0 +1,4 @@
+import { PayoutAccountDTO } from "@mercurjs/types"
+
+export const isPayoutReady = (account: PayoutAccountDTO | undefined): account is PayoutAccountDTO =>
+ !!account?.payouts_enabled && !!account.external_id
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/utils/plan-settlements.ts b/packages/plugins/stripe-connector/src/workflows/settlements/utils/plan-settlements.ts
new file mode 100644
index 000000000..5cff38fd8
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/utils/plan-settlements.ts
@@ -0,0 +1,170 @@
+import { PayoutStatus } from "@mercurjs/types"
+
+import { SettlementLineType, SettlementStatus } from "../../../types/common"
+import { SettlementSourceLine, buildSettlement } from "./settlement-builder"
+
+export type UnsettledLine = SettlementSourceLine & { currency_code: string }
+
+export type PreviousSettlement = {
+ currency_code: string
+ period_start: Date | string
+ period_end: Date | string
+ status: SettlementStatus
+ payout_status: PayoutStatus | null
+ provider_payout_id: string | null
+}
+
+export type SettlementSource = {
+ account: {
+ id: string
+ external_id: string | null
+ payouts_enabled: boolean
+ created_at: Date | string
+ }
+ seller_id: string | null
+ previous: PreviousSettlement[]
+ lines: UnsettledLine[]
+}
+
+export type PlannedSettlement = {
+ account_id: string
+ external_id: string | null
+ seller_id: string | null
+ currency_code: string
+ period_start: Date
+ period_end: Date
+ payouts_total: number
+ reversals_total: number
+ adjustments_total: number
+ amount: number
+ payout_amount: number | null
+ payout_currency_code: string | null
+ status: SettlementStatus
+ payout_status: PayoutStatus | null
+ status_reason: string | null
+ lines: {
+ type: SettlementLineType
+ amount: number
+ payout_id: string | null
+ payout_reversal_id: string | null
+ adjustment_id: string | null
+ }[]
+}
+
+export type SettlementPlan = {
+ settlements: PlannedSettlement[]
+ counts: Record<string, number>
+}
+
+export const lineReference = (line: SettlementSourceLine) => ({
+ payout_id: line.type === SettlementLineType.PAYOUT ? line.id : null,
+ payout_reversal_id: line.type === SettlementLineType.REVERSAL ? line.id : null,
+ adjustment_id:
+ line.type === SettlementLineType.ADJUSTMENT_CREDIT || line.type === SettlementLineType.ADJUSTMENT_DEBIT
+ ? line.id
+ : null,
+})
+
+// A bank payout the provider already accepted no longer holds the chain; one
+// that still has to be sent (or whose outcome is unknown) does.
+const holdsChain = (previous: PreviousSettlement) =>
+ previous.status === SettlementStatus.FAILED ||
+ (previous.status === SettlementStatus.OPEN &&
+ !(
+ previous.payout_status === PayoutStatus.PAID ||
+ previous.payout_status === PayoutStatus.ABORTED ||
+ (previous.payout_status === PayoutStatus.PROCESSING && !!previous.provider_payout_id)
+ ))
+
+export const latestByCurrency = (settlements: PreviousSettlement[]) => {
+ const latest = new Map<string, PreviousSettlement>()
+ for (const settlement of settlements) {
+ const current = latest.get(settlement.currency_code)
+ if (!current || new Date(settlement.period_end).getTime() > new Date(current.period_end).getTime()) {
+ latest.set(settlement.currency_code, settlement)
+ }
+ }
+ return latest
+}
+
+/**
+ * Where to start looking for unsettled lines: one window back from the oldest
+ * latest settlement across currencies, so a line paid while that settlement
+ * was being built is not missed. Null scans the whole history.
+ */
+export const unsettledSince = (settlements: PreviousSettlement[]): Date | null => {
+ const starts = Array.from(latestByCurrency(settlements).values()).map((s) => new Date(s.period_start).getTime())
+ return starts.length ? new Date(Math.min(...starts)) : null
+}
+
+/**
+ * One settlement per account and currency over the window since the previous
+ * one, netting every paid line not settled yet. A currency whose previous
+ * settlement is still unpaid is blocked until it is.
+ */
+export function planSettlements(sources: SettlementSource[], now: Date, mode: "plugin" | "provider"): SettlementPlan {
+ const counts: Record<string, number> = { settlements: 0, aborted: 0, on_hold: 0, blocked: 0 }
+ const settlements: PlannedSettlement[] = []
+
+ for (const source of sources) {
+ const latest = latestByCurrency(source.previous)
+ const currencies = Array.from(new Set(source.lines.map((line) => line.currency_code)))
+
+ for (const currency of currencies) {
+ const previous = latest.get(currency)
+ if (previous && holdsChain(previous)) {
+ counts.blocked += 1
+ continue
+ }
+
+ const periodStart = new Date(previous ? previous.period_end : source.account.created_at)
+ if (periodStart.getTime() >= now.getTime()) {
+ continue
+ }
+
+ const totals = buildSettlement(
+ source.lines.filter((line) => line.currency_code === currency),
+ now,
+ { payouts_enabled: source.account.payouts_enabled, seller_id: source.seller_id ?? source.account.id }
+ )
+ if (!totals.lines.length) {
+ continue
+ }
+
+ const payoutStatus = mode === "provider" && totals.payout_status ? PayoutStatus.PAID : totals.payout_status
+ const status =
+ totals.status === SettlementStatus.ABORTED
+ ? SettlementStatus.ABORTED
+ : mode === "provider"
+ ? SettlementStatus.PAID_OUT
+ : payoutStatus === PayoutStatus.ON_HOLD
+ ? SettlementStatus.FAILED
+ : SettlementStatus.OPEN
+
+ settlements.push({
+ account_id: source.account.id,
+ external_id: source.account.external_id,
+ seller_id: source.seller_id,
+ currency_code: currency,
+ period_start: periodStart,
+ period_end: now,
+ payouts_total: Number(totals.payouts_total),
+ reversals_total: Number(totals.reversals_total),
+ adjustments_total: Number(totals.adjustments_total),
+ amount: Number(totals.amount),
+ payout_amount: totals.payout_amount == null ? null : Number(totals.payout_amount),
+ payout_currency_code: totals.payout_currency_code,
+ status,
+ payout_status: payoutStatus,
+ status_reason: totals.payout_reason,
+ lines: totals.lines.map((line) => ({ type: line.type, amount: Number(line.amount), ...lineReference(line) })),
+ })
+
+ counts.settlements += 1
+ if (status === SettlementStatus.ABORTED) counts.aborted += 1
+ if (payoutStatus === PayoutStatus.ON_HOLD) counts.on_hold += 1
+ }
+ }
+
+ return { settlements, counts }
+}
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/utils/settlement-builder.ts b/packages/plugins/stripe-connector/src/workflows/settlements/utils/settlement-builder.ts
new file mode 100644
index 000000000..4e94c696d
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/utils/settlement-builder.ts
@@ -0,0 +1,122 @@
+import { BigNumberInput } from "@medusajs/framework/types"
+import { MathBN } from "@medusajs/framework/utils"
+import { PayoutStatus, PayoutStatusReason } from "@mercurjs/types"
+
+import { SettlementLineType, SettlementStatus } from "../../../types/common"
+
+export type SettlementSourceLine = {
+ id: string
+ type: SettlementLineType
+ amount: BigNumberInput
+ paid_at: Date | string
+ landed_amount?: number | null
+ landed_currency?: string | null
+}
+
+export type SettlementTotals = {
+ payouts_total: BigNumberInput
+ reversals_total: BigNumberInput
+ adjustments_total: BigNumberInput
+ amount: BigNumberInput
+ payout_amount: BigNumberInput | null
+ payout_currency_code: string | null
+ lines: SettlementSourceLine[]
+ status: SettlementStatus
+ payout_status: PayoutStatus | null
+ payout_reason: string | null
+}
+
+const SIGN: Record<SettlementLineType, 1 | -1> = {
+ [SettlementLineType.PAYOUT]: 1,
+ [SettlementLineType.REVERSAL]: -1,
+ [SettlementLineType.ADJUSTMENT_CREDIT]: 1,
+ [SettlementLineType.ADJUSTMENT_DEBIT]: -1,
+}
+
+/**
+ * The bank payout, in what the lines actually added to the connected balance.
+ * Stripe converts transfers into a currency the account holds, so it can
+ * differ from the settlement currency. Without a landed amount on every line,
+ * or with more than one landed currency, it stays in the settlement currency.
+ */
+function landedPayout(lines: SettlementSourceLine[]): { payout_amount: BigNumberInput | null; payout_currency_code: string | null } {
+ const currencies = new Set(lines.map((line) => (line.landed_amount == null ? null : line.landed_currency ?? null)))
+ const [currency] = currencies
+ if (!lines.length || currencies.size !== 1 || !currency) {
+ return { payout_amount: null, payout_currency_code: null }
+ }
+ const sum = lines.reduce<BigNumberInput>(
+ (acc, line) => MathBN.add(acc, MathBN.mult(line.landed_amount as number, SIGN[line.type])),
+ 0
+ )
+ return MathBN.gt(sum, 0) ? { payout_amount: sum, payout_currency_code: currency } : { payout_amount: null, payout_currency_code: null }
+}
+
+/**
+ * Nets every paid line not settled yet, up to the end of the window: payouts
+ * and credits count up, reversals and debits count down. A non-positive
+ * amount aborts the settlement so the chain of windows stays unbroken.
+ */
+export function buildSettlement(
+ lines: SettlementSourceLine[],
+ periodEnd: Date,
+ account: { payouts_enabled: boolean; seller_id: string } | null
+): SettlementTotals {
+ let payouts: BigNumberInput = 0
+ let reversals: BigNumberInput = 0
+ let adjustments: BigNumberInput = 0
+ const included: SettlementSourceLine[] = []
+
+ for (const line of lines) {
+ if (new Date(line.paid_at).getTime() > periodEnd.getTime()) {
+ continue
+ }
+ included.push(line)
+ switch (line.type) {
+ case SettlementLineType.PAYOUT:
+ payouts = MathBN.add(payouts, line.amount)
+ break
+ case SettlementLineType.REVERSAL:
+ reversals = MathBN.add(reversals, line.amount)
+ break
+ case SettlementLineType.ADJUSTMENT_CREDIT:
+ adjustments = MathBN.add(adjustments, line.amount)
+ break
+ case SettlementLineType.ADJUSTMENT_DEBIT:
+ adjustments = MathBN.sub(adjustments, line.amount)
+ break
+ }
+ }
+
+ const amount = MathBN.add(MathBN.sub(payouts, reversals), adjustments)
+ const totals = {
+ payouts_total: payouts,
+ reversals_total: reversals,
+ adjustments_total: adjustments,
+ amount,
+ ...landedPayout(included),
+ lines: included,
+ }
+
+ if (MathBN.lte(amount, 0)) {
+ return {
+ ...totals,
+ status: SettlementStatus.ABORTED,
+ payout_status: null,
+ payout_reason: PayoutStatusReason.INVALID_AMOUNT,
+ }
+ }
+
+ if (!account || !account.payouts_enabled) {
+ return {
+ ...totals,
+ status: SettlementStatus.OPEN,
+ payout_status: PayoutStatus.ON_HOLD,
+ payout_reason: account
+ ? PayoutStatusReason.ACCOUNT_PAYOUTS_DISABLED
+ : PayoutStatusReason.ACCOUNT_NOT_READY,
+ }
+ }
+
+ return { ...totals, status: SettlementStatus.OPEN, payout_status: PayoutStatus.PENDING, payout_reason: null }
+}
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/utils/settlement-payout.ts b/packages/plugins/stripe-connector/src/workflows/settlements/utils/settlement-payout.ts
new file mode 100644
index 000000000..527938a75
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/utils/settlement-payout.ts
@@ -0,0 +1,5 @@
+import { PayoutStatus } from "@mercurjs/types"
+
+/** A bank payout that did not go out: refused by Stripe, or held on a short balance. */
+export const isSettlementPayoutUnpaid = (settlement: { payout_status: PayoutStatus | null }) =>
+ settlement.payout_status === PayoutStatus.FAILED || settlement.payout_status === PayoutStatus.ON_HOLD
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/workflows/index.ts b/packages/plugins/stripe-connector/src/workflows/settlements/workflows/index.ts
new file mode 100644
index 000000000..4a90b98ad
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/workflows/index.ts
@@ -0,0 +1,2 @@
+export * from "./process-settlements"
+export * from "./retry-settlement-payout"
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/workflows/process-settlements.ts b/packages/plugins/stripe-connector/src/workflows/settlements/workflows/process-settlements.ts
new file mode 100644
index 000000000..d468b3b40
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/workflows/process-settlements.ts
@@ -0,0 +1,106 @@
+import { WorkflowResponse, createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+import { emitEventStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+import { StripeConnectorEvents } from "../../../types/common"
+import { JobStats } from "../../../utils/run-job"
+import {
+ createSettlementsStep,
+ loadSettlementSourcesStep,
+ processAdjustmentsStep,
+ processSettlementPayoutsStep,
+ retrySettlementPayoutsStep,
+} from "../steps"
+import { LoadSettlementSourcesStepInput } from "../steps/load-settlement-sources"
+import { planSettlements } from "../utils/plan-settlements"
+
+export type ProcessSettlementsWorkflowInput = {
+ seller_id?: string
+ now?: Date
+}
+
+export const processSettlementsWorkflowId = "process-stripe-settlements"
+
+/**
+ * Sends operator adjustments, retries held bank payouts, then nets each
+ * account's paid lines into a settlement and pays it out to the seller's bank.
+ */
+export const processSettlementsWorkflow = createWorkflow(
+ processSettlementsWorkflowId,
+ function (input: ProcessSettlementsWorkflowInput) {
+ const sellerLinks = when("settlements-of-one-seller", { input }, ({ input }) => !!input.seller_id).then(() => {
+ const { data } = useQueryGraphStep({
+ entity: "seller_payout_account",
+ fields: ["payout_account_id"],
+ filters: { seller_id: input.seller_id },
+ }).config({ name: "settlement-seller-accounts-query" })
+ return data
+ })
+
+ const accountIds = transform({ input, sellerLinks }, ({ input, sellerLinks }) =>
+ input.seller_id ? (sellerLinks ?? []).map((link) => link.payout_account_id as string) : null
+ )
+
+ const accounts = when("settlement-accounts", { accountIds }, ({ accountIds }) => !accountIds || accountIds.length > 0).then(
+ () => {
+ const { data } = useQueryGraphStep({
+ entity: "payout_account",
+ fields: ["id", "external_id", "payouts_enabled", "created_at", "seller.id"],
+ filters: transform({ accountIds }, ({ accountIds }) => (accountIds ? { id: accountIds } : {})),
+ }).config({ name: "settlement-accounts-query" })
+ return data
+ }
+ )
+
+ const adjustmentsProcessed = processAdjustmentsStep()
+ const payoutsRetried = retrySettlementPayoutsStep({ account_ids: accountIds })
+
+ const loaded = loadSettlementSourcesStep(
+ transform({ accounts }, ({ accounts }): LoadSettlementSourcesStepInput => ({
+ accounts: (accounts ?? []) as unknown as LoadSettlementSourcesStepInput["accounts"],
+ }))
+ )
+
+ const plan = transform({ input, loaded }, ({ input, loaded }) =>
+ planSettlements(
+ loaded.sources,
+ new Date(Math.max(new Date(input.now ?? Date.now()).getTime(), Date.now())),
+ loaded.mode
+ )
+ )
+
+ const created = createSettlementsStep(plan.settlements)
+ const processed = processSettlementPayoutsStep({ settlements: created })
+
+ emitEventStep({
+ eventName: StripeConnectorEvents.SETTLEMENT_CREATED,
+ data: transform({ created }, ({ created }) =>
+ created.map((settlement) => ({
+ id: settlement.id,
+ account_id: settlement.account_id,
+ seller_id: settlement.seller_id,
+ currency_code: settlement.currency_code,
+ amount: settlement.amount,
+ }))
+ ),
+ })
+
+ emitEventStep({
+ eventName: StripeConnectorEvents.SETTLEMENT_PAYOUT_FAILED,
+ data: transform({ payoutsRetried, processed }, ({ payoutsRetried, processed }) =>
+ [...payoutsRetried.failed_ids, ...processed.failed_ids].map((id) => ({ id }))
+ ),
+ }).config({ name: "emit-settlement-payout-failed" })
+
+ const stats = transform(
+ { plan, adjustmentsProcessed, payoutsRetried, processed },
+ ({ plan, adjustmentsProcessed, payoutsRetried, processed }): JobStats => ({
+ ...plan.counts,
+ adjustments_processed: adjustmentsProcessed,
+ payouts_retried: payoutsRetried.sent,
+ payouts: processed.sent,
+ })
+ )
+
+ return new WorkflowResponse(stats)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/settlements/workflows/retry-settlement-payout.ts b/packages/plugins/stripe-connector/src/workflows/settlements/workflows/retry-settlement-payout.ts
new file mode 100644
index 000000000..8b018bf37
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/settlements/workflows/retry-settlement-payout.ts
@@ -0,0 +1,55 @@
+import { WorkflowResponse, createWorkflow, transform } from "@medusajs/framework/workflows-sdk"
+import { emitEventStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"
+
+import { StripeConnectorEvents } from "../../../types/common"
+import { createSettlementPayoutStep, validateSettlementPayoutRetryStep } from "../steps"
+import { ValidateSettlementPayoutRetryStepInput } from "../steps/validate-settlement-payout-retry"
+import { isSettlementPayoutUnpaid } from "../utils/settlement-payout"
+
+export type RetrySettlementPayoutWorkflowInput = {
+ id: string
+}
+
+export const retrySettlementPayoutWorkflowId = "retry-stripe-settlement-payout"
+
+/** Sends a settlement's failed, held or unanswered bank payout again, on the operator's call. */
+export const retrySettlementPayoutWorkflow = createWorkflow(
+ retrySettlementPayoutWorkflowId,
+ function (input: RetrySettlementPayoutWorkflowInput) {
+ const { data: settlement } = useQueryGraphStep({
+ entity: "settlement",
+ fields: [
+ "id",
+ "payout_status",
+ "provider_payout_id",
+ "payout_account.id",
+ "payout_account.external_id",
+ "payout_account.payouts_enabled",
+ ],
+ filters: { id: input.id },
+ options: { isList: false, throwIfKeyNotFound: true },
+ }).config({ name: "retry-settlement-query" })
+
+ const validated = transform(
+ { settlement },
+ ({ settlement }) => ({ settlement }) as unknown as ValidateSettlementPayoutRetryStepInput
+ )
+ validateSettlementPayoutRetryStep(validated)
+
+ const updated = createSettlementPayoutStep(
+ transform({ validated }, ({ validated }) => ({
+ settlement_id: validated.settlement.id,
+ stripe_account_id: validated.settlement.payout_account?.external_id as string,
+ }))
+ )
+
+ emitEventStep({
+ eventName: StripeConnectorEvents.SETTLEMENT_PAYOUT_FAILED,
+ data: transform({ updated }, ({ updated }) =>
+ isSettlementPayoutUnpaid(updated) ? [{ id: updated.id }] : []
+ ),
+ })
+
+ return new WorkflowResponse(updated)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/webhooks/steps/index.ts b/packages/plugins/stripe-connector/src/workflows/webhooks/steps/index.ts
new file mode 100644
index 000000000..053d67f01
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/webhooks/steps/index.ts
@@ -0,0 +1 @@
+export * from "./update-settlement-bank-payout"
diff --git a/packages/plugins/stripe-connector/src/workflows/webhooks/steps/update-settlement-bank-payout.ts b/packages/plugins/stripe-connector/src/workflows/webhooks/steps/update-settlement-bank-payout.ts
new file mode 100644
index 000000000..e31fe938f
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/webhooks/steps/update-settlement-bank-payout.ts
@@ -0,0 +1,43 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import Stripe from "stripe"
+
+import { SettlementDTO } from "../../../types/common"
+import { resolveConnector } from "../../../utils/payout-module"
+
+export type UpdateSettlementBankPayoutStepInput = {
+ provider_payout_id: string
+ status: Stripe.Payout["status"]
+ status_reason: string | null
+}
+
+type Previous = Pick<SettlementDTO, "id" | "status" | "payout_status" | "status_reason">
+
+export const updateSettlementBankPayoutStepId = "update-stripe-settlement-bank-payout"
+
+export const updateSettlementBankPayoutStep = createStep(
+ updateSettlementBankPayoutStepId,
+ async (input: UpdateSettlementBankPayoutStepInput, { container }) => {
+ const connector = resolveConnector(container)
+ const [previous] = await connector.listSettlements(
+ { provider_payout_id: input.provider_payout_id },
+ { select: ["id", "status", "payout_status", "status_reason"] }
+ )
+ if (!previous) {
+ return new StepResponse<SettlementDTO | null, Previous | null>(null, null)
+ }
+
+ const updated = await connector.applySettlementPayoutEvent(input.provider_payout_id, input.status, input.status_reason)
+ return new StepResponse<SettlementDTO | null, Previous | null>(updated, {
+ id: previous.id,
+ status: previous.status,
+ payout_status: previous.payout_status,
+ status_reason: previous.status_reason,
+ })
+ },
+ async (previous, { container }) => {
+ if (!previous) {
+ return
+ }
+ await resolveConnector(container).updateSettlements(previous)
+ }
+)
diff --git a/packages/plugins/stripe-connector/src/workflows/webhooks/utils.ts b/packages/plugins/stripe-connector/src/workflows/webhooks/utils.ts
new file mode 100644
index 000000000..33788507e
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/webhooks/utils.ts
@@ -0,0 +1,3 @@
+export const LAST_WEBHOOK_CHECKPOINT = "last_webhook_at"
+
+export const BANK_PAYOUT_EVENTS = ["payout.paid", "payout.failed", "payout.canceled", "payout.updated"]
diff --git a/packages/plugins/stripe-connector/src/workflows/webhooks/workflows/index.ts b/packages/plugins/stripe-connector/src/workflows/webhooks/workflows/index.ts
new file mode 100644
index 000000000..66bc0696b
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/webhooks/workflows/index.ts
@@ -0,0 +1 @@
+export * from "./process-stripe-bank-payout-webhook"
diff --git a/packages/plugins/stripe-connector/src/workflows/webhooks/workflows/process-stripe-bank-payout-webhook.ts b/packages/plugins/stripe-connector/src/workflows/webhooks/workflows/process-stripe-bank-payout-webhook.ts
new file mode 100644
index 000000000..226c225ef
--- /dev/null
+++ b/packages/plugins/stripe-connector/src/workflows/webhooks/workflows/process-stripe-bank-payout-webhook.ts
@@ -0,0 +1,58 @@
+import { WorkflowResponse, createWorkflow, transform, when } from "@medusajs/framework/workflows-sdk"
+import { emitEventStep } from "@medusajs/medusa/core-flows"
+import { PayoutStatus } from "@mercurjs/types"
+import Stripe from "stripe"
+
+import { StripeConnectorEvents } from "../../../types/common"
+import { setCheckpointsStep } from "../../common/steps"
+import { updateSettlementBankPayoutStep } from "../steps"
+import { BANK_PAYOUT_EVENTS, LAST_WEBHOOK_CHECKPOINT } from "../utils"
+
+export type ProcessStripeBankPayoutWebhookWorkflowInput = {
+ type: string
+ received_at: string
+ payout?: Pick<Stripe.Payout, "id" | "status" | "failure_code" | "failure_message"> | null
+}
+
+export const processStripeBankPayoutWebhookWorkflowId = "process-stripe-bank-payout-webhook"
+
+/**
+ * Records when a verified Connect webhook arrived and follows the bank
+ * payouts of settlements, which core does not know about.
+ */
+export const processStripeBankPayoutWebhookWorkflow = createWorkflow(
+ processStripeBankPayoutWebhookWorkflowId,
+ function (input: ProcessStripeBankPayoutWebhookWorkflowInput) {
+ setCheckpointsStep(
+ transform({ input }, ({ input }) => [{ key: LAST_WEBHOOK_CHECKPOINT, value: input.received_at }])
+ )
+
+ const settlement = when(
+ "bank-payout-webhook",
+ { input },
+ ({ input }) => BANK_PAYOUT_EVENTS.includes(input.type) && !!input.payout
+ ).then(() =>
+ updateSettlementBankPayoutStep(
+ transform({ input }, ({ input }) => {
+ const payout = input.payout as NonNullable<ProcessStripeBankPayoutWebhookWorkflowInput["payout"]>
+ return {
+ provider_payout_id: payout.id,
+ status: payout.status,
+ status_reason: payout.failure_code
+ ? `${payout.failure_code}: ${payout.failure_message ?? "Unknown failure reason"}`
+ : null,
+ }
+ })
+ )
+ )
+
+ emitEventStep({
+ eventName: StripeConnectorEvents.SETTLEMENT_PAYOUT_FAILED,
+ data: transform({ settlement }, ({ settlement }) =>
+ settlement?.payout_status === PayoutStatus.FAILED ? [{ id: settlement.id }] : []
+ ),
+ })
+
+ return new WorkflowResponse(transform({ settlement }, ({ settlement }) => settlement ?? null))
+ }
+)
diff --git a/packages/plugins/stripe-connector/tsconfig.json b/packages/plugins/stripe-connector/tsconfig.json
new file mode 100644
index 000000000..33a8c852d
--- /dev/null
+++ b/packages/plugins/stripe-connector/tsconfig.json
@@ -0,0 +1,23 @@
+{
+ "compilerOptions": {
+ "target": "ES2021",
+ "esModuleInterop": true,
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "emitDecoratorMetadata": true,
+ "experimentalDecorators": true,
+ "skipLibCheck": true,
+ "skipDefaultLibCheck": true,
+ "declaration": false,
+ "sourceMap": false,
+ "inlineSourceMap": true,
+ "outDir": "./.medusa/server",
+ "rootDir": "./",
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "checkJs": false,
+ "strictNullChecks": true
+ },
+ "include": ["**/*", ".medusa/types/*"],
+ "exclude": ["node_modules", ".medusa/server", ".cache", "src/admin", "src/vendor", "src/ui", "**/__tests__/**", "**/*.spec.ts"]
+}
diff --git a/packages/providers/payout-stripe-connect/package.json b/packages/providers/payout-stripe-connect/package.json
deleted file mode 100644
index b42254ccf..000000000
--- a/packages/providers/payout-stripe-connect/package.json
+++ /dev/null
@@ -1,43 +0,0 @@
-{
- "name": "@mercurjs/payout-stripe-connect",
- "version": "2.3.9-canary.4",
- "description": "Stripe Connect payment provider for Mercur",
- "private": false,
- "type": "module",
- "repository": {
- "type": "git",
- "url": "https://github.com/mercurjs/mercur",
- "directory": "packages/providers/payout-stripe-connect"
- },
- "engines": {
- "node": ">=22.22.0"
- },
- "author": "Medusa",
- "license": "MIT",
- "files": [
- "dist"
- ],
- "exports": {
- ".": "./dist/index.js"
- },
- "scripts": {
- "dev": "tsup --watch",
- "build": "tsup"
- },
- "peerDependencies": {
- "@medusajs/framework": ">=2.22.0"
- },
- "devDependencies": {
- "@medusajs/framework": "2.22.0",
- "@mercurjs/types": "2.3.9-canary.4",
- "tsup": "^8.5.0"
- },
- "dependencies": {
- "stripe": "^15.5.0"
- },
- "keywords": [
- "medusa-plugin",
- "medusa-plugin-payment",
- "stripe-connect"
- ]
-}
diff --git a/packages/providers/payout-stripe-connect/src/index.ts b/packages/providers/payout-stripe-connect/src/index.ts
deleted file mode 100644
index 8739fe2f9..000000000
--- a/packages/providers/payout-stripe-connect/src/index.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { ModuleProvider, Modules } from "@medusajs/framework/utils"
-import StripeConnectProviderService from "./services/stripe-connect"
-
-export * from './types'
-
-export default ModuleProvider(Modules.PAYMENT, {
- services: [StripeConnectProviderService],
-})
\ 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
deleted file mode 100644
index e49cf6641..000000000
--- a/packages/providers/payout-stripe-connect/src/services/stripe-connect.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-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 readonly stripe_: Stripe
- protected readonly config_: StripeConnectOptions
-
- constructor(
- _cradle: Record<string, unknown>,
- 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 = { seller_id: extra.seller_id, ...(extra?.metadata ? extra.metadata : {}) } as Stripe.MetadataParam
-
-
- return res as Partial<Stripe.TransferCreateParams> & { destination: string }
- }
-
- private getWebhookResultFromAccount_(
- account: Stripe.Account
- ): PayoutWebhookResult {
- const accountId = account.metadata?.account_id
- 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: accountId,
- },
- }
- }
-
- 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: accountId,
- },
- }
- }
-
- if (disabledReason) {
- return {
- action: "account.restricted",
- data: {
- id: accountId,
- },
- }
- }
-
- return {
- action: "account.restricted",
- data: {
- id: accountId,
- },
- }
- }
-
- 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,
- metadata: {
- account_id: data?.account_id as string,
- },
- }, {
- 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.PAID
- }
- }
-
- 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",
- });
-
- 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)
- 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
deleted file mode 100644
index c0a129eab..000000000
--- a/packages/providers/payout-stripe-connect/src/types/index.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-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
deleted file mode 100644
index 2b94cee59..000000000
--- a/packages/providers/payout-stripe-connect/src/utils/index.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-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
deleted file mode 100644
index 5856465f6..000000000
--- a/packages/providers/payout-stripe-connect/tsconfig.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "compilerOptions": {
- "lib": ["ES2021"],
- "target": "ES2021",
- "outDir": "./dist",
- "esModuleInterop": true,
- "declaration": true,
- "declarationMap": true,
- "noUnusedLocals": true,
- "module": "ESNext",
- "moduleResolution": "Bundler",
- "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/providers/payout-stripe-connect/tsup.config.ts b/packages/providers/payout-stripe-connect/tsup.config.ts
deleted file mode 100644
index 2ad88f656..000000000
--- a/packages/providers/payout-stripe-connect/tsup.config.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { defineConfig } from "tsup";
-
-export default defineConfig({
- clean: true,
- dts: true,
- entry: ["src/index.ts"],
- format: ["esm"],
- sourcemap: true,
- target: "esnext",
- outDir: "dist",
- treeshake: true,
- external: ["@medusajs/framework", "@mercurjs/types"],
-});
diff --git a/packages/types/src/http/payout.ts b/packages/types/src/http/payout.ts
index 4e72c3ecb..335ce413e 100644
--- a/packages/types/src/http/payout.ts
+++ b/packages/types/src/http/payout.ts
@@ -1,5 +1,9 @@
import { PaginatedResponse } from "@medusajs/types"
-import { OnboardingDTO, PayoutAccountDTO, PayoutDTO } from "../payout"
+import {
+ OnboardingDTO,
+ PayoutAccountDTO,
+ PayoutDTO,
+} from "../payout"
export interface VendorPayoutAccountResponse {
payout_account: PayoutAccountDTO
@@ -21,6 +25,10 @@ export type VendorPayoutListResponse = PaginatedResponse<{
payouts: PayoutDTO[]
}>
+export interface VendorPayoutAccountMeResponse {
+ payout_account: (PayoutAccountDTO & { onboarding: OnboardingDTO | null }) | null
+}
+
export interface AdminPayoutResponse {
payout: PayoutDTO
}
diff --git a/packages/types/src/payout/common.ts b/packages/types/src/payout/common.ts
index 874461aad..e476b3ec3 100644
--- a/packages/types/src/payout/common.ts
+++ b/packages/types/src/payout/common.ts
@@ -1,4 +1,4 @@
-import { BigNumberInput, FulfillmentStatus, ModuleProviderExports } from "@medusajs/types"
+import { BigNumberInput, ModuleProviderExports } from "@medusajs/types"
export enum PayoutAccountStatus {
/**
@@ -22,104 +22,104 @@ export enum PayoutAccountStatus {
REJECTED = "rejected",
}
+export enum PayoutKycStatus {
+ PENDING_SUBMISSION = "pending_submission",
+ PENDING_APPROVAL = "pending_approval",
+ APPROVED = "approved",
+ REFUSED = "refused",
+}
+
export enum PayoutStatus {
PENDING = "pending",
+ ON_HOLD = "on_hold",
PROCESSING = "processing",
PAID = "paid",
FAILED = "failed",
- CANCELED = "canceled",
-}
-
-export enum PayoutEvents {
- // TODO: Move to order-related domain events
- OrderCaptureRequested = 'order.capture_requested',
- OrderAuthorizationExpired = 'order.authorization_expired',
- PayoutRequested = 'payout.requested',
+ ABORTED = "aborted",
}
+export const PayoutModuleEvents = {
+ ACCOUNT_UPDATED: "payout_account.updated",
+ PAYOUT_FAILED: "payout.failed",
+ PAYOUT_REVERSAL_FAILED: "payout.reversal_failed",
+ WEBHOOK_RECEIVED: "payout.webhook_received",
+} as const
export interface PayoutModuleOptions {
- /**
- * Providers to be registered
- */
providers?: {
- /**
- * The module provider to be registered
- */
resolve: string | ModuleProviderExports
- /**
- * The id of the provider
- */
id: string
- /**
- * Key value pair of the configuration to be passed to the provider constructor
- */
options?: Record<string, unknown>
}[]
- /**
- * 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
+ onboarding?: {
+ returnUrl?: string
+ refreshBaseUrl?: string
+ prefill?: boolean
+ defaultCountry?: string
+ /**
+ * How long the token in an onboarding refresh URL stays valid, in seconds.
+ * Defaults to 24 hours.
+ */
+ tokenTtlSeconds?: number
+ }
}
-export const PAYOUT_MODULE_OPTION_DEFAULTS: Required<Omit<PayoutModuleOptions, 'providers'>> = {
- disabled: false,
- authorizationWindowMs: 7 * 24 * 60 * 60 * 1000,
- sellerActionWindowMs: 72 * 60 * 60 * 1000,
- captureSafetyBufferMs: 24 * 60 * 60 * 1000,
- requiredFulfillmentStatus: "fulfilled",
+export type ResolvedPayoutModuleOptions = {
+ onboarding: {
+ returnUrl: string
+ refreshBaseUrl: string
+ prefill: boolean
+ defaultCountry?: string
+ tokenTtlSeconds: number
+ }
}
+export function resolvePayoutModuleOptions(
+ options?: PayoutModuleOptions | null
+): ResolvedPayoutModuleOptions {
+ return {
+ onboarding: {
+ returnUrl: "",
+ refreshBaseUrl: "",
+ prefill: false,
+ tokenTtlSeconds: 24 * 60 * 60,
+ ...(options?.onboarding ?? {}),
+ },
+ }
+}
export type PayoutWebhookAction =
| "not_supported"
+ | "account.updated"
| "account.activated"
| "account.restricted"
| "account.rejected"
- | "payout.processing"
| "payout.paid"
| "payout.failed"
- | "payout.canceled"
+ | "payout.reversed"
+export interface PayoutAccountRequirements {
+ currently_due: string[]
+ past_due: string[]
+ pending_verification: string[]
+}
export interface PayoutAccountDTO {
id: string
+ external_id: string | null
status: PayoutAccountStatus
+ kyc_status: PayoutKycStatus | null
+ payouts_enabled: boolean
+ charges_enabled: boolean
+ details_submitted: boolean
+ disabled_reason: string | null
+ onboarding_token: string | null
+ onboarding_token_issued_at: Date | null
+ last_synced_at: Date | null
data: Record<string, unknown>
context: Record<string, unknown> | null
+ onboarding?: OnboardingDTO | null
created_at: Date
updated_at: Date
}
@@ -137,11 +137,50 @@ export interface PayoutDTO {
id: string
display_id: number
account_id: string
+ order_id: string | null
amount: BigNumberInput
currency_code: string
status: PayoutStatus
+ status_reason: string | null
+ data: Record<string, unknown> | null
+ metadata: Record<string, unknown> | null
+ account?: PayoutAccountDTO
+ reversals?: PayoutReversalDTO[]
+ created_at: Date
+ updated_at: Date
+}
+
+export interface PayoutReversalDTO {
+ id: string
+ payout_id: string
+ refund_id: string | null
+ amount: BigNumberInput
+ status: PayoutStatus
+ status_reason: string | null
data: Record<string, unknown> | null
+ payout?: PayoutDTO
created_at: Date
updated_at: Date
}
+/**
+ * Stable codes stored in `status_reason` on payouts and payout reversals.
+ * Ids, statuses and provider messages behind a code go in `data.status_detail`.
+ */
+export const PayoutStatusReason = {
+ ACCOUNT_NOT_READY: "account_not_ready",
+ ACCOUNT_PAYOUTS_DISABLED: "account_payouts_disabled",
+ ORDER_NOT_READY: "order_not_ready",
+ ORDER_ABORTED: "order_aborted",
+ PAYMENT_NOT_READY: "payment_not_ready",
+ PAYMENT_FAILED: "payment_failed",
+ PAYMENT_CANCELED: "payment_canceled",
+ PAYMENT_REFUNDED: "payment_refunded",
+ PAYOUT_NOT_READY: "payout_not_ready",
+ REFUND_ABORTED: "refund_aborted",
+ REFUND_ABSORBED: "refund_absorbed",
+ INVALID_AMOUNT: "invalid_amount",
+ PROVIDER_ERROR: "provider_error",
+} as const
+
+export type PayoutStatusReasonCode = (typeof PayoutStatusReason)[keyof typeof PayoutStatusReason]
diff --git a/packages/types/src/payout/index.ts b/packages/types/src/payout/index.ts
index aae5c1592..f1a9451c0 100644
--- a/packages/types/src/payout/index.ts
+++ b/packages/types/src/payout/index.ts
@@ -1,3 +1,4 @@
export * from "./common"
export * from "./provider"
export * from "./mutations"
+export * from "./service"
diff --git a/packages/types/src/payout/mutations.ts b/packages/types/src/payout/mutations.ts
index 6f4637178..0b27939ae 100644
--- a/packages/types/src/payout/mutations.ts
+++ b/packages/types/src/payout/mutations.ts
@@ -1,26 +1,80 @@
-import { PayoutAccountStatus, PayoutStatus } from "./common"
+import { BigNumberInput } from "@medusajs/types"
+import {
+ PayoutAccountStatus,
+ PayoutKycStatus,
+ PayoutStatus,
+} from "./common"
import { PayoutProviderInput } from "./provider"
export interface CreatePayoutAccountDTO extends PayoutProviderInput {
+ seller?: {
+ id: string
+ name?: string | null
+ email?: string | null
+ phone?: string | null
+ website_url?: string | null
+ country_code?: string | null
+ is_company?: boolean
+ }
}
export interface CreateOnboardingDTO extends PayoutProviderInput {
account_id: string
+ /**
+ * Issue a new onboarding token even when the current one is still valid,
+ * so the refresh URL that was just used stops working.
+ */
+ rotate_token?: boolean
}
-export interface CreatePayoutDTO extends PayoutProviderInput {
+export interface UpdatePayoutAccountDTO {
+ id: string
+ status?: PayoutAccountStatus
+ kyc_status?: PayoutKycStatus | null
+ payouts_enabled?: boolean
+ charges_enabled?: boolean
+ details_submitted?: boolean
+ disabled_reason?: string | null
+ onboarding_token?: string | null
+ onboarding_token_issued_at?: Date | null
+ last_synced_at?: Date | null
+ data?: Record<string, unknown>
+}
+
+export interface CreatePayoutDTO {
account_id: string
- amount: number
+ amount: BigNumberInput
currency_code: string
+ order_id?: string | null
+ status?: PayoutStatus
+ status_reason?: string | null
+ data?: Record<string, unknown> | null
+ metadata?: Record<string, unknown> | null
}
-export interface UpdatePayoutAccountDTO {
+export interface UpdatePayoutDTO {
id: string
- status: PayoutAccountStatus
+ account_id?: string
+ amount?: BigNumberInput
+ status?: PayoutStatus
+ status_reason?: string | null
+ data?: Record<string, unknown> | null
+ metadata?: Record<string, unknown> | null
}
-export interface UpdatePayoutDTO {
- id: string
- status: PayoutStatus
+export interface CreatePayoutReversalDTO {
+ payout_id: string
+ amount: BigNumberInput
+ refund_id?: string | null
+ status?: PayoutStatus
+ status_reason?: string | null
+ data?: Record<string, unknown> | null
}
+export interface UpdatePayoutReversalDTO {
+ id: string
+ amount?: BigNumberInput
+ status?: PayoutStatus
+ status_reason?: string | null
+ data?: Record<string, unknown> | null
+}
diff --git a/packages/types/src/payout/provider.ts b/packages/types/src/payout/provider.ts
index bb1ef1d40..b619bf467 100644
--- a/packages/types/src/payout/provider.ts
+++ b/packages/types/src/payout/provider.ts
@@ -1,8 +1,14 @@
-import { PayoutAccountStatus, PayoutStatus, PayoutWebhookAction } from "./common"
import { BigNumberInput } from "@medusajs/types"
+import {
+ PayoutAccountRequirements,
+ PayoutAccountStatus,
+ PayoutStatus,
+ PayoutWebhookAction,
+} from "./common"
export interface PayoutProviderContext {
idempotency_key?: string
+ [key: string]: unknown
}
export interface PayoutProviderInput {
@@ -14,28 +20,90 @@ export interface PayoutProviderOutput {
data: Record<string, unknown>
}
-export interface CreatePayoutAccountInput extends PayoutProviderInput {
+export interface PayoutProviderAccountRef {
+ id: string
+ data: Record<string, unknown>
+}
+
+export interface CreateAccountInput extends PayoutProviderInput {
+ country?: string
+ business_type?: "individual" | "company"
+ business_profile?: {
+ name?: string | null
+ url?: string | null
+ support_email?: string | null
+ support_phone?: string | null
+ }
+ metadata?: Record<string, string>
}
-export interface CreatePayoutAccountResponse extends PayoutProviderOutput {
+export interface AccountOutput extends PayoutProviderOutput {
id: string
- status?: PayoutAccountStatus
+ status: PayoutAccountStatus
+ payouts_enabled: boolean
+ charges_enabled: boolean
+ details_submitted: boolean
+ disabled_reason: string | null
+ requirements: PayoutAccountRequirements
}
-export interface CreatePayoutInput extends PayoutProviderInput {
- amount: BigNumberInput
- currency_code: string
- account_id: string
+export interface RetrieveAccountInput extends PayoutProviderInput {
+ account: PayoutProviderAccountRef
+}
+
+export interface ListAccountsInput extends PayoutProviderInput {
+ limit?: number
+ starting_after?: string
}
-export interface CreatePayoutResponse extends PayoutProviderOutput {
- status?: PayoutStatus
+export interface ListAccountsOutput {
+ accounts: AccountOutput[]
+ has_more: boolean
}
export interface CreateOnboardingInput extends PayoutProviderInput {
+ account: PayoutProviderAccountRef
+ refresh_url: string
+ return_url: string
}
-export interface CreateOnboardingResponse extends PayoutProviderOutput {
+export interface CreateLoginLinkInput extends PayoutProviderInput {
+ account: PayoutProviderAccountRef
+}
+
+export interface LinkOutput extends PayoutProviderOutput {
+ url: string
+ expires_at?: Date | null
+}
+
+export interface SourcePaymentRef {
+ id: string
+ data: Record<string, unknown>
+}
+
+export interface CreatePayoutInput extends PayoutProviderInput {
+ account: PayoutProviderAccountRef
+ amount: BigNumberInput
+ currency_code: string
+ /**
+ * The customer payment the funds come from, for providers that tie a
+ * payout to the charge that funded it.
+ */
+ source_payment?: SourcePaymentRef | null
+ group?: string | null
+ metadata?: Record<string, string>
+}
+
+export interface ReversePayoutInput extends PayoutProviderInput {
+ payout: { id: string; data: Record<string, unknown> }
+ amount: BigNumberInput
+ currency_code: string
+ metadata?: Record<string, string>
+}
+
+export interface PayoutOutput extends PayoutProviderOutput {
+ id: string
+ status: PayoutStatus
}
export interface PayoutWebhookActionInput {
@@ -45,25 +113,63 @@ export interface PayoutWebhookActionInput {
}
export type PayoutWebhookResult = {
- action: PayoutWebhookAction,
+ action: PayoutWebhookAction
data?: {
- /* The ID of the payout or account */
+ /** The provider's id of the object the event is about. */
id: string
+ /** Mercur's payout id, for payout events: providers echo it from the metadata sent with the payout. */
+ payout_id?: string
+ status_reason?: string
}
}
-export interface IPayoutProvider {
- createPayoutAccount(
- data: CreatePayoutAccountInput
- ): Promise<CreatePayoutAccountResponse>
+export enum PayoutProviderErrorCode {
+ /**
+ * The outcome is unknown (timeout, network error, provider 5xx): the request
+ * may have gone through, so a retry reuses the same idempotency key.
+ */
+ UNKNOWN = "unknown",
+ /**
+ * The provider rejected the request and created nothing, so a retry is sent
+ * with a new idempotency key.
+ */
+ REFUSED = "refused",
+ /**
+ * The payout can never succeed and is aborted instead of retried.
+ */
+ FINAL = "final",
+}
- createPayout(data: CreatePayoutInput): Promise<CreatePayoutResponse>
+export class PayoutProviderError extends Error {
+ readonly code: PayoutProviderErrorCode
- createOnboarding(
- input: CreateOnboardingInput
- ): Promise<CreateOnboardingResponse>
+ constructor(message: string, options?: { code?: PayoutProviderErrorCode; final?: boolean }) {
+ super(message)
+ this.name = "PayoutProviderError"
+ this.code = options?.code ?? (options?.final ? PayoutProviderErrorCode.FINAL : PayoutProviderErrorCode.UNKNOWN)
+ }
- getWebhookActionAndData(
- payload: PayoutWebhookActionInput
- ): Promise<PayoutWebhookResult>
+ get final(): boolean {
+ return this.code === PayoutProviderErrorCode.FINAL
+ }
+}
+
+export interface DeleteAccountInput extends PayoutProviderInput {
+ account: PayoutProviderAccountRef
+}
+
+export interface IPayoutProvider {
+ createAccount(input: CreateAccountInput): Promise<AccountOutput>
+ retrieveAccount(input: RetrieveAccountInput): Promise<AccountOutput>
+ /**
+ * Removes an account created by `createAccount`, used to roll back an
+ * account creation. Optional: without it the account stays at the provider.
+ */
+ deleteAccount?(input: DeleteAccountInput): Promise<void>
+ listAccounts?(input: ListAccountsInput): Promise<ListAccountsOutput>
+ createOnboarding(input: CreateOnboardingInput): Promise<LinkOutput>
+ createLoginLink?(input: CreateLoginLinkInput): Promise<LinkOutput>
+ createPayout(input: CreatePayoutInput): Promise<PayoutOutput>
+ reversePayout(input: ReversePayoutInput): Promise<PayoutOutput>
+ getWebhookActionAndData(payload: PayoutWebhookActionInput): Promise<PayoutWebhookResult>
}
diff --git a/packages/types/src/payout/service.ts b/packages/types/src/payout/service.ts
new file mode 100644
index 000000000..d6eccaf0f
--- /dev/null
+++ b/packages/types/src/payout/service.ts
@@ -0,0 +1,201 @@
+import {
+ BaseFilterable,
+ Context,
+ FindConfig,
+ IModuleService,
+ OperatorMap,
+} from "@medusajs/types"
+
+import {
+ OnboardingDTO,
+ PayoutAccountDTO,
+ PayoutAccountStatus,
+ PayoutDTO,
+ PayoutKycStatus,
+ PayoutReversalDTO,
+ PayoutStatus,
+ ResolvedPayoutModuleOptions,
+} from "./common"
+import {
+ CreateOnboardingDTO,
+ CreatePayoutAccountDTO,
+ CreatePayoutDTO,
+ CreatePayoutReversalDTO,
+ UpdatePayoutAccountDTO,
+ UpdatePayoutDTO,
+ UpdatePayoutReversalDTO,
+} from "./mutations"
+import { PayoutWebhookActionInput, PayoutWebhookResult } from "./provider"
+
+export interface FilterablePayoutAccountProps
+ extends BaseFilterable<FilterablePayoutAccountProps> {
+ id?: string | string[]
+ external_id?: string | string[]
+ status?: PayoutAccountStatus | PayoutAccountStatus[]
+ kyc_status?: PayoutKycStatus | PayoutKycStatus[]
+ payouts_enabled?: boolean
+ onboarding_token?: string
+ created_at?: OperatorMap<string>
+ updated_at?: OperatorMap<string>
+}
+
+export interface FilterableOnboardingProps
+ extends BaseFilterable<FilterableOnboardingProps> {
+ id?: string | string[]
+ account_id?: string | string[]
+}
+
+export interface FilterablePayoutProps
+ extends BaseFilterable<FilterablePayoutProps> {
+ id?: string | string[]
+ account_id?: string | string[]
+ order_id?: string | string[]
+ status?: PayoutStatus | PayoutStatus[]
+ created_at?: OperatorMap<string>
+ updated_at?: OperatorMap<string>
+}
+
+export interface FilterablePayoutReversalProps
+ extends BaseFilterable<FilterablePayoutReversalProps> {
+ id?: string | string[]
+ payout_id?: string | string[]
+ refund_id?: string | string[]
+ status?: PayoutStatus | PayoutStatus[]
+ created_at?: OperatorMap<string>
+ updated_at?: OperatorMap<string>
+}
+
+export interface IPayoutModuleService extends IModuleService {
+ getOptions(): ResolvedPayoutModuleOptions
+
+ retrievePayoutAccount(
+ id: string,
+ config?: FindConfig<PayoutAccountDTO>,
+ sharedContext?: Context
+ ): Promise<PayoutAccountDTO>
+ listPayoutAccounts(
+ filters?: FilterablePayoutAccountProps,
+ config?: FindConfig<PayoutAccountDTO>,
+ sharedContext?: Context
+ ): Promise<PayoutAccountDTO[]>
+ listAndCountPayoutAccounts(
+ filters?: FilterablePayoutAccountProps,
+ config?: FindConfig<PayoutAccountDTO>,
+ sharedContext?: Context
+ ): Promise<[PayoutAccountDTO[], number]>
+ /**
+ * Stores account rows without calling the provider, e.g. for an account
+ * that already exists there. Use `createPayoutAccount` to open one.
+ */
+ createPayoutAccounts(
+ data: Partial<PayoutAccountDTO>[],
+ sharedContext?: Context
+ ): Promise<PayoutAccountDTO[]>
+ createPayoutAccounts(
+ data: Partial<PayoutAccountDTO>,
+ sharedContext?: Context
+ ): Promise<PayoutAccountDTO>
+ updatePayoutAccounts(
+ data: UpdatePayoutAccountDTO[],
+ sharedContext?: Context
+ ): Promise<PayoutAccountDTO[]>
+ updatePayoutAccounts(
+ data: UpdatePayoutAccountDTO,
+ sharedContext?: Context
+ ): Promise<PayoutAccountDTO>
+ deletePayoutAccounts(ids: string | string[], sharedContext?: Context): Promise<void>
+
+ retrieveOnboarding(
+ id: string,
+ config?: FindConfig<OnboardingDTO>,
+ sharedContext?: Context
+ ): Promise<OnboardingDTO>
+ listOnboardings(
+ filters?: FilterableOnboardingProps,
+ config?: FindConfig<OnboardingDTO>,
+ sharedContext?: Context
+ ): Promise<OnboardingDTO[]>
+
+ retrievePayout(
+ id: string,
+ config?: FindConfig<PayoutDTO>,
+ sharedContext?: Context
+ ): Promise<PayoutDTO>
+ listPayouts(
+ filters?: FilterablePayoutProps,
+ config?: FindConfig<PayoutDTO>,
+ sharedContext?: Context
+ ): Promise<PayoutDTO[]>
+ listAndCountPayouts(
+ filters?: FilterablePayoutProps,
+ config?: FindConfig<PayoutDTO>,
+ sharedContext?: Context
+ ): Promise<[PayoutDTO[], number]>
+ createPayouts(data: CreatePayoutDTO[], sharedContext?: Context): Promise<PayoutDTO[]>
+ createPayouts(data: CreatePayoutDTO, sharedContext?: Context): Promise<PayoutDTO>
+ updatePayouts(data: UpdatePayoutDTO[], sharedContext?: Context): Promise<PayoutDTO[]>
+ updatePayouts(data: UpdatePayoutDTO, sharedContext?: Context): Promise<PayoutDTO>
+ deletePayouts(ids: string | string[], sharedContext?: Context): Promise<void>
+
+ retrievePayoutReversal(
+ id: string,
+ config?: FindConfig<PayoutReversalDTO>,
+ sharedContext?: Context
+ ): Promise<PayoutReversalDTO>
+ listPayoutReversals(
+ filters?: FilterablePayoutReversalProps,
+ config?: FindConfig<PayoutReversalDTO>,
+ sharedContext?: Context
+ ): Promise<PayoutReversalDTO[]>
+ listAndCountPayoutReversals(
+ filters?: FilterablePayoutReversalProps,
+ config?: FindConfig<PayoutReversalDTO>,
+ sharedContext?: Context
+ ): Promise<[PayoutReversalDTO[], number]>
+ createPayoutReversals(
+ data: CreatePayoutReversalDTO[],
+ sharedContext?: Context
+ ): Promise<PayoutReversalDTO[]>
+ createPayoutReversals(
+ data: CreatePayoutReversalDTO,
+ sharedContext?: Context
+ ): Promise<PayoutReversalDTO>
+ updatePayoutReversals(
+ data: UpdatePayoutReversalDTO[],
+ sharedContext?: Context
+ ): Promise<PayoutReversalDTO[]>
+ updatePayoutReversals(
+ data: UpdatePayoutReversalDTO,
+ sharedContext?: Context
+ ): Promise<PayoutReversalDTO>
+ deletePayoutReversals(ids: string | string[], sharedContext?: Context): Promise<void>
+
+ /**
+ * Opens the account at the provider and stores it.
+ */
+ createPayoutAccount(
+ data: CreatePayoutAccountDTO,
+ sharedContext?: Context
+ ): Promise<PayoutAccountDTO>
+ /**
+ * Pulls the account from the provider and stores its flags and KYC status.
+ */
+ syncPayoutAccount(id: string, sharedContext?: Context): Promise<PayoutAccountDTO>
+ /**
+ * Deletes the account at the provider, when the provider supports it, and
+ * then the stored row.
+ */
+ deletePayoutAccount(id: string, sharedContext?: Context): Promise<void>
+ /**
+ * Publishes the link the seller follows next: an onboarding link until the
+ * provider has their details, a dashboard login link afterwards.
+ */
+ createOnboarding(data: CreateOnboardingDTO, sharedContext?: Context): Promise<OnboardingDTO>
+ /**
+ * Sends a pending or failed payout to the provider. A provider error is
+ * recorded on the payout instead of thrown.
+ */
+ processPayout(id: string, sharedContext?: Context): Promise<PayoutDTO>
+ processPayoutReversal(id: string, sharedContext?: Context): Promise<PayoutReversalDTO>
+ getWebhookActionAndData(data: PayoutWebhookActionInput): Promise<PayoutWebhookResult>
+}
diff --git a/packages/vendor/src/components/layout/main-layout/main-layout.tsx b/packages/vendor/src/components/layout/main-layout/main-layout.tsx
index 022afe384..dff9664d3 100644
--- a/packages/vendor/src/components/layout/main-layout/main-layout.tsx
+++ b/packages/vendor/src/components/layout/main-layout/main-layout.tsx
@@ -144,6 +144,7 @@ const useSidebarRoutes = () => {
icon: Icon ? <Icon /> : undefined,
translationNs: item.translationNs,
group: item.group,
+ type: "extension" as const,
items: addNestedItems(item.path, visibleMenuItems),
};
});
diff --git a/packages/vendor/src/components/layout/nav-item/nav-item.tsx b/packages/vendor/src/components/layout/nav-item/nav-item.tsx
index d2a967243..32f81b42c 100644
--- a/packages/vendor/src/components/layout/nav-item/nav-item.tsx
+++ b/packages/vendor/src/components/layout/nav-item/nav-item.tsx
@@ -150,16 +150,14 @@ export const NavItem = ({
isNested?: boolean;
isSetting?: boolean;
}) => {
- if (["core", "setting"].includes(type)) {
- isActive = pathname.startsWith(to);
+ isActive = pathname.startsWith(to);
- if (isActive && !isNested && items?.length) {
- const nestedIsActive = items.some((item) =>
- pathname.startsWith(item.to),
- );
- if (nestedIsActive) {
- isActive = false;
- }
+ if (isActive && !isNested && items?.length) {
+ const nestedIsActive = items.some((item) =>
+ pathname.startsWith(item.to),
+ );
+ if (nestedIsActive) {
+ isActive = false;
}
}
@@ -169,7 +167,7 @@ export const NavItem = ({
[SETTING_NAV_LINK_CLASSES]: isSetting,
});
},
- [type, pathname, items],
+ [pathname, items],
);
const isSetting = type === "setting";
diff --git a/packages/vendor/src/extension-targets.d.ts b/packages/vendor/src/extension-targets.d.ts
index 5c68c0346..7c36b1d9d 100644
--- a/packages/vendor/src/extension-targets.d.ts
+++ b/packages/vendor/src/extension-targets.d.ts
@@ -75,6 +75,8 @@ declare module "@mercurjs/dashboard-sdk" {
"orders.list.before": true
"payouts.detail.main.after": true
"payouts.detail.main.before": true
+ "payouts.detail.side.after": true
+ "payouts.detail.side.before": true
"payouts.list.after": true
"payouts.list.before": true
"price-lists.detail.main.after": true
diff --git a/packages/vendor/src/hooks/api/index.ts b/packages/vendor/src/hooks/api/index.ts
index 41a4e3878..593166b71 100644
--- a/packages/vendor/src/hooks/api/index.ts
+++ b/packages/vendor/src/hooks/api/index.ts
@@ -15,6 +15,7 @@ export * from "./offer-conditions"
export * from "./offers"
export * from "./orders"
export * from "./payments"
+export * from "./payout-accounts"
export * from "./payouts"
export * from "./price-lists"
export * from "./product-attributes"
diff --git a/packages/vendor/src/hooks/api/payout-accounts.tsx b/packages/vendor/src/hooks/api/payout-accounts.tsx
new file mode 100644
index 000000000..174c69586
--- /dev/null
+++ b/packages/vendor/src/hooks/api/payout-accounts.tsx
@@ -0,0 +1,50 @@
+import { ClientError, InferClientOutput } from "@mercurjs/client";
+import {
+ UseMutationOptions,
+ UseQueryOptions,
+ useMutation,
+ useQuery,
+} from "@tanstack/react-query";
+
+import { sdk } from "../../lib/client";
+import { queryClient } from "../../lib/query-client";
+import { queryKeysFactory } from "../../lib/query-key-factory";
+
+const PAYOUT_ACCOUNTS_QUERY_KEY = "payout_accounts" as const;
+export const payoutAccountsQueryKeys = queryKeysFactory(PAYOUT_ACCOUNTS_QUERY_KEY);
+
+type MyPayoutAccountResponse = InferClientOutput<typeof sdk.vendor.payoutAccounts.me.query>;
+
+export const useMyPayoutAccount = (
+ options?: Omit<
+ UseQueryOptions<MyPayoutAccountResponse, ClientError, MyPayoutAccountResponse>,
+ "queryKey" | "queryFn"
+ >,
+) => {
+ const { data, ...rest } = useQuery({
+ queryKey: payoutAccountsQueryKeys.detail("me"),
+ queryFn: async () => sdk.vendor.payoutAccounts.me.query({}),
+ ...options,
+ });
+
+ return { ...data, ...rest };
+};
+
+type OnboardingResponse = InferClientOutput<
+ typeof sdk.vendor.payoutAccounts.$id.onboarding.mutate
+>;
+
+export const useCreatePayoutOnboarding = (
+ accountId: string,
+ options?: UseMutationOptions<OnboardingResponse, ClientError, void>,
+) => {
+ return useMutation({
+ mutationFn: async () =>
+ sdk.vendor.payoutAccounts.$id.onboarding.mutate({ $id: accountId }),
+ onSuccess: (data, variables, context) => {
+ queryClient.invalidateQueries({ queryKey: payoutAccountsQueryKeys.all });
+ options?.onSuccess?.(data, variables, context);
+ },
+ ...options,
+ });
+};
diff --git a/packages/vendor/src/hooks/table/columns/use-payout-table-columns.tsx b/packages/vendor/src/hooks/table/columns/use-payout-table-columns.tsx
index 70069c1b9..e3140f3fa 100644
--- a/packages/vendor/src/hooks/table/columns/use-payout-table-columns.tsx
+++ b/packages/vendor/src/hooks/table/columns/use-payout-table-columns.tsx
@@ -11,25 +11,10 @@ import {
DisplayIdCell,
} from "../../../components/table/table-cells/order/display-id-cell"
import { getStylizedAmount } from "../../../lib/money-amount-helpers"
+import { payoutStatusColor } from "../../../pages/payouts/_components/payout-status"
const columnHelper = createColumnHelper<PayoutDTO>()
-const payoutStatusColor = (status: string) => {
- switch (status) {
- case "paid":
- return "green"
- case "processing":
- return "orange"
- case "pending":
- return "grey"
- case "failed":
- case "canceled":
- return "red"
- default:
- return "grey"
- }
-}
-
export const usePayoutTableColumns = () => {
const { t } = useTranslation()
diff --git a/packages/vendor/src/hooks/table/filters/use-payout-table-filters.tsx b/packages/vendor/src/hooks/table/filters/use-payout-table-filters.tsx
index 6a55c7ba9..dce817758 100644
--- a/packages/vendor/src/hooks/table/filters/use-payout-table-filters.tsx
+++ b/packages/vendor/src/hooks/table/filters/use-payout-table-filters.tsx
@@ -2,6 +2,7 @@ import { useTranslation } from "react-i18next"
import { useMemo } from "react"
import type { Filter } from "../../../components/table/data-table"
+import { PAYOUT_STATUSES } from "../../../pages/payouts/_components/payout-status"
export const usePayoutTableFilters = (): Filter[] => {
const { t } = useTranslation()
@@ -14,13 +15,10 @@ export const usePayoutTableFilters = (): Filter[] => {
label: t("fields.status"),
type: "select",
multiple: true,
- options: [
- { label: t("payouts.status.pending"), value: "pending" },
- { label: t("payouts.status.processing"), value: "processing" },
- { label: t("payouts.status.paid"), value: "paid" },
- { label: t("payouts.status.failed"), value: "failed" },
- { label: t("payouts.status.canceled"), value: "canceled" },
- ],
+ options: PAYOUT_STATUSES.map((value) => ({
+ label: t(`payouts.status.${value}`),
+ value,
+ })),
}
filters.push(statusFilter)
diff --git a/packages/vendor/src/i18n/translations/$schema.json b/packages/vendor/src/i18n/translations/$schema.json
index 536635c2a..e6be16abe 100644
--- a/packages/vendor/src/i18n/translations/$schema.json
+++ b/packages/vendor/src/i18n/translations/$schema.json
@@ -12270,12 +12270,21 @@
"noRecords": {
"type": "string"
},
+ "order": {
+ "type": "string"
+ },
+ "statusReason": {
+ "type": "string"
+ },
"status": {
"type": "object",
"properties": {
"pending": {
"type": "string"
},
+ "on_hold": {
+ "type": "string"
+ },
"processing": {
"type": "string"
},
@@ -12285,16 +12294,287 @@
"failed": {
"type": "string"
},
- "canceled": {
+ "aborted": {
"type": "string"
}
},
"required": [
"pending",
+ "on_hold",
"processing",
"paid",
"failed",
- "canceled"
+ "aborted"
+ ],
+ "additionalProperties": false
+ },
+ "reversals": {
+ "type": "object",
+ "properties": {
+ "header": {
+ "type": "string"
+ },
+ "refund": {
+ "type": "string"
+ },
+ "noRecordsTitle": {
+ "type": "string"
+ },
+ "noRecordsMessage": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "header",
+ "refund",
+ "noRecordsTitle",
+ "noRecordsMessage"
+ ],
+ "additionalProperties": false
+ },
+ "account": {
+ "type": "object",
+ "properties": {
+ "header": {
+ "type": "string"
+ },
+ "empty": {
+ "type": "string"
+ },
+ "enabled": {
+ "type": "string"
+ },
+ "notEnabled": {
+ "type": "string"
+ },
+ "linkReady": {
+ "type": "string"
+ },
+ "onboardingPanel": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "title",
+ "description"
+ ],
+ "additionalProperties": false
+ },
+ "fields": {
+ "type": "object",
+ "properties": {
+ "payouts": {
+ "type": "string"
+ },
+ "kycStatus": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "payouts",
+ "kycStatus"
+ ],
+ "additionalProperties": false
+ },
+ "actions": {
+ "type": "object",
+ "properties": {
+ "continueOnboarding": {
+ "type": "string"
+ },
+ "openDashboard": {
+ "type": "string"
+ },
+ "refreshLink": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "continueOnboarding",
+ "openDashboard",
+ "refreshLink"
+ ],
+ "additionalProperties": false
+ },
+ "status": {
+ "type": "object",
+ "properties": {
+ "pending": {
+ "type": "string"
+ },
+ "active": {
+ "type": "string"
+ },
+ "restricted": {
+ "type": "string"
+ },
+ "rejected": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "pending",
+ "active",
+ "restricted",
+ "rejected"
+ ],
+ "additionalProperties": false
+ },
+ "kyc": {
+ "type": "object",
+ "properties": {
+ "pending_submission": {
+ "type": "string"
+ },
+ "pending_approval": {
+ "type": "string"
+ },
+ "approved": {
+ "type": "string"
+ },
+ "refused": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "pending_submission",
+ "pending_approval",
+ "approved",
+ "refused"
+ ],
+ "additionalProperties": false
+ },
+ "disabled": {
+ "type": "object",
+ "properties": {
+ "pastDue": {
+ "type": "string"
+ },
+ "pendingVerification": {
+ "type": "string"
+ },
+ "requirements": {
+ "type": "string"
+ },
+ "rejected": {
+ "type": "string"
+ },
+ "underReview": {
+ "type": "string"
+ },
+ "other": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "pastDue",
+ "pendingVerification",
+ "requirements",
+ "rejected",
+ "underReview",
+ "other"
+ ],
+ "additionalProperties": false
+ }
+ },
+ "required": [
+ "header",
+ "empty",
+ "enabled",
+ "notEnabled",
+ "linkReady",
+ "onboardingPanel",
+ "fields",
+ "actions",
+ "status",
+ "kyc",
+ "disabled"
+ ],
+ "additionalProperties": false
+ },
+ "references": {
+ "type": "object",
+ "properties": {
+ "header": {
+ "type": "string"
+ },
+ "empty": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "header",
+ "empty"
+ ],
+ "additionalProperties": false
+ },
+ "statusReasons": {
+ "type": "object",
+ "properties": {
+ "account_not_ready": {
+ "type": "string"
+ },
+ "account_payouts_disabled": {
+ "type": "string"
+ },
+ "order_not_ready": {
+ "type": "string"
+ },
+ "order_aborted": {
+ "type": "string"
+ },
+ "payment_not_ready": {
+ "type": "string"
+ },
+ "payment_failed": {
+ "type": "string"
+ },
+ "payment_canceled": {
+ "type": "string"
+ },
+ "payment_refunded": {
+ "type": "string"
+ },
+ "payout_not_ready": {
+ "type": "string"
+ },
+ "refund_aborted": {
+ "type": "string"
+ },
+ "refund_absorbed": {
+ "type": "string"
+ },
+ "invalid_amount": {
+ "type": "string"
+ },
+ "provider_error": {
+ "type": "string"
+ },
+ "other": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "account_not_ready",
+ "account_payouts_disabled",
+ "order_not_ready",
+ "order_aborted",
+ "payment_not_ready",
+ "payment_failed",
+ "payment_canceled",
+ "payment_refunded",
+ "payout_not_ready",
+ "refund_aborted",
+ "refund_absorbed",
+ "invalid_amount",
+ "provider_error",
+ "other"
],
"additionalProperties": false
}
@@ -12303,7 +12583,13 @@
"domain",
"payout",
"noRecords",
- "status"
+ "order",
+ "statusReason",
+ "status",
+ "reversals",
+ "account",
+ "references",
+ "statusReasons"
],
"additionalProperties": false
},
diff --git a/packages/vendor/src/i18n/translations/ar.json b/packages/vendor/src/i18n/translations/ar.json
index 294a3cfce..17a6f7c14 100644
--- a/packages/vendor/src/i18n/translations/ar.json
+++ b/packages/vendor/src/i18n/translations/ar.json
@@ -3868,8 +3868,7 @@
"pending": "قيد الانتظار",
"processing": "قيد المعالجة",
"paid": "مدفوع",
- "failed": "فشل",
- "canceled": "ملغى"
+ "failed": "فشل"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/bg.json b/packages/vendor/src/i18n/translations/bg.json
index ae3d332d6..e60f4c0e1 100644
--- a/packages/vendor/src/i18n/translations/bg.json
+++ b/packages/vendor/src/i18n/translations/bg.json
@@ -3868,8 +3868,7 @@
"pending": "В изчакване",
"processing": "В обработка",
"paid": "Изплатено",
- "failed": "Неуспешно",
- "canceled": "Анулирана"
+ "failed": "Неуспешно"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/bs.json b/packages/vendor/src/i18n/translations/bs.json
index bb9d88b5b..67bbd20a4 100644
--- a/packages/vendor/src/i18n/translations/bs.json
+++ b/packages/vendor/src/i18n/translations/bs.json
@@ -3866,8 +3866,7 @@
"pending": "Na čekanju",
"processing": "U obradi",
"paid": "Isplaćeno",
- "failed": "Neuspješno",
- "canceled": "Otkazano"
+ "failed": "Neuspješno"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/cs.json b/packages/vendor/src/i18n/translations/cs.json
index b1f521307..207351f60 100644
--- a/packages/vendor/src/i18n/translations/cs.json
+++ b/packages/vendor/src/i18n/translations/cs.json
@@ -3864,8 +3864,7 @@
"pending": "Čeká se",
"processing": "Zpracovává se",
"paid": "Vyplaceno",
- "failed": "Selhalo",
- "canceled": "Zrušeno"
+ "failed": "Selhalo"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/de.json b/packages/vendor/src/i18n/translations/de.json
index cb10125b7..5bdfe8c67 100644
--- a/packages/vendor/src/i18n/translations/de.json
+++ b/packages/vendor/src/i18n/translations/de.json
@@ -3869,8 +3869,7 @@
"pending": "Ausstehend",
"processing": "In Bearbeitung",
"paid": "Bezahlt",
- "failed": "Fehlgeschlagen",
- "canceled": "Abgebrochen"
+ "failed": "Fehlgeschlagen"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/el.json b/packages/vendor/src/i18n/translations/el.json
index ed124e114..e81c68e16 100644
--- a/packages/vendor/src/i18n/translations/el.json
+++ b/packages/vendor/src/i18n/translations/el.json
@@ -3868,8 +3868,7 @@
"pending": "Σε εκκρεμότητα",
"processing": "Σε επεξεργασία",
"paid": "Πληρώθηκε",
- "failed": "Απέτυχε",
- "canceled": "Ακυρώθηκε"
+ "failed": "Απέτυχε"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/en.json b/packages/vendor/src/i18n/translations/en.json
index 031c42474..e31aa3ebd 100644
--- a/packages/vendor/src/i18n/translations/en.json
+++ b/packages/vendor/src/i18n/translations/en.json
@@ -3068,12 +3068,81 @@
"domain": "Payouts",
"payout": "Payout",
"noRecords": "No payouts found",
+ "order": "Order",
+ "statusReason": "Reason",
"status": {
"pending": "Pending",
+ "on_hold": "On hold",
"processing": "Processing",
"paid": "Paid",
"failed": "Failed",
- "canceled": "Canceled"
+ "aborted": "Aborted"
+ },
+ "reversals": {
+ "header": "Reversals",
+ "refund": "Refund",
+ "noRecordsTitle": "No reversals",
+ "noRecordsMessage": "Refunds on this order have not taken anything back from your payout."
+ },
+ "account": {
+ "header": "Payout account",
+ "empty": "Your payout account is being set up. It appears here once the payout provider has created it.",
+ "enabled": "Enabled",
+ "notEnabled": "Not enabled yet",
+ "linkReady": "A new onboarding link is ready.",
+ "onboardingPanel": {
+ "title": "Onboarding in progress",
+ "description": "Finish setting up your payout details to start getting paid."
+ },
+ "fields": {
+ "payouts": "Payouts",
+ "kycStatus": "KYC status"
+ },
+ "actions": {
+ "continueOnboarding": "Continue onboarding",
+ "openDashboard": "Manage payout details",
+ "refreshLink": "Refresh onboarding link"
+ },
+ "status": {
+ "pending": "Pending",
+ "active": "Active",
+ "restricted": "Restricted",
+ "rejected": "Rejected"
+ },
+ "kyc": {
+ "pending_submission": "Pending submission",
+ "pending_approval": "Pending approval",
+ "approved": "Approved",
+ "refused": "Refused"
+ },
+ "disabled": {
+ "pastDue": "Payouts are paused: the payout provider is waiting for overdue information.",
+ "pendingVerification": "Payouts are paused while the payout provider verifies your information.",
+ "requirements": "Payouts are paused until you finish onboarding with the payout provider.",
+ "rejected": "The payout provider rejected this account. Contact the marketplace.",
+ "underReview": "The payout provider is reviewing your account. Payouts are paused until the review ends.",
+ "other": "The payout provider has paused payouts for this account."
+ }
+ },
+ "references": {
+ "header": "References",
+ "empty": "This payout is not linked to an order."
+ },
+ "statusReasons": {
+ "account_not_ready": "Your payout account cannot receive payouts yet.",
+ "account_payouts_disabled": "Payouts are disabled on your payout account.",
+ "order_not_ready": "The order is not fulfilled yet.",
+ "order_aborted": "The order was canceled.",
+ "payment_not_ready": "The order's payment is not captured yet.",
+ "payment_failed": "The order's payment failed.",
+ "payment_canceled": "The order's payment was canceled.",
+ "payment_refunded": "The order's payment was refunded in full.",
+ "payout_not_ready": "The payout for this order has not been sent yet.",
+ "refund_aborted": "The refund was canceled.",
+ "refund_absorbed": "The refund was deducted before the payout was sent.",
+ "invalid_amount": "The amount to pay out is not valid.",
+ "provider_error": "The payout provider returned an error.",
+ "other": "This payout needs attention."
}
},
"reviews": {
diff --git a/packages/vendor/src/i18n/translations/es.json b/packages/vendor/src/i18n/translations/es.json
index 45ab48621..259d4f130 100644
--- a/packages/vendor/src/i18n/translations/es.json
+++ b/packages/vendor/src/i18n/translations/es.json
@@ -3927,8 +3927,7 @@
"pending": "Pendiente",
"processing": "Procesando",
"paid": "Pagado",
- "failed": "Fallido",
- "canceled": "Cancelado"
+ "failed": "Fallido"
}
},
"refundReasons": {
diff --git a/packages/vendor/src/i18n/translations/fa.json b/packages/vendor/src/i18n/translations/fa.json
index 9fb851a05..8d4f2c296 100644
--- a/packages/vendor/src/i18n/translations/fa.json
+++ b/packages/vendor/src/i18n/translations/fa.json
@@ -3868,8 +3868,7 @@
"pending": "در انتظار",
"processing": "در حال پردازش",
"paid": "پرداخت‌شده",
- "failed": "ناموفق",
- "canceled": "لغو شده"
+ "failed": "ناموفق"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/fr.json b/packages/vendor/src/i18n/translations/fr.json
index c3a17d2ee..bb54ec7cd 100644
--- a/packages/vendor/src/i18n/translations/fr.json
+++ b/packages/vendor/src/i18n/translations/fr.json
@@ -3869,8 +3869,7 @@
"pending": "En attente",
"processing": "En cours de traitement",
"paid": "Payé",
- "failed": "Échec",
- "canceled": "Annulé"
+ "failed": "Échec"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/he.json b/packages/vendor/src/i18n/translations/he.json
index dfdbcf5b8..5f0ca5646 100644
--- a/packages/vendor/src/i18n/translations/he.json
+++ b/packages/vendor/src/i18n/translations/he.json
@@ -3864,8 +3864,7 @@
"pending": "ממתין",
"processing": "בעיבוד",
"paid": "שולם",
- "failed": "נכשל",
- "canceled": "בוטל"
+ "failed": "נכשל"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/hu.json b/packages/vendor/src/i18n/translations/hu.json
index 35938f3a7..dbb3fada3 100644
--- a/packages/vendor/src/i18n/translations/hu.json
+++ b/packages/vendor/src/i18n/translations/hu.json
@@ -3867,8 +3867,7 @@
"pending": "Függőben",
"processing": "Feldolgozás alatt",
"paid": "Kifizetve",
- "failed": "Sikertelen",
- "canceled": "Törölt"
+ "failed": "Sikertelen"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/id.json b/packages/vendor/src/i18n/translations/id.json
index d3d63d60a..bb5b2ba17 100644
--- a/packages/vendor/src/i18n/translations/id.json
+++ b/packages/vendor/src/i18n/translations/id.json
@@ -3864,8 +3864,7 @@
"pending": "Tertunda",
"processing": "Sedang diproses",
"paid": "Dibayar",
- "failed": "Gagal",
- "canceled": "Dibatalkan"
+ "failed": "Gagal"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/it.json b/packages/vendor/src/i18n/translations/it.json
index 5e641b952..0467726f3 100644
--- a/packages/vendor/src/i18n/translations/it.json
+++ b/packages/vendor/src/i18n/translations/it.json
@@ -3869,8 +3869,7 @@
"pending": "In attesa",
"processing": "In elaborazione",
"paid": "Pagato",
- "failed": "Fallito",
- "canceled": "Annullato"
+ "failed": "Fallito"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/ja.json b/packages/vendor/src/i18n/translations/ja.json
index 54cc67468..ea4758e42 100644
--- a/packages/vendor/src/i18n/translations/ja.json
+++ b/packages/vendor/src/i18n/translations/ja.json
@@ -3869,8 +3869,7 @@
"pending": "保留中",
"processing": "処理中",
"paid": "支払い済み",
- "failed": "失敗",
- "canceled": "キャンセル済み"
+ "failed": "失敗"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/ko.json b/packages/vendor/src/i18n/translations/ko.json
index 2aa032762..128ed610e 100644
--- a/packages/vendor/src/i18n/translations/ko.json
+++ b/packages/vendor/src/i18n/translations/ko.json
@@ -3864,8 +3864,7 @@
"pending": "대기 중",
"processing": "처리 중",
"paid": "지급 완료",
- "failed": "실패",
- "canceled": "취소됨"
+ "failed": "실패"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/lt.json b/packages/vendor/src/i18n/translations/lt.json
index 22a448796..87438b780 100644
--- a/packages/vendor/src/i18n/translations/lt.json
+++ b/packages/vendor/src/i18n/translations/lt.json
@@ -3868,8 +3868,7 @@
"pending": "Laukia",
"processing": "Apdorojama",
"paid": "Apmokėta",
- "failed": "Nepavyko",
- "canceled": "Atšauktas"
+ "failed": "Nepavyko"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/mk.json b/packages/vendor/src/i18n/translations/mk.json
index 671124181..5c84e7f08 100644
--- a/packages/vendor/src/i18n/translations/mk.json
+++ b/packages/vendor/src/i18n/translations/mk.json
@@ -3868,8 +3868,7 @@
"pending": "Во очекување",
"processing": "Во обработка",
"paid": "Платено",
- "failed": "Не успеа",
- "canceled": "Откажано"
+ "failed": "Не успеа"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/mn.json b/packages/vendor/src/i18n/translations/mn.json
index 26684b9f5..f2dce0854 100644
--- a/packages/vendor/src/i18n/translations/mn.json
+++ b/packages/vendor/src/i18n/translations/mn.json
@@ -3868,8 +3868,7 @@
"pending": "Хүлээгдэж буй",
"processing": "Боловсруулж байна",
"paid": "Төлөгдсөн",
- "failed": "Амжилтгүй",
- "canceled": "Цуцлагдсан"
+ "failed": "Амжилтгүй"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/nl.json b/packages/vendor/src/i18n/translations/nl.json
index b275502a0..cec6c4ea6 100644
--- a/packages/vendor/src/i18n/translations/nl.json
+++ b/packages/vendor/src/i18n/translations/nl.json
@@ -3867,8 +3867,7 @@
"pending": "In behandeling",
"processing": "Wordt verwerkt",
"paid": "Betaald",
- "failed": "Mislukt",
- "canceled": "Geannuleerd"
+ "failed": "Mislukt"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/pl.json b/packages/vendor/src/i18n/translations/pl.json
index ced03be71..6f3da65c8 100644
--- a/packages/vendor/src/i18n/translations/pl.json
+++ b/packages/vendor/src/i18n/translations/pl.json
@@ -3033,8 +3033,7 @@
"pending": "Oczekuje",
"processing": "W trakcie przetwarzania",
"paid": "Wypłacono",
- "failed": "Nieudana",
- "canceled": "Anulowana"
+ "failed": "Nieudana"
}
},
"profile": {
diff --git a/packages/vendor/src/i18n/translations/ptBR.json b/packages/vendor/src/i18n/translations/ptBR.json
index f5538e7f8..b8803e819 100644
--- a/packages/vendor/src/i18n/translations/ptBR.json
+++ b/packages/vendor/src/i18n/translations/ptBR.json
@@ -3869,8 +3869,7 @@
"pending": "Pendente",
"processing": "Processando",
"paid": "Pago",
- "failed": "Falhou",
- "canceled": "Cancelado"
+ "failed": "Falhou"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/ptPT.json b/packages/vendor/src/i18n/translations/ptPT.json
index b1f11fe12..c78d1c4ad 100644
--- a/packages/vendor/src/i18n/translations/ptPT.json
+++ b/packages/vendor/src/i18n/translations/ptPT.json
@@ -3955,8 +3955,7 @@
"pending": "Pendente",
"processing": "Em processamento",
"paid": "Pago",
- "failed": "Falhou",
- "canceled": "Cancelada"
+ "failed": "Falhou"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/ro.json b/packages/vendor/src/i18n/translations/ro.json
index f7adc96cb..0bc8945e2 100644
--- a/packages/vendor/src/i18n/translations/ro.json
+++ b/packages/vendor/src/i18n/translations/ro.json
@@ -3868,8 +3868,7 @@
"pending": "În așteptare",
"processing": "În procesare",
"paid": "Plătit",
- "failed": "A eșuat",
- "canceled": "Anulat"
+ "failed": "A eșuat"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/ru.json b/packages/vendor/src/i18n/translations/ru.json
index c48c7cc93..aaf6ead03 100644
--- a/packages/vendor/src/i18n/translations/ru.json
+++ b/packages/vendor/src/i18n/translations/ru.json
@@ -3868,8 +3868,7 @@
"pending": "В обработке",
"processing": "В обработке",
"paid": "Выплачено",
- "failed": "Неудача",
- "canceled": "Отменен"
+ "failed": "Неудача"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/th.json b/packages/vendor/src/i18n/translations/th.json
index a2fcecb50..879341fc5 100644
--- a/packages/vendor/src/i18n/translations/th.json
+++ b/packages/vendor/src/i18n/translations/th.json
@@ -3869,8 +3869,7 @@
"pending": "รอดำเนินการ",
"processing": "กำลังดำเนินการ",
"paid": "จ่ายแล้ว",
- "failed": "ล้มเหลว",
- "canceled": "ยกเลิก"
+ "failed": "ล้มเหลว"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/tr.json b/packages/vendor/src/i18n/translations/tr.json
index afb9f0985..531d14f5d 100644
--- a/packages/vendor/src/i18n/translations/tr.json
+++ b/packages/vendor/src/i18n/translations/tr.json
@@ -3868,8 +3868,7 @@
"pending": "Beklemede",
"processing": "İşleniyor",
"paid": "Ödendi",
- "failed": "Başarısız",
- "canceled": "İptal edildi"
+ "failed": "Başarısız"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/uk.json b/packages/vendor/src/i18n/translations/uk.json
index 7819288d1..d64f69681 100644
--- a/packages/vendor/src/i18n/translations/uk.json
+++ b/packages/vendor/src/i18n/translations/uk.json
@@ -3869,8 +3869,7 @@
"pending": "Очікує",
"processing": "Обробляється",
"paid": "Виплачено",
- "failed": "Не вдалося",
- "canceled": "Скасовано"
+ "failed": "Не вдалося"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/vi.json b/packages/vendor/src/i18n/translations/vi.json
index 667c2f082..4a213d039 100644
--- a/packages/vendor/src/i18n/translations/vi.json
+++ b/packages/vendor/src/i18n/translations/vi.json
@@ -3864,8 +3864,7 @@
"pending": "Đang chờ xử lý",
"processing": "Đang xử lý",
"paid": "Đã thanh toán",
- "failed": "Thất bại",
- "canceled": "Đã hủy"
+ "failed": "Thất bại"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/zhCN.json b/packages/vendor/src/i18n/translations/zhCN.json
index 23803b23b..87ff88a6e 100644
--- a/packages/vendor/src/i18n/translations/zhCN.json
+++ b/packages/vendor/src/i18n/translations/zhCN.json
@@ -3864,8 +3864,7 @@
"pending": "处理中",
"processing": "处理中",
"paid": "已支付",
- "failed": "失败",
- "canceled": "已取消"
+ "failed": "失败"
}
},
"translations": {
diff --git a/packages/vendor/src/i18n/translations/zhTW.json b/packages/vendor/src/i18n/translations/zhTW.json
index 17d7d737c..313d848c4 100644
--- a/packages/vendor/src/i18n/translations/zhTW.json
+++ b/packages/vendor/src/i18n/translations/zhTW.json
@@ -3955,8 +3955,7 @@
"pending": "處理中",
"processing": "處理中",
"paid": "已支付",
- "failed": "失敗",
- "canceled": "已取消"
+ "failed": "失敗"
}
},
"translations": {
diff --git a/packages/vendor/src/pages/payouts/[id]/_components/payout-general-section.tsx b/packages/vendor/src/pages/payouts/[id]/_components/payout-general-section.tsx
index 20186c0de..39c8806d8 100644
--- a/packages/vendor/src/pages/payouts/[id]/_components/payout-general-section.tsx
+++ b/packages/vendor/src/pages/payouts/[id]/_components/payout-general-section.tsx
@@ -1,96 +1,48 @@
-import { Container, Heading, StatusBadge, Text } from "@medusajs/ui";
+import { Container, Heading, StatusBadge } from "@medusajs/ui";
import { PayoutDTO } from "@mercurjs/types";
import { DisplayExtensionZone, DisplayField } from "@mercurjs/dashboard-shared";
import { useTranslation } from "react-i18next";
+
+import { SectionRow } from "@components/common/section";
+import { useDate } from "@hooks/use-date";
import { getStylizedAmount } from "@lib/money-amount-helpers";
-const GENERAL_FIELD_IDS = [
- "display_id",
- "status",
- "amount",
- "created_at",
- "updated_at",
-];
+import { payoutStatusColor } from "../../_components/payout-status";
-const payoutStatusColor = (status: string) => {
- switch (status) {
- case "paid":
- return "green";
- case "processing":
- return "orange";
- case "pending":
- return "grey";
- case "failed":
- case "canceled":
- return "red";
- default:
- return "grey";
- }
-};
+const GENERAL_FIELD_IDS = ["amount", "status", "display_id", "created_at", "updated_at"];
export const PayoutGeneralSection = ({ payout }: { payout: PayoutDTO }) => {
const { t } = useTranslation();
+ const { getFullDate } = useDate();
- const statusText = t(`payouts.status.${payout.status}`, {
- defaultValue:
- payout.status.charAt(0).toUpperCase() + payout.status.slice(1),
- });
+ const formatDate = (value: Date | string | null | undefined) =>
+ value ? getFullDate({ date: value, includeTime: true }) : "-";
return (
- <Container className="divide-y p-0">
+ <Container className="divide-y p-0" data-testid="payout-general-section">
<div className="flex items-center justify-between px-6 py-4">
- <DisplayField model="payout" zone="general" id="display_id" data={payout}>
- <Heading>#{payout.display_id}</Heading>
+ <DisplayField model="payout" zone="general" id="amount" data={payout}>
+ <Heading data-testid="payout-general-section-heading">
+ {getStylizedAmount(Number(payout.amount), payout.currency_code)}
+ </Heading>
+ </DisplayField>
+ <DisplayField model="payout" zone="general" id="status" data={payout}>
+ <StatusBadge
+ color={payoutStatusColor(payout.status)}
+ data-testid="payout-general-section-status-badge"
+ >
+ {t(`payouts.status.${payout.status}`)}
+ </StatusBadge>
</DisplayField>
- <div className="flex items-center gap-x-2">
- <DisplayField model="payout" zone="general" id="status" data={payout}>
- <StatusBadge color={payoutStatusColor(payout.status)}>
- {statusText}
- </StatusBadge>
- </DisplayField>
- </div>
</div>
- <DisplayField model="payout" zone="general" id="amount" data={payout}>
- <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
- <Text size="small" leading="compact" weight="plus">
- {t("fields.amount")}
- </Text>
- <Text size="small" leading="compact">
- {getStylizedAmount(payout.amount as number, payout.currency_code)}
- </Text>
- </div>
+ <DisplayField model="payout" zone="general" id="display_id" data={payout}>
+ <SectionRow title={t("fields.id")} value={`#${payout.display_id}`} />
</DisplayField>
<DisplayField model="payout" zone="general" id="created_at" data={payout}>
- <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
- <Text size="small" leading="compact" weight="plus">
- {t("fields.createdAt")}
- </Text>
- <Text size="small" leading="compact">
- {new Date(payout.created_at).toLocaleDateString(undefined, {
- year: "numeric",
- month: "long",
- day: "numeric",
- hour: "2-digit",
- minute: "2-digit",
- })}
- </Text>
- </div>
+ <SectionRow title={t("fields.createdAt")} value={formatDate(payout.created_at)} />
</DisplayField>
<DisplayField model="payout" zone="general" id="updated_at" data={payout}>
- <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
- <Text size="small" leading="compact" weight="plus">
- {t("fields.updatedAt")}
- </Text>
- <Text size="small" leading="compact">
- {new Date(payout.updated_at).toLocaleDateString(undefined, {
- year: "numeric",
- month: "long",
- day: "numeric",
- hour: "2-digit",
- minute: "2-digit",
- })}
- </Text>
- </div>
+ <SectionRow title={t("fields.updatedAt")} value={formatDate(payout.updated_at)} />
</DisplayField>
<DisplayExtensionZone
model="payout"
diff --git a/packages/vendor/src/pages/payouts/[id]/_components/payout-references-section.tsx b/packages/vendor/src/pages/payouts/[id]/_components/payout-references-section.tsx
new file mode 100644
index 000000000..28f6873bd
--- /dev/null
+++ b/packages/vendor/src/pages/payouts/[id]/_components/payout-references-section.tsx
@@ -0,0 +1,37 @@
+import { ShoppingCart } from "@medusajs/icons";
+import { Container, Heading, Text } from "@medusajs/ui";
+import { PayoutDTO } from "@mercurjs/types";
+import { useTranslation } from "react-i18next";
+
+import { SidebarLink } from "@components/common/sidebar-link/sidebar-link";
+
+type PayoutWithOrder = PayoutDTO & {
+ order?: { id: string; display_id: number } | null;
+};
+
+export const PayoutReferencesSection = ({ payout }: { payout: PayoutWithOrder }) => {
+ const { t } = useTranslation();
+
+ return (
+ <Container className="p-0" data-testid="payout-references-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("payouts.references.header")}</Heading>
+ </div>
+ {payout.order_id ? (
+ <SidebarLink
+ to={`/orders/${payout.order_id}`}
+ labelKey={t("payouts.order")}
+ descriptionKey={payout.order?.display_id ? `#${payout.order.display_id}` : payout.order_id}
+ icon={<ShoppingCart />}
+ dataTestid="payout-reference-order"
+ />
+ ) : (
+ <div className="border-t px-6 py-4">
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ {t("payouts.references.empty")}
+ </Text>
+ </div>
+ )}
+ </Container>
+ );
+};
diff --git a/packages/vendor/src/pages/payouts/[id]/_components/payout-reversals-section.tsx b/packages/vendor/src/pages/payouts/[id]/_components/payout-reversals-section.tsx
new file mode 100644
index 000000000..2d3f2fafc
--- /dev/null
+++ b/packages/vendor/src/pages/payouts/[id]/_components/payout-reversals-section.tsx
@@ -0,0 +1,92 @@
+import { ExclamationCircle } from "@medusajs/icons";
+import { Container, Heading, Tooltip } from "@medusajs/ui";
+import { PayoutDTO, PayoutReversalDTO } from "@mercurjs/types";
+import { createColumnHelper } from "@tanstack/react-table";
+import { useMemo } from "react";
+import { useTranslation } from "react-i18next";
+
+import { NoRecords } from "@components/common/empty-table-content";
+import { _DataTable } from "@components/table/data-table/data-table";
+import { DateCell } from "@components/table/table-cells/common/date-cell";
+import { MoneyAmountCell } from "@components/table/table-cells/common/money-amount-cell";
+import { StatusCell } from "@components/table/table-cells/common/status-cell";
+import { TextCell } from "@components/table/table-cells/common/text-cell";
+import { useDataTable } from "@hooks/use-data-table";
+
+import { getPayoutStatusReasonLabel, payoutStatusColor } from "../../_components/payout-status";
+
+const columnHelper = createColumnHelper<PayoutReversalDTO>();
+
+export const PayoutReversalsSection = ({ payout }: { payout: PayoutDTO }) => {
+ const { t } = useTranslation();
+
+ const reversals = useMemo(() => payout.reversals ?? [], [payout.reversals]);
+
+ const columns = useMemo(
+ () => [
+ columnHelper.accessor("created_at", {
+ header: () => t("fields.date"),
+ cell: ({ getValue }) => <DateCell date={getValue()} />,
+ }),
+ columnHelper.accessor("refund_id", {
+ header: () => t("payouts.reversals.refund"),
+ cell: ({ getValue }) => <TextCell text={getValue() ?? "-"} />,
+ }),
+ columnHelper.accessor("amount", {
+ header: () => t("fields.amount"),
+ cell: ({ getValue }) => (
+ <MoneyAmountCell currencyCode={payout.currency_code} amount={Number(getValue())} />
+ ),
+ }),
+ columnHelper.accessor("status", {
+ header: () => t("fields.status"),
+ cell: ({ getValue, row }) => {
+ const reason = row.original.status_reason;
+ return (
+ <div className="flex h-full w-full items-center gap-x-2">
+ <StatusCell color={payoutStatusColor(getValue())}>
+ {t(`payouts.status.${getValue()}`)}
+ </StatusCell>
+ {reason && (
+ <Tooltip content={getPayoutStatusReasonLabel(reason, t)}>
+ <ExclamationCircle className="text-ui-tag-orange-icon shrink-0" />
+ </Tooltip>
+ )}
+ </div>
+ );
+ },
+ }),
+ ],
+ [t, payout.currency_code],
+ );
+
+ const { table } = useDataTable({
+ data: reversals,
+ count: reversals.length,
+ columns,
+ getRowId: (row) => row.id,
+ pageSize: Math.max(reversals.length, 1),
+ });
+
+ return (
+ <Container className="divide-y p-0" data-testid="payout-reversals-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("payouts.reversals.header")}</Heading>
+ </div>
+ {reversals.length > 0 ? (
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={Math.max(reversals.length, 1)}
+ count={reversals.length}
+ />
+ ) : (
+ <NoRecords
+ className="border-t"
+ title={t("payouts.reversals.noRecordsTitle")}
+ message={t("payouts.reversals.noRecordsMessage")}
+ />
+ )}
+ </Container>
+ );
+};
diff --git a/packages/vendor/src/pages/payouts/[id]/_components/payout-status-alert.tsx b/packages/vendor/src/pages/payouts/[id]/_components/payout-status-alert.tsx
new file mode 100644
index 000000000..2e935dd10
--- /dev/null
+++ b/packages/vendor/src/pages/payouts/[id]/_components/payout-status-alert.tsx
@@ -0,0 +1,31 @@
+import { Alert } from "@medusajs/ui";
+import { PayoutDTO } from "@mercurjs/types";
+import { useTranslation } from "react-i18next";
+
+import { getPayoutStatusReasonLabel } from "../../_components/payout-status";
+
+const variantForStatus = (status: string) => {
+ switch (status) {
+ case "failed":
+ case "aborted":
+ return "error";
+ case "on_hold":
+ return "warning";
+ default:
+ return "info";
+ }
+};
+
+export const PayoutStatusAlert = ({ payout }: { payout: PayoutDTO }) => {
+ const { t } = useTranslation();
+
+ if (!payout.status_reason) {
+ return null;
+ }
+
+ return (
+ <Alert variant={variantForStatus(payout.status)} data-testid="payout-status-alert">
+ {getPayoutStatusReasonLabel(payout.status_reason, t)}
+ </Alert>
+ );
+};
diff --git a/packages/vendor/src/pages/payouts/[id]/payout-detail-page.tsx b/packages/vendor/src/pages/payouts/[id]/payout-detail-page.tsx
index 790342fd4..ed6aa4053 100644
--- a/packages/vendor/src/pages/payouts/[id]/payout-detail-page.tsx
+++ b/packages/vendor/src/pages/payouts/[id]/payout-detail-page.tsx
@@ -1,12 +1,15 @@
import { Children, ReactNode } from "react";
import { useParams } from "react-router-dom";
-import { SingleColumnPageSkeleton } from "@components/common/skeleton";
-import { SingleColumnPage } from "@components/layout/pages";
+import { TwoColumnPageSkeleton } from "@components/common/skeleton";
+import { TwoColumnPage } from "@components/layout/pages";
import { WidgetZone } from "@mercurjs/dashboard-shared";
import { usePayout } from "@hooks/api/payouts";
import { PayoutGeneralSection } from "./_components/payout-general-section";
+import { PayoutReferencesSection } from "./_components/payout-references-section";
+import { PayoutReversalsSection } from "./_components/payout-reversals-section";
+import { PayoutStatusAlert } from "./_components/payout-status-alert";
const Root = ({ children }: { children?: ReactNode }) => {
const { id } = useParams();
@@ -14,26 +17,40 @@ const Root = ({ children }: { children?: ReactNode }) => {
const { payout, isLoading, isError, error } = usePayout(id!);
if (isLoading || !payout) {
- return <SingleColumnPageSkeleton sections={1} />;
+ return <TwoColumnPageSkeleton mainSections={2} sidebarSections={1} showJSON />;
}
if (isError) {
throw error;
}
- return (
- <SingleColumnPage showMetadata>
- {Children.count(children) > 0 ? (
- children
- ) : (
+ return Children.count(children) > 0 ? (
+ <TwoColumnPage data={payout} showJSON showMetadata>
+ {children}
+ </TwoColumnPage>
+ ) : (
+ <TwoColumnPage data={payout} showJSON showMetadata>
+ <TwoColumnPage.Main>
<WidgetZone id="payouts.detail.main" data={payout}>
+ <PayoutStatusAlert payout={payout} />
<PayoutGeneralSection payout={payout} />
+ <PayoutReversalsSection payout={payout} />
</WidgetZone>
- )}
- </SingleColumnPage>
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <WidgetZone id="payouts.detail.side" data={payout}>
+ <PayoutReferencesSection payout={payout} />
+ </WidgetZone>
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
);
};
export const PayoutDetailPage = Object.assign(Root, {
- GeneralSection: PayoutGeneralSection,
+ Main: TwoColumnPage.Main,
+ Sidebar: TwoColumnPage.Sidebar,
+ MainStatusAlert: PayoutStatusAlert,
+ MainGeneralSection: PayoutGeneralSection,
+ MainReversalsSection: PayoutReversalsSection,
+ SidebarReferencesSection: PayoutReferencesSection,
});
diff --git a/packages/vendor/src/pages/payouts/_components/active-payout-onboarding-section.tsx b/packages/vendor/src/pages/payouts/_components/active-payout-onboarding-section.tsx
new file mode 100644
index 000000000..e5243d102
--- /dev/null
+++ b/packages/vendor/src/pages/payouts/_components/active-payout-onboarding-section.tsx
@@ -0,0 +1,93 @@
+import { ExclamationCircleSolid } from "@medusajs/icons";
+import { Button, Container, Heading, Text, toast } from "@medusajs/ui";
+import { useTranslation } from "react-i18next";
+
+import { PermissionAction } from "@mercurjs/dashboard-shared";
+import { useCreatePayoutOnboarding, useMyPayoutAccount } from "@hooks/api/payout-accounts";
+
+type OnboardingLink = { url?: string; kind?: string } | null | undefined;
+
+type OnboardingAccount = {
+ status: string;
+ details_submitted: boolean;
+};
+
+export const isOnboardingPending = (account: OnboardingAccount) =>
+ account.status === "pending" && !account.details_submitted;
+
+const openLink = (url: string) => {
+ window.open(url, "_blank", "noreferrer");
+};
+
+export const ActivePayoutOnboardingSection = () => {
+ const { t } = useTranslation();
+ const { payout_account: account } = useMyPayoutAccount();
+ const onboarding = useCreatePayoutOnboarding(account?.id ?? "");
+
+ if (!account || !isOnboardingPending(account)) {
+ return null;
+ }
+
+ const link = account.onboarding?.data as OnboardingLink;
+
+ const onContinue = async () => {
+ if (link?.url && link.kind !== "login") {
+ openLink(link.url);
+ return;
+ }
+
+ await onboarding.mutateAsync(undefined, {
+ onSuccess: ({ onboarding }) => {
+ const url = (onboarding.data as OnboardingLink)?.url;
+ if (url) {
+ openLink(url);
+ } else {
+ toast.success(t("payouts.account.linkReady"));
+ }
+ },
+ onError: (error) => {
+ toast.error(error.message);
+ },
+ });
+ };
+
+ return (
+ <div
+ style={{
+ background:
+ "repeating-linear-gradient(-45deg, rgb(212, 212, 216, 0.15), rgb(212, 212, 216,.15) 10px, transparent 10px, transparent 20px)",
+ }}
+ className="-m-4 mb-1 border-b border-l p-4"
+ data-testid="active-payout-onboarding-section"
+ >
+ <Container className="flex items-center justify-between p-0">
+ <div className="flex w-full flex-row justify-between">
+ <div>
+ <div className="mb-2 flex items-center gap-2 px-6 pt-4">
+ <ExclamationCircleSolid className="text-blue-500" />
+ <Heading level="h2">{t("payouts.account.onboardingPanel.title")}</Heading>
+ </div>
+
+ <div className="gap-2 px-6 pb-4">
+ <Text>{t("payouts.account.onboardingPanel.description")}</Text>
+ </div>
+ </div>
+
+ <div className="flex items-center justify-end gap-x-2 rounded-b-xl px-4 py-4">
+ <PermissionAction permission="payouts:edit">
+ <Button
+ size="small"
+ variant="secondary"
+ onClick={onContinue}
+ isLoading={onboarding.isPending}
+ data-testid="active-payout-onboarding-continue"
+ >
+ {t("payouts.account.actions.continueOnboarding")}
+ </Button>
+ </PermissionAction>
+ </div>
+ </div>
+ </Container>
+ </div>
+ );
+};
diff --git a/packages/vendor/src/pages/payouts/_components/payout-account-section.tsx b/packages/vendor/src/pages/payouts/_components/payout-account-section.tsx
new file mode 100644
index 000000000..bbd230d26
--- /dev/null
+++ b/packages/vendor/src/pages/payouts/_components/payout-account-section.tsx
@@ -0,0 +1,137 @@
+import { ArrowPath, OpenRectArrowOut } from "@medusajs/icons";
+import { Alert, Container, Heading, StatusBadge, Text, toast } from "@medusajs/ui";
+import { TFunction } from "i18next";
+import { useTranslation } from "react-i18next";
+
+import { ActionMenu, type Action } from "@components/common/action-menu";
+import { SectionRow } from "@components/common/section";
+import { useCreatePayoutOnboarding, useMyPayoutAccount } from "@hooks/api/payout-accounts";
+
+import { isOnboardingPending } from "./active-payout-onboarding-section";
+
+type StatusColor = "green" | "orange" | "red" | "blue" | "grey";
+
+const ACCOUNT_STATUS_COLOR: Record<string, StatusColor> = {
+ pending: "orange",
+ active: "green",
+ restricted: "orange",
+ rejected: "red",
+};
+
+const KYC_STATUS_COLOR: Record<string, StatusColor> = {
+ pending_submission: "orange",
+ pending_approval: "blue",
+ approved: "green",
+ refused: "red",
+};
+
+// Providers report why payouts are off as a dotted code (`requirements.past_due`,
+// `rejected.fraud`, ...); only its family decides the message.
+const disabledReasonMessage = (reason: string, t: TFunction) => {
+ if (reason === "requirements.past_due") return t("payouts.account.disabled.pastDue");
+ if (reason === "requirements.pending_verification") return t("payouts.account.disabled.pendingVerification");
+ if (reason.startsWith("requirements.")) return t("payouts.account.disabled.requirements");
+ if (reason.startsWith("rejected.")) return t("payouts.account.disabled.rejected");
+ if (reason === "under_review" || reason === "listed") return t("payouts.account.disabled.underReview");
+ return t("payouts.account.disabled.other");
+};
+
+export const PayoutAccountSection = () => {
+ const { t } = useTranslation();
+ const { payout_account: account, isPending, isError, error } = useMyPayoutAccount();
+ const onboarding = useCreatePayoutOnboarding(account?.id ?? "");
+
+ if (isError) {
+ throw error;
+ }
+
+ if (isPending) {
+ return null;
+ }
+
+ if (!account) {
+ return (
+ <Container className="divide-y p-0" data-testid="payout-account-section">
+ <div className="px-6 py-4">
+ <Heading level="h2">{t("payouts.account.header")}</Heading>
+ </div>
+ <div className="px-6 py-4">
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ {t("payouts.account.empty")}
+ </Text>
+ </div>
+ </Container>
+ );
+ }
+
+ const link = account.onboarding?.data as { url?: string; kind?: string } | null;
+ const finishing = !account.details_submitted;
+
+ const actions: Action[] = [];
+ if (link?.url && !isOnboardingPending(account)) {
+ const url = link.url;
+ actions.push({
+ label: finishing
+ ? t("payouts.account.actions.continueOnboarding")
+ : t("payouts.account.actions.openDashboard"),
+ icon: <OpenRectArrowOut />,
+ onClick: () => {
+ window.open(url, "_blank", "noreferrer");
+ },
+ });
+ }
+ if (finishing) {
+ actions.push({
+ label: t("payouts.account.actions.refreshLink"),
+ icon: <ArrowPath />,
+ permission: "payouts:edit",
+ onClick: () =>
+ onboarding.mutate(undefined, {
+ onSuccess: () => toast.success(t("payouts.account.linkReady")),
+ onError: (e) => toast.error(e.message),
+ }),
+ });
+ }
+
+ return (
+ <div className="flex flex-col gap-y-3">
+ {account.disabled_reason && !isOnboardingPending(account) && (
+ <Alert
+ variant={account.disabled_reason.startsWith("rejected.") ? "error" : "warning"}
+ data-testid="payout-account-alert"
+ >
+ {disabledReasonMessage(account.disabled_reason, t)}
+ </Alert>
+ )}
+ <Container className="divide-y p-0" data-testid="payout-account-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("payouts.account.header")}</Heading>
+ <div className="flex items-center gap-x-2">
+ <StatusBadge color={ACCOUNT_STATUS_COLOR[account.status] ?? "grey"}>
+ {t(`payouts.account.status.${account.status}`)}
+ </StatusBadge>
+ {actions.length > 0 && (
+ <ActionMenu data-testid="payout-account-actions" groups={[{ actions }]} />
+ )}
+ </div>
+ </div>
+ <SectionRow
+ title={t("payouts.account.fields.payouts")}
+ value={account.payouts_enabled ? t("payouts.account.enabled") : t("payouts.account.notEnabled")}
+ />
+ <SectionRow
+ title={t("payouts.account.fields.kycStatus")}
+ value={
+ account.kyc_status ? (
+ <StatusBadge color={KYC_STATUS_COLOR[account.kyc_status] ?? "grey"}>
+ {t(`payouts.account.kyc.${account.kyc_status}`)}
+ </StatusBadge>
+ ) : (
+ "-"
+ )
+ }
+ />
+ </Container>
+ </div>
+ );
+};
diff --git a/packages/vendor/src/pages/payouts/_components/payout-status.ts b/packages/vendor/src/pages/payouts/_components/payout-status.ts
new file mode 100644
index 000000000..f9ad72f41
--- /dev/null
+++ b/packages/vendor/src/pages/payouts/_components/payout-status.ts
@@ -0,0 +1,50 @@
+import { TFunction } from "i18next"
+
+type BadgeColor = "green" | "red" | "blue" | "orange" | "grey"
+
+export const PAYOUT_STATUSES = [
+ "pending",
+ "on_hold",
+ "processing",
+ "paid",
+ "failed",
+ "aborted",
+] as const
+
+const STATUS_COLORS: Record<string, BadgeColor> = {
+ pending: "grey",
+ on_hold: "orange",
+ processing: "blue",
+ paid: "green",
+ failed: "red",
+ aborted: "red",
+}
+
+export const payoutStatusColor = (status: string): BadgeColor =>
+ STATUS_COLORS[status] ?? "grey"
+
+export const PAYOUT_STATUS_REASONS = [
+ "account_not_ready",
+ "account_payouts_disabled",
+ "order_not_ready",
+ "order_aborted",
+ "payment_not_ready",
+ "payment_failed",
+ "payment_canceled",
+ "payment_refunded",
+ "payout_not_ready",
+ "refund_aborted",
+ "refund_absorbed",
+ "invalid_amount",
+ "provider_error",
+] as const
+
+type PayoutStatusReason = (typeof PAYOUT_STATUS_REASONS)[number]
+
+const isPayoutStatusReason = (reason: string): reason is PayoutStatusReason =>
+ (PAYOUT_STATUS_REASONS as readonly string[]).includes(reason)
+
+export const getPayoutStatusReasonLabel = (reason: string, t: TFunction) =>
+ isPayoutStatusReason(reason)
+ ? t(`payouts.statusReasons.${reason}`)
+ : t("payouts.statusReasons.other")
diff --git a/packages/vendor/src/pages/payouts/payout-list-page.tsx b/packages/vendor/src/pages/payouts/payout-list-page.tsx
index 250465e73..8b14250a0 100644
--- a/packages/vendor/src/pages/payouts/payout-list-page.tsx
+++ b/packages/vendor/src/pages/payouts/payout-list-page.tsx
@@ -10,18 +10,30 @@ import {
PayoutListActions,
PayoutListTitle,
} from "./_components/payout-list-table";
+import { PayoutAccountSection } from "./_components/payout-account-section";
+import { ActivePayoutOnboardingSection } from "./_components/active-payout-onboarding-section";
const Root = ({ children }: { children?: ReactNode }) => {
return (
<SingleColumnPage>
<WidgetZone id="payouts.list">
- {Children.count(children) > 0 ? children : <PayoutListTable />}
+ {Children.count(children) > 0 ? (
+ children
+ ) : (
+ <>
+ <ActivePayoutOnboardingSection />
+ <PayoutAccountSection />
+ <PayoutListTable />
+ </>
+ )}
</WidgetZone>
</SingleColumnPage>
);
};
export const PayoutListPage = Object.assign(Root, {
+ OnboardingSection: ActivePayoutOnboardingSection,
+ AccountSection: PayoutAccountSection,
Table: PayoutListTable,
Header: PayoutListHeader,
HeaderTitle: PayoutListTitle,
diff --git a/scripts/deploy.sh b/scripts/deploy.sh
index da15415ff..1b720ab95 100755
--- a/scripts/deploy.sh
+++ b/scripts/deploy.sh
@@ -396,7 +396,7 @@ except Exception:
# Enumerate every published @mercurjs/* package name from the source tree.
mercur_names = set()
-for path in glob.glob(f"{SOURCE_DIR}/packages/*/package.json") + glob.glob(f"{SOURCE_DIR}/packages/providers/*/package.json"):
+for path in glob.glob(f"{SOURCE_DIR}/packages/*/package.json") + glob.glob(f"{SOURCE_DIR}/packages/plugins/*/package.json"):
with open(path) as f:
name = json.load(f).get("name")
if name and name.startswith(SCOPE):
diff --git a/scripts/stripe-listen.sh b/scripts/stripe-listen.sh
new file mode 100755
index 000000000..453bcc02a
--- /dev/null
+++ b/scripts/stripe-listen.sh
@@ -0,0 +1,64 @@
+#!/usr/bin/env bash
+# Forwards Stripe sandbox webhooks to the local API, the way the two production
+# endpoints would deliver them:
+# payment: platform events -> /hooks/payment/stripe-connector_stripe
+# payout: platform transfer.* and Connect account.* / payout.* -> /hooks/payout
+#
+# Usage: ./scripts/stripe-listen.sh (needs `stripe login` once)
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+ENV_FILE="$ROOT/apps/api/.env"
+API_URL="${API_URL:-http://localhost:9000}"
+LOG_DIR="$ROOT/.stripe"
+
+PAYMENT_EVENTS="payment_intent.amount_capturable_updated,payment_intent.succeeded,payment_intent.payment_failed,payment_intent.canceled,payment_intent.partially_funded,payment_intent.requires_action,charge.refunded"
+PAYOUT_EVENTS="account.updated,transfer.created,transfer.reversed,payout.paid,payout.failed,payout.canceled,payout.updated"
+
+command -v stripe >/dev/null || { echo "Install the Stripe CLI: brew install stripe/stripe-cli/stripe"; exit 1; }
+
+# Listen on the account the API charges, not whichever one `stripe login` picked.
+API_KEY="$(grep -E '^STRIPE_SECRET_KEY=' "$ENV_FILE" | tail -1 | cut -d= -f2- | tr -d "\"'" || true)"
+[ -n "$API_KEY" ] || { echo "Set STRIPE_SECRET_KEY in apps/api/.env"; exit 1; }
+case "$API_KEY" in sk_test_* | rk_test_*) ;; *) echo "Refusing to listen with a live Stripe key"; exit 1 ;; esac
+export STRIPE_API_KEY="$API_KEY"
+
+# The CLI signs every forwarded event with one secret per account, so both
+# webhook secrets in .env must hold it.
+SECRET="$(stripe listen --print-secret)"
+
+changed=0
+touch "$ENV_FILE"
+for var in STRIPE_OPERATOR_WEBHOOK_SECRET STRIPE_SELLERS_WEBHOOK_SECRET; do
+ if ! grep -qx "$var=$SECRET" "$ENV_FILE"; then
+ [ "$changed" = 1 ] || cp "$ENV_FILE" "$ENV_FILE.bak"
+ tmp="$(mktemp)"
+ grep -v "^$var=" "$ENV_FILE" > "$tmp" || true
+ echo "$var=$SECRET" >> "$tmp"
+ mv "$tmp" "$ENV_FILE"
+ changed=1
+ fi
+done
+if [ "$changed" = 1 ]; then
+ echo "Updated the webhook secrets in apps/api/.env (previous file in .env.bak) -- restart the API so it verifies with them."
+fi
+
+# The logs carry the webhook signing secret.
+umask 077
+mkdir -p "$LOG_DIR"
+trap 'kill 0' EXIT INT TERM
+
+stripe listen \
+ --events "$PAYMENT_EVENTS" \
+ --forward-to "$API_URL/hooks/payment/stripe-connector_stripe" \
+ 2>&1 | sed -u 's/^/[payment] /' | tee "$LOG_DIR/payment.log" &
+
+stripe listen \
+ --events "$PAYOUT_EVENTS" \
+ --forward-to "$API_URL/hooks/payout" \
+ --forward-connect-to "$API_URL/hooks/payout" \
+ 2>&1 | sed -u 's/^/[payout] /' | tee "$LOG_DIR/payout.log" &
+
+echo "Forwarding to $API_URL (logs in .stripe/). A 200 only means the event was queued;"
+echo "run 'bun --cwd apps/api run stripe:check-webhooks' to confirm it was processed."
+wait
diff --git a/templates/basic/packages/api/src/scripts/seed.ts b/templates/basic/packages/api/src/scripts/seed.ts
index 3fe4ad166..bd31cee71 100644
--- a/templates/basic/packages/api/src/scripts/seed.ts
+++ b/templates/basic/packages/api/src/scripts/seed.ts
@@ -339,15 +339,6 @@ export default async function seedDemoData({ container }: ExecArgs) {
}
logger.info("Finished seeding regions.");
- if (!store.default_region_id) {
- await updateStoresWorkflow(container).run({
- input: {
- selector: { id: store.id },
- update: { default_region_id: region.id },
- },
- });
- }
-
logger.info("Seeding tax regions...");
const taxModuleService = container.resolve(Modules.TAX);
const existingTaxRegions = await taxModuleService.listTaxRegions();