From 422fc821ff59adf8de5f6eb5da534d489d47950a Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:04:50 +0100 Subject: [PATCH 1/6] feat(core): split payments across vendor payout accounts --- .changeset/provider-split-allocations.md | 11 + packages/core/README.md | 1 + packages/core/src/admin/pages/VendorsPage.tsx | 288 ++++++++++++++++-- .../core/src/payment-provider/capabilities.ts | 2 + packages/core/src/payment-provider/index.ts | 1 + packages/core/src/payment-provider/types.ts | 26 ++ packages/core/src/routes/admin-api.ts | 171 ++++++++++- packages/core/src/routes/checkout.ts | 30 +- packages/core/src/types.ts | 20 ++ packages/core/src/vendors/provider-split.ts | 151 +++++++++ .../core/test/checkout-provider-split.test.ts | 175 +++++++++++ .../provider-credentials-settings.test.ts | 1 + packages/core/test/provider-split.test.ts | 220 +++++++++++++ .../core/test/vendor-payment-accounts.test.ts | 262 ++++++++++++++++ 14 files changed, 1325 insertions(+), 34 deletions(-) create mode 100644 .changeset/provider-split-allocations.md create mode 100644 packages/core/src/vendors/provider-split.ts create mode 100644 packages/core/test/checkout-provider-split.test.ts create mode 100644 packages/core/test/provider-split.test.ts create mode 100644 packages/core/test/vendor-payment-accounts.test.ts diff --git a/.changeset/provider-split-allocations.md b/.changeset/provider-split-allocations.md new file mode 100644 index 0000000..2d0572c --- /dev/null +++ b/.changeset/provider-split-allocations.md @@ -0,0 +1,11 @@ +--- +"@dashcommerce/core": minor +--- + +Let a payment provider split one payment across vendor payout accounts. + +- `capabilities.splits` and `InitCheckoutInput.allocations` / `platformRemainderMinor`. Core computes exact per-vendor minor amounts from trusted cart prices and the vendor's platform fee; a provider only routes them to the account reference core supplies. +- `Vendor.paymentAccounts`, keyed by provider id, for providers other than Stripe: `accountReference`, `status`, and an optional settlement currency and label. Stripe Connect keeps its existing fields. +- `admin/vendors/item` accepts `POST` to create a vendor without Stripe, and `PATCH` with `paymentAccount` / `paymentAccounts` to add, replace or remove a provider account. Vendor routes open when Connect is on **or** a split-capable provider is registered. +- Settings exposes each provider's `capabilities`. The Vendors page adds a vendor and edits payout accounts when a split-capable provider is active, without requiring Stripe. +- A vendor cart is refused with a readable 409 when the active provider cannot split, or when a vendor has no active account for it, instead of silently charging the platform account. diff --git a/packages/core/README.md b/packages/core/README.md index 5e9a141..3c6f4da 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -70,6 +70,7 @@ For provider authors, `PaymentProvider` can declare: - `credentialFields`: the label, accepted prefixes and help text for the settings form. - `webhookHeaders`: the headers that identify its webhooks, besides `x--signature`. `verifyWebhook` receives every request header, and `credentials` (the provider's saved secret key and webhook secret) for headers signed with the API key rather than the webhook secret. - `checkConnection`: one read-only call with the saved keys, behind a "Test connection" button in Settings. Return `{ ok, message }`, with `ok: false` and a message the merchant can act on for a wrong or under-permitted key. +- `capabilities.splits`: core computes `allocations` (`vendorId`, `accountReference`, `amountMinor`) and `platformRemainderMinor` when the cart has vendor-owned items. Vendors store their payout account under `paymentAccounts[providerId]`; the provider only routes the amounts core supplies. `parseWebhookEvent` may return `refund.updated` to move a pending refund to `succeeded` or `failed`. A failed refund stops counting against its order: the refunded total, payment status and order status are worked out again, and stock the refund put back is taken back off. diff --git a/packages/core/src/admin/pages/VendorsPage.tsx b/packages/core/src/admin/pages/VendorsPage.tsx index 1135908..efa6b5c 100644 --- a/packages/core/src/admin/pages/VendorsPage.tsx +++ b/packages/core/src/admin/pages/VendorsPage.tsx @@ -2,8 +2,9 @@ * Vendors admin page. * * When multi-vendor marketplace is disabled, this page renders a first-run - * empty state directing the operator to Settings. When enabled, it shows - * onboarding + list + inline edit for platform fee and Stripe refresh. + * empty state directing the operator to Settings. When enabled (Stripe + * Connect, or a provider that can split payments), it shows onboarding, the + * vendor list, and inline edit for the platform fee and payout accounts. */ import { useCallback, useEffect, useMemo, useState } from "react"; @@ -17,6 +18,7 @@ import { Loading, Money, NumberInput, + Select, Table, confirm, countryOptions, @@ -25,7 +27,7 @@ import { } from "../kit"; import { EmptyState } from "../ui/EmptyState"; import { StatusBadge } from "../ui/StatusBadge"; -import type { Vendor, VendorPayout } from "../../types"; +import type { Vendor, VendorPaymentAccount, VendorPayout } from "../../types"; import { T } from "../theme"; const STATUS_OPTIONS = [ @@ -38,6 +40,8 @@ const STATUS_OPTIONS = [ interface SettingsGateState { connectEnabled: boolean; defaultFeePercent: number; + /** Registered providers that can split a payment across vendor accounts. */ + splitsProviders: Array<{ id: string; label: string }>; } type PageState = "loading" | "disabled" | "ready" | "error"; @@ -60,9 +64,7 @@ export function VendorsPage() { const [payouts, setPayouts] = useState>({}); const [pending, setPending] = useState>({}); const [editing, setEditing] = useState<{ - vendorId: string; - name: string; - fee: number; + vendor: Vendor; } | null>(null); const loadVendors = useCallback(async () => { @@ -80,14 +82,25 @@ export function VendorsPage() { try { const settings = await api.get>("admin/settings"); const enabled = settings.connectEnabled === true; + const providers = Array.isArray(settings._providers) + ? (settings._providers as Array<{ + id: string; + label: string; + capabilities?: { splits?: boolean }; + }>) + : []; + const splitsProviders = providers + .filter((provider) => provider.capabilities?.splits === true) + .map((provider) => ({ id: provider.id, label: provider.label })); setGate({ connectEnabled: enabled, defaultFeePercent: typeof settings.connectPlatformFeePercent === "number" ? (settings.connectPlatformFeePercent as number) : 0, + splitsProviders, }); - if (!enabled) { + if (!enabled && splitsProviders.length === 0) { setPageState("disabled"); return; } @@ -125,7 +138,7 @@ export function VendorsPage() { - { - setLinkUrl(url); - await loadVendors(); - }} - /> + {gate?.connectEnabled ? ( + { + setLinkUrl(url); + await loadVendors(); + }} + /> + ) : gate && gate.splitsProviders.length > 0 ? ( + + ) : null} {linkUrl && ( @@ -261,9 +278,7 @@ export function VendorsPage() { size="sm" onClick={() => setEditing({ - vendorId: v.id, - name: v.name, - fee: v.platformFeePercent, + vendor: v, }) } > @@ -376,12 +391,13 @@ export function VendorsPage() { {editing && ( setEditing(null)} onSave={async (patch) => { try { await api.patch<{ vendor: Vendor }>( - `admin/vendors/item?id=${encodeURIComponent(editing.vendorId)}`, + `admin/vendors/item?id=${encodeURIComponent(editing.vendor.id)}`, patch, ); toast.success("Vendor updated"); @@ -519,17 +535,162 @@ function VendorOnboardingCard({ ); } +function ProviderVendorCard({ + gate, + api, + onSuccess, +}: { + gate: SettingsGateState; + api: ReturnType; + onSuccess: () => Promise; +}) { + const [name, setName] = useState(""); + const [email, setEmail] = useState(""); + const [fee, setFee] = useState(gate.defaultFeePercent); + const [providerId, setProviderId] = useState(gate.splitsProviders[0]?.id ?? ""); + const [accountReference, setAccountReference] = useState(""); + const [submitting, setSubmitting] = useState(false); + + const valid = + name.trim().length > 0 && + /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) && + typeof fee === "number" && + fee >= 0 && + fee <= 100 && + providerId.length > 0 && + accountReference.trim().length >= 4; + + async function add(): Promise { + if (!valid) return; + setSubmitting(true); + try { + await api.post("admin/vendors/item", { + name: name.trim(), + email: email.trim(), + platformFeePercent: fee ?? 0, + paymentAccount: { + providerId, + accountReference: accountReference.trim(), + status: "active", + }, + }); + toast.success("Vendor added"); + setName(""); + setEmail(""); + setAccountReference(""); + await onSuccess(); + } catch (err) { + toast.error("Could not add vendor", err instanceof Error ? err.message : undefined); + } finally { + setSubmitting(false); + } + } + + return ( + +

+ Paste the payout account id the provider gave you. For Flutterwave, create a collection + subaccount in the dashboard and use its RS_… id. +

+ + setName(e.currentTarget.value)} + placeholder="Acme Widgets" + disabled={submitting} + /> + + + setEmail(e.currentTarget.value)} + placeholder="ops@acme.example" + disabled={submitting} + /> + + {gate.splitsProviders.length > 1 && ( + + setAccountReference(e.currentTarget.value)} + placeholder="RS_…" + disabled={submitting} + /> + + + setFee(v ?? 0)} + min={0} + max={100} + step={0.1} + suffix="%" + disabled={submitting} + /> + + +
+ ); +} + +interface PaymentAccountDraft { + accountReference: string; + status: VendorPaymentAccount["status"]; +} + function EditVendorModal({ initial, + providers, onClose, onSave, }: { - initial: { vendorId: string; name: string; fee: number }; + initial: Vendor; + providers: Array<{ id: string; label: string }>; onClose: () => void; - onSave: (patch: { name?: string; platformFeePercent?: number }) => Promise; + onSave: (patch: { + name?: string; + platformFeePercent?: number; + paymentAccounts?: Array<{ + providerId: string; + accountReference: string | null; + status: VendorPaymentAccount["status"]; + }>; + }) => Promise; }) { const [name, setName] = useState(initial.name); - const [fee, setFee] = useState(initial.fee); + const [fee, setFee] = useState(initial.platformFeePercent); + const [accounts, setAccounts] = useState>(() => { + const out: Record = {}; + for (const provider of providers) { + const account = initial.paymentAccounts?.[provider.id]; + out[provider.id] = { + accountReference: account?.accountReference ?? "", + status: account?.status ?? "active", + }; + } + return out; + }); const [saving, setSaving] = useState(false); const isValid = name.trim().length > 0 && @@ -537,6 +698,17 @@ function EditVendorModal({ fee >= 0 && fee <= 100; + function setAccount(providerId: string, patch: Partial): void { + setAccounts((current) => ({ + ...current, + [providerId]: { + accountReference: current[providerId]?.accountReference ?? "", + status: current[providerId]?.status ?? "active", + ...patch, + }, + })); + } + return (

Edit vendor

@@ -586,6 +760,46 @@ function EditVendorModal({ disabled={saving} /> + {providers.map((provider) => ( +
+ + + setAccount(provider.id, { accountReference: e.currentTarget.value }) + } + placeholder="RS_…" + disabled={saving} + /> + + + { + setCountry(e.currentTarget.value); + setBankCode(""); + setAccountName(null); + }} + options={countries.map((c) => ({ value: c.value, label: c.label }))} + disabled={creating} + /> + + + { + setAccountNumber(e.currentTarget.value); + setAccountName(null); + }} + disabled={creating} + /> + + + {accountName && ( + + {accountName} + + )} + + setBusinessName(e.currentTarget.value)} + disabled={creating} + /> + + + setBusinessEmail(e.currentTarget.value)} + disabled={creating} + /> + + + setBusinessMobile(e.currentTarget.value)} + placeholder="+234…" + disabled={creating} + /> + + + - setAccount(provider.id, { accountReference: e.currentTarget.value }) - } - placeholder="RS_…" - disabled={saving} - /> - - - + setAccount(provider.id, { accountReference: e.currentTarget.value }) + } + placeholder="RS_…" + disabled={saving} + /> + + + setAccountReference(e.currentTarget.value)} - placeholder="RS_…" + placeholder="Account id" disabled={submitting} /> @@ -670,15 +703,26 @@ function PayoutAccountForm({ provider, vendor, api, + defaultFeePercent, + defaultCurrency, onChanged, }: { - provider: { id: string; label: string; payoutOnboarding: boolean }; + provider: { + id: string; + label: string; + payoutOnboarding: boolean; + payoutVerification: boolean; + }; vendor: Vendor; api: ReturnType; + defaultFeePercent: number; + defaultCurrency: string | null; onChanged: () => Promise; }) { const stored = vendor.paymentAccounts?.[provider.id]; - const [country, setCountry] = useState("NG"); + const initialCountry = + COUNTRY_BY_CURRENCY[(defaultCurrency ?? "").toUpperCase()] ?? "NG"; + const [country, setCountry] = useState(initialCountry); const [banks, setBanks] = useState | null>(null); const [bankCode, setBankCode] = useState(""); const [accountNumber, setAccountNumber] = useState(""); @@ -687,7 +731,9 @@ function PayoutAccountForm({ const [businessEmail, setBusinessEmail] = useState(vendor.email); const [businessMobile, setBusinessMobile] = useState(""); const [splitType, setSplitType] = useState<"percentage" | "flat">("percentage"); - const [splitValue, setSplitValue] = useState(vendor.platformFeePercent || 10); + const [splitValue, setSplitValue] = useState( + vendor.platformFeePercent > 0 ? vendor.platformFeePercent : defaultFeePercent, + ); const [verifying, setVerifying] = useState(false); const [creating, setCreating] = useState(false); const [removing, setRemoving] = useState(false); @@ -724,7 +770,12 @@ function PayoutAccountForm({ {stored.bankName ?? stored.bankCode} {stored.maskedAccountNumber ? ` ${stored.maskedAccountNumber}` : ""} ·{" "} {stored.status} + {stored.verified === false ? " · unverified" : ""} +

+ Removing it here detaches the account from this vendor in DashCommerce. The + account at the provider is unchanged. +

); } + const requiresVerification = provider.payoutVerification; const valid = country.length === 2 && bankCode.length > 0 && @@ -759,7 +811,7 @@ function PayoutAccountForm({ businessName.trim().length > 0 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(businessEmail) && businessMobile.trim().length > 0 && - accountName !== null && + (!requiresVerification || accountName !== null) && typeof splitValue === "number" && splitValue >= 0 && (splitType === "flat" ? splitValue > 0 : splitValue <= 100); @@ -826,18 +878,27 @@ function PayoutAccountForm({ disabled={creating} /> - - { @@ -847,16 +908,25 @@ function PayoutAccountForm({ disabled={creating} /> - - {accountName && ( - - {accountName} + {requiresVerification ? ( + <> + + {accountName && ( + + {accountName} + + )} + + ) : ( + + This provider cannot verify account names here. The account will be saved as + unverified. )} @@ -925,13 +995,22 @@ function EditVendorModal({ initial, providers, api, + defaultFeePercent, + defaultCurrency, onClose, onSave, onChanged, }: { initial: Vendor; - providers: Array<{ id: string; label: string; payoutOnboarding: boolean }>; + providers: Array<{ + id: string; + label: string; + payoutOnboarding: boolean; + payoutVerification: boolean; + }>; api: ReturnType; + defaultFeePercent: number; + defaultCurrency: string | null; onClose: () => void; onSave: (patch: { name?: string; @@ -1033,6 +1112,8 @@ function EditVendorModal({ provider={provider} vendor={initial} api={api} + defaultFeePercent={defaultFeePercent} + defaultCurrency={defaultCurrency} onChanged={onChanged} /> ) : ( @@ -1046,14 +1127,14 @@ function EditVendorModal({ > setAccount(provider.id, { accountReference: e.currentTarget.value }) } - placeholder="RS_…" + placeholder="Account id" disabled={saving} /> diff --git a/packages/core/src/payment-provider/types.ts b/packages/core/src/payment-provider/types.ts index a26c838..f6b5fbc 100644 --- a/packages/core/src/payment-provider/types.ts +++ b/packages/core/src/payment-provider/types.ts @@ -377,7 +377,10 @@ export interface CreatePayoutAccountInput { /** What a provider returns after creating a vendor payout account. */ export interface CreatedPayoutAccount { accountReference: string; - accountName: string; + /** Absent when the provider cannot resolve account names. */ + accountName?: string; + /** False when the provider created the account but has not verified it. */ + verified?: boolean; bankName?: string; bankCode?: string; country?: string; diff --git a/packages/core/src/routes/admin-api.ts b/packages/core/src/routes/admin-api.ts index 73ffa77..79feb7c 100644 --- a/packages/core/src/routes/admin-api.ts +++ b/packages/core/src/routes/admin-api.ts @@ -207,6 +207,7 @@ async function providerSettingsRows(ctx: PluginContext) { checkoutStyles: providerCheckoutStyles(provider), canCheckConnection: typeof provider.checkConnection === "function", payoutOnboarding: typeof provider.createPayoutAccount === "function", + payoutVerification: typeof provider.resolvePayoutAccount === "function", secrets: { secretKey: await secretStatus(ctx, `${provider.id}SecretKey`), webhookSecret: await secretStatus(ctx, `${provider.id}WebhookSecret`), @@ -1643,6 +1644,7 @@ async function createProviderPayoutAccount( 400, ); } + const canVerify = typeof provider.resolvePayoutAccount === "function"; const credentials = await loadPaymentProviderCredentials(ctx.kv, providerId); if (!credentials) { return json({ error: `Payment provider "${providerId}" is not configured` }, 400); @@ -1686,14 +1688,15 @@ async function createProviderPayoutAccount( if (!created.accountReference?.trim()) { return json({ error: "Provider returned no account reference" }, 502); } - if (!created.accountName?.trim()) { + if (canVerify && !created.accountName?.trim()) { return json({ error: "Provider returned no account name" }, 502); } const now = new Date().toISOString(); const account: VendorPaymentAccount = { accountReference: created.accountReference.trim(), status: "active", - accountName: created.accountName.trim(), + ...(created.accountName ? { accountName: created.accountName.trim() } : {}), + verified: created.verified ?? canVerify, ...(created.bankName ? { bankName: created.bankName } : {}), bankCode: created.bankCode ?? bankCode, country: created.country ?? country, diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 818664b..e213673 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -547,6 +547,8 @@ export interface VendorPaymentAccount { status: "active" | "pending" | "disabled"; /** Account holder name returned by the provider's account resolution. */ accountName?: string; + /** False when the provider created the account but has not verified it. */ + verified?: boolean; bankName?: string; bankCode?: string; /** ISO-2 country of the payout account. */ diff --git a/packages/core/test/provider-credentials-settings.test.ts b/packages/core/test/provider-credentials-settings.test.ts index 9f8ea5d..289d682 100644 --- a/packages/core/test/provider-credentials-settings.test.ts +++ b/packages/core/test/provider-credentials-settings.test.ts @@ -119,6 +119,7 @@ describe("provider credentials in the settings API", () => { capabilities: {}, canCheckConnection: false, payoutOnboarding: false, + payoutVerification: false, secrets: { secretKey: { isSet: true, hint: "••••1234" }, webhookSecret: { isSet: false, hint: null }, diff --git a/packages/core/test/provider-payout-onboarding.test.ts b/packages/core/test/provider-payout-onboarding.test.ts index 25aacb2..c2350a9 100644 --- a/packages/core/test/provider-payout-onboarding.test.ts +++ b/packages/core/test/provider-payout-onboarding.test.ts @@ -121,6 +121,7 @@ describe("provider payout onboarding", () => { expect(saved.paymentAccounts?.flw).toMatchObject({ accountReference: "RS_TEST", status: "active", + verified: true, accountName: "Name for 0690000031", bankName: "Access Bank", bankCode: "044", @@ -193,6 +194,63 @@ describe("provider payout onboarding", () => { expect(badFlat.status).toBe(400); }); + it("creates an unverified account when the provider cannot resolve names", async () => { + registerPaymentProvider({ + ...createMockPaymentProvider({ id: "flw" }), + label: "Flutterwave", + capabilities: { splits: true }, + async createPayoutAccount() { + return { + accountReference: "RS_UNVERIFIED", + bankName: "Access Bank", + bankCode: "044", + country: "NG", + maskedAccountNumber: "••••0031", + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ "settings:flwSecretKey": "test-key" }); + getCol("vendors").set("v1", vendor()); + + const res = await call(ctx, "admin/vendors/payout-account", "POST", createInput); + expect(res.status).toBe(201); + const account = (res.body.vendor as Vendor).paymentAccounts?.flw; + expect(account?.accountReference).toBe("RS_UNVERIFIED"); + expect(account?.accountName).toBeUndefined(); + expect(account?.verified).toBe(false); + }); + + it("stores an active-but-unverified account the provider reports", async () => { + registerPaymentProvider({ + ...createMockPaymentProvider({ id: "flw" }), + label: "Flutterwave", + capabilities: { splits: true }, + async resolvePayoutAccount() { + return { accountName: "Bale Gary" }; + }, + async createPayoutAccount() { + return { + accountReference: "RS_ACTIVE_UNVERIFIED", + accountName: "Bale Gary", + verified: false, + bankName: "Access Bank", + bankCode: "044", + country: "NG", + maskedAccountNumber: "••••0031", + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ "settings:flwSecretKey": "test-key" }); + getCol("vendors").set("v1", vendor()); + + const res = await call(ctx, "admin/vendors/payout-account", "POST", createInput); + expect(res.status).toBe(201); + const account = (res.body.vendor as Vendor).paymentAccounts?.flw; + expect(account?.status).toBe("active"); + expect(account?.verified).toBe(false); + expect(account?.accountName).toBe("Bale Gary"); + }); + it("is gated like the other vendor routes", async () => { const { ctx } = makeRouteContext({}); const res = await call(ctx, "admin/vendors/payout-banks", "GET"); @@ -206,5 +264,6 @@ describe("provider payout onboarding", () => { const providers = res.body._providers as Array>; const row = providers.find((provider) => provider.id === "flw"); expect(row?.payoutOnboarding).toBe(true); + expect(row?.payoutVerification).toBe(true); }); });