@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,154 @@
1
+ import { validateMoney } from "../stripe-twin.js";
2
+ import { refusePayout, settleTransfer, settleTransferReversal } from "./ledger.js";
3
+ import { at, created, fail, list, newest, send } from "./shared.js";
4
+ const transferMissing = (ctx, id) => fail(ctx, `No such transfer: '${id}'`, 404, 'resource_missing');
5
+ const emptyList = (url) => ({ object: 'list', data: [], has_more: false, total_count: 0, url });
6
+ /** A transfer to an account whose transfers capability is not active. */
7
+ function transfersInactive(ctx) {
8
+ return ctx.refuse({ status: 400, code: 'insufficient_capabilities_for_transfer', param: 'destination', message: 'Your destination account needs to have at least one of the following capabilities enabled: transfers, crypto_transfers, legacy_payments' });
9
+ }
10
+ const create = async (ctx) => {
11
+ const bad = validateMoney(ctx.params);
12
+ if (bad)
13
+ return send(ctx, bad);
14
+ const destination = typeof ctx.params.destination === 'string' ? ctx.params.destination : '';
15
+ if (!destination)
16
+ return fail(ctx, 'Missing required param: destination.', 400, 'parameter_missing');
17
+ const account = ctx.get('account', destination);
18
+ if (!account)
19
+ return fail(ctx, `No such destination: '${destination}'`, 400, 'resource_missing');
20
+ if ((account.capabilities?.transfers) !== 'active')
21
+ return transfersInactive(ctx);
22
+ const amount = Math.trunc(Number(ctx.params.amount) || 0);
23
+ const currency = String(ctx.params.currency ?? 'usd');
24
+ const sourceId = typeof ctx.params.source_transaction === 'string' ? ctx.params.source_transaction : undefined;
25
+ let availableOn;
26
+ let group;
27
+ if (sourceId) {
28
+ const charge = ctx.get('charge', sourceId);
29
+ if (!charge)
30
+ return fail(ctx, `No such charge: '${sourceId}'`, 400, 'resource_missing');
31
+ if (charge.status !== 'succeeded')
32
+ return fail(ctx, `The source_transaction ${sourceId} has not succeeded.`, 400, 'invalid_request_error');
33
+ // an authorization holds no funds to transfer
34
+ if (charge.captured === false)
35
+ return fail(ctx, `The source_transaction ${sourceId} has not been captured; capture it before transferring its funds.`, 400);
36
+ if (String(charge.currency ?? 'usd') !== currency)
37
+ return fail(ctx, `The currency of source_transaction ${sourceId} (${String(charge.currency)}) does not match the transfer's (${currency}).`, 400, 'invalid_request_error');
38
+ const already = ctx.rowsRaw('transfer').filter((t) => t.source_transaction === sourceId).reduce((sum, t) => sum + (Number(t.amount) || 0) - (Number(t.amount_reversed) || 0), 0);
39
+ if (already + amount > Number(charge.amount ?? 0))
40
+ return fail(ctx, `The transfers from source_transaction ${sourceId} would exceed its amount (${String(charge.amount)}).`, 400, 'invalid_request_error');
41
+ const bt = typeof charge.balance_transaction === 'string' ? ctx.get('balance_transaction', charge.balance_transaction) : undefined;
42
+ // a charge that has settled waives nothing: the transfer comes out of what is available
43
+ const settledRefusal = bt && Number(bt.available_on) <= Number(ctx.now()) ? settledSourceRefused(ctx, amount, currency) : undefined;
44
+ if (settledRefusal)
45
+ return settledRefusal;
46
+ availableOn = Math.max(Number(ctx.now()), Number(bt?.available_on) || 0);
47
+ group = typeof charge.transfer_group === 'string' ? charge.transfer_group : typeof charge.payment_intent === 'string' ? `group_${charge.payment_intent}` : undefined;
48
+ // the generated group is the charge's too
49
+ if (group && charge.transfer_group !== group)
50
+ await ctx.write('charge', sourceId, { transfer_group: group }, 'charge.transfer_group_assigned');
51
+ }
52
+ else {
53
+ const refused = refusePayout(ctx, amount, currency, undefined);
54
+ if (refused)
55
+ return refused;
56
+ }
57
+ const id = ctx.mint('transfer');
58
+ const bt = await settleTransfer(ctx, id, amount, currency, destination, availableOn ?? Number(ctx.now()), sourceId !== undefined);
59
+ return ctx.reply(await created(ctx, 'transfer', { id, ...ctx.params, ...(group ? { transfer_group: group } : {}) }, {
60
+ amount_reversed: 0, balance_transaction: bt, livemode: false, metadata: {},
61
+ reversed: false, source_type: 'card', source_transaction: null,
62
+ reversals: emptyList(`/v1/transfers/${id}/reversals`),
63
+ destination_payment: `py_${id.replace(/^tr_/, '')}`,
64
+ }));
65
+ };
66
+ /** A transfer from a charge whose funds have settled: "With a source_transaction, the transfer request returns success
67
+ * regardless of your available balance if the related charge hasn't settled yet" (docs.stripe.com/connect/separate-
68
+ * charges-and-transfers), so a settled one comes out of the available balance. */
69
+ function settledSourceRefused(ctx, amount, currency) {
70
+ return refusePayout(ctx, amount, currency, undefined);
71
+ }
72
+ /** An application fee refunded to its whole through its own refunds endpoint: the fee machine's move, or its refusal. */
73
+ function feeFullyRefunded(ctx, resource, flag, id) {
74
+ const refused = ctx.legal(resource, flag, ctx.call.operation.id, 'false', 'true', id);
75
+ return refused ? ctx.refuse(refused) : undefined;
76
+ }
77
+ /** Take `amount` (the remainder by default) back out of a parent's total, as a child row appended to its list. */
78
+ async function giveBack(ctx, o) {
79
+ const id = String(o.parent.id);
80
+ const total = Number(o.parent.amount ?? 0);
81
+ const already = Number(o.parent[o.doneField] ?? 0);
82
+ const remaining = total - already;
83
+ const amount = ctx.params.amount !== undefined ? Math.trunc(Number(ctx.params.amount) || 0) : remaining;
84
+ if (amount <= 0 || amount > remaining)
85
+ return fail(ctx, o.tooLarge(remaining), 400, 'amount_too_large');
86
+ const done = already + amount;
87
+ // a fee refunded in full is `refunded`: the application fee machine's move (a transfer's `reversed` is no state)
88
+ const feeRefusal = o.parentResource === 'application_fee' && done >= total && o.parent[o.flag] !== true ? feeFullyRefunded(ctx, o.parentResource, o.flag, id) : undefined;
89
+ if (feeRefusal)
90
+ return feeRefusal;
91
+ // the `metadata` a reversal or a fee refund is created with is its own ("Set of key-value pairs that you can attach to
92
+ // an object", docs.stripe.com/api/transfer_reversals/create, docs.stripe.com/api/fee_refunds/create)
93
+ const metadata = ctx.params.metadata && typeof ctx.params.metadata === 'object' ? { metadata: ctx.params.metadata } : {};
94
+ const child = await created(ctx, o.child, { ...o.childFields(amount), ...metadata }, o.childDefaults);
95
+ if (o.settle)
96
+ await o.settle(child, amount);
97
+ const existing = o.parent[o.flag === 'reversed' ? 'reversals' : 'refunds'] ?? { object: 'list', data: [], has_more: false, total_count: 0 };
98
+ const data = [...(existing.data ?? []), child];
99
+ await ctx.write(o.parentResource, id, {
100
+ [o.doneField]: done, [o.flag]: done >= total,
101
+ [o.flag === 'reversed' ? 'reversals' : 'refunds']: { ...existing, data, total_count: data.length, url: o.listUrl },
102
+ }, o.op);
103
+ return ctx.reply(child);
104
+ }
105
+ const reverse = async (ctx) => {
106
+ const id = at(ctx, 'id');
107
+ const tr = ctx.get('transfer', id);
108
+ if (!tr)
109
+ return transferMissing(ctx, id);
110
+ return giveBack(ctx, {
111
+ parent: tr, parentResource: 'transfer', child: 'transfer_reversal',
112
+ childFields: (amount) => ({ amount, currency: tr.currency ?? 'usd', transfer: id }),
113
+ childDefaults: { balance_transaction: null, destination_payment_refund: null, source_refund: null, metadata: {} },
114
+ doneField: 'amount_reversed', flag: 'reversed', listUrl: `/v1/transfers/${id}/reversals`, op: 'transfer.reversed',
115
+ tooLarge: (remaining) => `Transfer ${id} can only be reversed up to ${remaining}.`,
116
+ settle: async (child, amount) => {
117
+ const bt = await settleTransferReversal(ctx, String(child.id), amount, String(tr.currency ?? 'usd'), String(tr.destination));
118
+ await ctx.write('transfer_reversal', String(child.id), { balance_transaction: bt }, 'transfer_reversal.updated');
119
+ },
120
+ });
121
+ };
122
+ const reversals = async (ctx) => {
123
+ const id = at(ctx, 'id');
124
+ if (!ctx.get('transfer', id))
125
+ return transferMissing(ctx, id);
126
+ return list(ctx, 'transfer_reversal', newest(ctx, 'transfer_reversal').filter((r) => r.transfer === id));
127
+ };
128
+ const feeMissing = (ctx, id) => fail(ctx, `No such application fee: '${id}'`, 404, 'resource_missing');
129
+ const refundFee = async (ctx) => {
130
+ const id = at(ctx, 'id');
131
+ const fee = ctx.get('application_fee', id);
132
+ if (!fee)
133
+ return feeMissing(ctx, id);
134
+ return giveBack(ctx, {
135
+ parent: fee, parentResource: 'application_fee', child: 'fee_refund',
136
+ childFields: (amount) => ({ amount, currency: fee.currency ?? 'usd', fee: id }),
137
+ childDefaults: { balance_transaction: null, metadata: {} },
138
+ doneField: 'amount_refunded', flag: 'refunded', listUrl: `/v1/application_fees/${id}/refunds`, op: 'application_fee.refunded',
139
+ tooLarge: (remaining) => `Application fee ${id} can only be refunded up to ${remaining}.`,
140
+ });
141
+ };
142
+ const feeRefunds = async (ctx) => {
143
+ const id = at(ctx, 'id');
144
+ if (!ctx.get('application_fee', id))
145
+ return feeMissing(ctx, id);
146
+ return list(ctx, 'fee_refund', newest(ctx, 'fee_refund').filter((r) => r.fee === id));
147
+ };
148
+ export const transfers = {
149
+ PostTransfers: create,
150
+ PostTransfersIdReversals: reverse,
151
+ GetTransfersIdReversals: reversals,
152
+ PostApplicationFeesIdRefunds: refundFee,
153
+ GetApplicationFeesIdRefunds: feeRefunds,
154
+ };
@@ -0,0 +1,2 @@
1
+ import type { Semantics } from '@volter/world-core';
2
+ export declare const treasury: Record<string, Semantics>;
@@ -0,0 +1,377 @@
1
+ import { PLATFORM_ACCOUNT_ID, validateMoney } from "../stripe-twin.js";
2
+ import { at, created, fail, list, newest, send, where } from "./shared.js";
3
+ const FA = 'treasury.financial_account';
4
+ const TX = 'treasury.transaction';
5
+ const ENTRY = 'treasury.transaction_entry';
6
+ const ENTRY_TYPES = new Set(['credit_reversal', 'debit_reversal', 'inbound_transfer', 'inbound_transfer_return', 'issuing_authorization_hold', 'issuing_authorization_release', 'outbound_payment', 'outbound_transfer', 'received_credit', 'received_debit']);
7
+ const faMissing = (ctx, id, status = 404) => fail(ctx, `No such financial account: '${id}'`, status, 'resource_missing');
8
+ const metadataOf = (ctx) => (ctx.params.metadata && typeof ctx.params.metadata === 'object' ? ctx.params.metadata : {});
9
+ /** A financial account's features as the served spec's treasury.financial_account_features gives them: a toggle
10
+ * (card_issuing, deposit_insurance, intra_stripe_flows) or a feature per network (financial_addresses.aba,
11
+ * inbound_transfers.ach, outbound_payments.ach and .us_domestic_wire, outbound_transfers likewise), each
12
+ * { requested, status, status_details }. What a request asks for is laid over what the account had. Where the
13
+ * documentation stops and the twin decides: a requested feature is active at once (test mode), and one never requested
14
+ * is left out (each is optional in the served spec). Answers the features and the active features' paths. */
15
+ const NETWORKS = { financial_addresses: ['aba'], inbound_transfers: ['ach'], outbound_payments: ['ach', 'us_domestic_wire'], outbound_transfers: ['ach', 'us_domestic_wire'] };
16
+ const TOGGLES = ['card_issuing', 'deposit_insurance', 'intra_stripe_flows'];
17
+ function featuresOf(requested, had = {}) {
18
+ const on = (v) => v === true || v === 'true';
19
+ const setting = (asked) => ({ requested: asked, status: asked ? 'active' : 'restricted', status_details: [] });
20
+ const features = { ...had };
21
+ for (const t of TOGGLES) {
22
+ const r = requested[t];
23
+ if (r && typeof r === 'object' && r.requested !== undefined)
24
+ features[t] = setting(on(r.requested));
25
+ }
26
+ for (const [f, nets] of Object.entries(NETWORKS)) {
27
+ const r = requested[f];
28
+ if (!r || typeof r !== 'object')
29
+ continue;
30
+ const current = features[f] ?? {};
31
+ const next = { ...current };
32
+ for (const n of nets) {
33
+ const nr = r[n];
34
+ if (nr && typeof nr === 'object' && nr.requested !== undefined)
35
+ next[n] = setting(on(nr.requested));
36
+ }
37
+ features[f] = next;
38
+ }
39
+ const active = [];
40
+ for (const t of TOGGLES)
41
+ if (features[t]?.status === 'active')
42
+ active.push(t);
43
+ for (const [f, nets] of Object.entries(NETWORKS))
44
+ for (const n of nets)
45
+ if (features[f]?.[n]?.status === 'active')
46
+ active.push(`${f}.${n}`);
47
+ return { features, active };
48
+ }
49
+ /** The account's bank address once financial_addresses.aba is active: "The FinancialAccount gains a FinancialAddress
50
+ * when the `financial_addresses.aba` feature is active", and "A FinancialAddress is not added until the
51
+ * financial_addresses.aba feature has been activated" (docs.stripe.com/treasury/account-management/financial-accounts),
52
+ * whose test example answers "bank_name": "Stripe Test Bank", "routing_number": "000000001" and the networks "ach",
53
+ * "us_domestic_wire", "rtp"; "The full account_number is only returned if the request expands it" (the same page).
54
+ * Where the documentation stops and the twin decides: the account number is ten digits drawn from the account's id,
55
+ * answered by its last four (the full number is null: expanding it is not modelled), and the holder's name is the
56
+ * platform account's business name, its dashboard name or, with neither, its id. */
57
+ function abaAddress(ctx, faId) {
58
+ let n = 0;
59
+ for (const ch of faId)
60
+ n = (n * 31 + ch.charCodeAt(0)) % 10_000_000_000;
61
+ const number = String(n).padStart(10, '0');
62
+ const platform = ctx.get('account', PLATFORM_ACCOUNT_ID);
63
+ const name = (platform?.business_profile?.name ?? platform?.settings?.dashboard?.display_name ?? PLATFORM_ACCOUNT_ID);
64
+ return { type: 'aba', supported_networks: ['ach', 'us_domestic_wire', 'rtp'], aba: { account_holder_name: name, account_number: null, account_number_last4: number.slice(-4), bank_name: 'Stripe Test Bank', routing_number: '000000001' } };
65
+ }
66
+ const addressesOf = (ctx, faId, active) => (active.includes('financial_addresses.aba') ? [abaAddress(ctx, faId)] : []);
67
+ // an account opens with a zero balance in each supported currency and the requested features active
68
+ const open = async (ctx) => {
69
+ const p = ctx.params;
70
+ const currencies = Array.isArray(p.supported_currencies) ? p.supported_currencies.map(String) : typeof p.supported_currencies === 'string' ? [p.supported_currencies] : [];
71
+ if (currencies.length === 0)
72
+ return fail(ctx, 'Missing required param: supported_currencies.', 400, 'parameter_missing');
73
+ const requested = p.features && typeof p.features === 'object' ? p.features : {};
74
+ const { features, active } = featuresOf(requested);
75
+ const zero = Object.fromEntries(currencies.map((c) => [c, 0]));
76
+ const id = ctx.mint(FA);
77
+ return ctx.reply(await created(ctx, FA, { id }, {
78
+ livemode: false, status: 'open', country: p.country ?? 'US',
79
+ supported_currencies: currencies, active_features: active, pending_features: [], restricted_features: [],
80
+ features, balance: { cash: zero, inbound_pending: zero, outbound_pending: zero },
81
+ financial_addresses: addressesOf(ctx, id, active), platform_restrictions: null,
82
+ status_details: { closed: null },
83
+ metadata: metadataOf(ctx),
84
+ }));
85
+ };
86
+ // reading the features answers them; updating them lays the request over them (featuresOf)
87
+ const features = async (ctx) => {
88
+ const id = at(ctx, 'financial_account');
89
+ const f = ctx.get(FA, id);
90
+ if (!f)
91
+ return faMissing(ctx, id);
92
+ if (ctx.call.request.method === 'GET')
93
+ return ctx.reply({ object: 'treasury.financial_account_features', ...f.features });
94
+ const next = featuresOf(ctx.params, f.features ?? {});
95
+ const updated = await ctx.write(FA, id, { features: next.features, active_features: next.active, financial_addresses: addressesOf(ctx, id, next.active) }, 'financial_account.features_updated');
96
+ return ctx.reply({ object: 'treasury.financial_account_features', ...updated.features });
97
+ };
98
+ // only metadata and platform restrictions change
99
+ const updateAccount = async (ctx) => {
100
+ const id = at(ctx, 'financial_account');
101
+ if (!ctx.get(FA, id))
102
+ return faMissing(ctx, id);
103
+ const patch = {};
104
+ if (ctx.params.metadata !== undefined)
105
+ patch.metadata = ctx.params.metadata;
106
+ if (ctx.params.platform_restrictions !== undefined)
107
+ patch.platform_restrictions = ctx.params.platform_restrictions;
108
+ return ctx.reply(await ctx.write(FA, id, patch, 'financial_account.updated'));
109
+ };
110
+ /** Post a flow's double entry: a ledger transaction with its net balance impact, and its one entry. */
111
+ async function post(ctx, o) {
112
+ const now = ctx.now();
113
+ const txnId = ctx.mint(TX);
114
+ await ctx.write(TX, txnId, {
115
+ object: 'treasury.transaction', created: now, livemode: false,
116
+ amount: o.amount, currency: o.currency, financial_account: o.financial_account,
117
+ flow: o.flow, flow_type: o.flow_type, flow_details: null,
118
+ status: o.status, balance_impact: o.balance_impact, description: o.description,
119
+ entries: { object: 'list', has_more: false, url: `/v1/treasury/transaction_entries?transaction=${txnId}`, data: [] },
120
+ status_transitions: { posted_at: o.status === 'posted' ? now : null, void_at: null },
121
+ }, 'treasury_transaction.created');
122
+ await ctx.write(ENTRY, ctx.mint(ENTRY), {
123
+ object: 'treasury.transaction_entry', created: now, livemode: false,
124
+ amount: o.amount, currency: o.currency, financial_account: o.financial_account,
125
+ flow: o.flow, flow_type: o.flow_type,
126
+ flow_details: o.flowDetailKey ? { type: o.flowDetailKey, [o.flowDetailKey]: o.flow } : null,
127
+ transaction: txnId, effective_at: now,
128
+ balance_impact: o.balance_impact,
129
+ // what the entry records: its flow's kind where Stripe names one (docs.stripe.com/api/treasury/transaction_entries/object);
130
+ // a vendor `type`, kept apart from the kernel's row type
131
+ _stripe_type: ENTRY_TYPES.has(String(o.flow_type)) ? o.flow_type : 'other',
132
+ }, 'treasury_transaction_entry.created');
133
+ // the account's balance moves by the entry's impact: cash "Funds the user can spend right now", inbound_pending
134
+ // "Funds not spendable yet", outbound_pending "held for pending outbound flows" (the served spec's balance)
135
+ const account = ctx.get(FA, o.financial_account);
136
+ if (account) {
137
+ const bal = account.balance ?? { cash: {}, inbound_pending: {}, outbound_pending: {} };
138
+ const moved = Object.fromEntries(['cash', 'inbound_pending', 'outbound_pending'].map((k) => [k, { ...(bal[k] ?? {}), [o.currency]: ((bal[k] ?? {})[o.currency] ?? 0) + (Number(o.balance_impact[k]) || 0) }]));
139
+ await ctx.write(FA, o.financial_account, { balance: moved }, 'financial_account.balance_updated');
140
+ }
141
+ return txnId;
142
+ }
143
+ /** The request's funding account, or the refusal. */
144
+ function fundingAccount(ctx) {
145
+ const bad = validateMoney(ctx.params);
146
+ if (bad)
147
+ return send(ctx, bad);
148
+ const fa = typeof ctx.params.financial_account === 'string' ? ctx.params.financial_account : '';
149
+ if (!fa)
150
+ return fail(ctx, 'Missing required param: financial_account.', 400, 'parameter_missing');
151
+ return ctx.get(FA, fa) ? fa : faMissing(ctx, fa, 400);
152
+ }
153
+ const noTransitions = { canceled_at: null, failed_at: null, posted_at: null, returned_at: null };
154
+ /** Where an outbound flow sends its money, as the served spec's payment method details give it: the bank account's
155
+ * holder type, last four digits and routing number from what the request sent (a saved method's, or the test bank's
156
+ * when none is given), and its billing details (required): the name and email sent, the address lines null where not
157
+ * given. Where the documentation stops and the twin decides: a saved method's details are the test bank's. */
158
+ function destinationDetails(ctx, dest) {
159
+ const data = ctx.params.destination_payment_method_data && typeof ctx.params.destination_payment_method_data === 'object' ? ctx.params.destination_payment_method_data : {};
160
+ const bank = data.us_bank_account && typeof data.us_bank_account === 'object' ? data.us_bank_account : {};
161
+ const billing = data.billing_details && typeof data.billing_details === 'object' ? data.billing_details : {};
162
+ const address = billing.address && typeof billing.address === 'object' ? billing.address : {};
163
+ const number = typeof bank.account_number === 'string' ? bank.account_number.replace(/\D/g, '') : '';
164
+ const billing_details = { name: billing.name ?? null, email: billing.email ?? null, address: Object.fromEntries(['city', 'country', 'line1', 'line2', 'postal_code', 'state'].map((k) => [k, address[k] ?? null])) };
165
+ if (dest && data.type === undefined && dest.startsWith('fa_'))
166
+ return { type: 'financial_account', financial_account: { id: dest, network: 'stripe' }, billing_details };
167
+ return {
168
+ type: 'us_bank_account', billing_details,
169
+ us_bank_account: { last4: number ? number.slice(-4) : '6789', network: 'ach', routing_number: typeof bank.routing_number === 'string' ? bank.routing_number : '110000000', account_holder_type: typeof bank.account_holder_type === 'string' ? bank.account_holder_type : 'individual', account_type: typeof bank.account_type === 'string' ? bank.account_type : 'checking', bank_name: 'STRIPE TEST BANK', mandate: null },
170
+ };
171
+ }
172
+ /** An outbound payment that names no destination: "You must provide either destination_payment_method or
173
+ * destination_payment_method_data" (the served spec's outbound payment create). */
174
+ function noDestination(ctx) {
175
+ return fail(ctx, 'You must provide either `destination_payment_method` or `destination_payment_method_data`.', 400, 'parameter_missing');
176
+ }
177
+ const outboundPayment = async (ctx) => {
178
+ const fa = fundingAccount(ctx);
179
+ if (fa instanceof Response)
180
+ return fa;
181
+ const dest = typeof ctx.params.destination_payment_method === 'string' ? ctx.params.destination_payment_method : null;
182
+ if (!dest && !(ctx.params.destination_payment_method_data && typeof ctx.params.destination_payment_method_data === 'object'))
183
+ return noDestination(ctx);
184
+ const amount = ctx.params.amount;
185
+ const currency = String(ctx.params.currency);
186
+ const id = ctx.mint('treasury.outbound_payment');
187
+ const txn = await post(ctx, { financial_account: fa, amount: -amount, currency, flow: id, flow_type: 'outbound_payment', status: 'open', balance_impact: { cash: -amount, inbound_pending: 0, outbound_pending: amount }, description: 'OutboundPayment' });
188
+ return ctx.reply(await created(ctx, 'treasury.outbound_payment', { id }, {
189
+ amount, currency, financial_account: fa, livemode: false, status: 'processing', cancelable: true,
190
+ destination_payment_method: dest,
191
+ destination_payment_method_details: destinationDetails(ctx, dest),
192
+ destination_payment_method_data: null, end_user_details: null, expected_arrival_date: Number(ctx.now()) + 2 * 86400,
193
+ hosted_regulatory_receipt_url: null, returned_details: null, statement_descriptor: ctx.params.statement_descriptor ?? 'payment',
194
+ description: typeof ctx.params.description === 'string' ? ctx.params.description : null, transaction: txn, status_transitions: noTransitions, metadata: metadataOf(ctx),
195
+ }));
196
+ };
197
+ const outboundTransfer = async (ctx) => {
198
+ const fa = fundingAccount(ctx);
199
+ if (fa instanceof Response)
200
+ return fa;
201
+ const dest = typeof ctx.params.destination_payment_method === 'string' ? ctx.params.destination_payment_method : null;
202
+ const amount = ctx.params.amount;
203
+ const currency = String(ctx.params.currency);
204
+ const id = ctx.mint('treasury.outbound_transfer');
205
+ const txn = await post(ctx, { financial_account: fa, amount: -amount, currency, flow: id, flow_type: 'outbound_transfer', status: 'open', balance_impact: { cash: -amount, inbound_pending: 0, outbound_pending: amount }, description: 'OutboundTransfer' });
206
+ return ctx.reply(await created(ctx, 'treasury.outbound_transfer', { id }, {
207
+ amount, currency, financial_account: fa, livemode: false, status: 'processing', cancelable: true,
208
+ destination_payment_method: dest, destination_payment_method_details: destinationDetails(ctx, dest),
209
+ expected_arrival_date: Number(ctx.now()) + 2 * 86400, hosted_regulatory_receipt_url: null,
210
+ returned_details: null, statement_descriptor: ctx.params.statement_descriptor ?? 'transfer',
211
+ description: typeof ctx.params.description === 'string' ? ctx.params.description : null, transaction: txn, status_transitions: noTransitions, metadata: metadataOf(ctx),
212
+ }));
213
+ };
214
+ /** The bank account an inbound transfer may pull from: "You must first set up the account-attached payment method for
215
+ * inbound flows and verify the bank account using a SetupIntent", and invalid ones ("of unsupported types, containing
216
+ * an unverified bank account, or not set up for inbound flows") "throw the same errors as in live mode"
217
+ * (docs.stripe.com/treasury/moving-money/financial-accounts/into/inbound-transfers). A payment method is set up for
218
+ * inbound flows by a SetupIntent whose flow_directions holds `inbound`, and verified when that SetupIntent succeeded
219
+ * ("The bank account has been instantly verified or verification isn't necessary", its `succeeded` status,
220
+ * docs.stripe.com/treasury/connect/legacy/v1/moving-money/working-with-bankaccount-objects).
221
+ * Where the documentation stops and the twin decides: the page quotes no error, so the twin answers the documented code
222
+ * for the class, payment_method_unexpected_state ("The provided payment method's state was incompatible with the
223
+ * operation you were trying to perform", docs.stripe.com/error-codes), in its own words; an existing verified
224
+ * BankAccount (`ba_`), which the page also allows, is not checked. Answers the payment method, or the refusal. */
225
+ function inboundOrigin(ctx, origin) {
226
+ if (origin.startsWith('ba_'))
227
+ return undefined;
228
+ const pm = ctx.get('payment_method', origin);
229
+ if (!pm)
230
+ return fail(ctx, `No such PaymentMethod: '${origin}'`, 400, 'resource_missing');
231
+ if (pm.type !== 'us_bank_account')
232
+ return fail(ctx, `The PaymentMethod '${origin}' is of type ${String(pm.type)}; an InboundTransfer pulls from a us_bank_account.`, 400, 'payment_method_unexpected_state');
233
+ const setUp = ctx.rows('setup_intent').some((si) => si.payment_method === origin && si.status === 'succeeded' && Array.isArray(si.flow_directions) && si.flow_directions.map(String).includes('inbound'));
234
+ if (!setUp)
235
+ return fail(ctx, `The PaymentMethod '${origin}' has not been set up for inbound flows and verified with a SetupIntent.`, 400, 'payment_method_unexpected_state');
236
+ return pm;
237
+ }
238
+ const inboundTransfer = async (ctx) => {
239
+ const fa = fundingAccount(ctx);
240
+ if (fa instanceof Response)
241
+ return fa;
242
+ const origin = typeof ctx.params.origin_payment_method === 'string' ? ctx.params.origin_payment_method : '';
243
+ if (!origin)
244
+ return fail(ctx, 'Missing required param: origin_payment_method.', 400, 'parameter_missing');
245
+ const pm = inboundOrigin(ctx, origin);
246
+ if (pm instanceof Response)
247
+ return pm;
248
+ const bank = (pm?.us_bank_account ?? {});
249
+ const billing = (pm?.billing_details ?? {});
250
+ // the debit mandate the account's verification made (docs.stripe.com/payments/setup-intents#mandates)
251
+ const mandate = ctx.rows('setup_intent').find((si) => si.payment_method === origin && si.status === 'succeeded' && typeof si.mandate === 'string')?.mandate;
252
+ const amount = ctx.params.amount;
253
+ const currency = String(ctx.params.currency);
254
+ const id = ctx.mint('treasury.inbound_transfer');
255
+ // it starts processing, its funds pending inbound, until confirmed (succeedInbound)
256
+ const txn = await post(ctx, { financial_account: fa, amount, currency, flow: id, flow_type: 'inbound_transfer', status: 'open', balance_impact: { cash: 0, inbound_pending: amount, outbound_pending: 0 }, description: 'InboundTransfer', flowDetailKey: 'inbound_transfer' });
257
+ return ctx.reply(await created(ctx, 'treasury.inbound_transfer', { id }, {
258
+ amount, currency, financial_account: fa, origin_payment_method: origin, livemode: false,
259
+ status: 'processing', cancelable: true, returned: null,
260
+ // the pulled account as its payment method holds it
261
+ origin_payment_method_details: {
262
+ type: 'us_bank_account',
263
+ us_bank_account: { last4: bank.last4 ?? '6789', routing_number: bank.routing_number ?? '110000000', bank_name: bank.bank_name ?? 'STRIPE TEST BANK', account_holder_type: bank.account_holder_type ?? null, account_type: bank.account_type ?? null, fingerprint: bank.fingerprint ?? null, ...(mandate ? { mandate } : {}), network: 'ach' },
264
+ billing_details: { address: billing.address ?? {}, email: billing.email ?? null, name: billing.name ?? null },
265
+ },
266
+ failure_details: null, hosted_regulatory_receipt_url: null,
267
+ linked_flows: { received_debit: null }, statement_descriptor: ctx.params.statement_descriptor ?? 'transfer',
268
+ description: typeof ctx.params.description === 'string' ? ctx.params.description : null, transaction: txn, status_transitions: { succeeded_at: null, failed_at: null, canceled_at: null },
269
+ metadata: metadataOf(ctx),
270
+ }));
271
+ };
272
+ // test mode's stand-ins for money another party sends to the account or pulls from it
273
+ // (docs.stripe.com/treasury/moving-money/receiving-funds, docs.stripe.com/api/treasury/received_credits/test_mode_create)
274
+ function received(kind) {
275
+ return async (ctx) => {
276
+ const fa = fundingAccount(ctx);
277
+ if (fa instanceof Response)
278
+ return fa;
279
+ const network = typeof ctx.params.network === 'string' ? ctx.params.network : '';
280
+ if (!['ach', 'us_domestic_wire', 'stripe'].includes(network))
281
+ return fail(ctx, 'Missing required param: network.', 400, 'parameter_missing');
282
+ const amount = ctx.params.amount;
283
+ const currency = String(ctx.params.currency);
284
+ const id = ctx.mint(`treasury.${kind}`);
285
+ const signed = kind === 'received_credit' ? amount : -amount;
286
+ const txn = await post(ctx, { financial_account: fa, amount: signed, currency, flow: id, flow_type: kind, status: 'posted', balance_impact: { cash: signed, inbound_pending: 0, outbound_pending: 0 }, description: kind === 'received_credit' ? 'ReceivedCredit' : 'ReceivedDebit', flowDetailKey: kind });
287
+ return ctx.reply(await created(ctx, `treasury.${kind}`, { id }, {
288
+ amount, currency, financial_account: fa, network, livemode: false, status: 'succeeded', failure_code: null,
289
+ description: typeof ctx.params.description === 'string' ? ctx.params.description : kind === 'received_credit' ? 'Received credit' : 'Received debit',
290
+ hosted_regulatory_receipt_url: null, transaction: txn, reversal_details: null,
291
+ initiating_payment_method_details: { type: 'us_bank_account', billing_details: { address: {}, email: null, name: null }, us_bank_account: { bank_name: 'STRIPE TEST BANK', last4: '6789', routing_number: '110000000' } },
292
+ linked_flows: kind === 'received_credit' ? { credit_reversal: null, issuing_authorization: null, issuing_transaction: null, source_flow: null, source_flow_type: null } : { debit_reversal: null, inbound_transfer: null, issuing_authorization: null, issuing_transaction: null, payout: null },
293
+ }));
294
+ };
295
+ }
296
+ /** Test mode's confirmation of a processing inbound transfer: it succeeds, its transaction posts and the pending funds
297
+ * become cash ("The status changes to succeeded once the funds have been "confirmed" and a transaction is created and
298
+ * posted", docs.stripe.com/api/treasury/inbound_transfers). */
299
+ const succeedInbound = async (ctx) => {
300
+ const id = at(ctx, 'id');
301
+ const flow = ctx.get('treasury.inbound_transfer', id);
302
+ if (!flow)
303
+ return fail(ctx, `No such inbound transfer: '${id}'`, 404, 'resource_missing');
304
+ const refused = ctx.legal('treasury.inbound_transfer', 'status', 'PostTestHelpersTreasuryInboundTransfersIdSucceed', flow.status, 'succeeded', id);
305
+ if (refused)
306
+ return ctx.refuse(refused);
307
+ const txn = typeof flow.transaction === 'string' ? ctx.get(TX, flow.transaction) : undefined;
308
+ const amount = Number(flow.amount) || 0;
309
+ const cur = String(flow.currency ?? 'usd');
310
+ if (txn && txn.status === 'open') {
311
+ await ctx.write(TX, String(txn.id), { status: 'posted', balance_impact: { cash: amount, inbound_pending: 0, outbound_pending: 0 }, status_transitions: { ...txn.status_transitions, posted_at: ctx.now() } }, 'treasury_transaction.posted');
312
+ const account = ctx.get(FA, String(txn.financial_account));
313
+ if (account) {
314
+ const bal = account.balance ?? { cash: {}, inbound_pending: {}, outbound_pending: {} };
315
+ await ctx.write(FA, String(account.id), { balance: { ...bal, cash: { ...(bal.cash ?? {}), [cur]: ((bal.cash ?? {})[cur] ?? 0) + amount }, inbound_pending: { ...(bal.inbound_pending ?? {}), [cur]: ((bal.inbound_pending ?? {})[cur] ?? 0) - amount } } }, 'financial_account.balance_updated');
316
+ }
317
+ }
318
+ return ctx.reply(await ctx.write('treasury.inbound_transfer', id, { status: 'succeeded', cancelable: false, status_transitions: { ...flow.status_transitions, succeeded_at: ctx.now() } }, 'inbound_transfer.succeeded'));
319
+ };
320
+ /** Cancel a flow still processing; an outbound one must also still be cancelable. */
321
+ function cancel(resource, param, name, operationId, op, checkCancelable) {
322
+ return async (ctx) => {
323
+ const id = at(ctx, param);
324
+ const flow = ctx.get(resource, id);
325
+ if (!flow)
326
+ return fail(ctx, `No such ${name}: '${id}'`, 404, 'resource_missing');
327
+ // a processing flow that is no longer cancelable is refused as one no longer processing
328
+ const refused = ctx.legal(resource, 'status', operationId, checkCancelable && flow.cancelable !== true ? 'not_cancelable' : flow.status, undefined, id);
329
+ if (refused)
330
+ return ctx.refuse(refused);
331
+ // a canceled flow's open transaction is voided and what it held returns to the account (the reverse of its
332
+ // balance impact). Where the documentation stops and the twin decides: a flow already posted is only marked canceled
333
+ const txn = typeof flow.transaction === 'string' ? ctx.get(TX, flow.transaction) : undefined;
334
+ if (txn && txn.status === 'open') {
335
+ await ctx.write(TX, String(txn.id), { status: 'void', status_transitions: { ...txn.status_transitions, void_at: ctx.now() } }, 'treasury_transaction.voided');
336
+ const account = ctx.get(FA, String(txn.financial_account));
337
+ const impact = txn.balance_impact ?? {};
338
+ const cur = String(txn.currency ?? 'usd');
339
+ if (account) {
340
+ const bal = account.balance ?? { cash: {}, inbound_pending: {}, outbound_pending: {} };
341
+ const back = Object.fromEntries(['cash', 'inbound_pending', 'outbound_pending'].map((k) => [k, { ...(bal[k] ?? {}), [cur]: ((bal[k] ?? {})[cur] ?? 0) - (Number(impact[k]) || 0) }]));
342
+ await ctx.write(FA, String(account.id), { balance: back }, 'financial_account.balance_updated');
343
+ }
344
+ }
345
+ return ctx.reply(await ctx.write(resource, id, { status: 'canceled', cancelable: false, status_transitions: { ...flow.status_transitions, canceled_at: ctx.now() } }, op));
346
+ };
347
+ }
348
+ // the ledger is always read for one account
349
+ function ledger(resource, spec) {
350
+ return async (ctx) => {
351
+ if (typeof ctx.params.financial_account !== 'string' || !ctx.params.financial_account)
352
+ return fail(ctx, 'Missing required param: financial_account.', 400, 'parameter_missing');
353
+ return list(ctx, resource, where(ctx, newest(ctx, resource), spec));
354
+ };
355
+ }
356
+ export const treasury = {
357
+ PostTreasuryFinancialAccounts: open,
358
+ GetTreasuryFinancialAccountsFinancialAccountFeatures: features,
359
+ PostTreasuryFinancialAccountsFinancialAccountFeatures: features,
360
+ PostTreasuryFinancialAccountsFinancialAccount: updateAccount,
361
+ PostTreasuryOutboundPayments: outboundPayment,
362
+ PostTreasuryOutboundPaymentsIdCancel: cancel('treasury.outbound_payment', 'id', 'outbound payment', 'PostTreasuryOutboundPaymentsIdCancel', 'outbound_payment.canceled', true),
363
+ PostTreasuryOutboundTransfers: outboundTransfer,
364
+ PostTreasuryOutboundTransfersOutboundTransferCancel: cancel('treasury.outbound_transfer', 'outbound_transfer', 'outbound transfer', 'PostTreasuryOutboundTransfersOutboundTransferCancel', 'outbound_transfer.canceled', true),
365
+ PostTreasuryInboundTransfers: inboundTransfer,
366
+ PostTestHelpersTreasuryInboundTransfersIdSucceed: succeedInbound,
367
+ PostTestHelpersTreasuryReceivedCredits: received('received_credit'),
368
+ PostTestHelpersTreasuryReceivedDebits: received('received_debit'),
369
+ PostTreasuryInboundTransfersInboundTransferCancel: cancel('treasury.inbound_transfer', 'inbound_transfer', 'inbound transfer', 'PostTreasuryInboundTransfersInboundTransferCancel', 'inbound_transfer.canceled', false),
370
+ GetTreasuryTransactions: ledger(TX, {
371
+ financial_account: (r, v) => r.financial_account === v, status: (r, v) => r.status === v,
372
+ flow: (r, v) => r.flow === v, flow_type: (r, v) => r.flow_type === v,
373
+ }),
374
+ GetTreasuryTransactionEntries: ledger(ENTRY, {
375
+ financial_account: (r, v) => r.financial_account === v, flow: (r, v) => r.flow === v, transaction: (r, v) => r.transaction === v,
376
+ }),
377
+ };
@@ -0,0 +1,3 @@
1
+ import { type Semantics } from '@volter/world-core';
2
+ export declare function worldEndpointSecret(connect: boolean): string | undefined;
3
+ export declare const webhookEndpoints: Record<string, Semantics>;
@@ -0,0 +1,85 @@
1
+ // Webhook endpoint semantics: registering a URL and the events it subscribes to. Delivery reads
2
+ // the endpoints from the tree, signing each POST with the endpoint's own secret; a disabled one
3
+ // (the machine in ../manifest.ts) receives nothing. Endpoint list, retrieve and delete are the derived core's.
4
+ //
5
+ // The Events API lists and retrieves the stored events of the account a request acts for: an event of a connected
6
+ // account carries it ("Each event for a connected account contains a top-level `account` property that identifies the
7
+ // connected account. Because the connected account owns the object that triggered the event, you must make API
8
+ // requests for that object as the connected account", docs.stripe.com/connect/webhooks; the event's `account`: "The
9
+ // connected account that originates the event", spec/openapi.json.gz), so a request with the Stripe-Account header
10
+ // sees that account's events and one without it the platform's, those with no `account`. Where the documentation
11
+ // stops and the twin decides: a platform request does not see its connected accounts' events.
12
+ import { worldEnvValue } from '@volter/world-core';
13
+ import { asBool } from "../stripe-twin.js";
14
+ import { actingAccount } from "./ledger.js";
15
+ import { at, created, fail, inRange, list, newest, where } from "./shared.js";
16
+ const WE = 'webhook_endpoint';
17
+ // The signing secret is the World's where the World set one. Stripe mints an endpoint's secret and the app is given it
18
+ // (the dashboard, `stripe listen`); in a World the app's env is the World's, made at boot, so the World's value is the
19
+ // one the app verifies with, and an endpoint the app registers is signed with it: the twin's decision, since Stripe
20
+ // lets no one choose a secret. A Connect endpoint (`connect`) takes a Connect name first. Only a value the World sets
21
+ // counts (worldEnvValue), never one the caller's shell passes through; with none (a twin outside a World) the twin
22
+ // mints, as Stripe does.
23
+ const ACCOUNT_SECRET_ENV = ['STRIPE_WEBHOOK_SECRET', 'STRIPE_WEBHOOK_SIGNING_SECRET', 'STRIPE_ENDPOINT_SECRET', 'STRIPE_WEBHOOK_SECRET_KEY', 'NEXT_PRIVATE_STRIPE_WEBHOOK_SECRET'];
24
+ const CONNECT_SECRET_ENV = ['STRIPE_CONNECT_WEBHOOK_SECRET', 'STRIPE_WEBHOOK_SECRET_CONNECT', 'STRIPE_CONNECT_WEBHOOK_SIGNING_SECRET'];
25
+ export function worldEndpointSecret(connect) {
26
+ for (const name of connect ? [...CONNECT_SECRET_ENV, ...ACCOUNT_SECRET_ENV] : ACCOUNT_SECRET_ENV) {
27
+ const value = worldEnvValue(name);
28
+ if (value)
29
+ return value;
30
+ }
31
+ return undefined;
32
+ }
33
+ const create = async (ctx) => {
34
+ const params = ctx.params;
35
+ const url = typeof params.url === 'string' ? params.url : '';
36
+ if (!url)
37
+ return fail(ctx, 'Missing required param: url.', 400, 'parameter_missing');
38
+ const enabledEvents = Array.isArray(params.enabled_events) ? params.enabled_events.map(String) : typeof params.enabled_events === 'string' ? [params.enabled_events] : undefined;
39
+ if (!enabledEvents || enabledEvents.length === 0)
40
+ return fail(ctx, 'Missing required param: enabled_events.', 400, 'parameter_missing');
41
+ const id = ctx.mint(WE);
42
+ return ctx.reply(await created(ctx, WE, { ...params, id }, {
43
+ url, enabled_events: enabledEvents, status: 'enabled', livemode: false, metadata: {},
44
+ api_version: '2024-06-20', application: null, description: typeof params.description === 'string' ? params.description : null,
45
+ secret: worldEndpointSecret(asBool(params.connect)) ?? `whsec_twin_${id}`,
46
+ }));
47
+ };
48
+ // `disabled` switches delivery off (status disabled) and back on; it is a parameter, not a field
49
+ const update = async (ctx) => {
50
+ const id = at(ctx, 'webhook_endpoint');
51
+ const we = ctx.get(WE, id);
52
+ if (!we)
53
+ return ctx.notFound(WE, id);
54
+ const { disabled, ...fields } = { ...ctx.params };
55
+ if (Array.isArray(ctx.params.enabled_events))
56
+ fields.enabled_events = ctx.params.enabled_events.map(String);
57
+ if (disabled !== undefined)
58
+ return switchDelivery(ctx, id, we, fields, asBool(disabled));
59
+ return ctx.reply(await ctx.write(WE, id, fields, 'webhook_endpoint.update'));
60
+ };
61
+ /** `disabled` switches delivery off or back on (docs.stripe.com/api/webhook_endpoints/update#update_webhook_endpoint-disabled). */
62
+ async function switchDelivery(ctx, id, we, fields, off) {
63
+ const status = off ? 'disabled' : 'enabled';
64
+ const refused = ctx.legal(WE, 'status', 'PostWebhookEndpointsWebhookEndpoint', we.status, status, id);
65
+ if (refused)
66
+ return ctx.refuse(refused);
67
+ return ctx.reply(await ctx.write(WE, id, { ...fields, status }, 'webhook_endpoint.update'));
68
+ }
69
+ /** Whether a stored event is the acting account's (no `account`: the platform's). */
70
+ const ownEvent = (ctx, e) => (typeof e.account === 'string' ? e.account : undefined) === actingAccount(ctx);
71
+ const listEvents = async (ctx) => list(ctx, 'event', where(ctx, newest(ctx, 'event').filter((e) => ownEvent(ctx, e)), {
72
+ type: (e, v) => e.type === v,
73
+ types: (e, v) => (Array.isArray(v) ? v.map(String) : [String(v)]).includes(String(e.type)),
74
+ created: (e, v) => inRange(e.created, v),
75
+ }));
76
+ const retrieveEvent = async (ctx) => {
77
+ const e = ctx.get('event', at(ctx, 'id'));
78
+ return e && ownEvent(ctx, e) ? ctx.reply(e) : ctx.notFound('event', at(ctx, 'id'));
79
+ };
80
+ export const webhookEndpoints = {
81
+ GetEvents: listEvents,
82
+ GetEventsId: retrieveEvent,
83
+ PostWebhookEndpoints: create,
84
+ PostWebhookEndpointsWebhookEndpoint: update,
85
+ };