@volter/twin-stripe 0.1.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -27
- package/client/dashboard-api.ts +286 -0
- package/client/stripe-mirror.css +272 -159
- package/client/stripe-mirror.tsx +1384 -541
- package/dist/client/dashboard-api.d.ts +107 -0
- package/dist/client/dashboard-api.js +238 -0
- package/dist/client/dashboard-api.ts +286 -0
- package/dist/client/stripe-mirror.bundle.js +236 -0
- package/dist/client/stripe-mirror.css +275 -0
- package/dist/client/stripe-mirror.d.ts +134 -0
- package/dist/client/stripe-mirror.js +823 -0
- package/dist/client/stripe-mirror.tsx +1534 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +39 -0
- package/dist/src/generated/events.gen.json +1 -0
- package/dist/src/generated/surface.gen.json +1 -0
- package/dist/src/generated/ui.gen.json +1 -0
- package/dist/src/index.d.ts +14 -0
- package/dist/src/index.js +73 -0
- package/dist/src/manifest.d.ts +2 -0
- package/dist/src/manifest.js +1065 -0
- package/dist/src/screens/checkout.d.ts +31 -0
- package/dist/src/screens/checkout.js +241 -0
- package/dist/src/screens/consent-skin.d.ts +4 -0
- package/dist/src/screens/consent-skin.js +18 -0
- package/dist/src/screens/financial-connections.d.ts +5 -0
- package/dist/src/screens/financial-connections.js +90 -0
- package/dist/src/screens/identity.d.ts +5 -0
- package/dist/src/screens/identity.js +86 -0
- package/dist/src/screens/industries.d.ts +1 -0
- package/dist/src/screens/industries.js +267 -0
- package/dist/src/screens/onboarding.d.ts +13 -0
- package/dist/src/screens/onboarding.js +225 -0
- package/dist/src/screens/portal.d.ts +5 -0
- package/dist/src/screens/portal.js +214 -0
- package/dist/src/screens/public-details.d.ts +5 -0
- package/dist/src/screens/public-details.js +90 -0
- package/dist/src/semantics/after-payment.d.ts +22 -0
- package/dist/src/semantics/after-payment.js +93 -0
- package/dist/src/semantics/apps-secrets.d.ts +2 -0
- package/dist/src/semantics/apps-secrets.js +54 -0
- package/dist/src/semantics/balance.d.ts +11 -0
- package/dist/src/semantics/balance.js +195 -0
- package/dist/src/semantics/billing.d.ts +2 -0
- package/dist/src/semantics/billing.js +220 -0
- package/dist/src/semantics/charges.d.ts +28 -0
- package/dist/src/semantics/charges.js +201 -0
- package/dist/src/semantics/checkout.d.ts +15 -0
- package/dist/src/semantics/checkout.js +303 -0
- package/dist/src/semantics/connect.d.ts +5 -0
- package/dist/src/semantics/connect.js +476 -0
- package/dist/src/semantics/coupons.d.ts +6 -0
- package/dist/src/semantics/coupons.js +92 -0
- package/dist/src/semantics/credit-notes.d.ts +2 -0
- package/dist/src/semantics/credit-notes.js +172 -0
- package/dist/src/semantics/customers.d.ts +6 -0
- package/dist/src/semantics/customers.js +429 -0
- package/dist/src/semantics/disputes.d.ts +2 -0
- package/dist/src/semantics/disputes.js +51 -0
- package/dist/src/semantics/entitlements.d.ts +2 -0
- package/dist/src/semantics/entitlements.js +95 -0
- package/dist/src/semantics/ephemeral-keys.d.ts +2 -0
- package/dist/src/semantics/ephemeral-keys.js +34 -0
- package/dist/src/semantics/files.d.ts +2 -0
- package/dist/src/semantics/files.js +125 -0
- package/dist/src/semantics/invoices.d.ts +18 -0
- package/dist/src/semantics/invoices.js +541 -0
- package/dist/src/semantics/issuing.d.ts +13 -0
- package/dist/src/semantics/issuing.js +570 -0
- package/dist/src/semantics/ledger.d.ts +54 -0
- package/dist/src/semantics/ledger.js +181 -0
- package/dist/src/semantics/payment-intents.d.ts +18 -0
- package/dist/src/semantics/payment-intents.js +404 -0
- package/dist/src/semantics/payment-links.d.ts +2 -0
- package/dist/src/semantics/payment-links.js +133 -0
- package/dist/src/semantics/payment-methods.d.ts +20 -0
- package/dist/src/semantics/payment-methods.js +138 -0
- package/dist/src/semantics/plans.d.ts +5 -0
- package/dist/src/semantics/plans.js +121 -0
- package/dist/src/semantics/platform.d.ts +9 -0
- package/dist/src/semantics/platform.js +206 -0
- package/dist/src/semantics/products.d.ts +2 -0
- package/dist/src/semantics/products.js +140 -0
- package/dist/src/semantics/radar.d.ts +2 -0
- package/dist/src/semantics/radar.js +83 -0
- package/dist/src/semantics/refunds.d.ts +9 -0
- package/dist/src/semantics/refunds.js +195 -0
- package/dist/src/semantics/renewals.d.ts +47 -0
- package/dist/src/semantics/renewals.js +251 -0
- package/dist/src/semantics/setup-intents.d.ts +2 -0
- package/dist/src/semantics/setup-intents.js +84 -0
- package/dist/src/semantics/shared.d.ts +78 -0
- package/dist/src/semantics/shared.js +192 -0
- package/dist/src/semantics/subscription-schedules.d.ts +2 -0
- package/dist/src/semantics/subscription-schedules.js +119 -0
- package/dist/src/semantics/subscriptions.d.ts +11 -0
- package/dist/src/semantics/subscriptions.js +605 -0
- package/dist/src/semantics/tax.d.ts +2 -0
- package/dist/src/semantics/tax.js +197 -0
- package/dist/src/semantics/terminal.d.ts +5 -0
- package/dist/src/semantics/terminal.js +182 -0
- package/dist/src/semantics/test-clocks.d.ts +6 -0
- package/dist/src/semantics/test-clocks.js +73 -0
- package/dist/src/semantics/tokens.d.ts +4 -0
- package/dist/src/semantics/tokens.js +44 -0
- package/dist/src/semantics/transfers.d.ts +2 -0
- package/dist/src/semantics/transfers.js +154 -0
- package/dist/src/semantics/treasury.d.ts +2 -0
- package/dist/src/semantics/treasury.js +377 -0
- package/dist/src/semantics/webhook-endpoints.d.ts +3 -0
- package/dist/src/semantics/webhook-endpoints.js +85 -0
- package/dist/src/stripe-budget.d.ts +55 -0
- package/dist/src/stripe-budget.js +155 -0
- package/dist/src/stripe-capabilities.d.ts +3 -0
- package/dist/src/stripe-capabilities.js +5052 -0
- package/dist/src/stripe-conformance.d.ts +41 -0
- package/dist/src/stripe-conformance.js +96 -0
- package/dist/src/stripe-connector.d.ts +161 -0
- package/dist/src/stripe-connector.js +414 -0
- package/dist/src/stripe-emit.d.ts +2 -0
- package/dist/src/stripe-emit.js +145 -0
- package/dist/src/stripe-events.d.ts +93 -0
- package/dist/src/stripe-events.js +388 -0
- package/dist/src/stripe-js.d.ts +4 -0
- package/dist/src/stripe-js.js +70 -0
- package/dist/src/stripe-mirror-ui.d.ts +15 -0
- package/dist/src/stripe-mirror-ui.js +87 -0
- package/dist/src/stripe-params.d.ts +3 -0
- package/dist/src/stripe-params.js +43 -0
- package/dist/src/stripe-perform-harness.d.ts +9 -0
- package/dist/src/stripe-perform-harness.js +26 -0
- package/dist/src/stripe-server.d.ts +33 -0
- package/dist/src/stripe-server.js +326 -0
- package/dist/src/stripe-shared.d.ts +106 -0
- package/dist/src/stripe-shared.js +273 -0
- package/dist/src/stripe-twin.d.ts +155 -0
- package/dist/src/stripe-twin.js +1226 -0
- package/dist/src/stripe-ui-conformance.d.ts +5 -0
- package/dist/src/stripe-ui-conformance.js +79 -0
- package/dist/src/stripe-ui-structure.d.ts +3 -0
- package/dist/src/stripe-ui-structure.js +168 -0
- package/dist/src/stripe-version.d.ts +10 -0
- package/dist/src/stripe-version.js +285 -0
- package/dist/test-fixtures/stripe-known-deviations.json +105 -0
- package/dist/test-fixtures/stripe-openapi-operations.SOURCE.md +14 -0
- package/dist/test-fixtures/stripe-openapi-operations.json +4717 -0
- package/dist/test-fixtures/stripe-schemas.SOURCE.md +35 -0
- package/dist/test-fixtures/stripe-schemas.json +3740 -0
- package/package.json +18 -10
- package/src/cli.ts +7 -7
- package/src/generated/events.gen.json +1 -0
- package/src/generated/surface.gen.json +1 -0
- package/src/generated/ui.gen.json +1 -0
- package/src/index.ts +31 -9
- package/src/manifest.ts +1097 -0
- package/src/screens/checkout.tsx +252 -0
- package/src/screens/consent-skin.ts +20 -0
- package/src/screens/financial-connections.tsx +101 -0
- package/src/screens/identity.tsx +96 -0
- package/src/screens/industries.ts +267 -0
- package/src/screens/onboarding.tsx +243 -0
- package/src/screens/portal.tsx +218 -0
- package/src/screens/public-details.tsx +105 -0
- package/src/semantics/after-payment.ts +113 -0
- package/src/semantics/apps-secrets.ts +58 -0
- package/src/semantics/balance.ts +209 -0
- package/src/semantics/billing.ts +216 -0
- package/src/semantics/charges.ts +211 -0
- package/src/semantics/checkout.ts +297 -0
- package/src/semantics/connect.ts +471 -0
- package/src/semantics/coupons.ts +97 -0
- package/src/semantics/credit-notes.ts +168 -0
- package/src/semantics/customers.ts +432 -0
- package/src/semantics/disputes.ts +62 -0
- package/src/semantics/entitlements.ts +94 -0
- package/src/semantics/ephemeral-keys.ts +34 -0
- package/src/semantics/files.ts +143 -0
- package/src/semantics/invoices.ts +541 -0
- package/src/semantics/issuing.ts +585 -0
- package/src/semantics/ledger.ts +216 -0
- package/src/semantics/payment-intents.ts +420 -0
- package/src/semantics/payment-links.ts +148 -0
- package/src/semantics/payment-methods.ts +143 -0
- package/src/semantics/plans.ts +131 -0
- package/src/semantics/platform.ts +220 -0
- package/src/semantics/products.ts +154 -0
- package/src/semantics/radar.ts +85 -0
- package/src/semantics/refunds.ts +218 -0
- package/src/semantics/renewals.ts +274 -0
- package/src/semantics/setup-intents.ts +87 -0
- package/src/semantics/shared.ts +215 -0
- package/src/semantics/subscription-schedules.ts +129 -0
- package/src/semantics/subscriptions.ts +610 -0
- package/src/semantics/tax.ts +220 -0
- package/src/semantics/terminal.ts +195 -0
- package/src/semantics/test-clocks.ts +77 -0
- package/src/semantics/tokens.ts +52 -0
- package/src/semantics/transfers.ts +174 -0
- package/src/semantics/treasury.ts +383 -0
- package/src/semantics/webhook-endpoints.ts +87 -0
- package/src/stripe-budget.ts +4 -4
- package/src/stripe-capabilities.ts +1456 -222
- package/src/stripe-conformance.ts +6 -5
- package/src/stripe-connector.ts +68 -40
- package/src/stripe-emit.ts +14 -7
- package/src/stripe-events.ts +94 -36
- package/src/stripe-js.ts +70 -0
- package/src/stripe-mirror-ui.ts +28 -298
- package/src/stripe-params.ts +44 -0
- package/src/stripe-perform-harness.ts +29 -0
- package/src/stripe-server.ts +263 -38
- package/src/stripe-shared.ts +294 -0
- package/src/stripe-twin.ts +429 -5325
- package/src/stripe-ui-conformance.ts +70 -107
- package/src/stripe-ui-structure.ts +124 -348
- package/src/stripe-version.ts +278 -0
- package/test-fixtures/stripe-known-deviations.json +2 -7
- package/test-fixtures/stripe-openapi-operations.json +1188 -2855
- package/src/stripe-form.ts +0 -35
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// Balance and payout semantics. The balance is computed from the balance-transaction ledger (./ledger.ts), never
|
|
2
|
+
// stored: funds past their available_on are available, the rest pending, and Issuing funds their own section. The
|
|
3
|
+
// balance, the payouts and the ledger are the acting account's: the platform's, or a connected account's under the
|
|
4
|
+
// Stripe-Account header. A payout comes out of what that account has available and goes to its bank account, which a
|
|
5
|
+
// connected account must have (docs.stripe.com/connect/payouts-connected-accounts). A pending payout can be canceled,
|
|
6
|
+
// which returns its money; a connected account's paid payout can be reversed, which debits its bank account back
|
|
7
|
+
// into its balance (docs.stripe.com/api/payouts/reverse). The machine in ../manifest.ts says how a payout's status
|
|
8
|
+
// moves.
|
|
9
|
+
//
|
|
10
|
+
// Stripe also pays each account out on its own schedule (settings.payouts.schedule: daily by default, weekly or monthly
|
|
11
|
+
// on an anchor, or manual): an automatic payout takes what has become available since the last one, and the ledger
|
|
12
|
+
// lists the entries it paid (docs.stripe.com/payouts#payout-schedule, docs.stripe.com/connect/manage-payout-schedule).
|
|
13
|
+
// A connected account is paid out once it can be (payouts_enabled, with a bank account).
|
|
14
|
+
//
|
|
15
|
+
// Where the documentation stops and the twin decides: a payout arrives two days after it is made (Stripe's standard
|
|
16
|
+
// US schedule counts business days) and reads paid from then on; an automatic payout is made at midnight UTC on the
|
|
17
|
+
// first scheduled day on or after its funds become available, only when what it would pay is positive.
|
|
18
|
+
import type { Semantics, SemanticsContext } from '@volter/world-core';
|
|
19
|
+
import { validateMoney } from '../stripe-twin.ts';
|
|
20
|
+
import { accountSettings, PLATFORM_ACCOUNT_ID } from '../stripe-twin.ts';
|
|
21
|
+
import { actingAccount, balanceOf, refusePayout, settleAutomaticPayout, settlePayout, unpaidEntries } from './ledger.ts';
|
|
22
|
+
import { at, at_, created, fail, inRange, list, newest, send, where, type Row, kept } from './shared.ts';
|
|
23
|
+
|
|
24
|
+
const account = actingAccount;
|
|
25
|
+
const DAY = 86_400;
|
|
26
|
+
const payoutMissing = (ctx: SemanticsContext, id: string): Response => fail(ctx, `No such payout: '${id}'`, 404, 'resource_missing');
|
|
27
|
+
|
|
28
|
+
/** The acting account's Balance object (docs.stripe.com/api/balance/balance_object). */
|
|
29
|
+
export function balanceBody(ctx: SemanticsContext): Row {
|
|
30
|
+
const { available, pending, issuing } = balanceOf(ctx);
|
|
31
|
+
const toArr = (m: Map<string, number>) => {
|
|
32
|
+
const out = [...m.entries()].map(([currency, amount]) => ({ amount, currency, source_types: { card: amount } }));
|
|
33
|
+
return out.length ? out : [{ amount: 0, currency: 'usd', source_types: { card: 0 } }];
|
|
34
|
+
};
|
|
35
|
+
// a platform's balance holds its connected accounts' reserve, "Funds held due to negative balances on connected accounts
|
|
36
|
+
// where account.controller.requirement_collection is `application`" (docs.stripe.com/api/balance/balance_object, whose
|
|
37
|
+
// example answers `[{"amount": 0, "currency": "usd"}]`); the twin models no such reserve, so it is zero in each currency
|
|
38
|
+
const reserved = account(ctx) ? {} : { connect_reserved: toArr(available).map((b) => ({ amount: 0, currency: b.currency })) };
|
|
39
|
+
return {
|
|
40
|
+
object: 'balance', available: toArr(available), pending: toArr(pending), ...reserved, livemode: false,
|
|
41
|
+
...(issuing.size ? { issuing: { available: [...issuing.entries()].map(([currency, amount]) => ({ amount, currency, source_types: { card: amount } })) } } : {}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const balance: Semantics = async (ctx) => ctx.reply(balanceBody(ctx));
|
|
46
|
+
|
|
47
|
+
/** Time's arrivals, written: each of the acting account's payouts whose arrival date has come moves pending → paid
|
|
48
|
+
* (the clock's move, as asOf reads it), written as `payout.paid`, the event Stripe sends for it. Answers their ids. */
|
|
49
|
+
export async function payDuePayouts(ctx: SemanticsContext): Promise<string[]> {
|
|
50
|
+
const acct = account(ctx);
|
|
51
|
+
const now = Number(ctx.now());
|
|
52
|
+
const paid: string[] = [];
|
|
53
|
+
for (const p of newest(ctx, 'payout')) {
|
|
54
|
+
if ((acct ? kept(ctx, 'payout', p, '_account') !== acct : !!kept(ctx, 'payout', p, '_account')) || p.status !== 'pending' || Number(p.arrival_date) > now) continue;
|
|
55
|
+
if (ctx.legal('payout', 'status', ctx.call.operation.id, 'pending', 'paid', String(p.id), 'time')) continue;
|
|
56
|
+
await ctx.write('payout', String(p.id), { status: 'paid' }, 'payout.paid');
|
|
57
|
+
paid.push(String(p.id));
|
|
58
|
+
}
|
|
59
|
+
return paid;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Where a connected account's payout goes: "ID of the bank account or card the payout is sent to" (served spec,
|
|
63
|
+
* payout.destination), its default external account for the currency, "When multiple accounts are available for a given
|
|
64
|
+
* currency, Stripe uses the one set as `default_for_currency`" (docs.stripe.com/connect/payouts-bank-accounts), the
|
|
65
|
+
* newest such. Where the documentation stops and the twin decides: the platform's own bank account is not modelled, so
|
|
66
|
+
* its payouts name none. */
|
|
67
|
+
function payoutBank(ctx: SemanticsContext, account: string, currency: string): string | null {
|
|
68
|
+
const banks = newest(ctx, 'external_account').filter((e) => e.account === account && String(e.currency ?? currency) === currency);
|
|
69
|
+
return String((banks.find((e) => e.default_for_currency === true) ?? banks[0])?.id ?? '') || null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const payoutDefaults = (ctx: SemanticsContext): Row => ({
|
|
73
|
+
method: 'standard', type: 'bank_account', source_type: 'card', automatic: false,
|
|
74
|
+
reconciliation_status: 'not_applicable', arrival_date: Number(ctx.now()) + 2 * DAY, livemode: false, metadata: {},
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
/** A payout as the clock reads it: paid once its arrival date has come, the clock's move, asked of the
|
|
78
|
+
* machine as a write asks it. */
|
|
79
|
+
function asOf(ctx: SemanticsContext, p: Row): Row {
|
|
80
|
+
if (p.status !== 'pending' || Number(p.arrival_date) > Number(ctx.now())) return p;
|
|
81
|
+
ctx.legal('payout', 'status', ctx.call.operation.id, 'pending', 'paid', String(p.id), 'time');
|
|
82
|
+
return { ...p, status: 'paid' };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** A connected account's payout in a currency none of its bank accounts takes. */
|
|
86
|
+
function noExternalAccount(ctx: SemanticsContext, currency: string): Response {
|
|
87
|
+
return fail(ctx, `Sorry, you don't have any external accounts in that currency (${currency}).`, 400);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const createPayout: Semantics = async (ctx) => {
|
|
91
|
+
const bad = validateMoney(ctx.params);
|
|
92
|
+
if (bad) return send(ctx, bad);
|
|
93
|
+
const acct = account(ctx);
|
|
94
|
+
if (acct && !ctx.get('account', acct)) return fail(ctx, `No such account: '${acct}'`, 400, 'account_invalid');
|
|
95
|
+
const amount = Math.trunc(Number(ctx.params.amount) || 0);
|
|
96
|
+
const currency = String(ctx.params.currency ?? 'usd');
|
|
97
|
+
// a connected account is paid out to its own bank account
|
|
98
|
+
if (acct && !ctx.rows('external_account').some((e) => e.account === acct && (e.currency ?? currency) === currency)) return noExternalAccount(ctx, currency);
|
|
99
|
+
const refused = refusePayout(ctx, amount, currency);
|
|
100
|
+
if (refused) return refused;
|
|
101
|
+
const id = ctx.mint('payout');
|
|
102
|
+
const bt = await settlePayout(ctx, id, -amount, currency);
|
|
103
|
+
return ctx.reply(await created(ctx, 'payout', { ...ctx.params, id }, { status: 'pending', ...payoutDefaults(ctx), balance_transaction: bt, destination: acct ? payoutBank(ctx, acct, currency) : null, ...(acct ? { _account: acct } : {}) }));
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const listPayouts: Semantics = async (ctx) => {
|
|
107
|
+
const acct = account(ctx);
|
|
108
|
+
const scoped = newest(ctx, 'payout').filter((p) => (acct ? kept(ctx, 'payout', p, '_account') === acct : !kept(ctx, 'payout', p, '_account'))).map((p) => asOf(ctx, p));
|
|
109
|
+
return list(ctx, 'payout', where(ctx, scoped, { status: (p, v) => p.status === v, created: (p, v) => inRange(p.created, v), arrival_date: (p, v) => inRange(p.arrival_date, v) }));
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const DAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
|
|
113
|
+
/** The first scheduled payout time on or after `from`: midnight UTC of a day the schedule pays out on. */
|
|
114
|
+
function payoutDay(from: number, schedule: Row): number {
|
|
115
|
+
const first = Math.ceil(from / DAY) * DAY;
|
|
116
|
+
const pays = (day: number): boolean => {
|
|
117
|
+
const d = new Date(day * 1000);
|
|
118
|
+
if (schedule.interval === 'weekly') return DAYS[d.getUTCDay()] === String(schedule.weekly_anchor ?? 'monday');
|
|
119
|
+
if (schedule.interval === 'monthly') return d.getUTCDate() === Math.min(Number(schedule.monthly_anchor ?? 1), new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 0)).getUTCDate());
|
|
120
|
+
return true;
|
|
121
|
+
};
|
|
122
|
+
return Array.from({ length: 62 }, (_, i) => first + i * DAY).find(pays) ?? first;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Time's payouts, caught up to the World's clock: each account on an automatic schedule is paid out, on each of its
|
|
126
|
+
* scheduled days that has come, what became available by then. */
|
|
127
|
+
export async function advancePayouts(ctx: SemanticsContext): Promise<void> {
|
|
128
|
+
const now = Number(ctx.now());
|
|
129
|
+
const platform = ctx.get('account', PLATFORM_ACCOUNT_ID);
|
|
130
|
+
const accounts: Array<{ id: string | undefined; settings: unknown }> = [{ id: undefined, settings: platform?.settings }];
|
|
131
|
+
for (const a of ctx.rows('account')) {
|
|
132
|
+
if (a.id === PLATFORM_ACCOUNT_ID || a.payouts_enabled !== true) continue;
|
|
133
|
+
if (!ctx.rows('external_account').some((e) => e.account === a.id)) continue;
|
|
134
|
+
accounts.push({ id: String(a.id), settings: a.settings });
|
|
135
|
+
}
|
|
136
|
+
for (const acct of accounts) {
|
|
137
|
+
const schedule = ((accountSettings(acct.settings, (acct.settings as Row | undefined) ?? undefined).payouts as Row).schedule ?? {}) as Row;
|
|
138
|
+
if (schedule.interval === 'manual') continue;
|
|
139
|
+
const unpaid = unpaidEntries(ctx, acct.id);
|
|
140
|
+
const days = [...new Set(unpaid.map((t) => payoutDay(Number(t.available_on) || 0, schedule)))].filter((d) => d <= now).sort((x, y) => x - y);
|
|
141
|
+
const paid = new Set<unknown>();
|
|
142
|
+
for (const day of days) {
|
|
143
|
+
const due = unpaid.filter((t) => !paid.has(t.id) && (Number(t.available_on) || 0) <= day);
|
|
144
|
+
const byCurrency = new Map<string, Row[]>();
|
|
145
|
+
for (const t of due) byCurrency.set(String(t.currency ?? 'usd'), [...(byCurrency.get(String(t.currency ?? 'usd')) ?? []), t]);
|
|
146
|
+
for (const [currency, entries] of byCurrency) {
|
|
147
|
+
const amount = entries.reduce((n, t) => n + (Number(t.net) || 0), 0);
|
|
148
|
+
// nothing to pay yet: what came due is carried to the next payout
|
|
149
|
+
if (amount <= 0) continue;
|
|
150
|
+
// made on its day, as Stripe makes it, whenever the request that catches it up comes
|
|
151
|
+
const c = await at_(ctx)(day);
|
|
152
|
+
const id = c.mint('payout');
|
|
153
|
+
const bt = await settleAutomaticPayout(c, id, amount, currency, acct.id, day, entries);
|
|
154
|
+
await created(c, 'payout', { id, amount, currency }, {
|
|
155
|
+
status: 'pending', ...payoutDefaults(c), arrival_date: day + 2 * DAY, automatic: true, balance_transaction: bt, destination: acct.id ? payoutBank(c, String(acct.id), currency) : null,
|
|
156
|
+
description: 'STRIPE PAYOUT', ...(acct.id ? { _account: acct.id } : {}),
|
|
157
|
+
});
|
|
158
|
+
for (const t of entries) paid.add(t.id);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const retrievePayout: Semantics = async (ctx) => {
|
|
165
|
+
const p = ctx.get('payout', at(ctx, 'payout'));
|
|
166
|
+
return p ? ctx.reply(asOf(ctx, p)) : payoutMissing(ctx, at(ctx, 'payout'));
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
const cancelPayout: Semantics = async (ctx) => {
|
|
170
|
+
const id = at(ctx, 'payout');
|
|
171
|
+
const po = ctx.get('payout', id);
|
|
172
|
+
if (!po) return payoutMissing(ctx, id);
|
|
173
|
+
const refused = ctx.legal('payout', 'status', 'PostPayoutsPayoutCancel', asOf(ctx, po).status, undefined, id);
|
|
174
|
+
if (refused) return ctx.refuse(refused);
|
|
175
|
+
// the money comes back to the balance it left
|
|
176
|
+
const owner = kept(ctx, 'payout', po, '_account');
|
|
177
|
+
await settlePayout(ctx, id, Number(po.amount) || 0, String(po.currency ?? 'usd'), typeof owner === 'string' ? owner : null);
|
|
178
|
+
return ctx.reply(await ctx.write('payout', id, { status: 'canceled' }, 'payout.cancel'));
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
// a reversal is itself a payout in the other direction, back into the connected account's balance, as the reverse page's
|
|
182
|
+
// example answers it: a negative amount, pending until it arrives, carrying the request's metadata
|
|
183
|
+
// (docs.stripe.com/api/payouts/reverse); the original stays paid and names it
|
|
184
|
+
const reversePayout: Semantics = async (ctx) => {
|
|
185
|
+
const id = at(ctx, 'payout');
|
|
186
|
+
const po = ctx.get('payout', id);
|
|
187
|
+
if (!po) return payoutMissing(ctx, id);
|
|
188
|
+
const owner = kept(ctx, 'payout', po, '_account');
|
|
189
|
+
if (typeof owner !== 'string') return fail(ctx, "Payout reversals are only supported for payouts to connected accounts' bank accounts.", 400);
|
|
190
|
+
const status = String(asOf(ctx, po).status);
|
|
191
|
+
if (po.reversed_by || status !== 'paid') return ctx.refuse({ status: 400, code: 'payout_reversal_not_allowed', message: po.reversed_by ? 'This payout has already been reversed.' : `This payout cannot be reversed because it has a status of ${status}. A pending payout can be canceled instead.` });
|
|
192
|
+
const reversalId = ctx.mint('payout');
|
|
193
|
+
const bt = await settlePayout(ctx, reversalId, Number(po.amount) || 0, String(po.currency ?? 'usd'), owner);
|
|
194
|
+
const metadata = ctx.params.metadata && typeof ctx.params.metadata === 'object' ? { metadata: ctx.params.metadata } : {};
|
|
195
|
+
const reversal = await created(ctx, 'payout', { id: reversalId, amount: -(Number(po.amount) || 0), currency: po.currency, ...metadata }, {
|
|
196
|
+
status: 'pending', ...payoutDefaults(ctx), balance_transaction: bt, original_payout: id, destination: po.destination ?? null, _account: owner,
|
|
197
|
+
});
|
|
198
|
+
await ctx.write('payout', id, { reversed_by: reversal.id }, 'payout.reversed');
|
|
199
|
+
return ctx.reply(reversal);
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
export const balances: Record<string, Semantics> = {
|
|
203
|
+
GetBalance: balance,
|
|
204
|
+
PostPayouts: createPayout,
|
|
205
|
+
GetPayouts: listPayouts,
|
|
206
|
+
GetPayoutsPayout: retrievePayout,
|
|
207
|
+
PostPayoutsPayoutCancel: cancelPayout,
|
|
208
|
+
PostPayoutsPayoutReverse: reversePayout,
|
|
209
|
+
};
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// Billing semantics: meters (how usage events aggregate), the meter events that report usage and
|
|
2
|
+
// the summaries that aggregate them, prepaid credit grants and the balance they leave, and usage
|
|
3
|
+
// alerts. The machines in ../manifest.ts say how a meter and an alert move. Lists and retrieves
|
|
4
|
+
// with no scoping of their own are the derived core's.
|
|
5
|
+
import type { Semantics, SemanticsContext } from '@volter/world-core';
|
|
6
|
+
import { at, created, fail, list, newest, path, where, type Row } from './shared.ts';
|
|
7
|
+
|
|
8
|
+
const METER = 'billing.meter';
|
|
9
|
+
const meterMissing = (ctx: SemanticsContext, id: string): Response => fail(ctx, `No such meter: '${id}'`, 404, 'resource_missing');
|
|
10
|
+
const objectOf = (v: unknown): Row => (v && typeof v === 'object' ? (v as Row) : {});
|
|
11
|
+
|
|
12
|
+
// a meter needs a display name, the event name it counts, and how it aggregates (sum or count)
|
|
13
|
+
const createMeter: Semantics = async (ctx) => {
|
|
14
|
+
const params = ctx.params;
|
|
15
|
+
const displayName = typeof params.display_name === 'string' ? params.display_name : '';
|
|
16
|
+
if (!displayName) return fail(ctx, 'Missing required param: display_name.', 400, 'parameter_missing');
|
|
17
|
+
if (!((params.event_name as string) ?? '')) return fail(ctx, 'Missing required param: event_name.', 400, 'parameter_missing');
|
|
18
|
+
const formula = objectOf(params.default_aggregation).formula;
|
|
19
|
+
if (typeof formula !== 'string' || !formula) return fail(ctx, 'Missing required param: default_aggregation[formula] (sum or count).', 400, 'parameter_missing');
|
|
20
|
+
return ctx.reply(
|
|
21
|
+
await created(ctx, METER, params, {
|
|
22
|
+
status: 'active', livemode: false,
|
|
23
|
+
customer_mapping: (params.customer_mapping as object) ?? { event_payload_key: 'stripe_customer_id', type: 'by_id' },
|
|
24
|
+
event_time_window: (params.event_time_window as string) ?? null,
|
|
25
|
+
value_settings: (params.value_settings as object) ?? { event_payload_key: 'value' },
|
|
26
|
+
status_transitions: { deactivated_at: null }, updated: ctx.now(),
|
|
27
|
+
}),
|
|
28
|
+
);
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
function activation(kind: 'deactivate' | 'reactivate'): Semantics {
|
|
32
|
+
return async (ctx) => {
|
|
33
|
+
const id = at(ctx, 'id');
|
|
34
|
+
const m = ctx.get(METER, id);
|
|
35
|
+
if (!m) return meterMissing(ctx, id);
|
|
36
|
+
const refused = ctx.legal(METER, 'status', kind === 'deactivate' ? 'PostBillingMetersIdDeactivate' : 'PostBillingMetersIdReactivate', m.status, undefined, id);
|
|
37
|
+
if (refused) return ctx.refuse(refused);
|
|
38
|
+
const fields = { ...(kind === 'deactivate' ? { status: 'inactive', status_transitions: { deactivated_at: ctx.now() } } : { status: 'active', status_transitions: { deactivated_at: null } }), updated: ctx.now() };
|
|
39
|
+
return ctx.reply(await ctx.write(METER, id, fields, `billing_meter.${kind}`));
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// a meter event has no id of its own on Stripe (it carries an `identifier`); its object is billing.meter_event
|
|
44
|
+
const reportUsage: Semantics = async (ctx) => {
|
|
45
|
+
const params = ctx.params;
|
|
46
|
+
if (typeof params.event_name !== 'string' || !params.event_name) return fail(ctx, 'Missing required param: event_name.', 400, 'parameter_missing');
|
|
47
|
+
const payload = objectOf(params.payload);
|
|
48
|
+
const body = await created(ctx, 'billing.meter_event', { ...params }, {
|
|
49
|
+
livemode: false, timestamp: params.timestamp !== undefined ? Math.trunc(Number(params.timestamp)) : ctx.now(),
|
|
50
|
+
identifier: payload.identifier ?? null, payload,
|
|
51
|
+
});
|
|
52
|
+
return ctx.reply({ ...body, object: 'billing.meter_event' });
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
// the meter's events for one customer in [start_time, end_time), aggregated by its formula
|
|
56
|
+
const eventSummaries: Semantics = async (ctx) => {
|
|
57
|
+
const id = at(ctx, 'id');
|
|
58
|
+
const m = ctx.get(METER, id);
|
|
59
|
+
if (!m) return meterMissing(ctx, id);
|
|
60
|
+
const params = ctx.params;
|
|
61
|
+
const customer = typeof params.customer === 'string' ? params.customer : '';
|
|
62
|
+
if (!customer) return fail(ctx, 'Missing required param: customer.', 400, 'parameter_missing');
|
|
63
|
+
if (params.start_time === undefined) return fail(ctx, 'Missing required param: start_time.', 400, 'parameter_missing');
|
|
64
|
+
if (params.end_time === undefined) return fail(ctx, 'Missing required param: end_time.', 400, 'parameter_missing');
|
|
65
|
+
const startTime = Math.trunc(Number(params.start_time) || 0);
|
|
66
|
+
const endTime = Math.trunc(Number(params.end_time) || 0);
|
|
67
|
+
// "Must be aligned with minute boundaries" (start_time, end_time); "For hourly granularity, start and end times must
|
|
68
|
+
// align with hour boundaries … For daily granularity, … with UTC day boundaries (00:00 UTC)" (value_grouping_window;
|
|
69
|
+
// the served spec). Where the documentation stops and the twin decides: Stripe documents no error for it, so the
|
|
70
|
+
// twin answers a 400 naming the parameter and the boundary.
|
|
71
|
+
const window = params.value_grouping_window === 'hour' ? 3600 : params.value_grouping_window === 'day' ? 86_400 : 60;
|
|
72
|
+
const unit = window === 3600 ? 'hour' : window === 86_400 ? 'UTC day' : 'minute';
|
|
73
|
+
for (const [name, t] of [['start_time', startTime], ['end_time', endTime]] as const) {
|
|
74
|
+
if (t % window !== 0) return fail(ctx, `Invalid ${name}: ${t} is not aligned with ${unit} boundaries.`, 400);
|
|
75
|
+
}
|
|
76
|
+
const mapKey = typeof objectOf(m.customer_mapping).event_payload_key === 'string' ? String(objectOf(m.customer_mapping).event_payload_key) : 'stripe_customer_id';
|
|
77
|
+
const valueKey = typeof objectOf(m.value_settings).event_payload_key === 'string' ? String(objectOf(m.value_settings).event_payload_key) : 'value';
|
|
78
|
+
const formula = (objectOf(m.default_aggregation).formula as string) ?? 'sum';
|
|
79
|
+
let aggregate = 0;
|
|
80
|
+
for (const ev of ctx.rowsRaw('billing.meter_event', { withDeleted: true })) {
|
|
81
|
+
if (ev.event_name !== String(m.event_name ?? '')) continue;
|
|
82
|
+
const ts = Number(ev.timestamp) || 0;
|
|
83
|
+
if (ts < startTime || ts >= endTime) continue;
|
|
84
|
+
const payload = objectOf(ev.payload);
|
|
85
|
+
if (String(payload[mapKey] ?? '') !== customer) continue;
|
|
86
|
+
aggregate += formula === 'count' ? 1 : Number(payload[valueKey]) || 0;
|
|
87
|
+
}
|
|
88
|
+
return ctx.reply({
|
|
89
|
+
object: 'list', url: path(ctx), has_more: false,
|
|
90
|
+
data: [{ id: `mtrusg_twin_${id}_${customer}`, object: 'billing.meter_event_summary', meter: id, aggregated_value: aggregate, start_time: startTime, end_time: endTime, livemode: false }],
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// ── credit grants: a customer's prepaid credit, paid or promotional, in a monetary amount ──
|
|
95
|
+
|
|
96
|
+
const GRANT = 'billing.credit_grant';
|
|
97
|
+
const grantMissing = (ctx: SemanticsContext, id: string): Response => fail(ctx, `No such credit grant: '${id}'`, 404, 'resource_missing');
|
|
98
|
+
|
|
99
|
+
const createGrant: Semantics = async (ctx) => {
|
|
100
|
+
const params = ctx.params;
|
|
101
|
+
const customer = typeof params.customer === 'string' ? params.customer : '';
|
|
102
|
+
if (!customer) return fail(ctx, 'Missing required param: customer.', 400, 'parameter_missing');
|
|
103
|
+
if (!ctx.row('customer', customer, { withDeleted: true })) return fail(ctx, `No such customer: '${customer}'`, 404, 'resource_missing');
|
|
104
|
+
const category = typeof params.category === 'string' ? params.category : '';
|
|
105
|
+
if (category !== 'paid' && category !== 'promotional') return fail(ctx, 'Invalid category: must be paid or promotional.', 400, 'parameter_invalid_string_enum');
|
|
106
|
+
const monetary = params.amount && typeof params.amount === 'object' ? objectOf((params.amount as Row).monetary) : undefined;
|
|
107
|
+
if (!monetary || monetary.value === undefined || monetary.currency === undefined) return fail(ctx, 'Missing required param: amount[monetary][value] and amount[monetary][currency].', 400, 'parameter_missing');
|
|
108
|
+
return ctx.reply(
|
|
109
|
+
await created(ctx, GRANT, { customer }, {
|
|
110
|
+
category, livemode: false, name: params.name ?? null,
|
|
111
|
+
amount: { type: 'monetary', monetary: { currency: String(monetary.currency), value: Math.trunc(Number(monetary.value) || 0) } },
|
|
112
|
+
applicability_config: params.applicability_config && typeof params.applicability_config === 'object' ? params.applicability_config : { scope: { price_type: 'metered' } },
|
|
113
|
+
effective_at: params.effective_at !== undefined ? Math.trunc(Number(params.effective_at)) : ctx.now(),
|
|
114
|
+
expires_at: params.expires_at !== undefined ? Math.trunc(Number(params.expires_at)) : null,
|
|
115
|
+
priority: params.priority !== undefined ? Math.trunc(Number(params.priority)) : 50,
|
|
116
|
+
voided_at: null, metadata: params.metadata && typeof params.metadata === 'object' ? params.metadata : {}, updated: ctx.now(),
|
|
117
|
+
}),
|
|
118
|
+
);
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
// expiring or voiding a grant stamps the instant; it no longer counts toward the balance
|
|
122
|
+
function endGrant(kind: 'expire' | 'void'): Semantics {
|
|
123
|
+
return async (ctx) => {
|
|
124
|
+
const id = at(ctx, 'id');
|
|
125
|
+
if (!ctx.get(GRANT, id)) return grantMissing(ctx, id);
|
|
126
|
+
return ctx.reply(await ctx.write(GRANT, id, { ...(kind === 'void' ? { voided_at: ctx.now() } : { expires_at: ctx.now() }), updated: ctx.now() }, `credit_grant.${kind}`));
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// only the expiry and metadata change
|
|
131
|
+
const updateGrant: Semantics = async (ctx) => {
|
|
132
|
+
const id = at(ctx, 'id');
|
|
133
|
+
if (!ctx.get(GRANT, id)) return grantMissing(ctx, id);
|
|
134
|
+
const patch: Row = { updated: ctx.now() };
|
|
135
|
+
if (ctx.params.expires_at !== undefined) patch.expires_at = Math.trunc(Number(ctx.params.expires_at));
|
|
136
|
+
if (ctx.params.metadata !== undefined) patch.metadata = ctx.params.metadata;
|
|
137
|
+
return ctx.reply(await ctx.write(GRANT, id, patch, 'credit_grant.update'));
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
// the customer's live (unvoided, unexpired) monetary grants, summed per currency
|
|
141
|
+
const creditBalance: Semantics = async (ctx) => {
|
|
142
|
+
const customer = typeof ctx.params.customer === 'string' ? ctx.params.customer : '';
|
|
143
|
+
if (!customer) return fail(ctx, 'Missing required param: customer.', 400, 'parameter_missing');
|
|
144
|
+
if (!ctx.row('customer', customer, { withDeleted: true })) return fail(ctx, `No such customer: '${customer}'`, 404, 'resource_missing');
|
|
145
|
+
const now = Number(ctx.now());
|
|
146
|
+
const byCurrency: Record<string, number> = {};
|
|
147
|
+
for (const g of ctx.rows(GRANT)) {
|
|
148
|
+
if (g.customer !== customer || g.voided_at != null) continue;
|
|
149
|
+
if (typeof g.expires_at === 'number' && g.expires_at <= now) continue;
|
|
150
|
+
const monetary = objectOf(objectOf(g.amount).monetary);
|
|
151
|
+
const cur = String(monetary.currency ?? 'usd');
|
|
152
|
+
byCurrency[cur] = (byCurrency[cur] ?? 0) + (Number(monetary.value) || 0);
|
|
153
|
+
}
|
|
154
|
+
const balances = Object.entries(byCurrency).map(([currency, value]) => ({
|
|
155
|
+
available_balance: { type: 'monetary', monetary: { currency, value } },
|
|
156
|
+
ledger_balance: { type: 'monetary', monetary: { currency, value } },
|
|
157
|
+
}));
|
|
158
|
+
return ctx.reply({ object: 'billing.credit_balance_summary', customer, balances, livemode: false });
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
// ── alerts: a usage threshold on a meter ──
|
|
162
|
+
|
|
163
|
+
const ALERT = 'billing.alert';
|
|
164
|
+
|
|
165
|
+
const createAlert: Semantics = async (ctx) => {
|
|
166
|
+
const params = ctx.params;
|
|
167
|
+
if (params.alert_type !== 'usage_threshold') return fail(ctx, 'Invalid alert_type: must be usage_threshold.', 400, 'parameter_invalid_string_enum');
|
|
168
|
+
if (typeof params.title !== 'string' || !params.title) return fail(ctx, 'Missing required param: title.', 400, 'parameter_missing');
|
|
169
|
+
const ut = params.usage_threshold && typeof params.usage_threshold === 'object' ? (params.usage_threshold as Row) : undefined;
|
|
170
|
+
if (!ut || ut.gte === undefined || typeof ut.meter !== 'string') return fail(ctx, 'Missing required param: usage_threshold[gte] and usage_threshold[meter].', 400, 'parameter_missing');
|
|
171
|
+
// the spec requires recurrence too (one_time: the alert fires once)
|
|
172
|
+
if (ut.recurrence === undefined || ut.recurrence === '') return fail(ctx, 'Missing required param: usage_threshold[recurrence].', 400, 'parameter_missing');
|
|
173
|
+
if (!ctx.get(METER, ut.meter)) return fail(ctx, `No such meter: '${ut.meter}'`, 400, 'resource_missing');
|
|
174
|
+
return ctx.reply(
|
|
175
|
+
await created(ctx, ALERT, {}, {
|
|
176
|
+
alert_type: 'usage_threshold', livemode: false, status: 'active', title: params.title,
|
|
177
|
+
usage_threshold: { gte: Math.trunc(Number(ut.gte) || 0), meter: ut.meter, recurrence: String(ut.recurrence), filters: null },
|
|
178
|
+
}),
|
|
179
|
+
);
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
const listAlerts: Semantics = async (ctx) =>
|
|
183
|
+
list(ctx, ALERT, where(ctx, newest(ctx, ALERT), {
|
|
184
|
+
alert_type: (a, v) => a.alert_type === v,
|
|
185
|
+
meter: (a, v) => objectOf(a.usage_threshold).meter === v,
|
|
186
|
+
}));
|
|
187
|
+
|
|
188
|
+
function alertMove(kind: 'activate' | 'deactivate' | 'archive', operationId: string): Semantics {
|
|
189
|
+
return async (ctx) => {
|
|
190
|
+
const id = at(ctx, 'id');
|
|
191
|
+
const a = ctx.get(ALERT, id);
|
|
192
|
+
if (!a) return fail(ctx, `No such alert: '${id}'`, 404, 'resource_missing');
|
|
193
|
+
const refused = ctx.legal(ALERT, 'status', operationId, a.status, undefined, id);
|
|
194
|
+
if (refused) return ctx.refuse(refused);
|
|
195
|
+
const status = kind === 'activate' ? 'active' : kind === 'deactivate' ? 'inactive' : 'archived';
|
|
196
|
+
return ctx.reply(await ctx.write(ALERT, id, { status }, `billing_alert.${kind}`));
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export const billing: Record<string, Semantics> = {
|
|
201
|
+
PostBillingMeters: createMeter,
|
|
202
|
+
PostBillingMetersIdDeactivate: activation('deactivate'),
|
|
203
|
+
PostBillingMetersIdReactivate: activation('reactivate'),
|
|
204
|
+
PostBillingMeterEvents: reportUsage,
|
|
205
|
+
GetBillingMetersIdEventSummaries: eventSummaries,
|
|
206
|
+
PostBillingCreditGrants: createGrant,
|
|
207
|
+
PostBillingCreditGrantsIdExpire: endGrant('expire'),
|
|
208
|
+
PostBillingCreditGrantsIdVoid: endGrant('void'),
|
|
209
|
+
PostBillingCreditGrantsId: updateGrant,
|
|
210
|
+
GetBillingCreditBalanceSummary: creditBalance,
|
|
211
|
+
PostBillingAlerts: createAlert,
|
|
212
|
+
GetBillingAlerts: listAlerts,
|
|
213
|
+
PostBillingAlertsIdActivate: alertMove('activate', 'PostBillingAlertsIdActivate'),
|
|
214
|
+
PostBillingAlertsIdDeactivate: alertMove('deactivate', 'PostBillingAlertsIdDeactivate'),
|
|
215
|
+
PostBillingAlertsIdArchive: alertMove('archive', 'PostBillingAlertsIdArchive'),
|
|
216
|
+
};
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
// Charge semantics. The machine in ../manifest.ts says a charge is captured once; these handlers
|
|
2
|
+
// compute the money: a charge's `refunds` sub-list is derived on every read from the refunds that
|
|
3
|
+
// point at it, never a stored snapshot, while the cumulative `amount_refunded` / `refunded` stay
|
|
4
|
+
// stored (a partial capture moves them for a reason that is also a Refund row).
|
|
5
|
+
import type { Semantics, SemanticsContext } from '@volter/world-core';
|
|
6
|
+
import { asBool, cardError, chargeDefaults, declineFor, searchOver, validateMoney } from '../stripe-twin.ts';
|
|
7
|
+
import { afterCharge } from './after-payment.ts';
|
|
8
|
+
import { settleCharge } from './ledger.ts';
|
|
9
|
+
import { paymentMethodDetails } from './payment-methods.ts';
|
|
10
|
+
import { refundCharge } from './refunds.ts';
|
|
11
|
+
import { at, created, expanded, fail, finder, list, newest, path, refundDestination, send, where, type Row } from './shared.ts';
|
|
12
|
+
|
|
13
|
+
const chargeMissing = (ctx: SemanticsContext, id: string): Response => fail(ctx, `No such charge: '${id}'`, 404, 'resource_missing');
|
|
14
|
+
|
|
15
|
+
/** Every egress of a charge carries its refunds, derived from the refund rows in list order. */
|
|
16
|
+
export function chargeBody(ctx: SemanticsContext, c: Row): Row {
|
|
17
|
+
const data = newest(ctx, 'refund').filter((r) => r.charge === c.id);
|
|
18
|
+
return { ...c, refunds: { object: 'list', data, has_more: false, total_count: data.length, url: `/v1/charges/${String(c.id)}/refunds` } };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// A charge is written as the event Stripe sends for it (docs.stripe.com/api/events/types; Stripe has no
|
|
22
|
+
// `charge.created`): charge.succeeded, "Occurs whenever a charge is successful", for one made or authorized
|
|
23
|
+
// (capture=false: its status is succeeded, captured false), and charge.failed, "Occurs whenever a failed charge attempt
|
|
24
|
+
// occurs", for a declined attempt. The twin makes no pending charge (charge.pending, "Occurs whenever a pending charge is
|
|
25
|
+
// created"): its charges settle when made.
|
|
26
|
+
/** A Charges-API charge a declining test card refuses: a 402 card_error naming the failed charge Stripe records for the
|
|
27
|
+
* attempt (docs.stripe.com/declines). */
|
|
28
|
+
async function declinedCharge(ctx: SemanticsContext, decline: { code: string; decline_code?: string; message: string }): Promise<Response> {
|
|
29
|
+
const params = ctx.params;
|
|
30
|
+
const failedId = ctx.mint('charge');
|
|
31
|
+
const amount = Number(params.amount) || 0;
|
|
32
|
+
await created(ctx, 'charge', { ...params, id: failedId }, {
|
|
33
|
+
...chargeDefaults(failedId, amount, false, ctx.occurredAt), status: 'failed', paid: false, captured: false, capture_before: null,
|
|
34
|
+
failure_code: decline.code, failure_message: decline.message, balance_transaction: null,
|
|
35
|
+
outcome: { type: 'issuer_declined', network_status: 'declined_by_network', reason: decline.decline_code ?? decline.code, risk_level: 'normal', seller_message: 'The bank did not return any further details with this decline.' },
|
|
36
|
+
payment_method_details: paymentMethodDetails(ctx, params.payment_method ?? params.source ?? params.card) ?? null,
|
|
37
|
+
}, { operation: 'charge.failed' });
|
|
38
|
+
return send(ctx, cardError(decline, { charge: failedId }));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A charge's fraud report: "user_report … Assessments reported by you. If set, possible values of are `safe` and
|
|
42
|
+
* `fraudulent`" (docs.stripe.com/api/charges/object, fraud_details). */
|
|
43
|
+
function fraudReport(ctx: SemanticsContext, existing: Row, fd: Row): Row | Response {
|
|
44
|
+
const report = String(fd.user_report);
|
|
45
|
+
if (report !== 'safe' && report !== 'fraudulent') return fail(ctx, "Invalid fraud_details[user_report]: must be 'safe' or 'fraudulent'.", 400, 'parameter_invalid_string_enum');
|
|
46
|
+
const prior = existing.fraud_details && typeof existing.fraud_details === 'object' ? (existing.fraud_details as Row) : {};
|
|
47
|
+
return { user_report: report, stripe_report: prior.stripe_report ?? null };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const create: Semantics = async (ctx) => {
|
|
51
|
+
const params = ctx.params;
|
|
52
|
+
const bad = validateMoney(params);
|
|
53
|
+
if (bad) return send(ctx, bad);
|
|
54
|
+
// a declining test card answers a 402 card_error naming the failed charge Stripe records for the attempt
|
|
55
|
+
const decline = declineFor(finder(ctx), params);
|
|
56
|
+
if (decline) return declinedCharge(ctx, decline);
|
|
57
|
+
// capture=false authorizes only: succeeded and paid, but not captured, with a capture deadline
|
|
58
|
+
const captured = !(params.capture !== undefined && !asBool(params.capture));
|
|
59
|
+
// the id comes first so the charge's own `refunds` list can carry its URL
|
|
60
|
+
const id = typeof params.id === 'string' && params.id ? params.id : ctx.mint('charge');
|
|
61
|
+
const amount = Number(params.amount) || 0;
|
|
62
|
+
// a captured charge credits the balance; an authorization does when it is captured
|
|
63
|
+
const card = String(params.source ?? params.payment_method ?? (params.card as Row | undefined)?.number ?? '');
|
|
64
|
+
const bt = captured ? await settleCharge(ctx, id, amount, String(params.currency ?? 'usd'), card) : null;
|
|
65
|
+
const details = paymentMethodDetails(ctx, params.payment_method ?? params.source ?? params.card);
|
|
66
|
+
await created(ctx, 'charge', { ...params, id }, { ...chargeDefaults(id, amount, captured, ctx.occurredAt), balance_transaction: bt, payment_method_details: details ?? null }, { operation: 'charge.succeeded' });
|
|
67
|
+
await afterCharge(ctx, id, { amount, currency: String(params.currency ?? 'usd'), application_fee_amount: params.application_fee_amount, destination: (params.transfer_data as Row | undefined)?.destination }, params.payment_method ?? params.source ?? params.card);
|
|
68
|
+
return ctx.reply(chargeBody(ctx, ctx.get('charge', id)!));
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// capture takes `amount` (the whole authorization by default; docs.stripe.com/api/charges/capture); the rest of a
|
|
72
|
+
// partial capture is released with no Refund (captureAuthorization). `amount_to_capture` is the
|
|
73
|
+
// PaymentIntent capture's parameter, which a charge's capture does not know.
|
|
74
|
+
const capture: Semantics = async (ctx) => {
|
|
75
|
+
const id = at(ctx, 'charge');
|
|
76
|
+
const ch = ctx.get('charge', id);
|
|
77
|
+
if (!ch) return chargeMissing(ctx, id);
|
|
78
|
+
const refused = ctx.legal('charge', 'captured', 'PostChargesChargeCapture', ch.captured === true ? 'true' : 'false', undefined, id);
|
|
79
|
+
if (refused) return ctx.refuse(refused);
|
|
80
|
+
// "Capturing a charge will always succeed, unless the charge is already refunded, expired, captured, or an invalid
|
|
81
|
+
// capture amount is specified" (docs.stripe.com/api/charges/capture): a released authorization is refunded
|
|
82
|
+
if (ch.refunded === true) return fail(ctx, `Charge ${id} has already been refunded.`, 400, 'charge_already_refunded');
|
|
83
|
+
// a canceled PaymentIntent's authorization is released: "After it's canceled, no additional charges are made by the
|
|
84
|
+
// PaymentIntent and any operations on the PaymentIntent fail with an error" (docs.stripe.com/api/payment_intents/cancel).
|
|
85
|
+
// Where the documentation stops and the twin decides: its charge's capture answers payment_intent_unexpected_state
|
|
86
|
+
// ("The PaymentIntent's state was incompatible with the operation", docs.stripe.com/error-codes), in the twin's words.
|
|
87
|
+
const intent = typeof ch.payment_intent === 'string' ? ctx.get('payment_intent', ch.payment_intent) : undefined;
|
|
88
|
+
if (intent?.status === 'canceled') return fail(ctx, `Charge ${id} belongs to PaymentIntent ${String(intent.id)}, which is canceled; its authorization was released.`, 400, 'payment_intent_unexpected_state');
|
|
89
|
+
const full = Number(ch.amount) || 0;
|
|
90
|
+
const toCapture = ctx.params.amount !== undefined ? Math.min(full, Math.max(0, Math.trunc(Number(ctx.params.amount) || 0))) : full;
|
|
91
|
+
return ctx.reply(chargeBody(ctx, await captureAuthorization(ctx, ch, toCapture, 'PostChargesChargeCapture')));
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** A capture=false charge refunded while uncaptured: its authorization is released by the refund, as it would be
|
|
95
|
+
* "automatically refunded if uncaptured" (spec/openapi.json.gz, `capture_before`). The charge stays uncaptured and
|
|
96
|
+
* becomes refunded in full, a Refund records the release, and no money moves: none was ever received. Written as
|
|
97
|
+
* charge.refunded. Where the documentation stops and the twin decides: Stripe's basil change ("Partially capturing or
|
|
98
|
+
* canceling payments no longer creates a Refund", docs.stripe.com/changelog/basil/2025-03-31/remove-refund-from-partial-
|
|
99
|
+
* capture-and-payment-cancellation-flow) names partial capture and cancellation, not a refund asked for, so a refund
|
|
100
|
+
* still makes one; its reason is null and it has no balance transaction. Answers the Refund. */
|
|
101
|
+
export async function releaseAuthorization(ctx: SemanticsContext, ch: Row, operationId: string, given: Row = {}): Promise<Row> {
|
|
102
|
+
const id = String(ch.id);
|
|
103
|
+
const full = Number(ch.amount) || 0;
|
|
104
|
+
if (ch.refunded !== true) ctx.legal('charge', 'refunded', operationId, 'false', 'true', id);
|
|
105
|
+
const refund = await created(ctx, 'refund', { ...given, charge: id, amount: full - (Number(ch.amount_refunded) || 0), currency: String(ch.currency ?? 'usd') }, {
|
|
106
|
+
status: 'succeeded', metadata: {}, reason: null, receipt_number: null,
|
|
107
|
+
balance_transaction: null, source_transfer_reversal: null, transfer_reversal: null, ...refundDestination(ch, 'reversal'),
|
|
108
|
+
...(typeof ch.payment_intent === 'string' ? { payment_intent: ch.payment_intent } : {}),
|
|
109
|
+
});
|
|
110
|
+
await ctx.write('charge', id, { amount_refunded: full, refunded: true }, 'charge.refunded');
|
|
111
|
+
return refund;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** A PaymentIntent's authorization released by its cancel: "For PaymentIntents with a `status` of `requires_capture`, the
|
|
115
|
+
* remaining `amount_capturable` is automatically refunded" (docs.stripe.com/api/payment_intents/cancel), and since basil
|
|
116
|
+
* a cancellation makes no Refund: "`amount_captured` will be 0 instead of `nil` in payment cancellation flows",
|
|
117
|
+
* "`amount_refunded` will no longer be updated by these actions", "`refunded` will no longer be `true` for payment
|
|
118
|
+
* cancellation flows", and no charge.refunded is sent (docs.stripe.com/changelog/basil/2025-03-31/remove-refund-from-
|
|
119
|
+
* partial-capture-and-payment-cancellation-flow). The charge stays uncaptured; nothing is written as an event. */
|
|
120
|
+
export async function cancelAuthorization(ctx: SemanticsContext, ch: Row): Promise<Row> {
|
|
121
|
+
return ctx.write('charge', String(ch.id), { amount_captured: 0 }, 'charge.authorization_released');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** An authorized charge captured, by the charge's capture or its PaymentIntent's: what is captured credits the balance.
|
|
125
|
+
* Written as charge.captured, "Occurs whenever a previously uncaptured charge is captured" (docs.stripe.com/api/events/types).
|
|
126
|
+
* A partial capture releases the rest with no Refund and leaves amount_refunded and refunded as they were: "The following
|
|
127
|
+
* flows no longer result in a `Refund` object created and linked to the payment: Partial capture", "`amount_refunded`
|
|
128
|
+
* will no longer be updated by these actions", and "There will only be a single balance transaction for partial captures"
|
|
129
|
+
* (docs.stripe.com/changelog/basil/2025-03-31/remove-refund-from-partial-capture-and-payment-cancellation-flow).
|
|
130
|
+
* The caller has asked the machine whether it may capture. */
|
|
131
|
+
export async function captureAuthorization(ctx: SemanticsContext, ch: Row, toCapture: number, _operationId: string): Promise<Row> {
|
|
132
|
+
const id = String(ch.id);
|
|
133
|
+
const bt = toCapture > 0 ? await settleCharge(ctx, id, toCapture, String(ch.currency ?? 'usd'), String(ch.source ?? ch.payment_method ?? '')) : null;
|
|
134
|
+
return ctx.write('charge', id, { captured: true, amount_captured: toCapture, balance_transaction: bt }, 'charge.captured');
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const listCharges: Semantics = async (ctx) => {
|
|
138
|
+
const items = where(ctx, newest(ctx, 'charge'), {
|
|
139
|
+
customer: (c, v) => c.customer === v,
|
|
140
|
+
payment_intent: (c, v) => c.payment_intent === v,
|
|
141
|
+
});
|
|
142
|
+
return list(ctx, 'charge', items.map((c) => chargeBody(ctx, c)));
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const searchCharges: Semantics = async (ctx) => {
|
|
146
|
+
const found = searchOver(newest(ctx, 'charge'), ctx.params, path(ctx));
|
|
147
|
+
const body = found.body as { data?: Row[] };
|
|
148
|
+
if (found.status === 200 && Array.isArray(body.data)) body.data = body.data.map((c) => chargeBody(ctx, c));
|
|
149
|
+
return send(ctx, found);
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const retrieve: Semantics = async (ctx) => {
|
|
153
|
+
const c = ctx.get('charge', at(ctx, 'charge'));
|
|
154
|
+
return c ? ctx.reply(expanded(ctx, 'charge', chargeBody(ctx, c))) : chargeMissing(ctx, at(ctx, 'charge'));
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
// fraud_details[user_report] marks a charge safe or fraudulent; Stripe keeps its own stripe_report
|
|
158
|
+
const update: Semantics = async (ctx) => {
|
|
159
|
+
const id = at(ctx, 'charge');
|
|
160
|
+
const existing = ctx.get('charge', id);
|
|
161
|
+
if (!existing) return chargeMissing(ctx, id);
|
|
162
|
+
const fields: Row = { ...ctx.params };
|
|
163
|
+
const fd = ctx.params.fraud_details;
|
|
164
|
+
const fraud = fd && typeof fd === 'object' && 'user_report' in (fd as Row) ? fraudReport(ctx, existing, fd as Row) : undefined;
|
|
165
|
+
if (fraud instanceof Response) return fraud;
|
|
166
|
+
if (fraud) fields.fraud_details = fraud;
|
|
167
|
+
return ctx.reply(chargeBody(ctx, await ctx.write('charge', id, fields, 'charge.update')));
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
// ── the charge's own refunds: listed, created and read through it; another charge's refund is not found ──
|
|
171
|
+
|
|
172
|
+
const refunds: Semantics = async (ctx) => {
|
|
173
|
+
const id = at(ctx, 'charge');
|
|
174
|
+
if (!ctx.get('charge', id)) return chargeMissing(ctx, id);
|
|
175
|
+
return list(ctx, 'refund', newest(ctx, 'refund').filter((r) => r.charge === id));
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
const createRefund: Semantics = async (ctx) => {
|
|
179
|
+
const ch = ctx.get('charge', at(ctx, 'charge'));
|
|
180
|
+
if (!ch) return chargeMissing(ctx, at(ctx, 'charge'));
|
|
181
|
+
return refundCharge(ctx, ch, ctx.params);
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const chargeRefund = (ctx: SemanticsContext): Row | Response => {
|
|
185
|
+
if (!ctx.get('charge', at(ctx, 'charge'))) return chargeMissing(ctx, at(ctx, 'charge'));
|
|
186
|
+
const r = ctx.get('refund', at(ctx, 'refund'));
|
|
187
|
+
return r && r.charge === at(ctx, 'charge') ? r : fail(ctx, `No such refund: '${at(ctx, 'refund')}'`, 404, 'resource_missing');
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const refund: Semantics = async (ctx) => {
|
|
191
|
+
const r = chargeRefund(ctx);
|
|
192
|
+
return r instanceof Response ? r : ctx.reply(r);
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
const updateRefund: Semantics = async (ctx) => {
|
|
196
|
+
const r = chargeRefund(ctx);
|
|
197
|
+
return r instanceof Response ? r : ctx.reply(await ctx.write('refund', at(ctx, 'refund'), ctx.params, 'refund.update'));
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
export const charges: Record<string, Semantics> = {
|
|
201
|
+
PostCharges: create,
|
|
202
|
+
PostChargesChargeCapture: capture,
|
|
203
|
+
GetCharges: listCharges,
|
|
204
|
+
GetChargesSearch: searchCharges,
|
|
205
|
+
GetChargesCharge: retrieve,
|
|
206
|
+
PostChargesCharge: update,
|
|
207
|
+
GetChargesChargeRefunds: refunds,
|
|
208
|
+
PostChargesChargeRefunds: createRefund,
|
|
209
|
+
GetChargesChargeRefundsRefund: refund,
|
|
210
|
+
PostChargesChargeRefundsRefund: updateRefund,
|
|
211
|
+
};
|