Skip to content

feat(core): split settlement and refunds - #105

Merged
cavewebs merged 8 commits into
emdashCommerce:mainfrom
alexasomba:feat/provider-split-settlement
Dec 3, 2026
Merged

cavewebs merged 8 commits into
emdashCommerce:mainfrom
alexasomba:feat/provider-split-settlement

Conversation

@alexasomba

@alexasomba alexasomba commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Review status: The current head of this PR is included in Flutterwave payment provider #107, which carries split settlement and split refunds in the combined Flutterwave review. Please leave new review feedback on the combined PR. This PR stays open until the changes are confirmed on main. The scope and test results below describe this branch at the time it was submitted.

Part of the Flutterwave set described in Flutterwave integration roadmap #97. Items 8 and 9. Builds on Split payments across vendor payout accounts #101. Generic core; no Flutterwave code. The split-refund guard from Make split refunds explicit #112 is folded in; no review had started there.

Why

Flutterwave's verify response carries meta.split_settlement_info, which says what each subaccount actually earned and the platform's commission. Core was discarding it, so a merchant could see the vendor split at checkout but not what the provider settled. This records the provider's own numbers on the order.

What

  • NormalizedPaymentEvent charge.succeeded gains splitSettlement: allocations (accountReference, amountMinor), platformRemainderMinor, providerFeeMinor, currency and the raw payload.
  • Order.providerSplits stores the same in Money, with the account reference mapped to a vendor when core can resolve it from Vendor.paymentAccounts.
  • The webhook records it after the order is written. A failure is logged and does not make the webhook retry; the order is already complete, and a retry would be answered as a duplicate.
  • The admin order detail shows a Split settlement card: vendor (or “Unmatched account”), account reference, settled amount, platform remainder and provider fee.

What does not change

  • The vendor shares core computed. The provider's settlement is recorded for reconciliation, never used to reprice the order.
  • Orders without a settlement, and Stripe orders, are unchanged.

Tests

  • 349 core tests pass, including 4 new ones:
    • a signed webhook with a settlement creates the order and stores providerSplits with both account references mapped to v1/v2, amounts in minor units, platform remainder and provider fee;
    • a settlement-free event creates the order with no providerSplits;
    • a provider declaring splitRefunds: false is refused before the call and writes no refund row;
    • a provider that does not declare it keeps the existing refund behaviour.
  • Typecheck clean; changeset minor.

