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