diff --git a/.changeset/flutterwave-provider.md b/.changeset/flutterwave-provider.md new file mode 100644 index 0000000..729ba8f --- /dev/null +++ b/.changeset/flutterwave-provider.md @@ -0,0 +1,18 @@ +--- +"@dashcommerce/flutterwave": minor +--- + +New package: a Flutterwave payment provider for DashCommerce, built on core's PaymentProvider interface. + +- Hosted checkout and on-page Flutterwave Inline (card, M-Pesa, mobile money) in NGN, USD, GBP, EUR, KES, GHS, ZAR, UGX, TZS, RWF, XOF, XAF, ZMW, MWK and EGP. +- Amounts convert at the boundary: core keeps minor units, Flutterwave's v3 API charges major units. +- Orders only from a signed `charge.completed`, confirmed with a live verify. `verif-hash` is checked in constant time against the secret hash; repeat and overlapping deliveries are deduplicated. +- Refunds by transaction id or `tx_ref`, guarded against duplicates on retry, with Flutterwave's refund webhook moving each refund to succeeded or failed. +- Split payments: core's exact per-vendor allocations map to `subaccounts` with `flat_subaccount`, for hosted and Inline. The subaccount default may be percentage or flat; the transaction override keeps the shares exact. +- In-admin vendor onboarding: list banks or mobile-money channels, verify the account name, create the collection subaccount, and store the masked result. Re-adding the same bank account returns the existing subaccount instead of failing. +- Cart discounts: `capabilities.coupons` is true; the discount is applied to the amount Flutterwave charges. +- Subscriptions through Flutterwave Payment Plans: one plan per checkout (the plan id is the subscription key), `payment_plan` on hosted and Inline, renewal invoices from the `plan` field on verify/webhook, and cancel/resume through the plan. Card-only; no trials, pause or in-place upgrades. +- Split reconciliation: parses `meta.split_settlement_info` and `app_fee` into core's `splitSettlement`, so the order records what each subaccount earned. +- "Test Flutterwave connection" checks the saved key in test or live mode with a read-only balances call. + +Needs core 0.4.0 or later with the provider seams (public key, split allocations, payout onboarding, split settlement). Register with `import "@dashcommerce/flutterwave"`, add `api.flutterwave.com` to `allowedHosts`, and point the webhook at `…/checkout/webhook?provider=flutterwave`. 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-public-key.md b/.changeset/provider-public-key.md new file mode 100644 index 0000000..a2bedb8 --- /dev/null +++ b/.changeset/provider-public-key.md @@ -0,0 +1,9 @@ +--- +"@dashcommerce/core": minor +--- + +Let a payment provider save a browser public key. + +- `PaymentProviderCredentials.publicKey` and `credentialFields.publicKey`, saved as `settings:PublicKey` and validated against the prefixes the provider declares. Providers that need it for on-page checkout (Flutterwave Inline) can hand it to their browser client; nothing else changes for providers that do not. +- Settings shows the field only for a provider that declares it, beside the secret key and webhook secret. A provider that does not declare one cannot have a public key saved, and its settings row is unchanged. +- `loadPaymentProviderCredentials` returns `publicKey` when one is set. 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/.changeset/provider-split-refunds.md b/.changeset/provider-split-refunds.md new file mode 100644 index 0000000..e6d3bb4 --- /dev/null +++ b/.changeset/provider-split-refunds.md @@ -0,0 +1,9 @@ +--- +"@dashcommerce/core": minor +--- + +Make split refunds explicit. + +- `PaymentProviderCapabilities.splitRefunds` lets a provider declare that its API cannot refund a split charge. Missing means yes, preserving Stripe Connect behaviour. +- `refundOrder` refuses a split order before calling a provider that declares `splitRefunds: false`, with a message pointing to the provider's dashboard. +- The order detail's **Split settlement** card warns that a refund comes from the platform balance and that vendor shares are not recovered automatically. diff --git a/.changeset/provider-split-settlement.md b/.changeset/provider-split-settlement.md new file mode 100644 index 0000000..d0adb44 --- /dev/null +++ b/.changeset/provider-split-settlement.md @@ -0,0 +1,10 @@ +--- +"@dashcommerce/core": minor +--- + +Record provider-reported split settlements on the order. + +- `NormalizedPaymentEvent` `charge.succeeded` gains `splitSettlement`: per-account minor amounts, the platform remainder and the provider fee, when the provider reports them. +- `Order.providerSplits` stores it with the account reference mapped to a vendor when core can resolve it, for reconciliation. It never changes the vendor shares core computed. +- The webhook records it after the order is written. A failure is logged and does not make the webhook retry, because the order is already complete. +- The admin order detail shows a "Split settlement" card when the order has one. diff --git a/.changeset/provider-subscriptions.md b/.changeset/provider-subscriptions.md new file mode 100644 index 0000000..d9f123e --- /dev/null +++ b/.changeset/provider-subscriptions.md @@ -0,0 +1,12 @@ +--- +"@dashcommerce/core": minor +--- + +Add a provider-neutral subscription seam. + +- `PaymentProvider` gains optional `getSubscription`, `cancelSubscription` and `resumeSubscription`. Stripe keeps its existing Billing path; providers that manage billing themselves can use these. +- `charge.succeeded` and `PaymentStatusResult` can carry `ProviderSubscriptionInfo`, so a provider can identify the subscription/plan behind a charge. +- A normalised `subscription.updated` event lets a provider report a cancellation or status change outside a charge; core updates the local row. +- New `subscriptions/provider.ts` stores a provider-managed subscription and its invoices in the existing collections. The provider id is part of the unique storage key for both subscriptions and invoices (`${providerId}:${id}`), so two providers cannot collide on a numeric plan or transaction id. The first charge creates an order and a local subscription; later charges are recorded as invoices and extend the period, not as new orders. +- `subscriptions/lifecycle.ts` dispatches cancel/resume to a provider-managed subscription. Pause and in-place plan changes are refused for providers that do not support them. The admin and customer portal hide pause and the Stripe billing portal for those subscriptions. +- Stripe's `stripeSubscriptionId`/`stripeInvoiceId` fields keep their names for compatibility; they now hold the provider's subscription/plan and invoice id. diff --git a/bun.lock b/bun.lock index ab110bf..c7ed707 100644 --- a/bun.lock +++ b/bun.lock @@ -57,6 +57,18 @@ "typescript": "^5.9.0", }, }, + "packages/flutterwave": { + "name": "@dashcommerce/flutterwave", + "version": "0.0.0", + "devDependencies": { + "@dashcommerce/core": "workspace:*", + "tsdown": "^0.20.0", + "typescript": "^5.9.3", + }, + "peerDependencies": { + "@dashcommerce/core": "^0.4.0", + }, + }, "packages/lite": { "name": "@dashcommerce/lite", "version": "0.2.0", @@ -339,6 +351,8 @@ "@dashcommerce/create": ["@dashcommerce/create@workspace:packages/create"], + "@dashcommerce/flutterwave": ["@dashcommerce/flutterwave@workspace:packages/flutterwave"], + "@dashcommerce/lite": ["@dashcommerce/lite@workspace:packages/lite"], "@dashcommerce/registry-setup": ["@dashcommerce/registry-setup@workspace:packages/registry-setup"], diff --git a/packages/core/README.md b/packages/core/README.md index 5e9a141..bc29a23 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -62,14 +62,21 @@ Stripe is built in. A gateway package (for example `@dashcommerce/paystack`) reg emdash({ plugins: [dashcommerce({ allowedHosts: ["api.paystack.co"] })] }); ``` -3. **Choose the provider and enter its keys** in Settings → Payment provider. They are saved as `settings:SecretKey` and `settings:WebhookSecret`, masked like Stripe's. +3. **Choose the provider and enter its keys** in Settings → Payment provider. They are saved as `settings:SecretKey` and `settings:WebhookSecret` (plus `settings:PublicKey` when the provider declares one), masked like Stripe's. 4. **Point the provider's webhooks** at `/_emdash/api/plugins/dashcommerce/checkout/webhook?provider=`. For provider authors, `PaymentProvider` can declare: -- `credentialFields`: the label, accepted prefixes and help text for the settings form. +- `credentialFields`: the label, accepted prefixes and help text for the settings form. A `publicKey` field is shown only when declared, for on-page checkout that needs the browser key (Flutterwave Inline); `credentials.publicKey` carries the saved value. - `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. +- `capabilities.splitRefunds`: set `false` when the provider cannot refund a split charge. Core then refuses the refund before calling the provider and points the merchant to its dashboard. Missing means yes (Stripe Connect), though vendor shares are not clawed back. +- `splitSettlement` on a `charge.succeeded` event: optional provider-reported per-account amounts, platform remainder and fee. Core stores it on `Order.providerSplits` for reconciliation; it never changes the shares core computed. +- `capabilities.subscriptions` plus optional `getSubscription`, `cancelSubscription` and `resumeSubscription`: core stores the provider's subscription/plan id from the first `charge.succeeded` that carries `subscription`, records later charges as invoices, and dispatches cancel/resume. Return `ProviderSubscriptionInfo`. A provider that cannot pause or change plans in place can omit those methods; core refuses the action with a readable error. +- `parseWebhookEvent` may return `subscription.updated` for a cancellation or status change outside a charge. Core updates the local row and does not create an order. +- 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/OrderDetailPage.tsx b/packages/core/src/admin/pages/OrderDetailPage.tsx index d75c01c..b89d0e2 100644 --- a/packages/core/src/admin/pages/OrderDetailPage.tsx +++ b/packages/core/src/admin/pages/OrderDetailPage.tsx @@ -25,7 +25,13 @@ import { import { MoneyDisplay } from "../ui/MoneyDisplay"; import { StatusBadge } from "../ui/StatusBadge"; import { EmptyState } from "../ui/EmptyState"; -import type { Order, OrderItem, OrderStatus, Refund } from "../../types"; +import type { + Order, + OrderItem, + OrderProviderSplitAllocation, + OrderStatus, + Refund, +} from "../../types"; import { T } from "../theme"; // Allowed forward transitions mirrored from `../../orders/status.ts` so the @@ -130,6 +136,7 @@ export function OrderDetailPage() { + @@ -307,6 +314,61 @@ function ItemsCard({ items }: { items: OrderItem[] }) { ); } +// ──────────────────────────────────────────────────────────────────────────── +// Split settlement +// ──────────────────────────────────────────────────────────────────────────── + +function SplitSettlementCard({ order }: { order: Order }) { + const split = order.providerSplits; + if (!split) return null; + return ( + +

+ Reported by {split.providerId} when the payment was captured. This records what the + provider says each account earned; it does not change the shares DashCommerce + computed. +

+ + A refund comes out of the platform balance; vendor shares are not recovered + automatically. If the provider cannot refund a split payment from DashCommerce, use + its dashboard. + + + data={split.allocations} + getRowKey={(a) => a.accountReference} + columns={[ + { + key: "vendor", + header: "Vendor", + render: (a) => a.vendorId ?? "Unmatched account", + }, + { + key: "account", + header: "Account", + render: (a) => a.accountReference, + }, + { + key: "amount", + header: "Settled", + render: (a) => , + }, + ]} + /> + {split.platformRemainder && ( +

+ Platform remainder:{" "} + +

+ )} + {split.providerFee && ( +

+ Provider fee: +

+ )} +
+ ); +} + // ──────────────────────────────────────────────────────────────────────────── // Refund panel // ──────────────────────────────────────────────────────────────────────────── diff --git a/packages/core/src/admin/pages/SettingsPage.tsx b/packages/core/src/admin/pages/SettingsPage.tsx index cf623d0..031fa27 100644 --- a/packages/core/src/admin/pages/SettingsPage.tsx +++ b/packages/core/src/admin/pages/SettingsPage.tsx @@ -132,16 +132,25 @@ interface ProviderRow { description?: string | null; logo?: string | null; brandColour?: string | null; - credentialFields?: { secretKey?: CredentialField; webhookSecret?: CredentialField }; + credentialFields?: { + secretKey?: CredentialField; + webhookSecret?: CredentialField; + publicKey?: CredentialField; + }; canCheckConnection?: boolean; - secrets?: { secretKey: SecretMeta; webhookSecret: SecretMeta }; + secrets?: { + secretKey: SecretMeta; + webhookSecret: SecretMeta; + /** Present only when the provider declares a public key. */ + publicKey?: SecretMeta; + }; /** Absent from servers before on-page checkout: treat as hosted only. */ checkoutStyles?: Array<"hosted" | "on_page">; } /** - * Fixed settings, plus `SecretKey` / `WebhookSecret` - * for registered non-Stripe providers. + * Fixed settings, plus `SecretKey` / `WebhookSecret` / + * `PublicKey` for registered non-Stripe providers. */ type Draft = Partial> & { [providerCredential: string]: unknown; @@ -580,6 +589,21 @@ function GroupBody({ setField={setField} disabled={disabled} /> + {selected.credentialFields?.publicKey && ( + + )} {selected.canCheckConnection && ( )} @@ -831,7 +855,7 @@ function SecretField({ setField, disabled, }: { - /** `stripeSecretKey`, `stripeWebhookSecret`, or a provider's `SecretKey` / `WebhookSecret`. */ + /** `stripeSecretKey`, `stripeWebhookSecret`, or a provider's `SecretKey` / `WebhookSecret` / `PublicKey`. */ keyName: string; label: string; description?: string; diff --git a/packages/core/src/admin/pages/SubscriptionsPage.tsx b/packages/core/src/admin/pages/SubscriptionsPage.tsx index 1cdcd34..7cfe49b 100644 --- a/packages/core/src/admin/pages/SubscriptionsPage.tsx +++ b/packages/core/src/admin/pages/SubscriptionsPage.tsx @@ -3,9 +3,9 @@ * `useListControls`, plus cancel/pause/resume with confirm dialogs, * per-row pending states, and toast feedback. * - * Stripe is the source of truth for subscription state, so we deliberately - * avoid optimistic updates: after every action we reload the list so the - * row reflects whatever webhook response came back. + * The payment provider is the source of truth for subscription state, so we + * deliberately avoid optimistic updates: after every action we reload the + * list so the row reflects whatever webhook response came back. */ import { useCallback, useMemo, useState } from "react"; @@ -64,19 +64,21 @@ function isCancellable(sub: Subscription): boolean { return !cancelled.includes(sub.status) && !sub.cancelAtPeriodEnd; } +function isProviderManaged(sub: Subscription): boolean { + return Boolean(sub.providerId && sub.providerId !== "stripe"); +} + function isPausable(sub: Subscription): boolean { - return sub.status === "active" || sub.status === "trialing"; + return (sub.status === "active" || sub.status === "trialing") && !isProviderManaged(sub); } function isResumable(sub: Subscription): boolean { - return sub.status === "paused"; + return sub.status === "paused" || (isProviderManaged(sub) && sub.status === "canceled"); } export function SubscriptionsPage() { const api = usePluginAPI(); - const [pending, setPending] = useState<{ id: string; action: Action } | null>( - null, - ); + const [pending, setPending] = useState<{ id: string; action: Action } | null>(null); const buildQuery = useMemo( () => (f: SubscriptionsFilters) => ({ @@ -89,23 +91,14 @@ export function SubscriptionsPage() { [], ); - const { - filters, - setFilter, - resetFilters, - items, - loading, - error, - hasMore, - loadMore, - reload, - } = useListControls({ - api, - endpoint: "admin/subscriptions", - initialFilters: INITIAL, - buildQuery, - limit: 50, - }); + const { filters, setFilter, resetFilters, items, loading, error, hasMore, loadMore, reload } = + useListControls({ + api, + endpoint: "admin/subscriptions", + initialFilters: INITIAL, + buildQuery, + limit: 50, + }); const act = useCallback( async (sub: Subscription, action: Action): Promise => { @@ -116,7 +109,7 @@ export function SubscriptionsPage() { title: immediate ? "Cancel subscription now?" : "Cancel at period end?", description: immediate ? "The customer loses access immediately. Any remaining time in the current period is not refunded automatically." - : `Access continues until ${new Date(sub.currentPeriodEnd).toLocaleDateString()}, then Stripe will cancel the subscription.`, + : `Access continues until ${new Date(sub.currentPeriodEnd).toLocaleDateString()}, then the payment provider will cancel the subscription.`, confirmLabel: immediate ? "Cancel now" : "Cancel at period end", destructive: true, }); @@ -126,7 +119,7 @@ export function SubscriptionsPage() { const ok = await confirm({ title: "Pause subscription?", description: - "Stripe stops generating invoices until the subscription is resumed. The customer keeps their record but won't be billed.", + "The payment provider stops generating invoices until the subscription is resumed. The customer keeps their record but won't be billed.", confirmLabel: "Pause", }); if (!ok) return; @@ -153,10 +146,7 @@ export function SubscriptionsPage() { } await reload(); } catch (err) { - toast.error( - "Action failed", - err instanceof Error ? err.message : String(err), - ); + toast.error("Action failed", err instanceof Error ? err.message : String(err)); } finally { setPending(null); } @@ -186,12 +176,7 @@ export function SubscriptionsPage() { label="Status" value={filters.status} options={STATUS_FILTERS} - onChange={(e) => - setFilter( - "status", - e.currentTarget.value as SubscriptionStatus | "", - ) - } + onChange={(e) => setFilter("status", e.currentTarget.value as SubscriptionStatus | "")} /> 0 ? "No subscriptions match" : "No subscriptions yet" - } + title={activeFilters > 0 ? "No subscriptions match" : "No subscriptions yet"} description={ activeFilters > 0 ? "Try widening your filters." @@ -259,6 +242,16 @@ export function SubscriptionsPage() { data={items} getRowKey={(s) => s.id} columns={[ + { + key: "provider", + header: "Provider", + render: (s) => { + const provider = s.providerId ?? "stripe"; + if (provider === "stripe") return "Stripe"; + if (provider === "flutterwave") return "Flutterwave"; + return provider; + }, + }, { key: "status", header: "Status", @@ -272,9 +265,7 @@ export function SubscriptionsPage() { > {s.cancelAtPeriodEnd && ( - - Cancels at period end - + Cancels at period end )} ), @@ -306,11 +297,7 @@ export function SubscriptionsPage() { key: "act", header: "", render: (s) => ( - act(s, a)} - /> + act(s, a)} /> ), }, ]} @@ -379,14 +366,16 @@ function SubscriptionActions({ )} {isCancellable(sub) && ( <> - + {!isProviderManaged(sub) && ( + + )} - + {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} + /> + + +