diff --git a/.changeset/provider-payout-onboarding.md b/.changeset/provider-payout-onboarding.md new file mode 100644 index 0000000..6615254 --- /dev/null +++ b/.changeset/provider-payout-onboarding.md @@ -0,0 +1,11 @@ +--- +"@dashcommerce/core": minor +--- + +Provider-managed payout onboarding and richer vendor payout accounts. + +- `VendorPaymentAccount` gains `accountName`, `verified`, `bankName`, `bankCode`, `country`, `maskedAccountNumber`, `metadata` and `createdAt`. `verified: false` means the provider created a usable account it has not verified; core still accepts it for splits. +- `PaymentProvider` gains optional `listPayoutBanks`, `resolvePayoutAccount` and `createPayoutAccount`, so a provider can onboard a vendor's payout account without sending the merchant to its dashboard. +- `admin/vendors/payout-banks`, `admin/vendors/payout-account/resolve` and `admin/vendors/payout-account` expose that to the Vendors page, which renders a country/bank/account form for providers that implement it. +- Verification is optional. The form only requires it when the provider implements `resolvePayoutAccount`; otherwise the account is stored unverified. The country starts from the store's default currency, and `listPayoutBanks` may return mobile-money channels (e.g. M-PESA) as well as banks. +- The stored account keeps the resolved account name, bank and a masked account number; the full number is never persisted. Removing it detaches it from the vendor locally; the account at the provider is unchanged. diff --git a/.changeset/provider-split-allocations.md b/.changeset/provider-split-allocations.md new file mode 100644 index 0000000..a9be535 --- /dev/null +++ b/.changeset/provider-split-allocations.md @@ -0,0 +1,13 @@ +--- +"@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. +- `Vendor.stripeAccountId` is optional. A vendor paid through another provider omits it, so a shop without Stripe can create more than one vendor; a missing field is NULL, so the unique index does not clash. +- A cart-wide discount comes out of the platform remainder, matching the Connect plan; a discount larger than that remainder is refused with a readable 409 instead of silently reducing a vendor's payout. +- `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..b0c231c 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -70,6 +70,9 @@ 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. +- `listPayoutBanks`, `resolvePayoutAccount`, `createPayoutAccount`: optional provider-managed payout onboarding. The Vendors page lists banks or mobile-money channels, verifies the account name when the provider supports it, and creates the account; core stores the masked result on the vendor. A provider that creates an active but unverified account (Paystack's `is_verified: false`) should return `verified: false`; core still accepts it for splits. +- Keep your own transaction fee on the platform (Paystack's `bearer_type: account`, Flutterwave's default) so each vendor receives exactly the share core computed. `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/fields/VendorSelect.tsx b/packages/core/src/admin/fields/VendorSelect.tsx index b5a0b59..ab27225 100644 --- a/packages/core/src/admin/fields/VendorSelect.tsx +++ b/packages/core/src/admin/fields/VendorSelect.tsx @@ -8,22 +8,18 @@ * context (field definition, entry metadata) without needing changes here. * * Behaviour: - * - Reads `settings:connectEnabled` via the admin settings API on mount. - * - When multi-vendor is off, renders an info banner instead of the picker. - * - When on, fetches `admin/vendors` and renders a searchable Combobox of - * active/pending vendors, dimming entries with `chargesEnabled=false`. + * - Reads `settings:connectEnabled` and the registered providers' `splits` + * capability via the admin settings API on mount. + * - Marketplace mode is Stripe Connect **or** a provider that can split + * payments (Flutterwave subaccounts). + * - When neither is on, renders an info banner instead of the picker. + * - When on, fetches `admin/vendors` and renders a searchable Combobox, + * dimming vendors with no active payout account. */ import { useEffect, useMemo, useState } from "react"; -import { - Alert, - Combobox, - FormField, - Loading, - usePluginAPI, - type ComboboxOption, -} from "../kit"; import type { Vendor } from "../../types"; +import { Alert, Combobox, type ComboboxOption, FormField, Loading, usePluginAPI } from "../kit"; export interface VendorSelectProps { value?: string | null; @@ -35,7 +31,9 @@ export interface VendorSelectProps { export function VendorSelect(props: VendorSelectProps) { const api = usePluginAPI(); const [vendors, setVendors] = useState(null); - const [connectEnabled, setConnectEnabled] = useState(null); + const [marketplaceEnabled, setMarketplaceEnabled] = useState(null); + const [connectEnabled, setConnectEnabled] = useState(false); + const [splitsProviders, setSplitsProviders] = useState>([]); const [error, setError] = useState(null); useEffect(() => { @@ -44,22 +42,31 @@ export function VendorSelect(props: VendorSelectProps) { try { const settings = await api.get>("admin/settings"); if (!alive) return; - const on = settings.connectEnabled === true; - setConnectEnabled(on); - if (on) { + const connect = settings.connectEnabled === true; + const providers = Array.isArray(settings._providers) + ? (settings._providers as Array<{ + id: string; + label: string; + capabilities?: { splits?: boolean }; + }>) + : []; + const splits = providers + .filter((provider) => provider.capabilities?.splits === true) + .map((provider) => ({ id: provider.id, label: provider.label })); + const enabled = connect || splits.length > 0; + setConnectEnabled(connect); + setSplitsProviders(splits); + setMarketplaceEnabled(enabled); + if (enabled) { try { const res = await api.get<{ items: Vendor[] }>("admin/vendors"); if (alive) setVendors(res.items ?? []); } catch (err) { - if (alive) - setError( - err instanceof Error ? err.message : "Could not load vendors", - ); + if (alive) setError(err instanceof Error ? err.message : "Could not load vendors"); } } } catch (err) { - if (alive) - setError(err instanceof Error ? err.message : "Could not load settings"); + if (alive) setError(err instanceof Error ? err.message : "Could not load settings"); } } load(); @@ -71,29 +78,33 @@ export function VendorSelect(props: VendorSelectProps) { const options = useMemo(() => { if (!vendors) return []; return vendors.map((v) => { - const statusHint = - v.onboardingStatus === "active" && v.chargesEnabled - ? "Active" - : v.onboardingStatus === "restricted" - ? "Restricted" - : "Pending"; + const stripeReady = connectEnabled && v.chargesEnabled; + const providerReady = splitsProviders.some( + (provider) => v.paymentAccounts?.[provider.id]?.status === "active", + ); + const ready = stripeReady || providerReady; + const statusHint = ready + ? "Active" + : v.onboardingStatus === "restricted" + ? "Restricted" + : "Pending"; return { value: v.id, label: `${v.name} · ${v.email}`, hint: statusHint, - disabled: !v.chargesEnabled, + disabled: !ready, }; }); - }, [vendors]); + }, [vendors, connectEnabled, splitsProviders]); const { value, onChange, field, readOnly } = props; const label = field?.label ?? "Vendor"; - if (connectEnabled === null) { + if (marketplaceEnabled === null) { return ; } - if (!connectEnabled) { + if (!marketplaceEnabled) { return ( - Enable it in Settings → Stripe Connect to assign products to vendors. - Leave this field blank for now. + Enable it in Settings, or install a payment provider that supports split payments, to + assign products to vendors. Leave this field blank for now. ); diff --git a/packages/core/src/admin/pages/VendorsPage.tsx b/packages/core/src/admin/pages/VendorsPage.tsx index 1135908..2d50977 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 = [ @@ -35,9 +37,36 @@ const STATUS_OPTIONS = [ { value: "restricted", label: "Restricted" }, ]; +/** Best-effort initial country for payout onboarding, from the store currency. */ +const COUNTRY_BY_CURRENCY: Record = { + NGN: "NG", + KES: "KE", + GHS: "GH", + ZAR: "ZA", + USD: "US", + GBP: "GB", + EUR: "IE", + XOF: "CI", + XAF: "CM", + ZMW: "ZM", + MWK: "MW", + TZS: "TZ", + UGX: "UG", + RWF: "RW", + EGP: "EG", +}; + interface SettingsGateState { connectEnabled: boolean; defaultFeePercent: number; + defaultCurrency: string | null; + /** Registered providers that can split a payment across vendor accounts. */ + splitsProviders: Array<{ + id: string; + label: string; + payoutOnboarding: boolean; + payoutVerification: boolean; + }>; } type PageState = "loading" | "disabled" | "ready" | "error"; @@ -60,9 +89,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 +107,36 @@ 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 }; + payoutOnboarding?: boolean; + payoutVerification?: boolean; + }>) + : []; + const splitsProviders = providers + .filter((provider) => provider.capabilities?.splits === true) + .map((provider) => ({ + id: provider.id, + label: provider.label, + payoutOnboarding: provider.payoutOnboarding === true, + payoutVerification: provider.payoutVerification === true, + })); setGate({ connectEnabled: enabled, defaultFeePercent: typeof settings.connectPlatformFeePercent === "number" ? (settings.connectPlatformFeePercent as number) : 0, + defaultCurrency: + typeof settings.defaultCurrency === "string" + ? (settings.defaultCurrency as string) + : null, + splitsProviders, }); - if (!enabled) { + if (!enabled && splitsProviders.length === 0) { setPageState("disabled"); return; } @@ -125,7 +174,7 @@ export function VendorsPage() { - { - setLinkUrl(url); - await loadVendors(); - }} - /> + {gate?.connectEnabled ? ( + { + setLinkUrl(url); + await loadVendors(); + }} + /> + ) : gate && gate.splitsProviders.length > 0 ? ( + + ) : null} {linkUrl && ( @@ -261,41 +314,41 @@ export function VendorsPage() { size="sm" onClick={() => setEditing({ - vendorId: v.id, - name: v.name, - fee: v.platformFeePercent, + vendor: v, }) } > Edit - + {v.stripeAccountId && ( + + )} + + ); +} + +function PayoutAccountForm({ + provider, + vendor, + api, + defaultFeePercent, + defaultCurrency, + onChanged, +}: { + 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 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(""); + const [accountName, setAccountName] = useState(null); + const [businessName, setBusinessName] = useState(vendor.name); + const [businessEmail, setBusinessEmail] = useState(vendor.email); + const [businessMobile, setBusinessMobile] = useState(""); + const [splitType, setSplitType] = useState<"percentage" | "flat">("percentage"); + 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); + const [error, setError] = useState(null); + const countries = useMemo(() => countryOptions(), []); + + useEffect(() => { + if (stored) return; + let alive = true; + setBanks(null); + api + .get<{ banks: Array<{ code: string; name: string }> }>("admin/vendors/payout-banks", { + provider: provider.id, + country, + }) + .then((res) => { + if (alive) setBanks(res.banks ?? []); + }) + .catch((err) => { + if (alive) { + setError(err instanceof Error ? err.message : "Could not load banks"); + } + }); + return () => { + alive = false; + }; + }, [api, provider.id, country, stored]); + + if (stored) { + return ( +
+ + {stored.accountName ?? stored.label ?? "Account"} ·{" "} + {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 && + accountNumber.trim().length >= 4 && + businessName.trim().length > 0 && + /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(businessEmail) && + businessMobile.trim().length > 0 && + (!requiresVerification || accountName !== null) && + typeof splitValue === "number" && + splitValue >= 0 && + (splitType === "flat" ? splitValue > 0 : splitValue <= 100); + + async function verify(): Promise { + setVerifying(true); + setError(null); + try { + const res = await api.post<{ accountName: string }>( + "admin/vendors/payout-account/resolve", + { providerId: provider.id, accountNumber: accountNumber.trim(), bankCode }, + ); + setAccountName(res.accountName); + } catch (err) { + setAccountName(null); + setError(err instanceof Error ? err.message : "Could not verify the account"); + } finally { + setVerifying(false); + } + } + + async function create(): Promise { + setCreating(true); + setError(null); + try { + await api.post("admin/vendors/payout-account", { + providerId: provider.id, + vendorId: vendor.id, + accountNumber: accountNumber.trim(), + bankCode, + country, + businessName: businessName.trim(), + businessEmail: businessEmail.trim(), + businessMobile: businessMobile.trim(), + splitType, + splitValue: splitType === "percentage" ? (splitValue ?? 0) / 100 : (splitValue ?? 0), + }); + toast.success("Payout account created"); + await onChanged(); + } catch (err) { + setError(err instanceof Error ? err.message : "Could not create the account"); + } finally { + setCreating(false); + } + } + + return ( +
+

{provider.label} payout account

+ {error && ( + + {error} + + )} + + { + setAccountNumber(e.currentTarget.value); + setAccountName(null); + }} + disabled={creating} + /> + + {requiresVerification ? ( + <> + + {accountName && ( + + {accountName} + + )} + + ) : ( + + This provider cannot verify account names here. The account will be saved as + unverified. + + )} + + 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="Account id" + disabled={saving} + /> + + +