Split refunds (folded in from Make split refunds explicit #112)

A split payment cannot always be refunded through the provider from DashCommerce. Flutterwave answers a split refund with 400 "Refund request successfully logged" and no refund id; Stripe Connect refunds work, but the money comes from the platform balance and vendor shares are not clawed back.

  • PaymentProviderCapabilities.splitRefunds: optional. Missing means yes (existing Stripe behaviour). false means the provider cannot refund a split charge.
  • refundOrder refuses before loading credentials or calling the provider when order.providerSplits is present and the provider declares false, with a message pointing to its dashboard.
  • Order detail → Split settlement warns that the refund comes from the platform balance and vendor shares are not recovered automatically.
  • The Flutterwave package declares splitRefunds: false in feat(flutterwave): Flutterwave payment provider package #107.

Next

The Flutterwave package (Flutterwave payment provider #107) parses meta.split_settlement_info and app_fee into this event shape, so the real split we already tested is recorded on the order.

@moset15 moset15 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fits Paystack directly. charge.success for a split payment carries split.shares: subaccounts[].amount with subaccount_code → allocations, integration → platformRemainderMinor, paystack → providerFeeMinor. No change needed from the Paystack side.

createVendor stored stripeAccountId: "" and the field has a unique
index, so the second vendor failed. The field is now optional and
omitted when there is no Stripe account; a missing field is NULL.

Also documents the coupon rule for split allocations (the platform
absorbs a cart-wide discount; a larger one is a 409) and makes the
allocation comments generic for Paystack.
@alexasomba alexasomba changed the title feat(core): record provider split settlements on orders feat(core): split settlement and refunds Nov 25, 2026
moset15 added a commit to FIKANOVA/dashcommerce that referenced this pull request Nov 26, 2026
[FIK-78] feat(paystack): multi-vendor payments with Paystack splits (rebuilt on current emdashCommerce#101/emdashCommerce#103/emdashCommerce#105)

@cavewebs cavewebs left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good. I will take it through #107 rather than merging it on its own, so we avoid the sibling conflicts with #103.

cavewebs added a commit that referenced this pull request Nov 27, 2026
Part of the Flutterwave set described in #97. **Item 4** — a generic
core seam; no Flutterwave code in core.

## Why

A cart with vendor-owned items could not be paid by a non-Stripe
provider at all, and Stripe Connect deliberately rejects multi-vendor
carts. Flutterwave supports splitting one payment into collection
subaccounts with an exact `flat_subaccount` amount, but core had no way
to hand a provider per-vendor amounts.

This adds that seam. Core owns the arithmetic; a provider only routes
what core supplies.

## What

- **`capabilities.splits`** on `PaymentProvider`, and `splits` in
`unsupportedHostedCheckoutFeatures`. A vendor cart is now refused with a
readable 409 for a provider that cannot split, instead of silently
charging the platform account.
- **`InitCheckoutInput.allocations`** (`vendorId`, `accountReference`,
`amountMinor`) and **`platformRemainderMinor`**. Core computes them from
trusted cart prices and the vendor's platform fee; providers must not
reprice.
- **`Vendor.paymentAccounts`**, keyed by provider id, for providers
other than Stripe: `accountReference`, `status`, optional settlement
currency and label. Stripe Connect keeps its existing fields.
- **`computeProviderSplit`**: groups cart lines by vendor, requires an
active account in the cart's currency, applies the vendor/global
platform fee, and returns exact minor amounts. It throws
merchant-readable errors for a missing vendor, a
missing/pending/disabled account, a currency mismatch, a non-positive
share, or a cart-wide discount larger than the platform remainder.
- **Admin API**: `POST admin/vendors/item` creates a vendor without
Stripe; `PATCH` accepts `paymentAccount` or `paymentAccounts` to add,
replace or remove an account. Vendor routes open when Connect is on
**or** a split-capable provider is registered.
- **Settings** exposes each provider's `capabilities`, and the **Vendors
page** adds a vendor and edits payout accounts when a split-capable
provider is active — no Stripe onboarding needed. The Stripe
onboarding/refresh/payout routes still require Connect.
- **Product editor**: the vendor picker and the save-time validation now
accept a split-capable provider's active payout account, not only Stripe
`chargesEnabled`. A Flutterwave-only store can assign products to
vendors without turning on Stripe Connect.

## What does not change

- Stripe Connect: single-vendor destination charges are untouched;
multi-vendor Stripe carts still return 501.
- A cart without vendor items sends no allocations.
- Vendor records created by Stripe onboarding keep working;
`paymentAccounts` is additive.

## Tests

- **345 core tests pass**, including 18 new ones for split computation
and the vendor API, 5 for product-to-vendor assignment, and 4 that run
the real `checkout/create-session` route:
- two vendors at 10% → `135000` each, platform remainder `180000`
(platform item + fees);
  - no vendor items → no allocations;
  - a provider without `splits` → 409 naming `splits`;
  - a vendor with no account → 409 naming the vendor.
- Split computation covers fees, overrides, tax/shipping/platform items,
missing vendors, pending/disabled accounts, currency mismatch, zero
shares, a platform-absorbed discount and a discount larger than the
platform remainder.
- Vendor API covers the gate, create, add/replace/remove,
unknown/non-splitting providers, bad references/status, Stripe status
untouched, search by account reference, and creating two vendors without
a Stripe account.
- `tsc --noEmit` clean; Biome clean on the touched files.

## Next

The Flutterwave package is
[#107](#107), which
builds on this.
[#103](#103) (payout
onboarding) and
[#105](#105)
(settlement) also build on this.

## Review response (moset15)

- **Vendor unique index:** `Vendor.stripeAccountId` is now optional and
`createVendor` omits it for non-Stripe vendors. A missing field is NULL,
so a shop without Stripe can create any number of vendors; two vendors
still cannot share an `acct_…`. Test: two vendors through
`admin/vendors/item`. The Stripe Refresh action is hidden when a vendor
has no Stripe account.
- **Generic comments:** `accountReference` and `capabilities.splits` now
name Paystack's `ACCT_…` as well as Flutterwave's `RS_…`.
- **Fee bearer:** the README provider-author section says to keep the
fee on the platform so vendor shares stay exact.
- **Coupons:** intended. Shares are computed on pre-discount line
subtotals, matching `split.ts`; the platform absorbs a cart-wide
discount, and a discount larger than the platform remainder is refused
with a readable 409 rather than silently reducing a vendor's payout.
Tests cover both cases. If you want vendors to bear part of the
discount, that is a separate policy change.

## Review notes

- `onboardingStatus` is set to `active` for a non-Stripe vendor when any
provider account is active, so the existing status badge is meaningful.
A Stripe vendor's status is never changed by a provider account.
- The Vendors page only shows payout-account fields for providers that
declare `splits`; Connect-only stores see the page exactly as before.
- API-driven payout onboarding is #103, implemented for Flutterwave in
#107. The manual `RS_…` field remains as a fallback.
@alexasomba

Copy link
Copy Markdown
Contributor Author

The split-refund fix is in #107 (a38d530). Core records whether checkout sent split allocations, so it can block unsupported refunds even when the webhook omits settlement details.

@cavewebs
cavewebs merged commit 693454f into emdashCommerce:main Dec 3, 2026
cavewebs added a commit that referenced this pull request Dec 3, 2026
This PR brings the Flutterwave adapter and the Core changes it needs
into one review.

- Integration roadmap in #97

## Superseded package PRs

The changes from these five stacked PRs are included here.

- #98
- #100
- #102
- #104
- #106

## Review and merge order

Core support for provider public keys, split allocations, and checkout
and refund safety has merged in the following PRs.

- #99
- #101
- #115

This branch also includes the current heads of the following PRs. Review
their changes here if we merge the combined PR. Keep the original
threads open until the changes are confirmed on `main`.

- #103
- #105
- #114

A merge commit can preserve those PR heads and let GitHub mark them
merged indirectly. If this PR is squash-merged and any companions remain
open, verify their changes on `main` before closing them with a link
here.

moset15’s earlier draft [Stripe subscription checkout and customer
linking #138](#138)
overlaps with this PR in `storage-collections.ts`. When either PR lands,
bring the other up to date with `main` and preserve the draft’s customer
lookup index alongside this PR’s refund dispatch storage.

## Release

Changesets plans Flutterwave 0.1.0 with Core 0.6.0 when this PR is
included in the release. Flutterwave declares a Core peer range of
`>=0.6.0 <1.0.0`. The minimum release must contain its provider
interfaces and currency helper. If the release in [Core release PR
#120](#120) ships
before these changes land, update the Flutterwave peer floor to the next
Core release that actually includes them.

## What

`packages/flutterwave`: a `PaymentProvider` for Flutterwave v3. It
registers itself on `import "@dashcommerce/flutterwave"`.

| Area | Behaviour |
|---|---|
| Hosted checkout | Validate the hosted redirect URL, allow the sandbox
host with test credentials, and return the verified checkout reference
alongside the charge ID for [Verify hosted payments on return
#126](#126) |
| On-page | Flutterwave Inline over the store's checkout via
`./checkout-client`; `v3.js` loads only on Pay; orders still come only
from the webhook |
| Subscriptions | Payment Plans, card-only. One plan per checkout (the
plan id is the subscription key); `payment_plan` on hosted and Inline;
record verified renewals once after matching transaction, plan, amount,
and currency; late payments preserve cancellation; cancel/resume through
the plan |
| Amounts | Core minor units ↔ Flutterwave major units, converted once
at the boundary |
| Webhooks | Constant-time `verif-hash`, event deduplication, and
provider verification before settling. Preserve the customer email saved
at checkout when it is present |
| Refunds | Reserve the request before dispatch, reconcile retries by
the request tag and verified original charge, and keep acceptance
pending until Flutterwave reports disbursement or failure |
| Splits | Core allocations → `subaccounts` with `flat_subaccount` + the
exact amount, hosted and Inline |
| Vendor onboarding | List banks, verify the account name, create the
subaccount, store the masked result |
| Discounts | `capabilities.coupons: true`; the discount is applied to
the amount Flutterwave charges |
| Reconciliation | Parses `meta.split_settlement_info` + `app_fee` into
core's `splitSettlement`; the order records what each subaccount earned
|
| Connection check | Read-only `GET /v3/balances`, test/live mode |

Currencies: NGN, USD, GBP, EUR, KES, GHS, ZAR, UGX, TZS, RWF, XOF, XAF,
ZMW, MWK, EGP.

## API facts checked, not assumed

- Flutterwave subaccounts: default `split_type` is `percentage` or
`flat`; the transaction override supports `flat_subaccount`, `flat` and
`percentage`. DashCommerce uses `flat_subaccount` with the exact vendor
amount so the shares never drift; the default is only a fallback.
- `GET /v3/banks/{country}` → `{ code, name }`; `POST
/v3/accounts/resolve` → `account_name`; `POST /v3/subaccounts` requires
the bank, account, business name, country, mobile and `split_value` (and
email in practice).
- Paystack's docs define `type: percentage|flat` and `share` but not the
flat share unit; that remains an open question for its own PR.
- Payment Plans: `POST /v3/payment-plans` with `interval` (`monthly`,
`every 3 months`, …), `amount`, `currency` and `duration: 0`; pass
`payment_plan` on the first charge. `verify` returns `plan`, which is
how a charge is tied to the plan. `GET /v3/subscriptions` answered `400
"Service error"` on the test account, so the package uses the plan id
and cancels via `PUT /v3/payment-plans/{id}/cancel`.

## Live test-mode evidence (24 Nov 2026)

| Check | Result |
|---|---|
| Hosted link creation | 200, real link |
| Real KES 1,500 M-Pesa payment via Inline | Succeeded, transaction
`10633614`; `callback` → `finished` |
| Verify by id and `tx_ref` | `succeeded`, `150000` minor, KES |
| Two-vendor split (KES 1,500) | 900 to `RS_CD57…`, 450 to `RS_A075…`,
76.5 platform after the 73.5 fee; confirmed in
`meta.split_settlement_info` |
| Payout onboarding | 598 NG banks; `0690000033` resolved to `Bale
Gary`; created `RS_043B…`, then deleted the probe |
| Partial + settled-max refunds | Succeeded; verify still reports
`successful` (documented) |
| Split refund | Flutterwave returned `400` with `Refund request
successfully logged` and no id; treated as a failure and surfaced, not
claimed as success |
| Subscription plan + first charge | Plan `254811` (KES 100/month); real
test-card payment `10634465` through Inline; `verify` returned `plan:
254811` |
| Package-level plan creation | `initCheckout` created plan `254812` and
opened Inline with `payment_plan`; plan cancelled after the probe |

## Validation

- Frozen install, workspace typecheck, and workspace build passed
locally. All 789 workspace tests passed, including 398 Core and 137
Flutterwave tests.
- An isolated merge preview with #126 passed 14 focused tests, including
a verified Flutterwave checkout reference with a distinct numeric
capture ID.
- [GitHub checks for the review follow-up
commit](https://github.com/emdashCommerce/dashcommerce/actions/runs/47085699551).

The Flutterwave test-mode results above are historical. The refund-retry
and renewal edge cases use fixtures.

## Review fixes included

- The Flutterwave peer range covers Core 0.6.0 through the rest of the
0.x series, matching Paystack’s range pattern. The lockfile mirrors the
current workspace versions and peer declarations.
- The subscriptions table uses labels from the provider registry. Legacy
Stripe rows still show Stripe, and rows for removed providers show their
stored provider ID.
- Removed the duplicated provider doc-comment opener and kept a single
checkout guard for subscription carts with vendor-owned items.

This branch includes the changes requested on [Provider-managed payout
onboarding
#103](#103):
verification is optional when a provider cannot resolve names, an
active-but-unverified account is stored with `verified: false`
(Paystack's `is_verified: false`), the onboarding form starts on the
store's default-currency country, and the bank picker accepts
mobile-money channels such as M-PESA. Onboarding is also idempotent
here: re-adding the same bank account returns Flutterwave's existing
subaccount, matched by account number and bank rather than the error
text.

## Deliberately not included

- Country-specific subaccount `meta` (SWIFT/routing/branch) in the form.
The docs conflict between the create reference and the split guide, and
there are no test accounts for those countries; the README says to
create those accounts in the dashboard/API for now.
- API-driven split refunds: Flutterwave's split-refund response has no
refund id, so the package surfaces the message and points to the
dashboard.
- Subscription trials, pausing, in-place upgrades and multiple
subscription lines per checkout. All fail loudly; cancel and resume are
supported.
@cavewebs

cavewebs commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

This landed as part of #107, so I'm closing it here. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants