@volter/twin-stripe 0.1.1 → 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,216 @@
1
+ // Stripe's balance ledger (docs.stripe.com/api/balance_transactions): every movement of the account's money writes
2
+ // a balance transaction, and the balance is their sum. A captured charge adds its amount less Stripe's fee, pending
3
+ // until its available_on; a refund takes its amount back at once; a payout takes its amount out of what is available
4
+ // and is refused beyond it (balance_insufficient). A transaction's status is what the World clock says of its
5
+ // available_on (the machine's time move, pending → available), so a `wait` in a story settles funds as time does.
6
+ //
7
+ // Where the documentation stops and the twin decides: the fee is Stripe's standard US card pricing, 2.9% + 30¢
8
+ // (stripe.com/pricing), for every charge; funds become available two days after capture (Stripe's standard US
9
+ // payout schedule counts business days); the card 4000000000000077 settles at once, as Stripe's test card of that
10
+ // number does (docs.stripe.com/testing#available-balance).
11
+ //
12
+ // Each connected account keeps its own balance (docs.stripe.com/connect/account-balances): a transaction belongs to
13
+ // the account the request acts for (the Stripe-Account header), else to the platform. A transfer takes its amount out
14
+ // of the platform's available balance and adds it to the destination's; a destination charge transfers its amount
15
+ // less the application fee, available when the charge's funds are; a direct charge's application fee moves from the
16
+ // connected account to the platform.
17
+ import type { Semantics, SemanticsContext } from '@volter/world-core';
18
+ import { at, created, fail, inRange, kept, list, newest, where, type Row } from './shared.ts';
19
+
20
+ const BT = 'balance_transaction';
21
+ const DAY = 86_400;
22
+ const BYPASS_PENDING = '4000000000000077';
23
+
24
+ const feeOf = (amount: number): number => (amount > 0 ? Math.round(amount * 0.029) + 30 : 0);
25
+
26
+ /** A transaction as the clock reads it: available once its available_on has passed, the clock's move,
27
+ * asked of the machine as a write asks it. */
28
+ function asOf(ctx: SemanticsContext, t: Row): Row {
29
+ const due = Number(t.available_on);
30
+ if (t.status !== 'pending' || !Number.isFinite(due) || due > Number(ctx.now())) return t;
31
+ ctx.legal('balance_transaction', 'status', ctx.call.operation.id, 'pending', 'available', String(t.id), 'time');
32
+ return { ...t, status: 'available' };
33
+ }
34
+
35
+ /** The connected account a request acts for, or undefined for the platform. */
36
+ export const actingAccount = (ctx: SemanticsContext): string | undefined => ctx.call.request.headers.get('stripe-account') ?? undefined;
37
+
38
+ /** A ledger entry on an account's balance: the acting account's unless one is named (null names the platform). */
39
+ async function write(ctx: SemanticsContext, fields: Row, account: string | null | undefined = actingAccount(ctx)): Promise<string> {
40
+ const bt = await created(ctx, BT, {}, { status: 'available', fee_details: [], description: null, exchange_rate: null, balance_type: 'payments', ...fields, ...(account ? { _account: account } : {}) });
41
+ return String(bt.id);
42
+ }
43
+
44
+ /** Whether a stored ledger entry is on this account's balance (undefined: the platform's). */
45
+ const onAccount = (t: Row, account: string | undefined): boolean => (typeof t._account === 'string' ? t._account : undefined) === account;
46
+
47
+ /** A captured charge's credit: its amount less the fee, pending two days unless the card (a number, or a test
48
+ * payment method or token named for it) settles at once. The
49
+ * caller mints the charge's id first and stores the returned id as the charge's balance_transaction. */
50
+ export async function settleCharge(ctx: SemanticsContext, chargeId: string, amount: number, currency: string, card?: string): Promise<string> {
51
+ const now = Number(ctx.now());
52
+ const fee = feeOf(amount);
53
+ const settled = !!card && (card.replace(/\D/g, '') === BYPASS_PENDING || /bypassPending/i.test(card));
54
+ const id = await write(ctx, {
55
+ amount, currency, fee, net: amount - fee, type: 'charge', reporting_category: 'charge', source: chargeId,
56
+ status: settled ? 'available' : 'pending', available_on: settled ? now : now + 2 * DAY,
57
+ fee_details: fee ? [{ amount: fee, application: null, currency, description: 'Stripe processing fees', type: 'stripe_fee' }] : [],
58
+ });
59
+ return id;
60
+ }
61
+
62
+ /** A refund's debit, at once, on the acting account's balance unless one is named (null names the platform). */
63
+ export async function settleRefund(ctx: SemanticsContext, refundId: string, amount: number, currency: string, account: string | null | undefined = actingAccount(ctx)): Promise<string> {
64
+ return write(ctx, { amount: -amount, currency, fee: 0, net: -amount, type: 'refund', reporting_category: 'refund', source: refundId, available_on: Number(ctx.now()) }, account);
65
+ }
66
+
67
+ /** What an account had available in a currency at a moment: every entry of its payments balance whose funds had come
68
+ * due by then. */
69
+ export function availableAt(ctx: SemanticsContext, account: string | undefined, currency: string, at: number): number {
70
+ let sum = 0;
71
+ for (const t of ctx.rowsRaw(BT)) {
72
+ if (!onAccount(t, account) || t.balance_type === 'issuing' || String(t.currency ?? 'usd') !== currency) continue;
73
+ const due = Number(t.available_on ?? t.created);
74
+ if (Number.isFinite(due) && due <= at) sum += Number(t.net ?? 0);
75
+ }
76
+ return sum;
77
+ }
78
+
79
+ /** The moments after `from` and up to `until` when funds of an account came due, in order: when a held refund can
80
+ * next be covered. */
81
+ export function fundsDueBetween(ctx: SemanticsContext, account: string | undefined, currency: string, from: number, until: number): number[] {
82
+ const times = ctx.rowsRaw(BT).filter((t) => onAccount(t, account) && String(t.currency ?? 'usd') === currency).map((t) => Number(t.available_on ?? t.created)).filter((d) => Number.isFinite(d) && d > from && d <= until);
83
+ return [...new Set(times)].sort((a, b) => a - b);
84
+ }
85
+
86
+ /** A dispute's debit, at once: the disputed amount and the dispute fee (the twin's 1500 cents, Stripe's US $15). */
87
+ export async function settleDispute(ctx: SemanticsContext, disputeId: string, amount: number, currency: string): Promise<string> {
88
+ const fee = 1500;
89
+ return write(ctx, {
90
+ amount: -amount, currency, fee, net: -amount - fee, type: 'adjustment', reporting_category: 'dispute', source: disputeId, available_on: Number(ctx.now()),
91
+ fee_details: [{ amount: fee, application: null, currency, description: 'Dispute fee', type: 'stripe_fee' }],
92
+ });
93
+ }
94
+
95
+ /** A won dispute's credit, at once: the disputed amount returned (docs.stripe.com/disputes/how-disputes-work). Where the
96
+ * documentation stops and the twin decides: the dispute fee is not returned. */
97
+ export async function settleDisputeWon(ctx: SemanticsContext, disputeId: string, amount: number, currency: string): Promise<string> {
98
+ return write(ctx, { amount, currency, fee: 0, net: amount, type: 'adjustment', reporting_category: 'dispute_reversal', source: disputeId, available_on: Number(ctx.now()) });
99
+ }
100
+
101
+ /** An account's ledger entries an automatic payout has not yet paid out: every entry on its payments balance that no
102
+ * automatic payout took (the automatic payouts' own debits excluded), as stored. */
103
+ export function unpaidEntries(ctx: SemanticsContext, account: string | undefined): Row[] {
104
+ const automatic = new Set(ctx.rowsRaw('payout').filter((p) => p.automatic === true).map((p) => p.id));
105
+ return ctx.rowsRaw(BT).filter((t) => onAccount(t, account) && t.balance_type !== 'issuing' && !t._payout && !automatic.has(t.source));
106
+ }
107
+
108
+ /** An automatic payout's debit at `at`, and the entries it pays out marked with it, so the ledger lists them under
109
+ * the payout (docs.stripe.com/api/balance_transactions/list#balance_transaction_list-payout). */
110
+ export async function settleAutomaticPayout(ctx: SemanticsContext, payoutId: string, amount: number, currency: string, account: string | undefined, at: number, entries: Row[]): Promise<string> {
111
+ for (const t of entries) await ctx.write(BT, String(t.id), { _payout: payoutId }, 'balance_transaction.paid_out');
112
+ return write(ctx, { amount: -amount, currency, fee: 0, net: -amount, type: 'payout', reporting_category: 'payout', source: payoutId, available_on: at, _payout: payoutId }, account ?? null);
113
+ }
114
+
115
+ /** A payout's debit (negative) or a cancellation's or reversal's credit (positive), at once, on the payout's account. */
116
+ export async function settlePayout(ctx: SemanticsContext, payoutId: string, amount: number, currency: string, account: string | null | undefined = actingAccount(ctx)): Promise<string> {
117
+ const type = amount < 0 ? 'payout' : 'payout_cancel';
118
+ return write(ctx, { amount, currency, fee: 0, net: amount, type, reporting_category: type === 'payout' ? 'payout' : 'payout_reversal', source: payoutId, available_on: Number(ctx.now()) }, account);
119
+ }
120
+
121
+ /** A transfer's two entries: out of the platform's balance at once, into the destination's when `availableOn` comes
122
+ * (a plain transfer's funds are available already). Answers the platform's entry. */
123
+ export async function settleTransfer(ctx: SemanticsContext, transferId: string, amount: number, currency: string, destination: string, availableOn = Number(ctx.now()), fromPending = false): Promise<string> {
124
+ const settled = availableOn <= Number(ctx.now());
125
+ // a transfer from a charge's pending funds (source_transaction) leaves the platform when they arrive, not before
126
+ const platform = await write(ctx, { amount: -amount, currency, fee: 0, net: -amount, type: 'transfer', reporting_category: 'transfer', source: transferId, ...(fromPending ? { status: settled ? 'available' : 'pending', available_on: availableOn } : { available_on: Number(ctx.now()) }) }, null);
127
+ await write(ctx, { amount, currency, fee: 0, net: amount, type: 'payment', reporting_category: 'charge', source: transferId, status: settled ? 'available' : 'pending', available_on: availableOn }, destination);
128
+ return platform;
129
+ }
130
+
131
+ /** A transfer reversal's two entries: back into the platform's balance, out of the destination's. */
132
+ export async function settleTransferReversal(ctx: SemanticsContext, reversalId: string, amount: number, currency: string, destination: string): Promise<string> {
133
+ const platform = await write(ctx, { amount, currency, fee: 0, net: amount, type: 'transfer_refund', reporting_category: 'transfer_reversal', source: reversalId, available_on: Number(ctx.now()) }, null);
134
+ await write(ctx, { amount: -amount, currency, fee: 0, net: -amount, type: 'payment_refund', reporting_category: 'refund', source: reversalId, available_on: Number(ctx.now()) }, destination);
135
+ return platform;
136
+ }
137
+
138
+ /** A direct charge's application fee: out of the connected account's balance, into the platform's. */
139
+ export async function settleApplicationFee(ctx: SemanticsContext, feeId: string, amount: number, currency: string, account: string): Promise<string> {
140
+ await write(ctx, { amount: -amount, currency, fee: 0, net: -amount, type: 'application_fee', reporting_category: 'platform_earning', source: feeId, available_on: Number(ctx.now()) }, account);
141
+ return write(ctx, { amount, currency, fee: 0, net: amount, type: 'application_fee', reporting_category: 'platform_earning', source: feeId, available_on: Number(ctx.now()) }, null);
142
+ }
143
+
144
+ /** A top-up's credit, to the payments balance or, with `destination_balance=issuing`, to Issuing's
145
+ * (docs.stripe.com/issuing/funding/balance). Where the documentation stops and the twin decides: a test-mode top-up
146
+ * is available at once. */
147
+ export async function settleTopup(ctx: SemanticsContext, topupId: string, amount: number, currency: string, destination: string): Promise<string> {
148
+ const issuing = destination === 'issuing';
149
+ return write(ctx, { amount, currency, fee: 0, net: amount, type: 'topup', reporting_category: 'topup', source: topupId, available_on: Number(ctx.now()), balance_type: issuing ? 'issuing' : 'payments' });
150
+ }
151
+
152
+ /** Time's settlements, written: each entry on the acting account's balance whose funds came due by the World's clock
153
+ * moves pending → available (the clock's move the machine allows), so a settlement is recorded once. A read already
154
+ * sees it (asOf); the record is what lets Stripe's balance.available be sent once (stripe-server.ts, the drain).
155
+ * Answers the entries that moved. */
156
+ export async function settleDueEntries(ctx: SemanticsContext): Promise<Row[]> {
157
+ const now = Number(ctx.now());
158
+ const account = actingAccount(ctx);
159
+ const moved: Row[] = [];
160
+ for (const t of ctx.rowsRaw(BT)) {
161
+ if (!onAccount(t, account) || t.status !== 'pending' || !(Number(t.available_on) <= now)) continue;
162
+ if (ctx.legal(BT, 'status', ctx.call.operation.id, 'pending', 'available', String(t.id), 'time')) continue;
163
+ await ctx.write(BT, String(t.id), { status: 'available' }, 'balance_transaction.available');
164
+ moved.push(t);
165
+ }
166
+ return moved;
167
+ }
168
+
169
+ /** An account's balance, by currency: what the clock has made available, what is still pending, and Issuing's own. */
170
+ export function balanceOf(ctx: SemanticsContext, account: string | undefined = actingAccount(ctx)): { available: Map<string, number>; pending: Map<string, number>; issuing: Map<string, number> } {
171
+ const available = new Map<string, number>();
172
+ const pending = new Map<string, number>();
173
+ const issuing = new Map<string, number>();
174
+ for (const raw of ctx.rowsRaw(BT)) {
175
+ if (!onAccount(raw, account)) continue;
176
+ const t = asOf(ctx, raw);
177
+ const cur = String(t.currency ?? 'usd');
178
+ const net = Number(t.net ?? 0);
179
+ const bucket = t.balance_type === 'issuing' ? issuing : t.status === 'available' ? available : pending;
180
+ bucket.set(cur, (bucket.get(cur) ?? 0) + net);
181
+ }
182
+ return { available, pending, issuing };
183
+ }
184
+
185
+ /** balance_insufficient when a payout or transfer would take more than the account has available in its currency. */
186
+ export function refusePayout(ctx: SemanticsContext, amount: number, currency: string, account: string | undefined = actingAccount(ctx)): Response | undefined {
187
+ const have = balanceOf(ctx, account).available.get(currency) ?? 0;
188
+ if (amount <= have) return undefined;
189
+ return fail(ctx, "The transfer or payout couldn't be completed because the associated account doesn't have a sufficient balance available.", 400, 'balance_insufficient');
190
+ }
191
+
192
+ /** The ids of the ledger entries on the acting account's balance. */
193
+ const mine = (ctx: SemanticsContext): Set<unknown> => new Set(ctx.rowsRaw(BT).filter((t) => onAccount(t, actingAccount(ctx))).map((t) => t.id));
194
+
195
+ const retrieve: Semantics = async (ctx) => {
196
+ const t = ctx.get(BT, at(ctx, 'id'));
197
+ return t && mine(ctx).has(t.id) ? ctx.reply(asOf(ctx, t)) : ctx.notFound(BT, at(ctx, 'id'));
198
+ };
199
+
200
+ const listAll: Semantics = async (ctx) => {
201
+ const own = mine(ctx);
202
+ return list(ctx, BT, where(ctx, newest(ctx, BT).filter((t) => own.has(t.id)).map((t) => asOf(ctx, t)), {
203
+ type: (t, v) => t.type === v,
204
+ currency: (t, v) => t.currency === v,
205
+ source: (t, v) => t.source === v,
206
+ // an automatic payout lists the entries it paid out, its own debit among them
207
+ payout: (t, v) => t.source === v || kept(ctx, BT, t, '_payout') === v,
208
+ // a range of creation times (docs.stripe.com/api/balance_transactions/list#balance_transaction_list-created)
209
+ created: (t, v) => inRange(t.created, v),
210
+ }));
211
+ };
212
+
213
+ export const ledger: Record<string, Semantics> = {
214
+ GetBalanceTransactions: listAll,
215
+ GetBalanceTransactionsId: retrieve,
216
+ };