@volter/twin-stripe 2.0.38 → 3.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 (442) hide show
  1. package/README.md +82 -207
  2. package/dist/generated/pack-facts.json +94 -0
  3. package/dist/spec/SOURCE.md +14 -0
  4. package/dist/spec/fixtures3.json.gz +0 -0
  5. package/dist/spec/openapi.json.gz +0 -0
  6. package/dist/spec/patches.json +34 -0
  7. package/dist/spec/sources.json +378 -0
  8. package/dist/src/cli.js +12 -30
  9. package/dist/src/engine/after-payment.d.ts +9 -0
  10. package/dist/src/engine/after-payment.js +28 -0
  11. package/dist/src/engine/apps-secrets.d.ts +1 -0
  12. package/dist/src/engine/apps-secrets.js +3 -0
  13. package/dist/src/engine/balance.d.ts +5 -0
  14. package/dist/src/engine/balance.js +15 -0
  15. package/dist/src/engine/billing.d.ts +5 -0
  16. package/dist/src/engine/billing.js +6 -0
  17. package/dist/src/engine/charges.d.ts +6 -0
  18. package/dist/src/engine/charges.js +13 -0
  19. package/dist/src/engine/checkout.d.ts +24 -0
  20. package/dist/src/engine/checkout.js +30 -0
  21. package/dist/src/engine/common.d.ts +19 -0
  22. package/dist/src/engine/common.js +32 -0
  23. package/dist/src/{screens → engine}/connect-settings.d.ts +1 -7
  24. package/dist/src/engine/connect-settings.js +26 -0
  25. package/dist/src/engine/connect.d.ts +66 -0
  26. package/dist/src/engine/connect.js +189 -0
  27. package/dist/src/engine/coupons.d.ts +0 -0
  28. package/dist/src/engine/coupons.js +5 -0
  29. package/dist/src/engine/credit-notes.d.ts +1 -0
  30. package/dist/src/engine/credit-notes.js +5 -0
  31. package/dist/src/engine/customers.d.ts +12 -0
  32. package/dist/src/engine/customers.js +30 -0
  33. package/dist/src/engine/display.d.ts +14 -0
  34. package/dist/src/engine/display.js +16 -0
  35. package/dist/src/engine/disputes.d.ts +0 -0
  36. package/dist/src/engine/disputes.js +9 -0
  37. package/dist/src/engine/entitlements.d.ts +1 -0
  38. package/dist/src/engine/entitlements.js +4 -0
  39. package/dist/src/engine/ephemeral-keys.d.ts +0 -0
  40. package/dist/src/engine/ephemeral-keys.js +4 -0
  41. package/dist/src/engine/files.d.ts +18 -0
  42. package/dist/src/engine/files.js +33 -0
  43. package/dist/src/engine/front.d.ts +5 -0
  44. package/dist/src/engine/front.js +25 -0
  45. package/dist/src/engine/invoices.d.ts +24 -0
  46. package/dist/src/engine/invoices.js +57 -0
  47. package/dist/src/engine/issuing.d.ts +35 -0
  48. package/dist/src/engine/issuing.js +45 -0
  49. package/dist/src/engine/ledger.d.ts +9 -0
  50. package/dist/src/engine/ledger.js +9 -0
  51. package/dist/src/engine/oauth.d.ts +4 -0
  52. package/dist/src/engine/oauth.js +25 -0
  53. package/dist/src/engine/onboarding.d.ts +13 -0
  54. package/dist/src/engine/onboarding.js +42 -0
  55. package/dist/src/{stripe-params.d.ts → engine/params.d.ts} +20 -3
  56. package/dist/src/{stripe-params.js → engine/params.js} +7 -60
  57. package/dist/src/engine/payment-intents.d.ts +10 -0
  58. package/dist/src/engine/payment-intents.js +27 -0
  59. package/dist/src/engine/payment-links.d.ts +1 -0
  60. package/dist/src/engine/payment-links.js +5 -0
  61. package/dist/src/engine/payment-methods.d.ts +16 -0
  62. package/dist/src/engine/payment-methods.js +22 -0
  63. package/dist/src/engine/plans.d.ts +6 -0
  64. package/dist/src/engine/plans.js +26 -0
  65. package/dist/src/engine/platform.d.ts +39 -0
  66. package/dist/src/engine/platform.js +34 -0
  67. package/dist/src/engine/products.d.ts +0 -0
  68. package/dist/src/engine/products.js +4 -0
  69. package/dist/src/engine/radar.d.ts +2 -0
  70. package/dist/src/engine/radar.js +5 -0
  71. package/dist/src/engine/refunds.d.ts +1 -0
  72. package/dist/src/engine/refunds.js +28 -0
  73. package/dist/src/engine/renewals.d.ts +36 -0
  74. package/dist/src/engine/renewals.js +65 -0
  75. package/dist/src/engine/setup-intents.d.ts +1 -0
  76. package/dist/src/engine/setup-intents.js +4 -0
  77. package/dist/src/{stripe-twin.d.ts → engine/stripe.d.ts} +11 -39
  78. package/dist/src/{stripe-twin.js → engine/stripe.js} +25 -310
  79. package/dist/src/engine/subscription-schedules.d.ts +3 -0
  80. package/dist/src/engine/subscription-schedules.js +1 -0
  81. package/dist/src/engine/subscriptions.d.ts +12 -0
  82. package/dist/src/engine/subscriptions.js +31 -0
  83. package/dist/src/engine/tax.d.ts +7 -0
  84. package/dist/src/engine/tax.js +28 -0
  85. package/dist/src/engine/terminal.d.ts +4 -0
  86. package/dist/src/engine/terminal.js +20 -0
  87. package/dist/src/engine/test-clocks.d.ts +5 -0
  88. package/dist/src/engine/test-clocks.js +9 -0
  89. package/dist/src/engine/tokens.d.ts +7 -0
  90. package/dist/src/engine/tokens.js +20 -0
  91. package/dist/src/engine/transfers.d.ts +2 -0
  92. package/dist/src/engine/transfers.js +1 -0
  93. package/dist/src/engine/treasury.d.ts +23 -0
  94. package/dist/src/engine/treasury.js +45 -0
  95. package/dist/src/{stripe-version.js → engine/version.js} +4 -3
  96. package/dist/src/engine/webhook-endpoints.d.ts +1 -0
  97. package/dist/src/engine/webhook-endpoints.js +12 -0
  98. package/dist/src/engine/webhooks.d.ts +31 -0
  99. package/dist/src/engine/webhooks.js +68 -0
  100. package/dist/src/fetch.d.ts +2 -0
  101. package/dist/src/fetch.js +26 -0
  102. package/dist/src/generated/surface.gen.json +1 -1
  103. package/dist/src/generated/ui.gen.json +1 -1
  104. package/dist/src/index.d.ts +5 -14
  105. package/dist/src/index.js +8 -75
  106. package/dist/src/manifest.js +232 -758
  107. package/dist/src/screens/billing-portal.d.ts +3 -0
  108. package/dist/src/screens/{portal.js → billing-portal.js} +28 -54
  109. package/dist/src/screens/checkout.d.ts +2 -31
  110. package/dist/src/screens/checkout.js +32 -121
  111. package/dist/src/screens/connect-oauth.d.ts +3 -27
  112. package/dist/src/screens/connect-oauth.js +51 -132
  113. package/dist/src/screens/connect-onboarding.d.ts +3 -0
  114. package/dist/src/screens/{onboarding.js → connect-onboarding.js} +36 -102
  115. package/dist/src/screens/dashboard.d.ts +3 -0
  116. package/dist/src/screens/dashboard.js +117 -0
  117. package/dist/src/screens/shared.d.ts +27 -0
  118. package/dist/src/screens/shared.js +87 -0
  119. package/dist/src/screens/stripe-js.d.ts +3 -0
  120. package/dist/src/screens/stripe-js.js +135 -0
  121. package/dist/src/semantics/account_links.d.ts +2 -0
  122. package/dist/src/semantics/account_links.js +22 -0
  123. package/dist/src/semantics/accounts.d.ts +4 -0
  124. package/dist/src/semantics/accounts.js +38 -0
  125. package/dist/src/semantics/apps.d.ts +4 -0
  126. package/dist/src/semantics/{apps-secrets.js → apps.js} +14 -26
  127. package/dist/src/semantics/around.d.ts +2 -0
  128. package/dist/src/semantics/around.js +16 -0
  129. package/dist/src/semantics/balance.d.ts +2 -11
  130. package/dist/src/semantics/balance.js +3 -194
  131. package/dist/src/semantics/balance_transactions.d.ts +2 -0
  132. package/dist/src/semantics/balance_transactions.js +15 -0
  133. package/dist/src/semantics/billing_portal.d.ts +5 -0
  134. package/dist/src/semantics/billing_portal.js +42 -0
  135. package/dist/src/semantics/charges.d.ts +3 -28
  136. package/dist/src/semantics/charges.js +5 -202
  137. package/dist/src/semantics/checkout.d.ts +3 -20
  138. package/dist/src/semantics/checkout.js +8 -261
  139. package/dist/src/semantics/clock.d.ts +2 -0
  140. package/dist/src/semantics/clock.js +21 -0
  141. package/dist/src/semantics/coupons.d.ts +2 -6
  142. package/dist/src/semantics/coupons.js +2 -60
  143. package/dist/src/semantics/customers.d.ts +6 -6
  144. package/dist/src/semantics/customers.js +27 -387
  145. package/dist/src/semantics/disputes.d.ts +2 -2
  146. package/dist/src/semantics/disputes.js +3 -49
  147. package/dist/src/semantics/doors.d.ts +23 -0
  148. package/dist/src/semantics/doors.js +73 -0
  149. package/dist/src/semantics/entitlements.d.ts +2 -2
  150. package/dist/src/semantics/entitlements.js +5 -50
  151. package/dist/src/semantics/events.d.ts +12 -0
  152. package/dist/src/semantics/events.js +36 -0
  153. package/dist/src/semantics/index.d.ts +2 -0
  154. package/dist/src/semantics/index.js +107 -0
  155. package/dist/src/semantics/invoice_payments.d.ts +2 -0
  156. package/dist/src/semantics/invoice_payments.js +12 -0
  157. package/dist/src/semantics/invoiceitems.d.ts +3 -0
  158. package/dist/src/semantics/invoiceitems.js +59 -0
  159. package/dist/src/semantics/invoices.d.ts +16 -18
  160. package/dist/src/semantics/invoices.js +118 -444
  161. package/dist/src/semantics/payment_intents.d.ts +4 -0
  162. package/dist/src/semantics/payment_intents.js +79 -0
  163. package/dist/src/semantics/payment_methods.d.ts +5 -0
  164. package/dist/src/semantics/payment_methods.js +39 -0
  165. package/dist/src/semantics/payouts.d.ts +2 -0
  166. package/dist/src/semantics/payouts.js +21 -0
  167. package/dist/src/semantics/prices.d.ts +4 -0
  168. package/dist/src/semantics/prices.js +37 -0
  169. package/dist/src/semantics/products.d.ts +6 -2
  170. package/dist/src/semantics/products.js +15 -130
  171. package/dist/src/semantics/promotion_codes.d.ts +3 -0
  172. package/dist/src/semantics/promotion_codes.js +35 -0
  173. package/dist/src/semantics/radar.d.ts +2 -2
  174. package/dist/src/semantics/radar.js +5 -74
  175. package/dist/src/semantics/refunds.d.ts +3 -9
  176. package/dist/src/semantics/refunds.js +6 -192
  177. package/dist/src/semantics/setup_intents.d.ts +3 -0
  178. package/dist/src/semantics/{setup-intents.js → setup_intents.js} +10 -53
  179. package/dist/src/semantics/shared.d.ts +822 -47
  180. package/dist/src/semantics/shared.js +3044 -78
  181. package/dist/src/semantics/states.d.ts +531 -0
  182. package/dist/src/semantics/states.js +852 -0
  183. package/dist/src/semantics/subscription_items.d.ts +5 -0
  184. package/dist/src/semantics/subscription_items.js +55 -0
  185. package/dist/src/semantics/subscription_schedules.d.ts +4 -0
  186. package/dist/src/semantics/subscription_schedules.js +60 -0
  187. package/dist/src/semantics/subscriptions.d.ts +7 -11
  188. package/dist/src/semantics/subscriptions.js +44 -415
  189. package/dist/src/semantics/test_helpers.d.ts +6 -0
  190. package/dist/src/semantics/{test-clocks.js → test_helpers.js} +14 -40
  191. package/dist/src/semantics/transfers.d.ts +2 -2
  192. package/dist/src/semantics/transfers.js +6 -101
  193. package/dist/src/server.d.ts +7 -0
  194. package/dist/src/server.js +7 -0
  195. package/generated/pack-facts.json +94 -0
  196. package/package.json +10 -20
  197. package/spec/SOURCE.md +14 -0
  198. package/spec/fixtures3.json.gz +0 -0
  199. package/spec/openapi.json.gz +0 -0
  200. package/spec/patches.json +34 -0
  201. package/spec/sources.json +378 -0
  202. package/src/cli.ts +12 -26
  203. package/src/engine/after-payment.ts +31 -0
  204. package/src/engine/apps-secrets.ts +4 -0
  205. package/src/engine/balance.ts +33 -0
  206. package/src/engine/billing.ts +16 -0
  207. package/src/engine/charges.ts +19 -0
  208. package/src/engine/checkout.ts +40 -0
  209. package/src/engine/common.ts +47 -0
  210. package/src/engine/connect-settings.ts +23 -0
  211. package/src/engine/connect.ts +184 -0
  212. package/src/engine/coupons.ts +5 -0
  213. package/src/engine/credit-notes.ts +6 -0
  214. package/src/engine/customers.ts +35 -0
  215. package/src/engine/display.ts +19 -0
  216. package/src/engine/disputes.ts +9 -0
  217. package/src/engine/entitlements.ts +5 -0
  218. package/src/engine/ephemeral-keys.ts +3 -0
  219. package/src/engine/files.ts +41 -0
  220. package/src/engine/front.ts +31 -0
  221. package/src/engine/invoices.ts +71 -0
  222. package/src/engine/issuing.ts +61 -0
  223. package/src/engine/ledger.ts +50 -0
  224. package/src/engine/oauth.ts +19 -0
  225. package/src/engine/onboarding.ts +54 -0
  226. package/src/{stripe-params.ts → engine/params.ts} +8 -56
  227. package/src/engine/payment-intents.ts +33 -0
  228. package/src/engine/payment-links.ts +6 -0
  229. package/src/engine/payment-methods.ts +25 -0
  230. package/src/engine/plans.ts +42 -0
  231. package/src/engine/platform.ts +47 -0
  232. package/src/engine/products.ts +3 -0
  233. package/src/engine/radar.ts +6 -0
  234. package/src/engine/refunds.ts +29 -0
  235. package/src/engine/renewals.ts +73 -0
  236. package/src/engine/setup-intents.ts +5 -0
  237. package/src/{stripe-twin.ts → engine/stripe.ts} +28 -323
  238. package/src/engine/subscription-schedules.ts +10 -0
  239. package/src/engine/subscriptions.ts +40 -0
  240. package/src/engine/tax.ts +39 -0
  241. package/src/engine/terminal.ts +23 -0
  242. package/src/engine/test-clocks.ts +11 -0
  243. package/src/engine/tokens.ts +22 -0
  244. package/src/engine/transfers.ts +23 -0
  245. package/src/engine/treasury.ts +47 -0
  246. package/src/{stripe-version.ts → engine/version.ts} +4 -3
  247. package/src/engine/webhook-endpoints.ts +14 -0
  248. package/src/engine/webhooks.ts +72 -0
  249. package/src/fetch.ts +27 -0
  250. package/src/generated/surface.gen.json +1 -1
  251. package/src/generated/ui.gen.json +1 -1
  252. package/src/index.ts +8 -116
  253. package/src/manifest.ts +234 -786
  254. package/src/screens/{portal.tsx → billing-portal.tsx} +32 -37
  255. package/src/screens/checkout.tsx +33 -95
  256. package/src/screens/connect-oauth.tsx +64 -88
  257. package/src/screens/{onboarding.tsx → connect-onboarding.tsx} +38 -82
  258. package/src/screens/dashboard.tsx +198 -0
  259. package/src/screens/shared.tsx +84 -0
  260. package/src/screens/stripe-js.ts +170 -0
  261. package/src/semantics/account_links.ts +21 -0
  262. package/src/semantics/accounts.ts +43 -0
  263. package/src/semantics/{apps-secrets.ts → apps.ts} +17 -32
  264. package/src/semantics/around.ts +20 -0
  265. package/src/semantics/balance.ts +6 -207
  266. package/src/semantics/balance_transactions.ts +20 -0
  267. package/src/semantics/billing_portal.ts +51 -0
  268. package/src/semantics/charges.ts +12 -211
  269. package/src/semantics/checkout.ts +13 -268
  270. package/src/semantics/clock.ts +26 -0
  271. package/src/semantics/coupons.ts +5 -67
  272. package/src/semantics/customers.ts +29 -392
  273. package/src/semantics/disputes.ts +9 -59
  274. package/src/semantics/doors.ts +80 -0
  275. package/src/semantics/entitlements.ts +9 -56
  276. package/src/semantics/events.ts +44 -0
  277. package/src/semantics/index.ts +111 -0
  278. package/src/semantics/invoice_payments.ts +18 -0
  279. package/src/semantics/invoiceitems.ts +59 -0
  280. package/src/semantics/invoices.ts +109 -443
  281. package/src/semantics/payment_intents.ts +83 -0
  282. package/src/semantics/payment_methods.ts +43 -0
  283. package/src/semantics/payouts.ts +23 -0
  284. package/src/semantics/prices.ts +42 -0
  285. package/src/semantics/products.ts +18 -142
  286. package/src/semantics/promotion_codes.ts +39 -0
  287. package/src/semantics/radar.ts +8 -77
  288. package/src/semantics/refunds.ts +9 -212
  289. package/src/semantics/setup_intents.ts +45 -0
  290. package/src/semantics/shared.ts +3092 -106
  291. package/src/semantics/states.ts +883 -0
  292. package/src/semantics/subscription_items.ts +54 -0
  293. package/src/semantics/subscription_schedules.ts +66 -0
  294. package/src/semantics/subscriptions.ts +49 -432
  295. package/src/semantics/{test-clocks.ts → test_helpers.ts} +23 -47
  296. package/src/semantics/transfers.ts +11 -131
  297. package/src/server.ts +8 -0
  298. package/client/dashboard-api.ts +0 -286
  299. package/client/stripe-mirror.css +0 -277
  300. package/client/stripe-mirror.tsx +0 -1559
  301. package/dist/client/dashboard-api.d.ts +0 -107
  302. package/dist/client/dashboard-api.js +0 -238
  303. package/dist/client/dashboard-api.ts +0 -286
  304. package/dist/client/stripe-mirror.bundle.js +0 -236
  305. package/dist/client/stripe-mirror.css +0 -277
  306. package/dist/client/stripe-mirror.d.ts +0 -134
  307. package/dist/client/stripe-mirror.js +0 -859
  308. package/dist/client/stripe-mirror.tsx +0 -1559
  309. package/dist/src/screens/connect-settings.js +0 -103
  310. package/dist/src/screens/consent-skin.d.ts +0 -4
  311. package/dist/src/screens/consent-skin.js +0 -18
  312. package/dist/src/screens/financial-connections.d.ts +0 -5
  313. package/dist/src/screens/financial-connections.js +0 -90
  314. package/dist/src/screens/identity.d.ts +0 -5
  315. package/dist/src/screens/identity.js +0 -86
  316. package/dist/src/screens/onboarding.d.ts +0 -13
  317. package/dist/src/screens/portal.d.ts +0 -5
  318. package/dist/src/screens/public-details.d.ts +0 -5
  319. package/dist/src/screens/public-details.js +0 -90
  320. package/dist/src/semantics/after-payment.d.ts +0 -22
  321. package/dist/src/semantics/after-payment.js +0 -99
  322. package/dist/src/semantics/apps-secrets.d.ts +0 -2
  323. package/dist/src/semantics/billing.d.ts +0 -2
  324. package/dist/src/semantics/billing.js +0 -220
  325. package/dist/src/semantics/connect.d.ts +0 -5
  326. package/dist/src/semantics/connect.js +0 -493
  327. package/dist/src/semantics/credit-notes.d.ts +0 -2
  328. package/dist/src/semantics/credit-notes.js +0 -172
  329. package/dist/src/semantics/ephemeral-keys.d.ts +0 -2
  330. package/dist/src/semantics/ephemeral-keys.js +0 -34
  331. package/dist/src/semantics/files.d.ts +0 -2
  332. package/dist/src/semantics/files.js +0 -125
  333. package/dist/src/semantics/issuing.d.ts +0 -13
  334. package/dist/src/semantics/issuing.js +0 -575
  335. package/dist/src/semantics/ledger.d.ts +0 -59
  336. package/dist/src/semantics/ledger.js +0 -200
  337. package/dist/src/semantics/payment-intents.d.ts +0 -18
  338. package/dist/src/semantics/payment-intents.js +0 -452
  339. package/dist/src/semantics/payment-links.d.ts +0 -2
  340. package/dist/src/semantics/payment-links.js +0 -133
  341. package/dist/src/semantics/payment-methods.d.ts +0 -20
  342. package/dist/src/semantics/payment-methods.js +0 -140
  343. package/dist/src/semantics/plans.d.ts +0 -5
  344. package/dist/src/semantics/plans.js +0 -121
  345. package/dist/src/semantics/platform.d.ts +0 -9
  346. package/dist/src/semantics/platform.js +0 -206
  347. package/dist/src/semantics/renewals.d.ts +0 -47
  348. package/dist/src/semantics/renewals.js +0 -281
  349. package/dist/src/semantics/setup-intents.d.ts +0 -2
  350. package/dist/src/semantics/subscription-schedules.d.ts +0 -2
  351. package/dist/src/semantics/subscription-schedules.js +0 -119
  352. package/dist/src/semantics/tax.d.ts +0 -2
  353. package/dist/src/semantics/tax.js +0 -197
  354. package/dist/src/semantics/terminal.d.ts +0 -5
  355. package/dist/src/semantics/terminal.js +0 -182
  356. package/dist/src/semantics/test-clocks.d.ts +0 -6
  357. package/dist/src/semantics/tokens.d.ts +0 -4
  358. package/dist/src/semantics/tokens.js +0 -44
  359. package/dist/src/semantics/treasury.d.ts +0 -2
  360. package/dist/src/semantics/treasury.js +0 -377
  361. package/dist/src/semantics/webhook-endpoints.d.ts +0 -3
  362. package/dist/src/semantics/webhook-endpoints.js +0 -85
  363. package/dist/src/stripe-budget.d.ts +0 -55
  364. package/dist/src/stripe-budget.js +0 -155
  365. package/dist/src/stripe-capabilities.d.ts +0 -3
  366. package/dist/src/stripe-capabilities.js +0 -5836
  367. package/dist/src/stripe-conformance.d.ts +0 -43
  368. package/dist/src/stripe-conformance.js +0 -105
  369. package/dist/src/stripe-connector.d.ts +0 -161
  370. package/dist/src/stripe-connector.js +0 -414
  371. package/dist/src/stripe-emit.d.ts +0 -2
  372. package/dist/src/stripe-emit.js +0 -145
  373. package/dist/src/stripe-events.d.ts +0 -93
  374. package/dist/src/stripe-events.js +0 -392
  375. package/dist/src/stripe-js.d.ts +0 -4
  376. package/dist/src/stripe-js.js +0 -70
  377. package/dist/src/stripe-mirror-ui.d.ts +0 -15
  378. package/dist/src/stripe-mirror-ui.js +0 -87
  379. package/dist/src/stripe-perform-harness.d.ts +0 -9
  380. package/dist/src/stripe-perform-harness.js +0 -26
  381. package/dist/src/stripe-server.d.ts +0 -33
  382. package/dist/src/stripe-server.js +0 -429
  383. package/dist/src/stripe-shared.d.ts +0 -109
  384. package/dist/src/stripe-shared.js +0 -276
  385. package/dist/src/stripe-ui-conformance.d.ts +0 -5
  386. package/dist/src/stripe-ui-conformance.js +0 -79
  387. package/dist/src/stripe-ui-structure.d.ts +0 -3
  388. package/dist/src/stripe-ui-structure.js +0 -168
  389. package/dist/test-fixtures/stripe-known-deviations.json +0 -110
  390. package/dist/test-fixtures/stripe-openapi-operations.SOURCE.md +0 -14
  391. package/dist/test-fixtures/stripe-openapi-operations.json +0 -4717
  392. package/dist/test-fixtures/stripe-schemas.SOURCE.md +0 -35
  393. package/dist/test-fixtures/stripe-schemas.json +0 -3813
  394. package/src/screens/connect-settings.tsx +0 -121
  395. package/src/screens/consent-skin.ts +0 -20
  396. package/src/screens/financial-connections.tsx +0 -101
  397. package/src/screens/identity.tsx +0 -96
  398. package/src/screens/public-details.tsx +0 -105
  399. package/src/semantics/after-payment.ts +0 -118
  400. package/src/semantics/billing.ts +0 -216
  401. package/src/semantics/connect.ts +0 -487
  402. package/src/semantics/credit-notes.ts +0 -168
  403. package/src/semantics/ephemeral-keys.ts +0 -34
  404. package/src/semantics/files.ts +0 -143
  405. package/src/semantics/issuing.ts +0 -590
  406. package/src/semantics/ledger.ts +0 -253
  407. package/src/semantics/payment-intents.ts +0 -463
  408. package/src/semantics/payment-links.ts +0 -148
  409. package/src/semantics/payment-methods.ts +0 -145
  410. package/src/semantics/plans.ts +0 -131
  411. package/src/semantics/platform.ts +0 -220
  412. package/src/semantics/renewals.ts +0 -279
  413. package/src/semantics/setup-intents.ts +0 -87
  414. package/src/semantics/subscription-schedules.ts +0 -129
  415. package/src/semantics/tax.ts +0 -220
  416. package/src/semantics/terminal.ts +0 -195
  417. package/src/semantics/tokens.ts +0 -52
  418. package/src/semantics/treasury.ts +0 -383
  419. package/src/semantics/webhook-endpoints.ts +0 -87
  420. package/src/stripe-budget.ts +0 -181
  421. package/src/stripe-capabilities.ts +0 -5651
  422. package/src/stripe-conformance.ts +0 -124
  423. package/src/stripe-connector.ts +0 -462
  424. package/src/stripe-emit.ts +0 -157
  425. package/src/stripe-events.ts +0 -434
  426. package/src/stripe-js.ts +0 -70
  427. package/src/stripe-mirror-ui.ts +0 -90
  428. package/src/stripe-perform-harness.ts +0 -29
  429. package/src/stripe-server.ts +0 -393
  430. package/src/stripe-shared.ts +0 -297
  431. package/src/stripe-ui-conformance.ts +0 -88
  432. package/src/stripe-ui-structure.ts +0 -182
  433. package/test-fixtures/stripe-known-deviations.json +0 -110
  434. package/test-fixtures/stripe-openapi-operations.json +0 -4717
  435. package/test-fixtures/stripe-schemas.json +0 -3813
  436. /package/dist/src/{screens → engine}/industries.d.ts +0 -0
  437. /package/dist/src/{screens → engine}/industries.js +0 -0
  438. /package/dist/src/{semantics → engine}/test-cards.d.ts +0 -0
  439. /package/dist/src/{semantics → engine}/test-cards.js +0 -0
  440. /package/dist/src/{stripe-version.d.ts → engine/version.d.ts} +0 -0
  441. /package/src/{screens → engine}/industries.ts +0 -0
  442. /package/src/{semantics → engine}/test-cards.ts +0 -0
@@ -1,24 +1,1401 @@
1
- // What every Stripe family's semantics share: Stripe's list envelope and order, its expand walk,
2
- // its create stamp, and the answers its hand-written routes gave. All of it is over the
3
- // SemanticsContext; the manifest (../manifest.ts) says which fields embed which resource.
4
- import type { SemanticsContext } from '@volter/world-core';
5
- import surface from '../generated/surface.gen.json' with { type: 'json' };
6
- import { manifest } from '../manifest.ts';
7
- import { OBJECT_NAME, paginate, searchOver, stashVendorType, view, type StripeResponse } from '../stripe-twin.ts';
1
+ // What Stripe's manifest takes from its handlers' side: the events its writes send, as data the kernel renders, stores,
2
+ // signs and delivers (world-core events.ts; ./events.ts renders each event's `data` and its further values).
3
+ import type { EventsDecl, Handler, HandlerContext, TwinResource } from '@volter/world-core';
4
+ import { NAMED_EVENTS, readDecision, STRIPE_EVENT_TYPES, STRIPE_REALTIME_AUTH_TIMEOUT_MS, type StripeAuthRequestOutcome, stripeSignature } from '../engine/webhooks.ts';
5
+ import { redactKey, requestKey } from '../engine/oauth.ts';
6
+ import { HOUR, INV, itemQuantity, itemsOf, keptAfter, oneTimeLines, RENEWING, SUB, unspentDiscounts } from '../engine/renewals.ts';
7
+ import { DAY, payoutDay } from '../engine/balance.ts';
8
+ import { AFTER_SUCCESS_CARDS, BY_NUMBER, type Outcome } from '../engine/after-payment.ts';
9
+ import { accountSettings, addBillingInterval, applyCouponDiscount, asBool, buildDiscount, buildSubscriptionItemsList, cardError, chargeDefaults, type CheckoutItem, declineFor, disputeEvidence, lineItemEntries, microdepositsNextAction, mintClientSecret, nowUnix, OBJECT_NAME, paginate, paymentMethodSubObject, PLATFORM_ACCOUNT_ID, priceAmount, requiresAuthentication, requiresMicrodeposits, resolveLineItem, resolveSubscriptionBillingInterval, resolveTrial, searchOver, type StripeResponse, subscriptionItemEntries, subscriptionItemPrice, TEST_TOKEN_DECLINES, threeDsNextAction, validateMoney, view } from '../engine/stripe.ts';
10
+ import { AUTO_VALIDATED, euVatCountry } from '../engine/customers.ts';
11
+ import { SI } from '../engine/setup-intents.ts';
12
+ import { BY_CLIENT_SECRET, PUBLISHABLE_CREATES } from '../engine/front.ts';
13
+ import { WE } from '../engine/webhook-endpoints.ts';
14
+ import { ENTRY, ENTRY_TYPES, FA, TX } from '../engine/treasury.ts';
15
+ import { SECRET } from '../engine/apps-secrets.ts';
16
+ import { draft, invoicePrefix, linesOf, sumLines, transitions, unlinkedLine } from '../engine/invoices.ts';
17
+ import { CN } from '../engine/credit-notes.ts';
18
+ import { CS, type EnteredCard, isOneTime, nestedMetadata } from '../engine/checkout.ts';
19
+ import { externalList, type Find, refundDestination, type Row, SPEC_FIELDS } from '../engine/common.ts';
20
+ import { noBilling, PM, TEST_PM_CARDS, testCardOf } from '../engine/payment-methods.ts';
21
+ import { type Interval, SS } from '../engine/subscription-schedules.ts';
22
+ import { OAUTH_CONNECTIONS } from '../engine/display.ts';
23
+ import { intentCarries, PI, TYPES_GIVEN } from '../engine/payment-intents.ts';
24
+ import { BT, BYPASS_NUMBERS, feeOf, onAccount, UNSENT } from '../engine/ledger.ts';
25
+ import { withoutCard } from '../engine/charges.ts';
26
+ import { MAX_TRIAL, movedTrial } from '../engine/subscriptions.ts';
27
+ import { VL, VLI } from '../engine/radar.ts';
28
+ import { AUTH, CARD, historyEntry, merchantData, PD, REALTIME_WINDOW_SECONDS, TXN } from '../engine/issuing.ts';
29
+ import { has } from '../engine/onboarding.ts';
30
+ import { REFUND_REASONS } from '../engine/refunds.ts';
31
+ import { ADVANCE_SECONDS, CLOCK } from '../engine/test-clocks.ts';
32
+ import { BYPASS_PENDING_CARDS } from '../engine/test-cards.ts';
33
+ import { type ConnectOAuthSettings, PLATFORM_CLIENT_ID, SETTINGS } from '../engine/connect-settings.ts';
34
+ import { controllerOf, customRequirements } from '../engine/connect.ts';
35
+ import { READER } from '../engine/terminal.ts';
36
+ import { expandOf, render, SERVED_VERSION, servesCurrent, withoutEndpointSecret } from '../engine/version.ts';
37
+ import { ALERT, GRANT, METER } from '../engine/billing.ts';
38
+ import { CHECKOUT_METHOD_TYPES, DOCUMENTED, methodTypesRemoved, oneOf, OPS, PAYMENT_METHOD_TYPES, REMOVED_TYPES, TYPED, TYPES_DOC } from '../engine/params.ts';
8
39
 
9
- export type Row = Record<string, unknown>;
40
+ /** Stripe's events: `Stripe-Signature: t=…,v1=…` over `${t}.${body}` keyed by the endpoint's secret
41
+ * (docs.stripe.com/webhooks#verify-manually); the Event object (docs.stripe.com/api/events/object) kept as the account's
42
+ * own (`GET /v1/events`), whether or not an endpoint takes it; an endpoint live while `enabled`, taking the types its
43
+ * `enabled_events` names (`*` all, `<family>.*` a family), and a Connect endpoint (`connect: true`) its connected
44
+ * accounts' events ("Connected accounts" scope, docs.stripe.com/connect/webhooks), any other the account's own. */
45
+ export const STRIPE_EVENTS: EventsDecl = {
46
+ scheme: { kind: 'timestamp-v1', header: 'Stripe-Signature' },
47
+ types: NAMED_EVENTS,
48
+ known: STRIPE_EVENT_TYPES,
49
+ store: 'event',
50
+ envelope: {
51
+ id: '$id', object: 'event', account: '$account', api_version: '$version', created: '$time.s', data: '$data', livemode: false,
52
+ pending_webhooks: 0, request: { id: null, idempotency_key: null }, type: '$type',
53
+ },
54
+ endpoints: { storedAs: 'webhook_endpoint', url: 'url', secret: 'secret', filter: 'enabled_events', status: { field: 'status', live: 'enabled' }, scope: { field: 'connect', value: '$account' } },
55
+ };
56
+
57
+ // ── what the handlers share: Stripe's behaviour over the context ──
58
+
59
+ export type Reads = Pick<HandlerContext, 'rowsRaw'>;
60
+
61
+ /** Whether a connected account's OAuth connection to the platform was revoked (deauthorized, or its code reused). */
62
+ export function connectionRevoked(ctx: Reads, account: string): boolean {
63
+ return ctx.rowsRaw(OAUTH_CONNECTIONS).some((c) => c.id === account && c.revoked === true);
64
+ }
65
+
66
+ /** The connected account an OAuth key acts as — the connection's current access_token (sk_test_oauth_…) or its
67
+ * stripe_publishable_key (pk_test_oauth_…) — with the scope it was issued; undefined for any other key, and null for an
68
+ * OAuth-shaped key no live connection holds (revoked, replaced by a refresh, or never issued). */
69
+ export function oauthKeyAccount(ctx: Reads, key: string): { account: string; scope: string } | null | undefined {
70
+ if (!/^(sk|pk)_test_oauth_/.test(key)) return undefined;
71
+ const held = ctx.rowsRaw(OAUTH_CONNECTIONS).find((c) => c.revoked !== true && (c.access_token === key || c.publishable_key === key));
72
+ return held ? { account: String(held.id), scope: String(key.startsWith('pk_') ? held.scope : held.access_scope ?? held.scope) } : null;
73
+ }
74
+
75
+ /** A customer's now: its test clock's frozen time when it is on one (docs.stripe.com/billing/testing/test-clocks), the
76
+ * World's otherwise. */
77
+ export function clockNow(ctx: HandlerContext, customer: unknown): number {
78
+ const clock = typeof customer === 'string' ? ctx.get('customer', customer)?.test_clock : undefined;
79
+ const frozen = typeof clock === 'string' ? ctx.get('test_helpers.test_clock', clock)?.frozen_time : undefined;
80
+ return frozen !== undefined ? Number(frozen) : Number(nowUnix(ctx.occurredAt));
81
+ }
82
+
83
+ /** What a subscription's invoices charge: its own default payment method, else its customer's. */
84
+ export function payerOf(ctx: HandlerContext, sub: Row): string | undefined {
85
+ return typeof sub.default_payment_method === 'string' && sub.default_payment_method ? sub.default_payment_method : customerDefault(ctx, sub);
86
+ }
87
+
88
+ /** The customer's default for invoices, charged when the subscription names none of its own. */
89
+ export function customerDefault(ctx: HandlerContext, sub: Row): string | undefined {
90
+ const customer = typeof sub.customer === 'string' ? ctx.get('customer', sub.customer) : undefined;
91
+ const settings = customer?.invoice_settings as Row | undefined;
92
+ return typeof settings?.default_payment_method === 'string' && settings.default_payment_method ? settings.default_payment_method : undefined;
93
+ }
94
+
95
+ /** A subscription whose invoice has just been finalized: the `once` coupon that invoice took is spent, and a once coupon
96
+ * it did not take (added after it was drafted) stays for the next (unspentDiscounts). */
97
+ export async function spendOnceCoupon(ctx: HandlerContext, invoice: Row): Promise<void> {
98
+ const subId = typeof invoice.subscription === 'string' ? invoice.subscription : undefined;
99
+ const sub = subId ? ctx.get(SUB, subId) : undefined;
100
+ if (!sub || !subId) return;
101
+ const all = (sub.discounts as Row[] | undefined) ?? [];
102
+ const kept = keptAfter(all, invoice);
103
+ if (kept.length !== all.length) await ctx.write(SUB, subId, { discounts: kept }, 'subscription.discount_spent');
104
+ }
105
+
106
+ /** A draft invoice for one period of a subscription, its lines the subscription's items and any one-time lines `once`
107
+ * gives it (a Checkout session's one-time prices, "on the initial invoice only", docs.stripe.com/api/checkout/sessions/
108
+ * create#create_checkout_session-line_items), under the subscription's discount. Answers the invoice id. */
109
+ export async function draftSubscriptionInvoice(ctx: HandlerContext, sub: Row, o: { start: number; end: number; reason: 'subscription_create' | 'subscription_cycle' | 'subscription_update'; trial?: boolean; once?: Row[]; id?: string }): Promise<string> {
110
+ const id = o.id ?? ctx.mint(INV);
111
+ const currency = String(sub.currency ?? 'usd');
112
+ const lines = itemsOf(sub).map((it, i) => {
113
+ const price = it.price && typeof it.price === 'object' ? (it.price as Row) : ctx.get('price', String(it.price ?? ''));
114
+ const quantity = itemQuantity(it);
115
+ return {
116
+ id: `il_twin_${id}_${i + 1}`, object: 'line_item', type: 'subscription',
117
+ // a trial's first invoice bills nothing for the trial period (docs.stripe.com/billing/subscriptions/trials)
118
+ amount: o.trial ? 0 : priceAmount(price, quantity), currency, quantity, proration: false,
119
+ price: price ?? null, subscription: sub.id, subscription_item: it.id ?? null, invoice_item: null,
120
+ period: { start: o.start, end: o.end }, description: o.trial ? `Trial period for ${String(ctx.get('product', String(price?.product ?? ''))?.name ?? 'the plan')}` : null,
121
+ };
122
+ });
123
+ if (o.once?.length) lines.push(...oneTimeLines(id, sub, o.once, lines.length, o.start, currency));
124
+ const subtotal = lines.reduce((s, l) => s + l.amount, 0);
125
+ // a discount the subscription still carries applies; a `once` coupon is removed once an invoice finalizes
126
+ // (spendOnceCoupon), so it discounts one invoice (docs.stripe.com/billing/subscriptions/coupons#coupon-duration)
127
+ const discount = ((sub.discounts as Row[] | undefined) ?? [])[0];
128
+ const coupon = discount && typeof discount === 'object' ? (discount.coupon as Row | undefined) : undefined;
129
+ const off = coupon ? applyCouponDiscount(subtotal, coupon) : 0;
130
+ const total = Math.max(0, subtotal - off);
131
+ await created(ctx, INV, { id, customer: sub.customer, subscription: sub.id }, {
132
+ created: o.start, status: 'draft', livemode: false, currency, collection_method: 'charge_automatically',
133
+ billing_reason: o.reason, auto_advance: true, attempt_count: 0, attempted: false, next_payment_attempt: null,
134
+ amount_due: total, amount_paid: 0, amount_remaining: total, amount_overpaid: 0, amount_paid_off_stripe: 0, amount_shipping: 0,
135
+ subtotal, total, starting_balance: 0, post_payment_credit_notes_amount: 0, pre_payment_credit_notes_amount: 0,
136
+ // "The invoice that consumed the coupon still shows the applied discount" (docs.stripe.com/billing/subscriptions/coupons)
137
+ period_start: o.start, period_end: o.end, default_tax_rates: [], discounts: coupon && discount ? [discount] : [],
138
+ lines: { object: 'list', data: lines, has_more: false, total_count: lines.length, url: `/v1/invoices/${id}/lines` },
139
+ automatic_tax: { enabled: false, liability: null, status: null },
140
+ status_transitions: { finalized_at: null, marked_uncollectible_at: null, paid_at: null, voided_at: null },
141
+ issuer: { type: 'self' }, payment_settings: { default_mandate: null, payment_method_options: null, payment_method_types: null },
142
+ payment_intent: null, charge: null,
143
+ });
144
+ return id;
145
+ }
146
+
147
+ /** Finalize a subscription's draft invoice at `at` and charge what its subscription pays with. The move is time's (a
148
+ * renewal), the customer's (the Checkout page they paid on) or the API's (an update that ends a trial, which names the
149
+ * payer, may ask for no attempt, and moves the subscription itself: semantics/subscriptions.ts applyTrialEnd). Answers
150
+ * whether it was paid. */
151
+ export async function collectSubscriptionInvoice(ctx: HandlerContext, invoiceId: string, at: number, actor: 'time' | 'external' | 'api', opts: { payer?: string; attempt?: boolean } = {}): Promise<boolean> {
152
+ const inv = ctx.get(INV, invoiceId);
153
+ const sub = inv && typeof inv.subscription === 'string' ? ctx.get(SUB, inv.subscription) : undefined;
154
+ if (!inv || !sub || inv.status !== 'draft') return false;
155
+ const total = Number(inv.total) || 0;
156
+ const numbered = { ...finalizedFields(ctx, inv, at), status_transitions: { ...(inv.status_transitions as Row), finalized_at: at } };
157
+ const op = ctx.call.operation.id;
158
+ // nothing due (a trial's first invoice) is paid as it is finalized; finalizing spends a `once` coupon
159
+ if (total <= 0) {
160
+ if (ctx.legal(INV, 'status', op, 'draft', 'paid', invoiceId, actor)) return false;
161
+ await spendOnceCoupon(ctx, inv);
162
+ await ctx.write(INV, invoiceId, { ...numbered, status: 'paid', paid: true, auto_advance: false, status_transitions: { ...numbered.status_transitions, paid_at: at } }, 'invoice.paid');
163
+ return true;
164
+ }
165
+ const payer = actor === 'api' ? opts.payer : payerOf(ctx, sub);
166
+ // default_incomplete finalizes the invoice without attempting payment (docs.stripe.com/api/subscriptions/update#update_subscription-payment_behavior)
167
+ const attempt = opts.attempt !== false;
168
+ const decline = payer && attempt ? declineFor(finder(ctx), { payment_method: payer }) : undefined;
169
+ const pays = attempt && !!payer && !decline;
170
+ if (ctx.legal(INV, 'status', op, 'draft', pays ? 'paid' : 'open', invoiceId, actor)) return false;
171
+ await spendOnceCoupon(ctx, inv);
172
+ const piId = ctx.mint('payment_intent');
173
+ const currency = String(inv.currency ?? 'usd');
174
+ const chargeId = pays ? await mintCharge(ctx, piId, { currency, customer: inv.customer, payment_method: payer, invoice: invoiceId }, total) : null;
175
+ await created(ctx, 'payment_intent', { id: piId, amount: total, currency, customer: inv.customer, invoice: invoiceId, payment_method: pays ? payer : null }, {
176
+ status: pays ? 'succeeded' : 'requires_payment_method', client_secret: mintClientSecret(piId, await ctx.secret(`client-secret:${piId}`)), livemode: false,
177
+ capture_method: 'automatic', amount_capturable: 0, amount_received: pays ? total : 0, next_action: null, latest_charge: chargeId,
178
+ last_payment_error: decline ? { type: 'card_error', code: decline.code, decline_code: decline.decline_code ?? null, message: decline.message, payment_method: { id: payer } } : null,
179
+ automatic_payment_methods: null, payment_method_types: ['card'], payment_method_options: {},
180
+ });
181
+ await ctx.write(INV, invoiceId, {
182
+ ...numbered, status: pays ? 'paid' : 'open', paid: pays, attempt_count: attempt ? 1 : 0, attempted: attempt, payment_intent: piId, charge: chargeId,
183
+ amount_paid: pays ? total : 0, amount_remaining: pays ? 0 : total, auto_advance: attempt && !pays, next_payment_attempt: null,
184
+ status_transitions: { ...numbered.status_transitions, paid_at: pays ? at : null },
185
+ }, pays ? 'invoice.paid' : attempt ? 'invoice.payment_failed' : 'invoice.finalized');
186
+ if (actor !== 'api' && !pays && sub.status !== 'past_due' && !ctx.legal(SUB, 'status', op, sub.status, 'past_due', String(sub.id), 'time')) {
187
+ await ctx.write(SUB, String(sub.id), { status: 'past_due' }, 'customer.subscription.updated');
188
+ }
189
+ return pays;
190
+ }
191
+
192
+ /** Pay a subscription's open invoice with `paymentMethod` (the customer on the portal, `external`): the charge on the
193
+ * invoice's PaymentIntent, the invoice paid, a past_due subscription active. Answers the decline, if the card is refused. */
194
+ export async function payOpenInvoice(ctx: HandlerContext, invoiceId: string, paymentMethod: string): Promise<{ code: string; message: string } | undefined> {
195
+ const inv = ctx.get(INV, invoiceId);
196
+ if (!inv || inv.status !== 'open') return { code: 'invoice_not_open', message: 'This invoice is no longer open.' };
197
+ const decline = declineFor(finder(ctx), { payment_method: paymentMethod });
198
+ if (decline) return decline;
199
+ const op = ctx.call.operation.id;
200
+ const refused = ctx.legal(INV, 'status', op, 'open', 'paid', invoiceId, 'external');
201
+ if (refused) return { code: String(refused.code ?? 'invoice_not_open'), message: refused.message };
202
+ const total = Number(inv.amount_remaining ?? inv.total) || 0;
203
+ const now = Number(nowUnix(ctx.occurredAt));
204
+ const piId = typeof inv.payment_intent === 'string' ? inv.payment_intent : undefined;
205
+ let chargeId: string | null = null;
206
+ const pi = piId ? ctx.get('payment_intent', piId) : undefined;
207
+ if (piId && pi && !ctx.legal('payment_intent', 'status', op, pi.status, 'succeeded', piId, 'external')) {
208
+ chargeId = await mintCharge(ctx, piId, { ...pi, payment_method: paymentMethod, invoice: invoiceId }, total);
209
+ await ctx.write('payment_intent', piId, { status: 'succeeded', payment_method: paymentMethod, amount_received: total, last_payment_error: null, latest_charge: chargeId }, 'payment_intent.succeeded');
210
+ }
211
+ await ctx.write(INV, invoiceId, {
212
+ status: 'paid', paid: true, amount_paid: total, amount_remaining: 0, charge: chargeId, auto_advance: false,
213
+ attempt_count: (Number(inv.attempt_count) || 0) + 1, attempted: true,
214
+ status_transitions: { ...(inv.status_transitions as Row), paid_at: now },
215
+ }, 'invoice.paid');
216
+ const sub = typeof inv.subscription === 'string' ? ctx.get(SUB, inv.subscription) : undefined;
217
+ if (sub && sub.status === 'past_due' && !ctx.legal(SUB, 'status', op, 'past_due', 'active', String(sub.id), 'external')) {
218
+ await ctx.write(SUB, String(sub.id), { status: 'active' }, 'customer.subscription.updated');
219
+ }
220
+ return undefined;
221
+ }
222
+
223
+ /** Time's moves on subscriptions, caught up to each customer's clock in the order they fell due, each made at the
224
+ * moment it was due: a period that ended renews (a trial's end among them) or, set to cancel, cancels; a renewal
225
+ * drafted an hour or more ago is finalized and charged. */
226
+ export async function advanceBilling(ctx: HandlerContext, only?: (sub: Row) => boolean): Promise<void> {
227
+ // Stripe's own move wherever a handler reaches it: a read that catches a renewal up records it with no caller
228
+ await ctx.asVendor(async () => {
229
+ const at = at_(ctx);
230
+ for (let guard = 0; guard < 10_000 && (await billingStep(ctx, at, only)); guard++);
231
+ });
232
+ }
233
+
234
+ /** The earliest move that has come due, made at its moment; false when none has. */
235
+ export async function billingStep(ctx: HandlerContext, at: (t: number) => Promise<HandlerContext>, only?: (sub: Row) => boolean): Promise<boolean> {
236
+ // the earliest move that has come due, of any subscription
237
+ let next: { t: number; kind: 'period' | 'collect'; id: string } | undefined;
238
+ for (const sub of ctx.rows(SUB)) {
239
+ if (only && !only(sub)) continue;
240
+ if (!RENEWING.includes(String(sub.status)) || typeof sub.current_period_end !== 'number' || sub.pause_collection) continue;
241
+ if (sub.current_period_end <= clockNow(ctx, sub.customer) && (!next || sub.current_period_end < next.t)) next = { t: sub.current_period_end, kind: 'period', id: String(sub.id) };
242
+ }
243
+ for (const inv of ctx.rows(INV)) {
244
+ if (inv.status !== 'draft' || inv.billing_reason !== 'subscription_cycle' || inv.auto_advance !== true) continue;
245
+ const sub = typeof inv.subscription === 'string' ? ctx.get(SUB, inv.subscription) : undefined;
246
+ if (!sub || (only && !only(sub))) continue;
247
+ const t = Number(inv.created) + HOUR;
248
+ if (t <= clockNow(ctx, sub.customer) && (!next || t < next.t)) next = { t, kind: 'collect', id: String(inv.id) };
249
+ }
250
+ if (!next) return false;
251
+ const c = await at(next.t);
252
+ if (next.kind === 'collect') {
253
+ await collectSubscriptionInvoice(c, next.id, next.t, 'time');
254
+ return true;
255
+ }
256
+ const id = next.id;
257
+ const sub = c.get(SUB, id)!;
258
+ const op = c.call.operation.id;
259
+ // one set to cancel at its period's end is canceled then, with no renewal
260
+ // (docs.stripe.com/billing/subscriptions/cancel#cancel-at-end-of-cycle)
261
+ if (sub.cancel_at_period_end === true) {
262
+ if (c.legal(SUB, 'status', op, sub.status, 'canceled', id, 'time')) return false;
263
+ await c.write(SUB, id, { status: 'canceled', ended_at: next.t, canceled_at: sub.canceled_at ?? next.t }, 'customer.subscription.deleted');
264
+ return true;
265
+ }
266
+ const start = next.t;
267
+ const { interval, interval_count } = resolveSubscriptionBillingInterval(itemsOf(sub), finder(c));
268
+ const end = addBillingInterval(start, interval, interval_count);
269
+ const trialEnds = sub.status === 'trialing';
270
+ if (trialEnds && c.legal(SUB, 'status', op, 'trialing', 'active', id, 'time')) return false;
271
+ const invoiceId = await draftSubscriptionInvoice(c, sub, { start, end, reason: 'subscription_cycle' });
272
+ await c.write(SUB, id, { current_period_start: start, current_period_end: end, latest_invoice: invoiceId, ...(trialEnds ? { status: 'active' } : {}) }, 'customer.subscription.updated');
273
+ return true;
274
+ }
275
+
276
+ export const account = (ctx: HandlerContext): string | undefined => actingAccount(ctx);
277
+
278
+ export const payoutMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such payout: '${id}'`, 404, 'resource_missing');
279
+
280
+ /** The acting account's Balance object (docs.stripe.com/api/balance/balance_object). */
281
+ export function balanceBody(ctx: HandlerContext, acct: string | undefined = account(ctx)): Row {
282
+ const { available, pending, issuing } = balanceOf(ctx, acct);
283
+ const toArr = (m: Map<string, number>) => {
284
+ const out = [...m.entries()].map(([currency, amount]) => ({ amount, currency, source_types: { card: amount } }));
285
+ return out.length ? out : [{ amount: 0, currency: 'usd', source_types: { card: 0 } }];
286
+ };
287
+ // a platform's balance holds its connected accounts' reserve, "Funds held due to negative balances on connected accounts
288
+ // where account.controller.requirement_collection is `application`" (docs.stripe.com/api/balance/balance_object, whose
289
+ // example answers `[{"amount": 0, "currency": "usd"}]`); the twin models no such reserve, so it is zero in each currency
290
+ const reserved = acct ? {} : { connect_reserved: toArr(available).map((b) => ({ amount: 0, currency: b.currency })) };
291
+ return {
292
+ object: 'balance', available: toArr(available), pending: toArr(pending), ...reserved, livemode: false,
293
+ ...(issuing.size ? { issuing: { available: [...issuing.entries()].map(([currency, amount]) => ({ amount, currency, source_types: { card: amount } })) } } : {}),
294
+ };
295
+ }
296
+
297
+ /** Time's arrivals, written: each of the acting account's payouts whose arrival date has come moves pending → paid
298
+ * (the clock's move, as asOf reads it), written as `payout.paid`, the event Stripe sends for it. Answers their ids. */
299
+ export async function payDuePayouts(ctx: HandlerContext, acct: string | undefined = account(ctx)): Promise<string[]> {
300
+ const now = Number(nowUnix(ctx.occurredAt));
301
+ const paid: string[] = [];
302
+ for (const p of newest(ctx, 'payout')) {
303
+ if ((acct ? kept(ctx, 'payout', p, '_account') !== acct : !!kept(ctx, 'payout', p, '_account')) || p.status !== 'pending' || Number(p.arrival_date) > now) continue;
304
+ if (ctx.legal('payout', 'status', ctx.call.operation.id, 'pending', 'paid', String(p.id), 'time')) continue;
305
+ await ctx.write('payout', String(p.id), { status: 'paid' }, 'payout.paid');
306
+ paid.push(String(p.id));
307
+ }
308
+ return paid;
309
+ }
310
+
311
+ /** Where a connected account's payout goes: "ID of the bank account or card the payout is sent to" (served spec,
312
+ * payout.destination), its default external account for the currency, "When multiple accounts are available for a given
313
+ * currency, Stripe uses the one set as `default_for_currency`" (docs.stripe.com/connect/payouts-bank-accounts), the
314
+ * newest such. Where the documentation stops and the twin decides: the platform's own bank account is not modelled, so
315
+ * its payouts name none. */
316
+ export function payoutBank(ctx: HandlerContext, account: string, currency: string): string | null {
317
+ const banks = newest(ctx, 'external_account').filter((e) => e.account === account && String(e.currency ?? currency) === currency);
318
+ return String((banks.find((e) => e.default_for_currency === true) ?? banks[0])?.id ?? '') || null;
319
+ }
320
+
321
+ export const payoutDefaults = (ctx: HandlerContext): Row => ({
322
+ method: 'standard', type: 'bank_account', source_type: 'card', automatic: false,
323
+ reconciliation_status: 'not_applicable', arrival_date: Number(nowUnix(ctx.occurredAt)) + 2 * DAY, livemode: false, metadata: {},
324
+ });
325
+
326
+ /** A payout as the clock reads it: paid once its arrival date has come, the clock's move, asked of the
327
+ * machine as a write asks it. */
328
+ export function asOf(ctx: HandlerContext, p: Row): Row {
329
+ if (p.status !== 'pending' || Number(p.arrival_date) > Number(nowUnix(ctx.occurredAt))) return p;
330
+ ctx.legal('payout', 'status', ctx.call.operation.id, 'pending', 'paid', String(p.id), 'time');
331
+ return { ...p, status: 'paid' };
332
+ }
333
+
334
+ /** A connected account's payout in a currency none of its bank accounts takes. */
335
+ export function noExternalAccount(ctx: HandlerContext, currency: string): Response {
336
+ return fail(ctx, `Sorry, you don't have any external accounts in that currency (${currency}).`, 400);
337
+ }
338
+
339
+ /** Time's payouts, caught up to the World's clock: each account on an automatic schedule is paid out, on each of its
340
+ * scheduled days that has come, what became available by then. */
341
+ export async function advancePayouts(ctx: HandlerContext): Promise<void> {
342
+ const now = Number(nowUnix(ctx.occurredAt));
343
+ const platform = ctx.get('account', PLATFORM_ACCOUNT_ID);
344
+ const accounts: Array<{ id: string | undefined; settings: unknown }> = [{ id: undefined, settings: platform?.settings }];
345
+ for (const a of ctx.rows('account')) {
346
+ if (a.id === PLATFORM_ACCOUNT_ID || a.payouts_enabled !== true) continue;
347
+ if (!ctx.rows('external_account').some((e) => e.account === a.id)) continue;
348
+ accounts.push({ id: String(a.id), settings: a.settings });
349
+ }
350
+ for (const acct of accounts) {
351
+ const schedule = ((accountSettings(acct.settings, (acct.settings as Row | undefined) ?? undefined).payouts as Row).schedule ?? {}) as Row;
352
+ if (schedule.interval === 'manual') continue;
353
+ const unpaid = unpaidEntries(ctx, acct.id);
354
+ const days = [...new Set(unpaid.map((t) => payoutDay(Number(t.available_on) || 0, schedule)))].filter((d) => d <= now).sort((x, y) => x - y);
355
+ const paid = new Set<unknown>();
356
+ for (const day of days) {
357
+ const due = unpaid.filter((t) => !paid.has(t.id) && (Number(t.available_on) || 0) <= day);
358
+ const byCurrency = new Map<string, Row[]>();
359
+ for (const t of due) byCurrency.set(String(t.currency ?? 'usd'), [...(byCurrency.get(String(t.currency ?? 'usd')) ?? []), t]);
360
+ for (const [currency, entries] of byCurrency) {
361
+ const amount = entries.reduce((n, t) => n + (Number(t.net) || 0), 0);
362
+ // nothing to pay yet: what came due is carried to the next payout
363
+ if (amount <= 0) continue;
364
+ // made on its day, as Stripe makes it, whenever the request that catches it up comes
365
+ const c = await at_(ctx)(day);
366
+ const id = c.mint('payout');
367
+ const bt = await settleAutomaticPayout(c, id, amount, currency, acct.id, day, entries);
368
+ await created(c, 'payout', { id, amount, currency }, {
369
+ status: 'pending', ...payoutDefaults(c), arrival_date: day + 2 * DAY, automatic: true, balance_transaction: bt, destination: acct.id ? payoutBank(c, String(acct.id), currency) : null,
370
+ description: 'STRIPE PAYOUT', ...(acct.id ? { _account: acct.id } : {}),
371
+ });
372
+ for (const t of entries) paid.add(t.id);
373
+ }
374
+ }
375
+ }
376
+ }
377
+
378
+ /** What Stripe does after a card succeeds: from a raw number, a test name (pm_card_* or tok_*), or a stored
379
+ * PaymentMethod that recorded it when it was made. */
380
+ export function afterSuccessOf(ctx: HandlerContext, ref: unknown): Outcome | undefined {
381
+ // a card given as a token (card[token], payment_method_data[card][token]) is the card the token names
382
+ if (ref && typeof ref === 'object' && typeof (ref as Row).token === 'string') return afterSuccessOf(ctx, (ref as Row).token);
383
+ if (ref && typeof ref === 'object') return BY_NUMBER[String((ref as Row).number ?? '').replace(/\D/g, '')];
384
+ if (typeof ref !== 'string' || !ref) return undefined;
385
+ const stored = ctx.row('payment_method', ref);
386
+ if (stored) return (stored._afterSuccess as Outcome | undefined) ?? undefined;
387
+ return AFTER_SUCCESS_CARDS[ref.replace(/^tok_/, 'pm_card_')]?.outcome ?? BY_NUMBER[ref.replace(/\D/g, '')];
388
+ }
389
+
390
+ /** Stripe's acts on a charge that just succeeded: a dispute or a review its card brings, and the platform's fee. */
391
+ export async function afterCharge(ctx: HandlerContext, chargeId: string, charge: { amount: number; currency: string; payment_intent?: string | undefined; application_fee_amount?: unknown; destination?: unknown }, ref: unknown): Promise<void> {
392
+ const outcome = afterSuccessOf(ctx, ref);
393
+ const pi = charge.payment_intent ? { payment_intent: charge.payment_intent } : { payment_intent: null };
394
+ const now = Number(nowUnix(ctx.occurredAt));
395
+ if (outcome === 'dispute' || outcome === 'dispute_not_received' || outcome === 'inquiry') {
396
+ const dispute = await created(ctx, 'dispute', { charge: chargeId, ...pi, amount: charge.amount, currency: charge.currency }, {
397
+ reason: outcome === 'dispute_not_received' ? 'product_not_received' : 'fraudulent', status: outcome === 'inquiry' ? 'warning_needs_response' : 'needs_response', is_charge_refundable: false,
398
+ evidence: disputeEvidence(), evidence_details: { due_by: now + 7 * DAY, has_evidence: false, past_due: false, submission_count: 0, enhanced_eligibility: {} },
399
+ balance_transactions: [], livemode: false, metadata: {}, enhanced_eligibility_types: [],
400
+ });
401
+ // an inquiry moves no money; a dispute takes the amount and its fee until it is decided
402
+ if (outcome !== 'inquiry') {
403
+ const bt = await settleDispute(ctx, String(dispute.id), charge.amount, charge.currency);
404
+ await ctx.write('dispute', String(dispute.id), { balance_transactions: [ctx.get('balance_transaction', bt) ?? bt] }, 'dispute.funds_withdrawn');
405
+ }
406
+ await ctx.write('charge', chargeId, { disputed: true }, 'charge.dispute.created');
407
+ }
408
+ if (outcome === 'review') await openReview(ctx, chargeId, pi);
409
+ const feeAmount = Math.trunc(Number(charge.application_fee_amount) || 0);
410
+ const destination = typeof charge.destination === 'string' && charge.destination ? charge.destination : undefined;
411
+ const direct = actingAccount(ctx);
412
+ const account = destination ?? direct;
413
+ // a destination charge transfers what it collected, less the platform's fee, available when the charge's funds are
414
+ if (destination) {
415
+ const amount = charge.amount - feeAmount;
416
+ const chargeBt = ctx.get('charge', chargeId)?.balance_transaction;
417
+ const availableOn = Number(ctx.get('balance_transaction', String(chargeBt))?.available_on ?? nowUnix(ctx.occurredAt));
418
+ const tr = await created(ctx, 'transfer', { amount, currency: charge.currency, destination }, {
419
+ amount_reversed: 0, balance_transaction: null, livemode: false, metadata: {}, reversed: false, source_type: 'card', source_transaction: chargeId,
420
+ reversals: { object: 'list', data: [], has_more: false, total_count: 0, url: '' },
421
+ });
422
+ const bt = await settleTransfer(ctx, String(tr.id), amount, charge.currency, destination, availableOn);
423
+ await ctx.write('transfer', String(tr.id), { balance_transaction: bt, destination_payment: `py_${String(tr.id).replace(/^tr_/, '')}`, reversals: { object: 'list', data: [], has_more: false, total_count: 0, url: `/v1/transfers/${String(tr.id)}/reversals` } }, 'transfer.created');
424
+ await ctx.write('charge', chargeId, { transfer: tr.id }, 'charge.updated');
425
+ }
426
+ if (feeAmount > 0 && account) {
427
+ const fee = await created(ctx, 'application_fee', { account, amount: feeAmount, charge: chargeId, currency: charge.currency }, {
428
+ amount_refunded: 0, application: 'ca_twin', balance_transaction: null, originating_transaction: null, refunded: false, livemode: false,
429
+ });
430
+ // a direct charge's fee moves from the connected account to the platform (a destination charge kept it back)
431
+ const bt = !destination && direct ? await settleApplicationFee(ctx, String(fee.id), feeAmount, charge.currency, direct) : null;
432
+ await ctx.write('application_fee', String(fee.id), { balance_transaction: bt, refunds: { object: 'list', data: [], has_more: false, total_count: 0, url: `/v1/application_fees/${String(fee.id)}/refunds` } }, 'application_fee.created');
433
+ await ctx.write('charge', chargeId, { application_fee: fee.id, application_fee_amount: feeAmount }, 'charge.updated');
434
+ }
435
+ }
436
+
437
+ /** Radar places an elevated-risk card's charge in review (docs.stripe.com/radar/reviews). */
438
+ export async function openReview(ctx: HandlerContext, chargeId: string, pi: { payment_intent: string | null }): Promise<void> {
439
+ const review = await created(ctx, 'review', { charge: chargeId, ...pi }, {
440
+ open: true, opened_reason: 'rule', reason: 'rule', closed_reason: null, billing_zip: null, ip_address: null, ip_address_location: null, session: null, livemode: false,
441
+ });
442
+ const existing = (ctx.get('charge', chargeId)?.outcome as Row | undefined) ?? {};
443
+ await ctx.write('charge', chargeId, {
444
+ review: review.id,
445
+ outcome: { ...existing, type: 'manual_review', risk_level: 'elevated', risk_score: 67, seller_message: 'Stripe evaluated this payment as having elevated risk, and placed it in review.' },
446
+ }, 'review.opened');
447
+ }
448
+
449
+ /** The mandate a verified bank account carries for a payment (single use) or a setup (multi use). */
450
+ export async function mintMandate(ctx: HandlerContext, paymentMethod: unknown, use: 'single_use' | 'multi_use', amount?: number, currency?: string): Promise<string> {
451
+ const now = Number(nowUnix(ctx.occurredAt));
452
+ const mandate = await created(ctx, 'mandate', { payment_method: typeof paymentMethod === 'string' ? paymentMethod : null }, {
453
+ status: 'active', type: use, livemode: false,
454
+ customer_acceptance: { type: 'online', accepted_at: now, online: { ip_address: '127.0.0.1', user_agent: 'twin' } },
455
+ payment_method_details: { type: 'us_bank_account', us_bank_account: { collection_method: 'paper' } },
456
+ ...(use === 'single_use' ? { single_use: { amount: amount ?? 0, currency: currency ?? 'usd' } } : { multi_use: {} }),
457
+ }, { timeField: '_created' });
458
+ return String(mandate.id);
459
+ }
460
+
461
+ export const customerMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such customer: '${id}'`, 404, 'resource_missing');
462
+
463
+ /** The discount a customer's `coupon` makes, a parameter of API versions before the served one. */
464
+ export function customerDiscount(ctx: HandlerContext, couponId: string): Row | Response {
465
+ const coupon = ctx.get('coupon', couponId);
466
+ return coupon ? buildDiscount(coupon, '', Number(nowUnix(ctx.occurredAt))) : fail(ctx, `No such coupon: '${couponId}'`, 400, 'resource_missing');
467
+ }
468
+
469
+ /** A tax ID for its owner: the account itself, or one of its customers. */
470
+ export async function makeTaxId(ctx: HandlerContext, customer: string | undefined): Promise<Response> {
471
+ const given = ctx.params;
472
+ const { owner: _owner, ...params } = given;
473
+ if (params.type === undefined || params.type === '') return fail(ctx, 'Missing required param: type.', 400, 'parameter_missing');
474
+ if (params.value === undefined || params.value === '') return fail(ctx, 'Missing required param: value.', 400, 'parameter_missing');
475
+ const vatCountry = params.type === 'eu_vat' ? euVatCountry(String(params.value)) : undefined;
476
+ if (params.type === 'eu_vat' && !vatCountry) return ctx.refuse({ status: 400, code: 'tax_id_invalid', param: 'value', message: `Invalid value for eu_vat.` });
477
+ return ctx.reply(
478
+ await created(ctx, 'tax_id', { ...params, ...(customer ? { customer } : {}) }, {
479
+ livemode: false,
480
+ country: vatCountry ?? (typeof params.country === 'string' ? params.country : null),
481
+ owner: customer ? { type: 'customer', customer } : { type: 'self' },
482
+ verification: { status: AUTO_VALIDATED.has(String(params.type)) ? 'pending' : 'unavailable', verified_address: null, verified_name: null },
483
+ }),
484
+ );
485
+ }
486
+
487
+ /** The owner a top-level tax-ID call names: the account itself unless `owner[type]=customer` names a customer
488
+ * (docs.stripe.com/api/tax_ids/list: owner defaults to self). */
489
+ export function ownerOf(ctx: HandlerContext): { customer?: string } | Response {
490
+ const owner = (ctx.params.owner ?? {}) as Row;
491
+ const type = String(owner.type ?? 'self');
492
+ if (type === 'self') return {};
493
+ if (type !== 'customer') return fail(ctx, `Invalid owner[type]: must be one of self or customer.`, 400, 'parameter_invalid_string_enum');
494
+ const customer = typeof owner.customer === 'string' ? owner.customer : '';
495
+ if (!customer) return fail(ctx, 'Missing required param: owner[customer].', 400, 'parameter_missing');
496
+ if (!ctx.get('customer', customer)) return customerMissing(ctx, customer);
497
+ return { customer };
498
+ }
499
+
500
+ // ── the cash balance: per-currency sums of the funding ledger, and the reconciliation setting ──
501
+
502
+ export function cashBalance(ctx: HandlerContext, customer: string): Row {
503
+ const byCurrency: Record<string, number> = {};
504
+ for (const t of ctx.rows('customer_cash_balance_transaction')) {
505
+ if (t.customer !== customer) continue;
506
+ const cur = String(t.currency ?? 'usd');
507
+ byCurrency[cur] = (byCurrency[cur] ?? 0) + (Number(t.net_amount) || 0);
508
+ }
509
+ const cust = ctx.row('customer', customer);
510
+ const mode = typeof cust?._cash_balance_mode === 'string' ? cust._cash_balance_mode : 'automatic';
511
+ return {
512
+ object: 'cash_balance', customer,
513
+ available: Object.keys(byCurrency).length ? byCurrency : null,
514
+ settings: { reconciliation_mode: mode, using_merchant_default: mode === 'merchant_default' },
515
+ livemode: false,
516
+ };
517
+ }
518
+
519
+ /** Automatic reconciliation (docs.stripe.com/payments/customer-balance/reconciliation): funds that arrive pay the
520
+ * customer's open invoices that take bank transfers (payment_method_types customer_balance), the one whose number
521
+ * the transfer's reference names first, then the oldest. Where the documentation stops and the twin decides: an
522
+ * invoice is paid only when the balance covers all of what remains; a smaller balance waits for more funds. */
523
+ export async function reconcile(ctx: HandlerContext, customer: string, currency: string, reference: string | null): Promise<void> {
524
+ const takesTransfers = (inv: Row): boolean => ((inv.payment_settings as Row | undefined)?.payment_method_types as unknown[] | undefined)?.includes('customer_balance') === true;
525
+ const open = ctx.rows('invoice').filter((inv) => inv.customer === customer && inv.status === 'open' && String(inv.currency ?? 'usd') === currency && takesTransfers(inv))
526
+ .sort((a, b) => (reference && a.number === reference ? -1 : reference && b.number === reference ? 1 : Number(a.created) - Number(b.created)));
527
+ for (const inv of open) {
528
+ const available = Number(((cashBalance(ctx, customer).available as Row | null) ?? {})[currency] ?? 0);
529
+ const amount = Number(inv.amount_remaining ?? inv.amount_due) || 0;
530
+ if (amount <= 0 || available < amount) continue;
531
+ const id = String(inv.id);
532
+ if (ctx.legal('invoice', 'status', 'PostTestHelpersCustomersCustomerFundCashBalance', inv.status, 'paid', id)) continue;
533
+ // the payment the balance makes: the invoice's own PaymentIntent (every invoice finalized with an amount due has one,
534
+ // semantics/invoices.ts), paid from the cash balance, its charge, and the ledger's entry
535
+ const piId = String(inv.payment_intent);
536
+ await created(ctx, 'customer_cash_balance_transaction', { customer }, { currency, type: 'applied_to_payment', net_amount: -amount, ending_balance: available - amount, applied_to_payment: { payment_intent: piId }, livemode: false });
537
+ const charge = await mintCharge(ctx, piId, { currency, customer, invoice: id }, amount);
538
+ await ctx.write('payment_intent', piId, { status: 'succeeded', amount_received: amount, latest_charge: charge }, 'payment_intent.succeeded');
539
+ await ctx.write('invoice', id, {
540
+ status: 'paid', paid: true, amount_paid: amount, amount_remaining: 0, payment_intent: piId, charge,
541
+ status_transitions: { ...((inv.status_transitions as Row | undefined) ?? {}), paid_at: nowUnix(ctx.occurredAt) },
542
+ }, 'invoice.paid');
543
+ }
544
+ }
545
+
546
+ /** The customer's source the path names, or undefined. */
547
+ export const customerSource = (ctx: HandlerContext): Row | undefined => {
548
+ const s = ctx.get('source', at(ctx, 'id'));
549
+ return s && s.customer === at(ctx, 'customer') ? s : undefined;
550
+ };
551
+
552
+ export const sourceMissing = (ctx: HandlerContext): Response => fail(ctx, `No such source: '${at(ctx, 'id')}'`, 404, 'resource_missing');
553
+
554
+ /** The intent the path names, and the machine's refusal when this operation may not move it. */
555
+ export function load(ctx: HandlerContext, operationId: string): { si: Row } | { answer: Response } {
556
+ const id = at(ctx, 'intent');
557
+ const si = ctx.get(SI, id);
558
+ if (!si) return { answer: fail(ctx, `No such setup_intent: '${id}'`, 404, 'resource_missing') };
559
+ const refused = ctx.legal(SI, 'status', operationId, si.status, undefined, id);
560
+ return refused ? { answer: ctx.refuse(refused) } : { si };
561
+ }
562
+
563
+ /** The request event asked of the endpoint, signed with its secret and rendered in the event's API version, and its
564
+ * answer read as the decision. */
565
+ export async function askForAuthorization(ctx: HandlerContext, url: string, event: Record<string, unknown>, secret: string): Promise<StripeAuthRequestOutcome> {
566
+ const payload = JSON.stringify(render(event, typeof event.api_version === 'string' ? event.api_version : undefined));
567
+ const signature = stripeSignature(payload, secret, Math.floor(Date.parse(ctx.occurredAt) / 1000));
568
+ const answer = await ctx.ask(url, { method: 'POST', headers: { 'content-type': 'application/json', 'stripe-signature': signature }, body: payload }, STRIPE_REALTIME_AUTH_TIMEOUT_MS);
569
+ if (answer.missed === 'timeout') return { kind: 'timeout', message: 'Webhook endpoint did not respond within the real-time authorization window.' };
570
+ if (answer.missed === 'unreachable') return { kind: 'timeout', message: 'Webhook endpoint was unreachable within the real-time authorization window.' };
571
+ return readDecision(answer);
572
+ }
573
+
574
+ /** Stripe's refusal of a call a publishable key may not make, or undefined when the key may make it. */
575
+ export function publishableKeyRefused(ctx: HandlerContext): Response | undefined {
576
+ // the key however it is sent, Bearer or Basic's user (requestKey): a publishable key is public, and sent as Basic it
577
+ // is still one
578
+ if (!requestKey(ctx.call.request).startsWith('pk_')) return undefined;
579
+ const op = ctx.call.operation.id;
580
+ if (PUBLISHABLE_CREATES.has(op)) return undefined;
581
+ const scoped = BY_CLIENT_SECRET[op];
582
+ if (!scoped) return ctx.refuse({ status: 403, code: 'secret_key_required', message: 'The API key provided is a publishable key, but a secret key is required.' });
583
+ const secret = typeof ctx.params.client_secret === 'string' ? ctx.params.client_secret : '';
584
+ if (!secret) return ctx.refuse({ status: 400, code: 'parameter_missing', param: 'client_secret', message: 'Missing required param: client_secret.' });
585
+ const id = ctx.call.params[scoped.param] ?? '';
586
+ return ctx.get(scoped.type, id)?.client_secret === secret ? undefined : ctx.refuse({ status: 404, code: 'resource_missing', param: scoped.param, message: `No such ${scoped.type}: '${id}'` });
587
+ }
588
+
589
+ // ── an account whose OAuth connection was revoked ──
590
+ // "After revocation, the account can't be accessed by your platform in the Dashboard or through the API"
591
+ // (docs.stripe.com/connect/oauth-reference, deauthorize; so too a connection revoked by a reused code). A call made as it
592
+ // (the Stripe-Account header) or naming it (/v1/accounts/{account}…) is refused with the error Stripe documents for a
593
+ // Stripe-Account the key cannot use: "account_invalid | The account ID provided as a value for the Stripe-Account header
594
+ // is invalid" (docs.stripe.com/error-codes), as 403. Where the documentation stops and the twin decides: the message's
595
+ // wording; an account the platform created itself, or never connected by OAuth, is not affected.
596
+ export function revokedAccountRefused(ctx: HandlerContext): Response | undefined {
597
+ const request = ctx.call.request;
598
+ const named = [request.headers.get('stripe-account') ?? undefined, ctx.call.operation.path.startsWith('/v1/accounts/{account}') ? ctx.call.params.account : undefined].filter((a): a is string => !!a);
599
+ const revoked = named.find((a) => connectionRevoked(ctx, a));
600
+ if (!revoked) return undefined;
601
+ return ctx.refuse({ status: 403, code: 'account_invalid', message: `The provided key '${redactKey(requestKey(request))}' does not have access to account '${revoked}' (or that account does not exist). Application access may have been revoked.` });
602
+ }
603
+
604
+ // A connected account's OAuth keys (../screens/connect-oauth.tsx): the token endpoint's access_token is "Use the
605
+ // Stripe-Account header with your platform's secret key (that can make requests on behalf of this Stripe account)" and
606
+ // its stripe_publishable_key the same with the publishable key (docs.stripe.com/connect/oauth-reference): a request made
607
+ // with one acts as that account, as a request with the Stripe-Account header does. A key no live connection holds (its
608
+ // connection revoked, or replaced by a refresh: "Any existing access token with the same scope and mode ... is
609
+ // revoked") is Stripe's unknown key, 401 "Invalid API Key provided" (docs.stripe.com/api/authentication); one sent with
610
+ // a Stripe-Account header naming another account cannot act as it (account_invalid). Where the documentation stops and
611
+ // the twin decides: the messages' wording; a read_only key is not held to reads (manifest todo
612
+ // stripe.connect.oauth_scope_enforcement).
613
+ /** The platform's own keys, as the dashboard's API keys page makes them (the `appCredentials` door): a secret key and a
614
+ * publishable key, held by their SHA-256. A request with no key is refused, as is a platform key Stripe never issued
615
+ * ("Invalid API Key provided"); a connected account's OAuth key is checked where it is read (actingAsOAuthKey). */
616
+ // source: https://docs.stripe.com/api/authentication "API requests without authentication also fail."
617
+ export function platformKeyRefused(ctx: HandlerContext, request: Request): Response | undefined {
618
+ const key = requestKey(request);
619
+ if (!key) return ctx.refuse({ status: 401, message: "You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/." });
620
+ if (/^(sk|pk)_test_oauth_/.test(key)) return undefined;
621
+ const held = ctx.rowsRaw('_platform_key').some((k) => k._sha256 === ctx.crypto.sha256(key) && k.deleted !== true);
622
+ return held ? undefined : ctx.refuse({ status: 401, message: `Invalid API Key provided: ${redactKey(key)}` });
623
+ }
624
+
625
+ export async function actingAsOAuthKey(ctx: HandlerContext, request: Request): Promise<Request | Response> {
626
+ const key = requestKey(request);
627
+ if (!/^(sk|pk)_test_oauth_/.test(key)) return request;
628
+ const held = oauthKeyAccount(ctx, key);
629
+ if (!held) return ctx.refuse({ status: 401, message: `Invalid API Key provided: ${redactKey(key)}` });
630
+ const named = request.headers.get('stripe-account');
631
+ if (named && named !== held.account) return ctx.refuse({ status: 403, code: 'account_invalid', message: `The provided key '${redactKey(key)}' does not have access to account '${named}' (or that account does not exist). Application access may have been revoked.` });
632
+ const headers = new Headers(request.headers);
633
+ headers.set('stripe-account', held.account);
634
+ const bodied = request.method !== 'GET' && request.method !== 'HEAD';
635
+ return new Request(request.url, { method: request.method, headers, ...(bodied ? { body: await request.arrayBuffer() } : {}) });
636
+ }
637
+
638
+ // ── metadata ──
639
+ // "This parameter uses a merge mechanism, which allows you to add new key-value pairs to an object in an update call
640
+ // without affecting any existing metadata"; "Pass in the key with an empty string as the value to remove the key from the
641
+ // metadata"; "Pass an empty string as the value for the metadata attribute to delete all of the keys simultaneously"
642
+ // (docs.stripe.com/metadata), and "Individual keys can be unset by posting an empty value to them" holds on a create
643
+ // too: an object never holds a key set to "" (stripe-node encodes a `null` value as `metadata[key]=`). The derived core
644
+ // merges a nested hash on an update (dropping keys set to ""), so for it only a clear-all is rewritten; where a handler
645
+ // stores the request's metadata whole, the request carries the merged hash, its removed keys as "". The rewritten
646
+ // request is JSON.
647
+ export function withMetadata(ctx: HandlerContext, request: Request): Request {
648
+ if (request.method !== 'POST' || (request.headers.get('content-type') ?? '').includes('multipart')) return request;
649
+ if (!('metadata' in ctx.params)) return request;
650
+ const op = ctx.call.operation;
651
+ const given = ctx.params.metadata;
652
+ let metadata: Row;
653
+ if (op.class === 'create') {
654
+ if (given === '') metadata = {};
655
+ else if (given && typeof given === 'object' && !Array.isArray(given) && Object.values(given).includes('')) metadata = Object.fromEntries(Object.entries(given as Row).filter(([, v]) => v !== ''));
656
+ else return request;
657
+ } else if (op.class === 'update' && op.resource) {
658
+ // a plan is kept as the recurring price it is (../semantics/plans.ts)
659
+ const resource = op.resource === 'plan' ? 'price' : op.resource;
660
+ const id = Object.values(ctx.call.params).at(-1) ?? '';
661
+ const held = ctx.get(resource, id)?.metadata;
662
+ const prior = held && typeof held === 'object' ? (held as Row) : {};
663
+ // the merged hash, a key removed carried as "" so a merging update (the derived core's) drops it too; an object
664
+ // never answers a key set to "" (../engine/version.ts render)
665
+ if (given === '') metadata = Object.fromEntries(Object.keys(prior).map((k) => [k, '']));
666
+ else if (given && typeof given === 'object' && !Array.isArray(given)) metadata = { ...prior, ...(given as Row) };
667
+ else return request;
668
+ } else return request;
669
+ const headers = new Headers(request.headers);
670
+ headers.set('content-type', 'application/json');
671
+ return new Request(request.url, { method: request.method, headers, body: JSON.stringify({ ...ctx.params, metadata }) });
672
+ }
673
+
674
+ /** `disabled` switches delivery off or back on (docs.stripe.com/api/webhook_endpoints/update#update_webhook_endpoint-disabled). */
675
+ export async function switchDelivery(ctx: HandlerContext, id: string, we: Row, fields: Row, off: boolean): Promise<Response> {
676
+ const status = off ? 'disabled' : 'enabled';
677
+ const refused = ctx.legal(WE, 'status', 'PostWebhookEndpointsWebhookEndpoint', we.status, status, id);
678
+ if (refused) return ctx.refuse(refused);
679
+ return ctx.reply(await ctx.write(WE, id, { ...fields, status }, 'webhook_endpoint.update'));
680
+ }
681
+
682
+ /** Whether a stored event is the acting account's (no `account`: the platform's). */
683
+ export const ownEvent = (ctx: HandlerContext, e: Row): boolean => (typeof e.account === 'string' ? e.account : undefined) === actingAccount(ctx);
684
+
685
+ export const faMissing = (ctx: HandlerContext, id: string, status = 404): Response => fail(ctx, `No such financial account: '${id}'`, status, 'resource_missing');
686
+
687
+ export const metadataOf = (ctx: HandlerContext): unknown => (ctx.params.metadata && typeof ctx.params.metadata === 'object' ? ctx.params.metadata : {});
688
+
689
+ /** The account's bank address once financial_addresses.aba is active: "The FinancialAccount gains a FinancialAddress
690
+ * when the `financial_addresses.aba` feature is active", and "A FinancialAddress is not added until the
691
+ * financial_addresses.aba feature has been activated" (docs.stripe.com/treasury/account-management/financial-accounts),
692
+ * whose test example answers "bank_name": "Stripe Test Bank", "routing_number": "000000001" and the networks "ach",
693
+ * "us_domestic_wire", "rtp"; "The full account_number is only returned if the request expands it" (the same page).
694
+ * Where the documentation stops and the twin decides: the account number is ten digits drawn from the account's id,
695
+ * answered by its last four (the full number is null: expanding it is not modelled), and the holder's name is the
696
+ * platform account's business name, its dashboard name or, with neither, its id. */
697
+ export function abaAddress(ctx: HandlerContext, faId: string): Row {
698
+ let n = 0;
699
+ for (const ch of faId) n = (n * 31 + ch.charCodeAt(0)) % 10_000_000_000;
700
+ const number = String(n).padStart(10, '0');
701
+ const platform = ctx.get('account', PLATFORM_ACCOUNT_ID) as Row | undefined;
702
+ const name = ((platform?.business_profile as Row | undefined)?.name ?? ((platform?.settings as Row | undefined)?.dashboard as Row | undefined)?.display_name ?? PLATFORM_ACCOUNT_ID) as string;
703
+ 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' } };
704
+ }
705
+
706
+ export const addressesOf = (ctx: HandlerContext, faId: string, active: string[]): Row[] => (active.includes('financial_addresses.aba') ? [abaAddress(ctx, faId)] : []);
707
+
708
+ /** Post a flow's double entry: a ledger transaction with its net balance impact, and its one entry. */
709
+ export async function post(ctx: HandlerContext, o: {
710
+ financial_account: string; amount: number; currency: string; flow: string; flow_type: string;
711
+ status: 'open' | 'posted'; balance_impact: Row; description: string; flowDetailKey?: string;
712
+ }): Promise<string> {
713
+ const now = nowUnix(ctx.occurredAt);
714
+ const txnId = ctx.mint(TX);
715
+ await ctx.write(TX, txnId, {
716
+ object: 'treasury.transaction', created: now, livemode: false,
717
+ amount: o.amount, currency: o.currency, financial_account: o.financial_account,
718
+ flow: o.flow, flow_type: o.flow_type, flow_details: null,
719
+ status: o.status, balance_impact: o.balance_impact, description: o.description,
720
+ entries: { object: 'list', has_more: false, url: `/v1/treasury/transaction_entries?transaction=${txnId}`, data: [] },
721
+ status_transitions: { posted_at: o.status === 'posted' ? now : null, void_at: null },
722
+ }, 'treasury_transaction.created');
723
+ await ctx.write(ENTRY, ctx.mint(ENTRY), {
724
+ object: 'treasury.transaction_entry', created: now, livemode: false,
725
+ amount: o.amount, currency: o.currency, financial_account: o.financial_account,
726
+ flow: o.flow, flow_type: o.flow_type,
727
+ flow_details: o.flowDetailKey ? { type: o.flowDetailKey, [o.flowDetailKey]: o.flow } : null,
728
+ transaction: txnId, effective_at: now,
729
+ balance_impact: o.balance_impact,
730
+ // what the entry records: its flow's kind where Stripe names one (docs.stripe.com/api/treasury/transaction_entries/object);
731
+ // a vendor `type`, kept apart from the kernel's row type
732
+ type: ENTRY_TYPES.has(String(o.flow_type)) ? o.flow_type : 'other',
733
+ }, 'treasury_transaction_entry.created');
734
+ // the account's balance moves by the entry's impact: cash "Funds the user can spend right now", inbound_pending
735
+ // "Funds not spendable yet", outbound_pending "held for pending outbound flows" (the served spec's balance)
736
+ const account = ctx.get(FA, o.financial_account);
737
+ if (account) {
738
+ const bal = (account.balance as Record<string, Record<string, number>> | undefined) ?? { cash: {}, inbound_pending: {}, outbound_pending: {} };
739
+ const moved = Object.fromEntries((['cash', 'inbound_pending', 'outbound_pending'] as const).map((k) => [k, { ...(bal[k] ?? {}), [o.currency]: ((bal[k] ?? {})[o.currency] ?? 0) + (Number(o.balance_impact[k]) || 0) }]));
740
+ await ctx.write(FA, o.financial_account, { balance: moved }, 'financial_account.balance_updated');
741
+ }
742
+ return txnId;
743
+ }
744
+
745
+ /** The request's funding account, or the refusal. */
746
+ export function fundingAccount(ctx: HandlerContext): string | Response {
747
+ const bad = validateMoney(ctx.params);
748
+ if (bad) return send(ctx, bad);
749
+ const fa = typeof ctx.params.financial_account === 'string' ? ctx.params.financial_account : '';
750
+ if (!fa) return fail(ctx, 'Missing required param: financial_account.', 400, 'parameter_missing');
751
+ return ctx.get(FA, fa) ? fa : faMissing(ctx, fa, 400);
752
+ }
753
+
754
+ /** Where an outbound flow sends its money, as the served spec's payment method details give it: the bank account's
755
+ * holder type, last four digits and routing number from what the request sent (a saved method's, or the test bank's
756
+ * when none is given), and its billing details (required): the name and email sent, the address lines null where not
757
+ * given. Where the documentation stops and the twin decides: a saved method's details are the test bank's. */
758
+ export function destinationDetails(ctx: HandlerContext, dest: string | null): Row {
759
+ const data = ctx.params.destination_payment_method_data && typeof ctx.params.destination_payment_method_data === 'object' ? (ctx.params.destination_payment_method_data as Row) : {};
760
+ const bank = data.us_bank_account && typeof data.us_bank_account === 'object' ? (data.us_bank_account as Row) : {};
761
+ const billing = data.billing_details && typeof data.billing_details === 'object' ? (data.billing_details as Row) : {};
762
+ const address = billing.address && typeof billing.address === 'object' ? (billing.address as Row) : {};
763
+ const number = typeof bank.account_number === 'string' ? bank.account_number.replace(/\D/g, '') : '';
764
+ 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])) };
765
+ if (dest && data.type === undefined && dest.startsWith('fa_')) return { type: 'financial_account', financial_account: { id: dest, network: 'stripe' }, billing_details };
766
+ return {
767
+ type: 'us_bank_account', billing_details,
768
+ 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 },
769
+ };
770
+ }
771
+
772
+ /** An outbound payment that names no destination: "You must provide either destination_payment_method or
773
+ * destination_payment_method_data" (the served spec's outbound payment create). */
774
+ export function noDestination(ctx: HandlerContext): Response {
775
+ return fail(ctx, 'You must provide either `destination_payment_method` or `destination_payment_method_data`.', 400, 'parameter_missing');
776
+ }
777
+
778
+ /** The bank account an inbound transfer may pull from: "You must first set up the account-attached payment method for
779
+ * inbound flows and verify the bank account using a SetupIntent", and invalid ones ("of unsupported types, containing
780
+ * an unverified bank account, or not set up for inbound flows") "throw the same errors as in live mode"
781
+ * (docs.stripe.com/treasury/moving-money/financial-accounts/into/inbound-transfers). A payment method is set up for
782
+ * inbound flows by a SetupIntent whose flow_directions holds `inbound`, and verified when that SetupIntent succeeded
783
+ * ("The bank account has been instantly verified or verification isn't necessary", its `succeeded` status,
784
+ * docs.stripe.com/treasury/connect/legacy/v1/moving-money/working-with-bankaccount-objects).
785
+ * Where the documentation stops and the twin decides: the page quotes no error, so the twin answers the documented code
786
+ * for the class, payment_method_unexpected_state ("The provided payment method's state was incompatible with the
787
+ * operation you were trying to perform", docs.stripe.com/error-codes), in its own words; an existing verified
788
+ * BankAccount (`ba_`), which the page also allows, is not checked. Answers the payment method, or the refusal. */
789
+ export function inboundOrigin(ctx: HandlerContext, origin: string): Row | Response | undefined {
790
+ if (origin.startsWith('ba_')) return undefined;
791
+ const pm = ctx.get('payment_method', origin);
792
+ if (!pm) return fail(ctx, `No such PaymentMethod: '${origin}'`, 400, 'resource_missing');
793
+ if (pm.type !== 'us_bank_account') 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');
794
+ 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'));
795
+ if (!setUp) return fail(ctx, `The PaymentMethod '${origin}' has not been set up for inbound flows and verified with a SetupIntent.`, 400, 'payment_method_unexpected_state');
796
+ return pm;
797
+ }
798
+
799
+ // test mode's stand-ins for money another party sends to the account or pulls from it
800
+ // (docs.stripe.com/treasury/moving-money/receiving-funds, docs.stripe.com/api/treasury/received_credits/test_mode_create)
801
+ export function received(kind: 'received_credit' | 'received_debit'): Handler {
802
+ return async (ctx) => {
803
+ const fa = fundingAccount(ctx);
804
+ if (fa instanceof Response) return fa;
805
+ const network = typeof ctx.params.network === 'string' ? ctx.params.network : '';
806
+ if (!['ach', 'us_domestic_wire', 'stripe'].includes(network)) return fail(ctx, 'Missing required param: network.', 400, 'parameter_missing');
807
+ const amount = ctx.params.amount as number;
808
+ const currency = String(ctx.params.currency);
809
+ const id = ctx.mint(`treasury.${kind}`);
810
+ const signed = kind === 'received_credit' ? amount : -amount;
811
+ 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 });
812
+ return ctx.reply(
813
+ await created(ctx, `treasury.${kind}`, { id }, {
814
+ amount, currency, financial_account: fa, network, livemode: false, status: 'succeeded', failure_code: null,
815
+ description: typeof ctx.params.description === 'string' ? ctx.params.description : kind === 'received_credit' ? 'Received credit' : 'Received debit',
816
+ hosted_regulatory_receipt_url: null, transaction: txn, reversal_details: null,
817
+ 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' } },
818
+ 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 },
819
+ }),
820
+ );
821
+ };
822
+ }
823
+
824
+ /** Cancel a flow still processing; an outbound one must also still be cancelable. */
825
+ export function cancel(resource: string, param: string, name: string, operationId: string, op: string, checkCancelable: boolean): Handler {
826
+ return async (ctx) => {
827
+ const id = at(ctx, param);
828
+ const flow = ctx.get(resource, id);
829
+ if (!flow) return fail(ctx, `No such ${name}: '${id}'`, 404, 'resource_missing');
830
+ // a processing flow that is no longer cancelable is refused as one no longer processing
831
+ const refused = ctx.legal(resource, 'status', operationId, checkCancelable && flow.cancelable !== true ? 'not_cancelable' : flow.status, undefined, id);
832
+ if (refused) return ctx.refuse(refused);
833
+ // a canceled flow's open transaction is voided and what it held returns to the account (the reverse of its
834
+ // balance impact). Where the documentation stops and the twin decides: a flow already posted is only marked canceled
835
+ const txn = typeof flow.transaction === 'string' ? ctx.get(TX, flow.transaction) : undefined;
836
+ if (txn && txn.status === 'open') {
837
+ await ctx.write(TX, String(txn.id), { status: 'void', status_transitions: { ...(txn.status_transitions as object), void_at: nowUnix(ctx.occurredAt) } }, 'treasury_transaction.voided');
838
+ const account = ctx.get(FA, String(txn.financial_account));
839
+ const impact = (txn.balance_impact as Record<string, number> | undefined) ?? {};
840
+ const cur = String(txn.currency ?? 'usd');
841
+ if (account) {
842
+ const bal = (account.balance as Record<string, Record<string, number>> | undefined) ?? { cash: {}, inbound_pending: {}, outbound_pending: {} };
843
+ const back = Object.fromEntries((['cash', 'inbound_pending', 'outbound_pending'] as const).map((k) => [k, { ...(bal[k] ?? {}), [cur]: ((bal[k] ?? {})[cur] ?? 0) - (Number(impact[k]) || 0) }]));
844
+ await ctx.write(FA, String(account.id), { balance: back }, 'financial_account.balance_updated');
845
+ }
846
+ }
847
+ return ctx.reply(await ctx.write(resource, id, { status: 'canceled', cancelable: false, status_transitions: { ...(flow.status_transitions as object), canceled_at: nowUnix(ctx.occurredAt) } }, op));
848
+ };
849
+ }
850
+
851
+ // the ledger is always read for one account
852
+ export function ledger(resource: string, spec: Record<string, (r: Row, v: unknown) => boolean>): Handler {
853
+ return async (ctx) => {
854
+ if (typeof ctx.params.financial_account !== 'string' || !ctx.params.financial_account) return fail(ctx, 'Missing required param: financial_account.', 400, 'parameter_missing');
855
+ return list(ctx, resource, where(ctx, newest(ctx, resource), spec));
856
+ };
857
+ }
858
+
859
+ export function scopeKeyOf(ctx: HandlerContext): string {
860
+ const scope = ctx.params.scope && typeof ctx.params.scope === 'object' ? (ctx.params.scope as Row) : undefined;
861
+ const scopeType = scope && typeof scope.type === 'string' ? scope.type : 'account';
862
+ return scopeType === 'user' ? `user:${String(scope!.user)}` : 'account';
863
+ }
864
+
865
+ export const named = (ctx: HandlerContext, name: string): Row | undefined => ctx.rows(SECRET).find((s) => s.name === name && kept(ctx, SECRET, s, '_scope_key') === scopeKeyOf(ctx));
866
+
867
+ export const invoiceMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such invoice: '${id}'`, 404, 'resource_missing');
868
+
869
+ /** Write a draft's line list and the totals derived from it. */
870
+ export async function writeLines(ctx: HandlerContext, invoiceId: string, next: Row[]): Promise<Row> {
871
+ const subtotal = sumLines(next);
872
+ const lines = { object: 'list', data: next, has_more: false, total_count: next.length, url: `/v1/invoices/${invoiceId}/lines` };
873
+ return ctx.write(INV, invoiceId, { lines, subtotal, total: subtotal, amount_due: subtotal, amount_remaining: subtotal }, 'invoice.update');
874
+ }
875
+
876
+ /** Paying an invoice with nothing to pay it: "If not set, defaults to the subscription's default payment method, if any,
877
+ * or to the default payment method in the customer's invoice settings" (docs.stripe.com/api/invoices/object,
878
+ * default_payment_method), and none of them is set. */
879
+ export function nothingToPayWith(ctx: HandlerContext): Response {
880
+ return fail(ctx, 'This customer has no attached payment source or default payment method. Please consider adding a default payment method.', 400, 'missing');
881
+ }
882
+
883
+ /** A subscription waiting on the invoice paid through the invoice's own pay (incomplete on its first, past_due on a
884
+ * failed renewal) is active again. */
885
+ export async function activatedByPayment(ctx: HandlerContext, subId: string): Promise<void> {
886
+ await ctx.write('subscription', subId, { status: 'active' }, 'subscription.update');
887
+ }
888
+
889
+ /** Re-derive a draft's lines from the items still on it: an item that changed or was deleted moves the invoice with it. */
890
+ export async function resyncDraftLines(ctx: HandlerContext, invoiceId: string): Promise<void> {
891
+ const inv = ctx.get(INV, invoiceId);
892
+ if (!inv || inv.status !== 'draft') return;
893
+ const next: Row[] = [];
894
+ for (const line of linesOf(inv)) {
895
+ const itemId = typeof line.invoice_item === 'string' ? line.invoice_item : '';
896
+ if (!itemId) next.push(unlinkedLine(line));
897
+ const item = itemId ? ctx.get('invoiceitem', itemId) : undefined;
898
+ if (item) next.push({ ...line, amount: Number(item.amount) || 0, description: (item.description as string) ?? null });
899
+ }
900
+ await writeLines(ctx, invoiceId, next);
901
+ }
902
+
903
+ // ── invoice items: a price-based item takes its amount from the price; one naming a draft invoice
904
+ // lands on its lines at once ──
905
+
906
+ /** An item priced by a Price: its unit amount times the quantity, in its currency (docs.stripe.com/api/invoiceitems/create#create_invoiceitem-pricing). */
907
+ export function pricedItem(ctx: HandlerContext, priceRef: string, qty: number): { amount: number; currency: string | undefined } | Response {
908
+ const price = ctx.get('price', priceRef);
909
+ if (!price) return fail(ctx, `No such price: '${priceRef}'`, 400, 'resource_missing');
910
+ return { amount: priceAmount(price, qty), currency: typeof price.currency === 'string' ? price.currency : undefined };
911
+ }
912
+
913
+ export const itemMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such invoiceitem: '${id}'`, 404, 'resource_missing');
914
+
915
+ /** A draft invoice another object makes (an accepted quote): its customer's, with an invoice item per line the
916
+ * object gives, and the object named as its parent. Answers the invoice's id. */
917
+ export async function draftInvoiceFor(ctx: HandlerContext, customer: string, currency: string, parent: Row, lines: Array<{ price: unknown; quantity: number; amount: number; description: unknown }>): Promise<string> {
918
+ const now = Number(nowUnix(ctx.occurredAt));
919
+ const id = ctx.mint(INV);
920
+ const holder = ctx.get('customer', customer);
921
+ const inv = await created(ctx, INV, { id, customer, currency, parent }, { ...draft(now), currency, customer_email: holder?.email ?? null, customer_name: holder?.name ?? null, lines: { object: 'list', data: [], has_more: false, total_count: 0, url: `/v1/invoices/${id}/lines` } });
922
+ for (const l of lines) {
923
+ const price = typeof l.price === 'string' ? l.price : l.price && typeof l.price === 'object' ? String((l.price as Row).id) : null;
924
+ const item = await created(ctx, 'invoiceitem', { customer, currency, amount: l.amount, quantity: l.quantity, ...(price ? { price } : {}), description: l.description ?? null }, { date: now, livemode: false, metadata: {}, discountable: true, proration: false, period: { start: now, end: now } });
925
+ await pullPendingItem(ctx, id, inv, item, now);
926
+ }
927
+ return id;
928
+ }
929
+
930
+ /** A customer's pending invoice item, made before the invoice, pulled onto it (docs.stripe.com/api/invoices/create#create_invoice-pending_invoice_items_behavior). */
931
+ export async function pullPendingItem(ctx: HandlerContext, invoiceId: string, inv: Row, item: Row, now: number): Promise<void> {
932
+ const current = ctx.get(INV, invoiceId) ?? inv;
933
+ await writeLines(ctx, invoiceId, [...linesOf(current), {
934
+ id: `il_${String(item.id)}`, object: 'line_item', type: 'invoiceitem', amount: Number(item.amount) || 0, currency: String(current.currency ?? item.currency ?? 'usd'),
935
+ quantity: Number(item.quantity) || 1, proration: false, invoice_item: item.id, price: item.price ?? null,
936
+ period: item.period ?? { start: now, end: now }, description: (item.description as string) ?? null,
937
+ discountable: item.discountable ?? true, discounts: [], livemode: false, metadata: item.metadata ?? {}, tax_amounts: [], tax_rates: [],
938
+ }]);
939
+ await ctx.write('invoiceitem', String(item.id), { invoice: invoiceId }, 'invoiceitem.update');
940
+ }
941
+
942
+ /** The invoice the path names, and the machine's refusal when this operation may not move it. */
943
+ export function invoicesLoad(ctx: HandlerContext, operationId: string): { inv: Row } | { answer: Response } {
944
+ const id = at(ctx, 'invoice');
945
+ const inv = ctx.get(INV, id);
946
+ if (!inv) return { answer: invoiceMissing(ctx, id) };
947
+ const refused = ctx.legal(INV, 'status', operationId, inv.status, undefined, id);
948
+ return refused ? { answer: ctx.refuse(refused) } : { inv };
949
+ }
950
+
951
+ /** The PaymentIntent a charge_automatically invoice with a balance gets when it is finalized; it
952
+ * waits for confirmation when the invoice already names a default payment method. */
953
+ export async function openPaymentIntent(ctx: HandlerContext, piId: string, inv: Row, invoiceId: string): Promise<void> {
954
+ const defaultPaymentMethod = typeof inv.default_payment_method === 'string' ? inv.default_payment_method : undefined;
955
+ await created(ctx, 'payment_intent', {
956
+ id: piId, amount: Number(inv.amount_due) || 0, currency: String(inv.currency ?? 'usd'), customer: inv.customer, invoice: invoiceId,
957
+ ...(defaultPaymentMethod ? { payment_method: defaultPaymentMethod } : {}),
958
+ }, {
959
+ status: defaultPaymentMethod ? 'requires_confirmation' : 'requires_payment_method',
960
+ client_secret: mintClientSecret(piId, await ctx.secret(`client-secret:${piId}`)), livemode: false,
961
+ capture_method: 'automatic', amount_capturable: 0, amount_received: 0, next_action: null,
962
+ automatic_payment_methods: null, payment_method_types: ['card', 'link'], payment_method_options: {},
963
+ });
964
+ }
965
+
966
+ export function finalizedFields(ctx: HandlerContext, inv: Row, now: number): Row {
967
+ const customerId = typeof inv.customer === 'string' ? inv.customer : '';
968
+ const customer = customerId ? ctx.get('customer', customerId) : undefined;
969
+ const prefix = typeof customer?.invoice_prefix === 'string' && customer.invoice_prefix
970
+ ? customer.invoice_prefix
971
+ : invoicePrefix(customerId);
972
+ const numbered = ctx.rows(INV).filter((i) => i.customer === customerId && typeof i.number === 'string' && i.id !== inv.id).length;
973
+ const fields: Row = { number: typeof inv.number === 'string' && inv.number ? inv.number : `${prefix}-${String(numbered + 1).padStart(4, '0')}` };
974
+ const days = Number(inv.days_until_due);
975
+ if (inv.collection_method === 'send_invoice' && inv.due_date == null && Number.isFinite(days) && days > 0) fields.due_date = now + days * 86400;
976
+ return fields;
977
+ }
978
+
979
+ // add_lines, update_lines and remove_lines edit a draft's lines in bulk and re-derive its totals
980
+ export function editLines(kind: 'add' | 'update' | 'remove'): Handler {
981
+ return async (ctx) => {
982
+ const id = at(ctx, 'invoice');
983
+ const inv = ctx.get(INV, id);
984
+ if (!inv) return invoiceMissing(ctx, id);
985
+ if (inv.status !== 'draft') return fail(ctx, `You can only add/update/remove lines on a draft invoice (this one is ${String(inv.status)}).`, 400, 'invoice_not_editable');
986
+ const cur = linesOf(inv);
987
+ let next = [...cur];
988
+ const raw = ctx.params.lines;
989
+ const entries = Array.isArray(raw) ? (raw as Row[]) : raw && typeof raw === 'object' ? [raw as Row] : [];
990
+ if (entries.length === 0) return fail(ctx, 'Missing required param: lines.', 400, 'parameter_missing');
991
+ const currency = String(inv.currency ?? 'usd');
992
+ if (kind === 'add') {
993
+ for (let i = 0; i < entries.length; i++) {
994
+ const e = entries[i]!;
995
+ const priceRef = typeof e.price === 'string' ? e.price : '';
996
+ const price = priceRef ? ctx.get('price', priceRef) : undefined;
997
+ if (priceRef && !price) return fail(ctx, `No such price: '${priceRef}'`, 400, 'resource_missing');
998
+ const quantity = e.quantity !== undefined ? Math.max(1, Math.trunc(Number(e.quantity) || 1)) : 1;
999
+ const unit = Math.trunc(Number(e.amount) || 0);
1000
+ next.push({ id: `il_twin_${id}_${cur.length + i + 1}`, object: 'line_item', amount: price ? priceAmount(price, quantity) : unit, currency, quantity, price: price ?? (priceRef || null), description: typeof e.description === 'string' ? e.description : null, proration: false });
1001
+ }
1002
+ } else if (kind === 'update') {
1003
+ for (const e of entries) {
1004
+ const lid = typeof e.id === 'string' ? e.id : '';
1005
+ next = next.map((l) => (l.id === lid ? { ...l, ...(e.amount !== undefined ? { amount: Math.trunc(Number(e.amount) || 0) } : {}), ...(e.quantity !== undefined ? { quantity: Math.max(1, Math.trunc(Number(e.quantity) || 1)) } : {}), ...(e.description !== undefined ? { description: e.description } : {}) } : l));
1006
+ }
1007
+ } else {
1008
+ const remove = new Set(entries.map((e) => (typeof e.id === 'string' ? e.id : '')).filter(Boolean));
1009
+ next = next.filter((l) => !remove.has(String(l.id)));
1010
+ }
1011
+ return ctx.reply(await writeLines(ctx, id, next));
1012
+ };
1013
+ }
1014
+
1015
+ export const noteMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such credit note: '${id}'`, 404, 'resource_missing');
1016
+
1017
+ /** The credit note the request describes (the `amount` form: one custom line), or Stripe's refusal. */
1018
+ export function build(ctx: HandlerContext, id: string): Row | Response {
1019
+ const params = ctx.params;
1020
+ const invoiceId = typeof params.invoice === 'string' ? params.invoice : '';
1021
+ if (!invoiceId) return fail(ctx, 'Missing required param: invoice.', 400, 'parameter_missing');
1022
+ const invoice = ctx.get('invoice', invoiceId);
1023
+ if (!invoice) return fail(ctx, `No such invoice: '${invoiceId}'`, 404, 'resource_missing');
1024
+ if (params.amount === undefined) return fail(ctx, 'Missing required param: amount.', 400, 'parameter_missing');
1025
+ const amount = Number(params.amount);
1026
+ if (!Number.isInteger(amount) || amount <= 0) return fail(ctx, 'Invalid integer: amount must be a positive integer.', 400, 'parameter_invalid_integer');
1027
+ const vendorType = invoice.status === 'paid' ? 'post_payment' : 'pre_payment';
1028
+ const outOfBand = Number(params.out_of_band_amount) || 0;
1029
+ // a paid invoice's credit is paid back: "The sum of refunds, customer balance credits, and outside of Stripe credits
1030
+ // must equal the post_payment_amount" (docs.stripe.com/api/credit_notes/create); the message's wording is the twin's
1031
+ if (vendorType === 'post_payment') {
1032
+ const split = (Number(params.refund_amount) || 0) + (Number(params.credit_amount) || 0) + outOfBand;
1033
+ if (split !== amount) return fail(ctx, `The sum of refund_amount, credit_amount and out_of_band_amount (${split}) must equal the credit note's post_payment_amount (${amount}).`, 400, 'parameter_invalid_integer');
1034
+ }
1035
+ const line = {
1036
+ object: 'credit_note_line_item', id: `cnli_${id}_1`, type: 'custom_line_item',
1037
+ amount, description: typeof params.memo === 'string' ? params.memo : null,
1038
+ // a custom line credits no invoice line: invoice_line_item ("ID of the invoice line item being credited") is left
1039
+ // out, the served spec not letting it be null
1040
+ discount_amount: 0, discount_amounts: [], livemode: false,
1041
+ pretax_credit_amounts: [], quantity: null, tax_rates: [], taxes: [],
1042
+ unit_amount: null, unit_amount_decimal: null,
1043
+ };
1044
+ return {
1045
+ amount, amount_shipping: 0, created: nowUnix(ctx.occurredAt), currency: typeof invoice.currency === 'string' ? invoice.currency : 'usd', customer: typeof invoice.customer === 'string' ? invoice.customer : null,
1046
+ customer_balance_transaction: null,
1047
+ // "The date when this credit note is in effect. Same as `created` unless overwritten" (the served spec)
1048
+ discount_amount: 0, discount_amounts: [], effective_at: params.effective_at !== undefined ? Number(params.effective_at) : nowUnix(ctx.occurredAt), invoice: invoiceId,
1049
+ lines: { object: 'list', data: [line], has_more: false, total_count: 1, url: `/v1/credit_notes/${id}/lines` },
1050
+ livemode: false, memo: params.memo ?? null, metadata: params.metadata && typeof params.metadata === 'object' ? params.metadata : {},
1051
+ number: `${invoiceId}-CN-01`, out_of_band_amount: outOfBand || null,
1052
+ pdf: `https://files.twin.local/credit_notes/${id}.pdf`,
1053
+ post_payment_amount: vendorType === 'post_payment' ? amount : 0,
1054
+ pre_payment_amount: vendorType === 'pre_payment' ? amount : 0,
1055
+ pretax_credit_amounts: [],
1056
+ reason: typeof params.reason === 'string' ? params.reason : null,
1057
+ refunds: [], shipping_cost: null, status: 'issued',
1058
+ subtotal: amount, subtotal_excluding_tax: amount,
1059
+ type: vendorType, total: amount, total_excluding_tax: amount, total_taxes: [],
1060
+ voided_at: null,
1061
+ };
1062
+ }
1063
+
1064
+ /** The invoice's credit-note sums, from its issued credit notes; a pre-payment credit lowers what is owed. */
1065
+ export async function syncInvoice(ctx: HandlerContext, invoiceId: string): Promise<void> {
1066
+ const inv = ctx.get('invoice', invoiceId);
1067
+ if (!inv) return;
1068
+ let pre = 0;
1069
+ let post = 0;
1070
+ for (const cn of ctx.rows(CN)) {
1071
+ if (cn.invoice !== invoiceId || cn.status === 'void') continue;
1072
+ if (cn.type === 'post_payment') post += Number(cn.amount) || 0;
1073
+ else pre += Number(cn.amount) || 0;
1074
+ }
1075
+ const total = Number(inv.total ?? inv.amount_due) || 0;
1076
+ const paid = Number(inv.amount_paid) || 0;
1077
+ await ctx.write('invoice', invoiceId, { pre_payment_credit_notes_amount: pre, post_payment_credit_notes_amount: post, amount_remaining: Math.max(0, total - paid - pre) }, 'invoice.update');
1078
+ }
1079
+
1080
+ /** What a post-payment credit pays back: "Refunds: create a new refund (using refund_amount)"; "Customer balance credit:
1081
+ * credit the customer's balance (using credit_amount) which will be automatically applied to their next invoice when
1082
+ * it's finalized" (docs.stripe.com/api/credit_notes/create). The refund is made on the invoice's charge as a refund
1083
+ * call makes it (refunds.ts); the credit is a customer balance transaction of type credit_note. Where the documentation
1084
+ * stops and the twin decides: the refund carries no reason of its own. */
1085
+ export async function payBack(ctx: HandlerContext, id: string, cn: Row): Promise<Row | Response> {
1086
+ const params = ctx.params;
1087
+ const out: Row = {};
1088
+ const refundAmount = Number(params.refund_amount) || 0;
1089
+ if (refundAmount > 0) {
1090
+ const invoice = ctx.get('invoice', String(cn.invoice));
1091
+ const pi = typeof invoice?.payment_intent === 'string' ? ctx.get('payment_intent', invoice.payment_intent) : undefined;
1092
+ const chargeId = typeof invoice?.charge === 'string' ? invoice.charge : typeof pi?.latest_charge === 'string' ? pi.latest_charge : undefined;
1093
+ const charge = chargeId ? ctx.get('charge', chargeId) : undefined;
1094
+ if (!charge) return fail(ctx, 'This invoice was not paid with a charge that can be refunded.', 400, 'invoice_no_charge_to_refund');
1095
+ const answer = await refundCharge(ctx, charge, { amount: refundAmount });
1096
+ if (answer.status >= 400) return answer;
1097
+ const refund = (await answer.json()) as Row;
1098
+ out.refunds = [{ amount_refunded: refundAmount, refund: refund.id, type: 'refund', payment_record_refund: null }];
1099
+ }
1100
+ const creditAmount = Number(params.credit_amount) || 0;
1101
+ const customer = typeof cn.customer === 'string' ? cn.customer : undefined;
1102
+ if (creditAmount > 0 && customer) {
1103
+ const ending = (Number(ctx.get('customer', customer)?.balance) || 0) - creditAmount;
1104
+ const txn = await created(ctx, 'customer_balance_transaction', { customer, amount: -creditAmount, currency: cn.currency, credit_note: id, invoice: cn.invoice }, {
1105
+ ending_balance: ending, type: 'credit_note', livemode: false, metadata: {}, description: null, checkout_session: null,
1106
+ });
1107
+ await ctx.write('customer', customer, { balance: ending }, `customer.balance_adjusted:${String(txn.id)}`);
1108
+ out.customer_balance_transaction = txn.id;
1109
+ }
1110
+ return out;
1111
+ }
1112
+
1113
+ /** A coupon for a fixed amount off, in its currency (docs.stripe.com/api/coupons/create#create_coupon-amount_off). */
1114
+ export function amountOffOf(ctx: HandlerContext, params: Record<string, unknown>): number | Response {
1115
+ const amountOff = Number(params.amount_off);
1116
+ if (!Number.isInteger(amountOff) || amountOff <= 0) return fail(ctx, 'Invalid integer: amount_off must be a positive integer.', 400, 'parameter_invalid_integer');
1117
+ if (params.currency === undefined || params.currency === '') return fail(ctx, 'Missing required param: currency.', 400, 'parameter_missing');
1118
+ return amountOff;
1119
+ }
1120
+
1121
+ /** Time's lapsing of coupons, caught up to the World's clock: a valid coupon whose redeem_by has passed is no longer
1122
+ * valid from that moment (manifest.ts). Where the documentation stops and the twin decides: the lapse sends no event
1123
+ * (the events page names none for it). */
1124
+ export async function lapseCoupons(ctx: HandlerContext): Promise<void> {
1125
+ const now = Number(nowUnix(ctx.occurredAt));
1126
+ for (const c of ctx.rowsRaw('coupon')) {
1127
+ if (c.valid !== true || typeof c.redeem_by !== 'number' || c.redeem_by > now) continue;
1128
+ const t = await at_(ctx)(c.redeem_by);
1129
+ t.legal('coupon', 'valid', ctx.call.operation.id, 'true', 'false', String(c.id), 'time');
1130
+ await t.write('coupon', String(c.id), { valid: false }, 'coupon.lapsed');
1131
+ }
1132
+ }
1133
+
1134
+ export const planMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such plan: '${id}'`, 404, 'resource_missing');
1135
+
1136
+ /** A recurring price the Plans API still answers: one whose plan was deleted is not a plan any more. */
1137
+ export const recurring = (ctx: HandlerContext, p: Row | undefined): p is Row => !!p && !!p.recurring && kept(ctx, 'price', p, '_plan_deleted') !== true;
1138
+
1139
+ /** The request's line items resolved against their prices, or the refusal for a missing price. */
1140
+ export function resolved(ctx: HandlerContext): CheckoutItem[] | Response {
1141
+ const entries = lineItemEntries(ctx.params);
1142
+ const items: CheckoutItem[] = [];
1143
+ for (let i = 0; i < entries.length; i++) {
1144
+ const { item, priceMissing } = resolveLineItem(entries[i]!, i, 'usd', finder(ctx));
1145
+ if (priceMissing) return fail(ctx, `No such price: '${priceMissing}'`, 400, 'resource_missing');
1146
+ items.push(item);
1147
+ }
1148
+ return items;
1149
+ }
1150
+
1151
+ /** A page of the line items a stored object carries. */
1152
+ export function linePage(ctx: HandlerContext, holder: Row): Response {
1153
+ const li = holder.line_items as { data?: Row[] } | undefined;
1154
+ const { page, hasMore } = paginate(Array.isArray(li?.data) ? li!.data! : [], ctx.params);
1155
+ return ctx.reply({ object: 'list', url: path(ctx), has_more: hasMore, data: page });
1156
+ }
1157
+
1158
+ export const linkMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such payment link: '${id}'`, 404, 'resource_missing');
1159
+
1160
+ // ── quotes ──
1161
+
1162
+ export const quoteMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such quote: '${id}'`, 404, 'resource_missing');
10
1163
 
11
- export const send = (ctx: SemanticsContext, r: StripeResponse): Response => ctx.reply(r.body, r.status);
1164
+ export function move(action: 'finalize' | 'accept' | 'cancel', operationId: string): Handler {
1165
+ return async (ctx) => {
1166
+ const id = at(ctx, 'quote');
1167
+ const q = ctx.get('quote', id);
1168
+ if (!q) return quoteMissing(ctx, id);
1169
+ const refused = ctx.legal('quote', 'status', operationId, q.status, undefined, id);
1170
+ if (refused) return ctx.refuse(refused);
1171
+ const now = nowUnix(ctx.occurredAt);
1172
+ const stamp = action === 'finalize' ? { finalized_at: now } : action === 'accept' ? { accepted_at: now } : { canceled_at: now };
1173
+ // "Accepted quotes automatically generate an invoice, subscription, or subscription schedule"; "Quotes without
1174
+ // recurring prices: A draft invoice is created with auto_advance set to false" (docs.stripe.com/quotes/overview),
1175
+ // the quote its parent ("Details about the quote that generated this invoice", the served spec). Where the
1176
+ // documentation stops and the twin decides: a quote with recurring prices makes no subscription yet.
1177
+ let made: Row = {};
1178
+ if (action === 'accept') {
1179
+ const lines = ((q.line_items as Row | undefined)?.data as Row[] | undefined) ?? [];
1180
+ const recurring = lines.some((l) => l.price && typeof l.price === 'object' && (l.price as Row).recurring);
1181
+ if (!recurring && typeof q.customer === 'string') {
1182
+ const invoice = await draftInvoiceFor(ctx, q.customer, String(q.currency ?? 'usd'), { type: 'quote_details', quote_details: { quote: id }, subscription_details: null }, lines.map((l) => ({ price: l.price, quantity: Number(l.quantity) || 1, amount: Number(l.amount_subtotal ?? l.amount_total) || 0, description: l.description })));
1183
+ made = { invoice };
1184
+ }
1185
+ }
1186
+ return ctx.reply(
1187
+ await ctx.write('quote', id, {
1188
+ status: action === 'finalize' ? 'open' : action === 'accept' ? 'accepted' : 'canceled',
1189
+ status_transitions: { ...((q.status_transitions as Row) ?? {}), ...stamp },
1190
+ ...(action === 'finalize' ? { number: `QT-${id.toUpperCase()}` } : {}),
1191
+ ...made,
1192
+ }, `quote.${action}`),
1193
+ );
1194
+ };
1195
+ }
1196
+
1197
+ export const sessionMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such checkout.session: '${id}'`, 404, 'resource_missing');
1198
+
1199
+ // Stripe normalizes the create input into the Session: line_items become the list envelope, and
1200
+ // subscription_data (create-only) is kept aside for completion to copy onto the subscription
1201
+ /** The discount a session is created with (discounts[0][promotion_code] or [coupon]), or Stripe's refusal: an unknown
1202
+ * code or coupon, and one that has expired or been deactivated, are refused at create
1203
+ * (docs.stripe.com/api/checkout/sessions/create#create_checkout_session-discounts, docs.stripe.com/error-codes#coupon-expired).
1204
+ * Where the documentation stops and the twin decides: the refusals' wording. */
1205
+ export function discountOf(ctx: HandlerContext, params: Row, now: number): { coupon: Row; promotion?: string } | Response | undefined {
1206
+ const first = Array.isArray(params.discounts) ? (params.discounts[0] as Row | undefined) : undefined;
1207
+ if (!first || typeof first !== 'object') return undefined;
1208
+ const expired = (what: string) => ctx.refuse({ status: 400, code: 'coupon_expired', param: 'discounts', message: `This ${what} has expired.` });
1209
+ let promotion: string | undefined;
1210
+ let couponId = typeof first.coupon === 'string' ? first.coupon : undefined;
1211
+ if (typeof first.promotion_code === 'string') {
1212
+ const pc = ctx.get('promotion_code', first.promotion_code);
1213
+ if (!pc) return ctx.refuse({ status: 400, code: 'resource_missing', param: 'discounts[0][promotion_code]', message: `No such promotion code: '${first.promotion_code}'` });
1214
+ if (typeof pc.expires_at === 'number' && pc.expires_at <= now) return expired('promotion code');
1215
+ if (pc.active === false) return ctx.refuse({ status: 400, param: 'discounts[0][promotion_code]', message: 'This promotion code is inactive.' });
1216
+ promotion = String(pc.id);
1217
+ couponId = typeof pc.coupon === 'string' ? pc.coupon : String((pc.coupon as Row | undefined)?.id ?? '');
1218
+ }
1219
+ const coupon = couponId ? ctx.get('coupon', couponId) : undefined;
1220
+ if (!coupon) return ctx.refuse({ status: 400, code: 'resource_missing', param: 'discounts[0][coupon]', message: `No such coupon: '${couponId ?? ''}'` });
1221
+ if (coupon.valid === false || (typeof coupon.redeem_by === 'number' && coupon.redeem_by <= now)) return expired('coupon');
1222
+ return { coupon, ...(promotion ? { promotion } : {}) };
1223
+ }
1224
+
1225
+ /** A payment or subscription session with nothing to sell (docs.stripe.com/api/checkout/sessions/create#create_checkout_session-line_items). */
1226
+ export function noLineItems(ctx: HandlerContext): Response {
1227
+ return fail(ctx, 'You must provide at least one recurring price in `subscription` mode when not using `line_items[].price_data` or a Price with `recurring`, and at least one `line_items` for `payment` mode.', 400, 'parameter_missing');
1228
+ }
1229
+
1230
+ /** A destination charge to an account the platform does not have (docs.stripe.com/connect/destination-charges). */
1231
+ export function checkoutNoDestination(ctx: HandlerContext, destination: unknown): Response {
1232
+ return ctx.refuse({ status: 400, code: 'resource_missing', param: 'payment_intent_data[transfer_data][destination]', message: `No such destination: '${String(destination)}'` });
1233
+ }
1234
+
1235
+ /** A session's trial Stripe refuses: `subscription_data.trial_end` "Has to be at least 48 hours in the future", and
1236
+ * `subscription_data.trial_period_days` "Has to be at least 1" (docs.stripe.com/api/checkout/sessions/create). Where the
1237
+ * documentation stops and the twin decides: the refusals' wording. */
1238
+ export function sessionTrialRefused(ctx: HandlerContext, data: unknown, now: number): Response | undefined {
1239
+ if (!data || typeof data !== 'object') return undefined;
1240
+ const { trial_end: end, trial_period_days: days } = data as Row;
1241
+ const endRefused = end !== undefined && !(Number.isInteger(Number(end)) && Number(end) >= now + 48 * 3600);
1242
+ const daysRefused = days !== undefined && !(Number.isInteger(Number(days)) && Number(days) >= 1);
1243
+ return endRefused || daysRefused ? sessionTrialRefusal(ctx, endRefused ? 'trial_end' : 'trial_period_days') : undefined;
1244
+ }
1245
+
1246
+ export function sessionTrialRefusal(ctx: HandlerContext, param: 'trial_end' | 'trial_period_days'): Response {
1247
+ const message = param === 'trial_end' ? 'The `subscription_data[trial_end]` timestamp has to be at least 48 hours in the future.' : 'The `subscription_data[trial_period_days]` has to be at least 1.';
1248
+ return ctx.refuse({ status: 400, param: `subscription_data[${param}]`, message });
1249
+ }
1250
+
1251
+ /** What completing a session makes, by its mode, as the fields that link it: a payment is a PaymentIntent paid with
1252
+ * the entered card, its charge in the ledger as any payment's is. */
1253
+ export async function complete(ctx: HandlerContext, id: string, existing: Row, card?: EnteredCard): Promise<Row> {
1254
+ const link: Row = { status: 'complete' };
1255
+ const customer = typeof existing.customer === 'string' ? existing.customer : undefined;
1256
+ const currency = typeof existing.currency === 'string' ? existing.currency : 'usd';
1257
+ // the entered card becomes a PaymentMethod carrying what a later charge to it answers and what Stripe does after it
1258
+ // succeeds (docs.stripe.com/testing#declined-payments, #disputes)
1259
+ const made = card ? await created(ctx, 'payment_method', {}, { type: 'card', customer: null, livemode: false, billing_details: { address: null, email: null, name: null, phone: null }, ...paymentMethodSubObject('card', { card }), _declineOutcome: declineFor(() => undefined, { card }) ?? null, ...(afterSuccessOf(ctx, card) ? { _afterSuccess: afterSuccessOf(ctx, card) } : {}) }) : undefined;
1260
+ // and Checkout attaches it to the customer when it saves it: a subscription's card ("If your Checkout Session uses
1261
+ // subscription mode, Stripe saves the payment method by default", docs.stripe.com/payments/checkout/how-checkout-works),
1262
+ // a setup session's (it exists to save one), and a payment's only under payment_intent_data.setup_future_usage ("to have
1263
+ // Checkout automatically attach the payment method to the Customer you pass in", docs.stripe.com/api/checkout/sessions/
1264
+ // create#create_checkout_session-customer). Attaching is its own write, so payment_method.attached is delivered ("Occurs
1265
+ // whenever a new payment method is attached to a customer", docs.stripe.com/api/events/types) before what the card then
1266
+ // pays for. Where the documentation stops and the twin decides: the order of the events, which Stripe does not
1267
+ // guarantee (docs.stripe.com/webhooks#event-ordering). A gap: the customer's own opt-in to save a payment's card
1268
+ // (saved_payment_method_options.payment_method_save) is not modelled; the page offers no such box.
1269
+ const saves = existing.mode !== 'payment' || !!((ctx.row(CS, id)?._payment_intent_data ?? {}) as Row).setup_future_usage;
1270
+ const pm = made && customer && saves ? await ctx.write('payment_method', String(made.id), { customer }, 'payment_method.attach') : made;
1271
+ if (existing.mode === 'payment') {
1272
+ const amount = Number(existing.amount_total) || 0;
1273
+ const piId = ctx.mint('payment_intent');
1274
+ const pid = (ctx.row(CS, id)?._payment_intent_data ?? {}) as Row;
1275
+ const connect = {
1276
+ ...(pid.application_fee_amount !== undefined ? { application_fee_amount: Math.trunc(Number(pid.application_fee_amount) || 0) } : {}),
1277
+ ...(pid.transfer_data && typeof pid.transfer_data === 'object' ? { transfer_data: { destination: (pid.transfer_data as Row).destination } } : {}),
1278
+ ...(typeof pid.description === 'string' ? { description: pid.description } : {}),
1279
+ // the session's setup_future_usage is its PaymentIntent's (payment_intent_data: "A subset of parameters to be passed to PaymentIntent creation")
1280
+ ...(typeof pid.setup_future_usage === 'string' ? { setup_future_usage: pid.setup_future_usage } : {}),
1281
+ ...(nestedMetadata(pid.metadata) ? { metadata: nestedMetadata(pid.metadata) } : {}),
1282
+ };
1283
+ const fields = { amount, currency, id: piId, ...(customer ? { customer } : {}), ...(pm ? { payment_method: pm.id } : {}), ...connect };
1284
+ await created(ctx, 'payment_intent', fields, { status: 'succeeded', amount_received: amount, client_secret: mintClientSecret(piId, await ctx.secret(`client-secret:${piId}`)), livemode: false, payment_method_types: Array.isArray(existing.payment_method_types) ? existing.payment_method_types : ['card'] });
1285
+ const charge = await mintCharge(ctx, piId, fields, amount);
1286
+ await ctx.write('payment_intent', piId, { latest_charge: charge }, 'payment_intent.succeeded');
1287
+ link.payment_intent = piId;
1288
+ link.payment_status = 'paid';
1289
+ } else if (existing.mode === 'subscription') {
1290
+ if (customer) {
1291
+ // the subscription bills the session's own (already resolved) line items, and takes the
1292
+ // session's subscription_data: metadata, description, and a trial as its first period
1293
+ const now = Number(nowUnix(ctx.occurredAt));
1294
+ // "Line items with one-time Prices will be on the initial invoice only" (docs.stripe.com/api/checkout/sessions/
1295
+ // create#create_checkout_session-line_items): the subscription's items are the recurring ones
1296
+ const inline = (ctx.row(CS, id)?._price_data as Array<Row | null> | undefined) ?? [];
1297
+ const lines = ((existing.line_items as { data?: unknown } | undefined)?.data as Row[] | undefined) ?? [];
1298
+ const allLineItems = inline.some(Boolean) ? await sessionPrices(ctx, lines, inline) : lines;
1299
+ const sessionLineItems = allLineItems.filter((it) => !isOneTime(it));
1300
+ const oneTime = allLineItems.filter((it) => isOneTime(it));
1301
+ const { interval, interval_count } = resolveSubscriptionBillingInterval(sessionLineItems, finder(ctx));
1302
+ const subId = ctx.mint('subscription');
1303
+ // the session's view never carries its create-only subscription_data: read the stored row
1304
+ const raw = ctx.row(CS, id)?._subscription_data;
1305
+ const subData = (raw && typeof raw === 'object' ? raw : {}) as Row;
1306
+ const subMetadata = nestedMetadata(subData.metadata) ?? {};
1307
+ // a trial of `trial_period_days` from now, or to `trial_end` (docs.stripe.com/payments/checkout/free-trials)
1308
+ const trialEnd = resolveTrial(subData, now)?.end ?? null;
1309
+ const sub = await created(ctx, 'subscription', { customer, id: subId }, {
1310
+ status: trialEnd === null ? 'active' : 'trialing', livemode: false, currency, collection_method: 'charge_automatically',
1311
+ // a trial's end is the billing anchor (docs.stripe.com/api/subscriptions/create#create_subscription-trial_end)
1312
+ cancel_at_period_end: false, start_date: now, billing_cycle_anchor: trialEnd ?? now, metadata: subMetadata,
1313
+ description: typeof subData.description === 'string' ? subData.description : null,
1314
+ // the session's discount is the subscription's (docs.stripe.com/payments/checkout/discounts)
1315
+ discounts: sessionDiscount(ctx, id, customer, now), billing_schedules: [],
1316
+ trial_start: trialEnd === null ? null : now, trial_end: trialEnd,
1317
+ current_period_start: now, current_period_end: trialEnd ?? addBillingInterval(now, interval, interval_count),
1318
+ // Checkout saves the card as the subscription's default payment method (docs.stripe.com/payments/checkout/how-checkout-works)
1319
+ default_payment_method: pm?.id ?? null,
1320
+ items: buildSubscriptionItemsList(sessionLineItems, subId, now, finder(ctx)),
1321
+ automatic_tax: { enabled: false, liability: null }, billing_mode: { type: 'classic' },
1322
+ invoice_settings: { issuer: { type: 'self' } },
1323
+ });
1324
+ await storeItems(ctx, subId, ((sub.items as Row | undefined)?.data as Row[] | undefined) ?? []);
1325
+ // its first invoice, paid on the page by the card just entered (nothing is due on a trial's)
1326
+ // (docs.stripe.com/billing/subscriptions/overview#how-payments-work-subscriptions)
1327
+ const invoice = await draftSubscriptionInvoice(ctx, sub, { start: now, end: Number(sub.current_period_end), reason: 'subscription_create', trial: trialEnd !== null, once: oneTime });
1328
+ await collectSubscriptionInvoice(ctx, invoice, now, 'external');
1329
+ await ctx.write('subscription', subId, { latest_invoice: invoice }, 'subscription.update');
1330
+ link.subscription = sub.id;
1331
+ link.invoice = invoice;
1332
+ }
1333
+ link.payment_status = 'paid';
1334
+ } else link.setup_intent = await completeSetup(ctx, customer, pm);
1335
+ return link;
1336
+ }
1337
+
1338
+ /** A subscription session's lines at completion, each inline `price_data` made the Price it generates ("Data used to
1339
+ * generate a new Price object inline", the same page), under the product it names or one made from its product_data,
1340
+ * so the subscription's items bill it. Where the documentation stops and the twin decides: such a Price is archived
1341
+ * (active=false), as a subscription item's price_data makes one (docs.stripe.com/products-prices/manage-prices). */
1342
+ export async function sessionPrices(ctx: HandlerContext, lines: Row[], inline: Array<Row | null>): Promise<Row[]> {
1343
+ const out: Row[] = [];
1344
+ for (const [i, line] of lines.entries()) {
1345
+ const d = inline[i];
1346
+ if (!d) { out.push(line); continue; }
1347
+ const pd = d.product_data && typeof d.product_data === 'object' ? (d.product_data as Row) : undefined;
1348
+ const product = typeof d.product === 'string' ? d.product : String((await created(ctx, 'product', { name: pd?.name ?? 'Item' }, { active: true, livemode: false, images: [], marketing_features: [], metadata: {}, updated: nowUnix(ctx.occurredAt) })).id);
1349
+ const r = d.recurring && typeof d.recurring === 'object' ? (d.recurring as Row) : undefined;
1350
+ const price = await created(ctx, 'price', {
1351
+ product, currency: String(d.currency ?? line.currency ?? 'usd').toLowerCase(),
1352
+ unit_amount: d.unit_amount_decimal !== undefined ? null : Math.trunc(Number(d.unit_amount) || 0),
1353
+ unit_amount_decimal: d.unit_amount_decimal !== undefined ? String(d.unit_amount_decimal) : String(Math.trunc(Number(d.unit_amount) || 0)),
1354
+ ...(r ? { recurring: { interval: r.interval, interval_count: Math.max(1, Math.trunc(Number(r.interval_count ?? 1)) || 1), usage_type: 'licensed', trial_period_days: null, meter: null } } : { recurring: null }),
1355
+ }, { active: false, livemode: false, billing_scheme: 'per_unit', type: r ? 'recurring' : 'one_time', metadata: {}, lookup_key: null, nickname: null, tax_behavior: 'unspecified' });
1356
+ out.push({ ...line, price });
1357
+ }
1358
+ return out;
1359
+ }
1360
+
1361
+ /** A setup session saves the card through a succeeded SetupIntent (docs.stripe.com/payments/save-and-reuse?platform=checkout). */
1362
+ export async function completeSetup(ctx: HandlerContext, customer: string | undefined, pm: Row | undefined): Promise<unknown> {
1363
+ const siId = ctx.mint('setup_intent');
1364
+ const si = await created(ctx, 'setup_intent', { id: siId, ...(customer ? { customer } : {}), ...(pm ? { payment_method: pm.id } : {}) }, { status: 'succeeded', usage: 'off_session', client_secret: mintClientSecret(siId, await ctx.secret(`client-secret:${siId}`)), payment_method_types: ['card'], livemode: false });
1365
+ return si.id;
1366
+ }
1367
+
1368
+ /** The discount a completed subscription session gives its subscription. */
1369
+ export function sessionDiscount(ctx: HandlerContext, id: string, customer: string, now: number): Row[] {
1370
+ const d = ctx.row(CS, id)?._discount as Row | undefined;
1371
+ const coupon = d && typeof d.coupon === 'string' ? ctx.get('coupon', d.coupon) : undefined;
1372
+ return coupon ? [{ ...buildDiscount(coupon, customer, now), promotion_code: d?.promotion_code ?? null, checkout_session: id }] : [];
1373
+ }
1374
+
1375
+ /** The customer paying on the hosted page (src/screens/checkout.tsx): the external actor's move on the
1376
+ * session's machine, then what the payment made, linked, and the session stored complete. */
1377
+ export async function completeSession(ctx: HandlerContext, id: string, existing: Row, details: Row = {}, card?: EnteredCard): Promise<Row | Response> {
1378
+ const refused = ctx.legal(CS, 'status', 'PostCheckoutSessionsSession', existing.status, 'complete', id, 'external');
1379
+ if (refused) return ctx.refuse(refused);
1380
+ const link = await complete(ctx, id, existing, card);
1381
+ // the discount the buyer took is redeemed (shared.ts redeemCoupon)
1382
+ const d = ctx.row(CS, id)?._discount as Row | undefined;
1383
+ if (d) await redeemCoupon(ctx, d.coupon, d.promotion_code);
1384
+ // the session's url "is only present when the session is active" (docs.stripe.com/api/checkout/sessions/object)
1385
+ return ctx.write(CS, id, { ...details, ...link, url: null }, 'checkout.session.completed');
1386
+ }
1387
+
1388
+ export const send = (ctx: HandlerContext, r: StripeResponse): Response => ctx.reply(r.body, r.status);
12
1389
 
13
1390
  /** Stripe's error body: an invalid_request_error with the message, and the code when there is one. */
14
- export const fail = (ctx: SemanticsContext, message: string, status = 404, code?: string): Response => ctx.refuse({ status, message, ...(code ? { code } : {}) });
1391
+ export const fail = (ctx: HandlerContext, message: string, status = 404, code?: string): Response => ctx.refuse({ status, message, ...(code ? { code } : {}) });
15
1392
 
16
1393
  /** A file parameter whose description requires a purpose refuses a file of another one. The served spec requires it
17
1394
  * on every such parameter ("Must have a `purpose` value of `issuing_logo`", personalization designs' card_logo;
18
1395
  * "The file's `purpose` must be one of the following: …", file links' file). Where the documentation stops and the
19
1396
  * twin decides: Stripe documents no error for it (docs.stripe.com/error-codes names none), so the twin answers the
20
1397
  * 400 invalid_request_error it answers for an unknown file, naming the parameter and the purposes allowed. */
21
- export function filePurposeRefused(ctx: SemanticsContext, param: string, allowed: readonly string[]): Response | undefined {
1398
+ export function filePurposeRefused(ctx: HandlerContext, param: string, allowed: readonly string[]): Response | undefined {
22
1399
  const given = ctx.params[param];
23
1400
  if (given === undefined || given === '') return undefined;
24
1401
  const file = ctx.get('file', String(given));
@@ -29,15 +1406,15 @@ export function filePurposeRefused(ctx: SemanticsContext, param: string, allowed
29
1406
  }
30
1407
 
31
1408
  /** The request's path, as the list envelope's `url` carries it. */
32
- export const path = (ctx: SemanticsContext): string => new URL(ctx.call.request.url).pathname.replace(/\/+$/, '') || '/';
1409
+ export const path = (ctx: HandlerContext): string => new URL(ctx.call.request.url).pathname.replace(/\/+$/, '') || '/';
33
1410
 
34
1411
  /** A path parameter, by the name the spec gives it. */
35
- export const at = (ctx: SemanticsContext, name: string): string => ctx.call.params[name] ?? '';
1412
+ export const at = (ctx: HandlerContext, name: string): string => ctx.call.params[name] ?? '';
36
1413
 
37
1414
  /** An update's fields laid over what is stored, as the derived core does: a nested hash is merged into the stored one,
38
1415
  * not put in its place (Stripe updates only the keys a request names; docs.stripe.com/api/metadata and each update
39
1416
  * reference), and an empty string unsets a key. */
40
- export function mergeUpdate(ctx: SemanticsContext, resource: string, id: string, fields: Row): Row {
1417
+ export function mergeUpdate(ctx: HandlerContext, resource: string, id: string, fields: Row): Row {
41
1418
  const current = ctx.get(resource, id) ?? {};
42
1419
  const out: Row = {};
43
1420
  for (const [k, v] of Object.entries(fields)) {
@@ -49,27 +1426,14 @@ export function mergeUpdate(ctx: SemanticsContext, resource: string, id: string,
49
1426
  return out;
50
1427
  }
51
1428
 
52
- /** The tree's type for a resource: what its rows are stored under. */
53
- export const stored = (resource: string): string => manifest.resources[resource]?.storedAs ?? resource;
54
-
55
1429
  /** A resource's rows in Stripe's list order: newest first by `timeField`, ties by mint order (as the derived core breaks them). */
56
1430
  /** A subject's bookkeeping field (`_…`): kept on the stored row, never in the wire view ctx.get and ctx.rows answer. */
57
- export const kept = (ctx: SemanticsContext, resource: string, row: Row, key: string): unknown => ctx.row(resource, String(row.id), { withDeleted: true })?.[key];
58
-
59
- /** A removed discount as Stripe answers it: the discount, marked deleted (docs.stripe.com/api/discounts/delete). */
60
- export function deletedDiscount(d: Row, now: unknown): Row {
61
- const coupon = d.coupon && typeof d.coupon === 'object' ? String((d.coupon as Row).id) : typeof d.coupon === 'string' ? d.coupon : null;
62
- return {
63
- id: d.id ?? `di_${coupon ?? 'twin'}`, object: 'discount', deleted: true, checkout_session: d.checkout_session ?? null, customer: d.customer ?? null,
64
- invoice: d.invoice ?? null, invoice_item: d.invoice_item ?? null, promotion_code: d.promotion_code ?? null, subscription: d.subscription ?? null,
65
- subscription_item: d.subscription_item ?? null, source: d.source ?? { type: 'coupon', coupon }, start: d.start ?? now,
66
- };
67
- }
1431
+ export const kept = (ctx: HandlerContext, resource: string, row: Row, key: string): unknown => ctx.row(resource, String(row.id), { withDeleted: true })?.[key];
68
1432
 
69
1433
  /** A create's parameter that describes a confirmation, sent without confirm=true: the served spec gives each "This
70
1434
  * parameter can only be used with `confirm=true`" (off_session: "can only be used when confirm=true"); the message's
71
1435
  * wording is the twin's. Answers the refusal, or undefined. */
72
- export function confirmOnly(ctx: SemanticsContext, names: string[], confirm: boolean): Response | undefined {
1436
+ export function confirmOnly(ctx: HandlerContext, names: string[], confirm: boolean): Response | undefined {
73
1437
  const sent = confirm ? undefined : names.find((n) => ctx.params[n] !== undefined);
74
1438
  return sent ? fail(ctx, `\`${sent}\` can only be used when \`confirm\` is set to \`true\`.`, 400, 'parameter_invalid') : undefined;
75
1439
  }
@@ -78,40 +1442,35 @@ export function confirmOnly(ctx: SemanticsContext, names: string[], confirm: boo
78
1442
  * applied to a customer" (the served spec's coupon), counts it, as the code's "Number of times this promotion code
79
1443
  * has been used" (its promotion_code). Where the documentation stops and the twin decides: reaching max_redemptions
80
1444
  * does not yet lapse the coupon. */
81
- export async function redeemCoupon(ctx: SemanticsContext, couponId: unknown, promotionCode?: unknown): Promise<void> {
1445
+ export async function redeemCoupon(ctx: HandlerContext, couponId: unknown, promotionCode?: unknown): Promise<void> {
82
1446
  const coupon = typeof couponId === 'string' ? ctx.get('coupon', couponId) : undefined;
83
1447
  if (coupon) await ctx.write('coupon', couponId as string, { times_redeemed: (Number(coupon.times_redeemed) || 0) + 1 }, 'coupon.redeemed');
84
1448
  const code = typeof promotionCode === 'string' ? ctx.get('promotion_code', promotionCode) : undefined;
85
1449
  if (code) await ctx.write('promotion_code', promotionCode as string, { times_redeemed: (Number(code.times_redeemed) || 0) + 1 }, 'promotion_code.redeemed');
86
1450
  }
87
1451
 
88
- export function newest(ctx: SemanticsContext, resource: string, timeField = 'created'): Row[] {
1452
+ export function newest(ctx: HandlerContext, resource: string, timeField = 'created'): Row[] {
89
1453
  // an object Stripe gives no creation time is ordered by the one the twin keeps for it
90
1454
  const raw = new Map(ctx.rowsRaw(resource).map((r) => [String(r.id), r]));
91
1455
  const when = (r: Row): number => Number(r[timeField] ?? raw.get(String(r.id))?._created ?? 0);
92
- return ctx.rows(resource).sort((a, b) => {
1456
+ // ties by the order the World made them (an event's id is a digest, not a count)
1457
+ const rows = ctx.rows(resource);
1458
+ const made = new Map(rows.map((r, i) => [r, i]));
1459
+ return rows.sort((a, b) => {
93
1460
  const ta = when(a), tb = when(b);
94
1461
  if (tb !== ta) return tb - ta;
95
- return String(b.id).localeCompare(String(a.id), undefined, { numeric: true });
1462
+ return made.get(b)! - made.get(a)!;
96
1463
  });
97
1464
  }
98
1465
 
99
- /** Keep the rows whose field equals the request's parameter of the same name, for each name given. */
100
- /** A list's range filter on a unix time (`created[gte]=…&created[lt]=…`, or one exact time). */
101
- export function inRange(t: unknown, v: unknown): boolean {
102
- const at = Number(t);
103
- const r = (v && typeof v === 'object' ? v : { gte: v, lte: v }) as Row;
104
- return (r.gt === undefined || at > Number(r.gt)) && (r.gte === undefined || at >= Number(r.gte)) && (r.lt === undefined || at < Number(r.lt)) && (r.lte === undefined || at <= Number(r.lte));
105
- }
106
-
107
1466
  /** A context at the moment Stripe would have made a move time makes (a renewal, a payout on its schedule), so what
108
1467
  * the move writes carries that moment (its events' occurredAt, `created`, a charge's funds' available_on), not the
109
1468
  * moment a later request caught it up. */
110
- export function at_(ctx: SemanticsContext): (t: number) => Promise<SemanticsContext> {
1469
+ export function at_(ctx: HandlerContext): (t: number) => Promise<HandlerContext> {
111
1470
  return (t) => ctx.at(new Date(t * 1000).toISOString());
112
1471
  }
113
1472
 
114
- export function where(ctx: SemanticsContext, items: Row[], spec: Record<string, (item: Row, value: unknown) => boolean>): Row[] {
1473
+ export function where(ctx: HandlerContext, items: Row[], spec: Record<string, (item: Row, value: unknown) => boolean>): Row[] {
115
1474
  let out = items;
116
1475
  for (const [key, pred] of Object.entries(spec)) {
117
1476
  const value = ctx.params[key];
@@ -120,107 +1479,1734 @@ export function where(ctx: SemanticsContext, items: Row[], spec: Record<string,
120
1479
  return out;
121
1480
  }
122
1481
 
123
- function expandPaths(ctx: SemanticsContext): string[][] {
1482
+ export function expandPaths(ctx: HandlerContext): string[][] {
124
1483
  const expand = ctx.params.expand;
125
1484
  return Array.isArray(expand) ? expand.map((p) => String(p).split('.')) : [];
126
1485
  }
127
1486
 
128
1487
  /** A balance transaction as the clock reads it: available once its available_on has passed, the clock's move,
129
- * asked of the machine as a write asks it (semantics/ledger.ts). */
130
- export function asOf(ctx: SemanticsContext, t: Row): Row {
1488
+ * asked of the machine as a write asks it (./ledger.ts). */
1489
+ export function commonAsOf(ctx: HandlerContext, t: Row): Row {
131
1490
  const due = Number(t.available_on);
132
- if (t.status !== 'pending' || !Number.isFinite(due) || due > Number(ctx.now())) return t;
1491
+ if (t.status !== 'pending' || !Number.isFinite(due) || due > Number(nowUnix(ctx.occurredAt))) return t;
133
1492
  ctx.legal('balance_transaction', 'status', ctx.call.operation.id, 'pending', 'available', String(t.id), 'time');
134
1493
  return { ...t, status: 'available' };
135
1494
  }
136
1495
 
137
- /** Stripe's expand walk: each dotted path replaces an id with the resource the manifest says it
138
- * holds, one segment at a time; an id the tree lacks stays an id. A balance transaction reads as the clock has it
139
- * (asOf), as its own retrieve does. */
140
- export function expandRow(ctx: SemanticsContext, resource: string, body: Row, paths: string[][]): Row {
141
- const embeds = manifest.resources[resource]?.embeds;
142
- if (!embeds || paths.length === 0) return body;
143
- let out = body;
144
- const byHead = new Map<string, string[][]>();
145
- for (const p of paths) {
146
- if (p.length === 0) continue;
147
- const list = byHead.get(p[0]!) ?? [];
148
- list.push(p.slice(1));
149
- byHead.set(p[0]!, list);
150
- }
151
- for (const [head, tails] of byHead) {
152
- const target = embeds[head];
153
- if (!target) continue;
154
- const cur = out[head];
155
- const found = typeof cur === 'string' && cur ? ctx.get(target, cur) : cur && typeof cur === 'object' && !Array.isArray(cur) ? (cur as Row) : undefined;
156
- if (!found) continue;
157
- const sub = target === 'balance_transaction' ? asOf(ctx, found) : found;
158
- const deeper = tails.filter((t) => t.length > 0);
159
- out = { ...out, [head]: deeper.length ? expandRow(ctx, target, sub, deeper) : sub };
160
- }
161
- return out;
1496
+ /** Stripe's expand walk (the kernel's, over the manifest's `embeds`): each dotted path replaces an id with the resource
1497
+ * it holds, one segment at a time; an id the tree lacks stays an id. An embedded balance transaction reads as the clock
1498
+ * has it (asOf), as its own retrieve does. */
1499
+ export function expandRow(ctx: HandlerContext, resource: string, body: Row, paths: string[][]): Row {
1500
+ if (paths.length === 0) return body;
1501
+ const asOf = (v: unknown): unknown => {
1502
+ if (Array.isArray(v)) return v.map(asOf);
1503
+ if (!v || typeof v !== 'object') return v;
1504
+ const o = Object.fromEntries(Object.entries(v as Row).map(([k, x]) => [k, asOf(x)]));
1505
+ return o.object === 'balance_transaction' ? commonAsOf(ctx, o) : o;
1506
+ };
1507
+ const out = ctx.expand(resource, body, paths.map((p) => p.join('.')));
1508
+ return Object.fromEntries(Object.entries(out).map(([k, v]) => [k, asOf(v)]));
162
1509
  }
163
1510
 
164
1511
  /** One resource with the request's `expand[]` applied. */
165
- export const expanded = (ctx: SemanticsContext, resource: string, body: Row): Row => expandRow(ctx, resource, body, expandPaths(ctx));
1512
+ export const expanded = (ctx: HandlerContext, resource: string, body: Row): Row => expandRow(ctx, resource, body, expandPaths(ctx));
166
1513
 
167
1514
  /** Stripe's list envelope over rows already in list order: a page, `has_more`, and `expand[]=data.*`. */
168
- export function list(ctx: SemanticsContext, resource: string, items: Row[]): Response {
1515
+ export function list(ctx: HandlerContext, resource: string, items: Row[]): Response {
169
1516
  const { page, hasMore } = paginate(items, ctx.params);
170
1517
  const paths = expandPaths(ctx).filter((p) => p[0] === 'data').map((p) => p.slice(1)).filter((p) => p.length > 0);
171
1518
  return ctx.reply({ object: 'list', url: path(ctx), has_more: hasMore, data: paths.length ? page.map((r) => expandRow(ctx, resource, r, paths)) : page });
172
1519
  }
173
1520
 
174
1521
  /** Stripe's search over a resource's rows (`query` in its search language). */
175
- export const search = (ctx: SemanticsContext, resource: string, timeField = 'created'): Response => send(ctx, searchOver(newest(ctx, resource, timeField), ctx.params, path(ctx)));
176
-
177
- const SPEC_FIELDS = new Map((surface.resources as Array<{ name: string; fields: Array<{ name: string }> }>).map((r) => [r.name, new Set(r.fields.map((f) => f.name))]));
1522
+ export const search = (ctx: HandlerContext, resource: string, timeField = 'created'): Response => send(ctx, searchOver(newest(ctx, resource, timeField), ctx.params, path(ctx)));
178
1523
 
179
1524
  /** A create as Stripe stamps it: the caller's id when it gave one (seeding uses real ids), else a
180
1525
  * minted one; `object`, the creation time, the defaults, then the request's own fields. An object
181
1526
  * Stripe gives no creation time keeps the twin's as `_created`, for ordering. (A request parameter the
182
1527
  * object has no field for stays on the row, where the rules read it; the wire answer leaves it out,
183
- * stripe-version.ts.) */
184
- export async function created(ctx: SemanticsContext, resource: string, params: Row, defaults: Row, opts: { timeField?: string; operation?: string } = {}): Promise<Row> {
1528
+ * ./version.ts.) */
1529
+ export async function created(ctx: HandlerContext, resource: string, params: Row, defaults: Row, opts: { timeField?: string; operation?: string } = {}): Promise<Row> {
185
1530
  const { id: provided, ...rest } = params;
186
- const type = stored(resource);
1531
+ const type = ctx.storedType(resource);
187
1532
  const id = typeof provided === 'string' && provided ? provided : ctx.mint(resource);
188
1533
  const known = SPEC_FIELDS.get(resource);
189
1534
  const timeField = opts.timeField ?? 'created';
190
1535
  const stamped = !known || known.has(timeField) || timeField in defaults || timeField in rest ? timeField : '_created';
191
- const fields = stashVendorType(type, { object: OBJECT_NAME[type] ?? type, [stamped]: ctx.now(), ...defaults, ...rest });
1536
+ const fields = { object: OBJECT_NAME[type] ?? type, [stamped]: nowUnix(ctx.occurredAt), ...defaults, ...rest };
192
1537
  return ctx.write(resource, id, fields, opts.operation ?? `${type}.create`);
193
1538
  }
194
1539
 
195
- /** A stored subject of any stored type, tombstones included, in the pack's view: what the pack's
196
- * shared helpers look a price, a payment method or a card up by, read from the context's tree. */
197
- export type Find = (storedType: string, id: string) => Row | undefined;
198
- export const finder = (ctx: SemanticsContext): Find => {
199
- const tree = ctx.tree();
200
- return (storedType, id) => {
201
- const r = tree.find((x) => x.type === storedType && x.id === id);
202
- return r ? view(storedType, r) : undefined;
203
- };
1540
+ export const finder = (ctx: Pick<HandlerContext, 'rowsRaw'>): Find => (storedType, id) => {
1541
+ const r = ctx.rowsRaw(storedType, { withDeleted: true }).find((x) => x.id === id);
1542
+ return r ? view(storedType, r as TwinResource) : undefined;
204
1543
  };
205
1544
 
206
- /** A refund's destination_details for a card charge: "If this is a `card` refund, this hash contains the transaction
207
- * specific details" and its `type` "can be `refund`, `reversal`, or `pending`" — a reversal, where "The original charge
208
- * will drop off the bank statement altogether", for an authorization released uncaptured, else a refund, "a credit entry
209
- * on the bank statement" (docs.stripe.com/api/refunds/object). The network's reference number the twin never has. A
210
- * charge not paid by card answers none. */
211
- export function refundDestination(charge: Row, type: 'refund' | 'reversal'): Row {
212
- const pmd = charge.payment_method_details as Row | null | undefined;
213
- if (pmd && pmd.type !== 'card') return {};
214
- return { destination_details: { type: 'card', card: { reference: null, reference_status: null, reference_type: null, type } } };
215
- }
216
-
217
- /** An account's external_accounts, "External accounts (bank accounts and debit cards) currently attached to this
218
- * account" (docs.stripe.com/api/accounts/object), as the list its example answers. */
219
- export const externalList = (account: string, data: Row[]): Row => ({ object: 'list', data, has_more: false, total_count: data.length, url: `/v1/accounts/${account}/external_accounts` });
220
-
221
1545
  /** The account's external_accounts list, rewritten from its external accounts after one is added or removed. */
222
- export async function syncExternals(ctx: SemanticsContext, account: string): Promise<void> {
1546
+ export async function syncExternals(ctx: HandlerContext, account: string): Promise<void> {
223
1547
  if (!ctx.get('account', account)) return;
224
1548
  await ctx.write('account', account, { external_accounts: externalList(account, newest(ctx, 'external_account').filter((e) => e.account === account)) }, 'account.external_accounts');
225
1549
  }
226
1550
 
1551
+ /** A decision over the rows and the write it makes, taken together: the read and the write follow one another with
1552
+ * nothing between them (a code spent once, a connection revoked once). */
1553
+ export async function decide<T>(ctx: HandlerContext, decision: (rows: (resource: string) => Row[]) => { value: T; write?: { resource: string; id: string; fields: Row; operation: string } }): Promise<T> {
1554
+ const d = decision((resource) => ctx.rowsRaw(resource));
1555
+ if (d.write) await ctx.write(d.write.resource, d.write.id, d.write.fields, d.write.operation);
1556
+ return d.value;
1557
+ }
1558
+
1559
+ export const catalog = (ctx: HandlerContext, data: Row[]): Response => ctx.reply({ object: 'list', url: path(ctx), has_more: false, data });
1560
+
1561
+ export const orderMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such order: '${id}'`, 404, 'resource_missing');
1562
+
1563
+ /** Each pending report run completes, caught up before anything is answered: "When the run completes, Stripe updates
1564
+ * the object, and it has a status of succeeded. It also has a nested result object, containing a URL that you can use
1565
+ * to access the file", the guide's example a File of purpose report_run and type csv (docs.stripe.com/reports/api).
1566
+ * "Most runs complete within a few minutes" (the same page). Where the documentation stops and the twin decides: a run
1567
+ * completes one minute after it was created (the guide's example: created 1580832900, succeeded_at 1580832960), and
1568
+ * its CSV holds the report type's header row alone (its size that row's bytes). */
1569
+ export async function finishReportRuns(ctx: HandlerContext): Promise<void> {
1570
+ for (const run of ctx.rowsRaw('reporting.report_run')) {
1571
+ if (run.status !== 'pending') continue;
1572
+ const done = Number(run.created) + 60;
1573
+ if (Number(nowUnix(ctx.occurredAt)) < done) continue;
1574
+ const id = String(run.id);
1575
+ const header = 'category,currency,description,net_amount\n';
1576
+ const file = await created(ctx, 'file', { purpose: 'report_run' }, {
1577
+ filename: `${String(run.report_type)}_${id}.csv`, size: header.length, type: 'csv', title: null, expires_at: null, url: null,
1578
+ links: { object: 'list', data: [], has_more: false, url: '' },
1579
+ });
1580
+ await ctx.write('file', String(file.id), { url: `https://files.twin.local/v1/files/${String(file.id)}/contents` }, 'file.updated');
1581
+ ctx.legal('reporting.report_run', 'status', ctx.call.operation.id, 'pending', 'succeeded', id, 'vendor');
1582
+ await ctx.write('reporting.report_run', id, { status: 'succeeded', succeeded_at: done, result: ctx.get('file', String(file.id)) }, 'reporting.report_run.succeeded');
1583
+ }
1584
+ }
1585
+
1586
+ /** A feature whose lookup_key an unarchived feature already has: "A unique key you provide as your own system identifier"
1587
+ * (docs.stripe.com/api/entitlements/feature/create). */
1588
+ export function lookupKeyTaken(ctx: HandlerContext, lookupKey: string): Response {
1589
+ return fail(ctx, `A feature with lookup_key '${lookupKey}' already exists.`, 400, 'resource_already_exists');
1590
+ }
1591
+
1592
+ export const pmMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such payment_method: '${id}'`, 404, 'resource_missing');
1593
+
1594
+ /** The card a charge was paid with, as its payment_method_details reports it
1595
+ * (docs.stripe.com/api/charges/object#charge_object-payment_method_details): a stored PaymentMethod's card, a
1596
+ * documented test name (pm_card_* or tok_*, the same cards), or a raw card; undefined for anything else. */
1597
+ export function paymentMethodDetails(ctx: HandlerContext, ref: unknown): Row | undefined {
1598
+ let card: Row | undefined;
1599
+ // a payment method of another kind (a US bank account) is described by its own block, as the charge reports it
1600
+ const stored = typeof ref === 'string' && ref ? ctx.get(PM, ref) : undefined;
1601
+ // Stripe's US bank account test methods (pm_us_bank_account, pm_usBankAccount_*) are its test bank's account
1602
+ const pm = stored ?? (typeof ref === 'string' && /^pm_us_?bank_?account/i.test(ref) ? { type: 'us_bank_account', ...paymentMethodSubObject('us_bank_account', {}) } : undefined);
1603
+ if (pm && typeof pm.type === 'string' && pm.type !== 'card') {
1604
+ const own = (pm[pm.type] as Row | undefined) ?? {};
1605
+ const pick = ['account_holder_type', 'account_type', 'bank_name', 'fingerprint', 'last4', 'routing_number'];
1606
+ return { type: pm.type, [pm.type]: Object.fromEntries(pick.filter((k) => own[k] !== undefined).map((k) => [k, own[k]])) };
1607
+ }
1608
+ if (typeof ref === 'string' && ref) {
1609
+ const stored = ctx.get(PM, ref)?.card as Row | undefined;
1610
+ if (stored) card = stored;
1611
+ else card = testCardOf(ref);
1612
+ } else if (ref && typeof ref === 'object') card = paymentMethodSubObject('card', { card: ref }).card as Row;
1613
+ if (!card) return undefined;
1614
+ return {
1615
+ type: 'card',
1616
+ card: {
1617
+ brand: card.brand, last4: card.last4, exp_month: card.exp_month, exp_year: card.exp_year, funding: card.funding ?? 'credit',
1618
+ country: card.country ?? 'US', network: card.brand, fingerprint: card.fingerprint ?? null,
1619
+ checks: card.checks ?? { address_line1_check: null, address_postal_code_check: null, cvc_check: 'pass' },
1620
+ three_d_secure: null, wallet: null, installments: null, mandate: null,
1621
+ },
1622
+ };
1623
+ }
1624
+
1625
+ // attaching needs an existing customer; a well-known test token (pm_card_visa, …) is a template:
1626
+ // attaching it mints a new PaymentMethod on the customer carrying that card's outcome
1627
+ /** Whether a payment method can be attached: a stored one, or a documented test name that attaching mints. */
1628
+ export const attachable = (ctx: HandlerContext, id: string): boolean => !!ctx.get(PM, id) || (id.startsWith('pm_card_') && (id in TEST_TOKEN_DECLINES || id in AFTER_SUCCESS_CARDS));
1629
+
1630
+ export async function attachPaymentMethod(ctx: HandlerContext, id: string, customer: string): Promise<Row> {
1631
+ if (!ctx.get(PM, id)) return materializeTestMethod(ctx, id, customer);
1632
+ return ctx.write(PM, id, { customer }, 'payment_method.attach');
1633
+ }
1634
+
1635
+ /** A documented test name (pm_card_visa, pm_card_visa_chargeDeclined, …) made a real PaymentMethod, as Stripe
1636
+ * does when one is used: the brand and number it stands for (docs.stripe.com/testing#cards) and its outcome. */
1637
+ export async function materializeTestMethod(ctx: HandlerContext, id: string, customer: string | null): Promise<Row> {
1638
+ const card = TEST_PM_CARDS[id] ?? { brand: 'visa', number: '4242424242424242' };
1639
+ const sub = paymentMethodSubObject('card', { card: { number: card.number } });
1640
+ (sub.card as Record<string, unknown>).brand = card.brand;
1641
+ const afterSuccess = AFTER_SUCCESS_CARDS[id]?.outcome;
1642
+ return created(ctx, PM, { type: 'card', customer, livemode: false, billing_details: noBilling, ...sub, _declineOutcome: TEST_TOKEN_DECLINES[id] ?? null, ...(afterSuccess ? { _afterSuccess: afterSuccess } : {}) }, {});
1643
+ }
1644
+
1645
+ /** A PaymentMethod made from a confirm's `payment_method_data` ("If provided, this hash will be used to create a
1646
+ * PaymentMethod", docs.stripe.com/api/setup_intents/confirm, docs.stripe.com/api/payment_intents/confirm), or none. */
1647
+ export async function methodFromData(ctx: HandlerContext, data: unknown): Promise<string | undefined> {
1648
+ if (!data || typeof data !== 'object') return undefined;
1649
+ const d = data as Row;
1650
+ const type = typeof d.type === 'string' ? d.type : 'card';
1651
+ const made = await created(ctx, PM, {}, {
1652
+ type, customer: null, livemode: false, metadata: {},
1653
+ billing_details: { ...noBilling, ...((d.billing_details as Row | undefined) ?? {}) },
1654
+ ...paymentMethodSubObject(type, d),
1655
+ // what follows its card's success (a dispute, funds straight to available), as a PaymentMethod created directly carries
1656
+ ...(type === 'card' && afterSuccessOf(ctx, d.card) ? { _afterSuccess: afterSuccessOf(ctx, d.card) } : {}),
1657
+ });
1658
+ return String(made.id);
1659
+ }
1660
+
1661
+ /** Whether an intent sets up or pays with a bank account by micro-deposits because it asks for them:
1662
+ * payment_method_options[us_bank_account][verification_method]=microdeposits with a us_bank_account method
1663
+ * ("Microdeposit only verification", docs.stripe.com/payments/ach-direct-debit/set-up-payment). */
1664
+ export function microdepositsAsked(ctx: HandlerContext, params: Row, intent: Row, pm: string | undefined): boolean {
1665
+ const options = ((params.payment_method_options ?? intent.payment_method_options) as Row | undefined)?.us_bank_account as Row | undefined;
1666
+ return options?.verification_method === 'microdeposits' && !!pm && ctx.get(PM, pm)?.type === 'us_bank_account';
1667
+ }
1668
+
1669
+ export const scheduleMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such subscription_schedule: '${id}'`, 404, 'resource_missing');
1670
+
1671
+ /** A schedule's phases as Stripe answers them (the served spec's subscription_schedule_phase_configuration): each
1672
+ * starts where the last ended (the first at the schedule's start_date, "now" or a timestamp), and ends at its
1673
+ * end_date or after its duration ("duration: interval, interval_count", the served spec's phases[] parameter) on the
1674
+ * calendar; its currency is its first price's, each item carries its price, quantity and (empty) discounts. Where the
1675
+ * documentation stops and the twin decides: a phase with neither lasts one interval of its first price. */
1676
+ export function phasesOf(ctx: HandlerContext, given: Row[], start: number): Row[] {
1677
+ let cursor = start;
1678
+ return given.map((p) => {
1679
+ const items = (Array.isArray(p.items) ? (p.items as Row[]) : []).map((it) => ({ price: it.price ?? null, quantity: Math.max(1, Math.trunc(Number(it.quantity) || 1)), discounts: [], metadata: {}, tax_rates: [], billing_thresholds: null }));
1680
+ const price = typeof items[0]?.price === 'string' ? ctx.get('price', items[0]!.price as string) : undefined;
1681
+ const recurring = (price?.recurring as Row | undefined) ?? {};
1682
+ const d = p.duration && typeof p.duration === 'object' ? (p.duration as Row) : undefined;
1683
+ const startDate = cursor;
1684
+ const end = p.end_date !== undefined && p.end_date !== 'now' ? Number(p.end_date)
1685
+ : d ? addBillingInterval(startDate, String(d.interval) as Interval, Math.max(1, Number(d.interval_count) || 1))
1686
+ : addBillingInterval(startDate, String(recurring.interval ?? 'month') as Interval, Math.max(1, Number(recurring.interval_count) || 1));
1687
+ cursor = end;
1688
+ return {
1689
+ add_invoice_items: [], application_fee_percent: null, automatic_tax: { enabled: false, liability: null, disabled_reason: null }, billing_cycle_anchor: null,
1690
+ billing_thresholds: null, collection_method: null, currency: String(price?.currency ?? 'usd'), default_payment_method: null, default_tax_rates: [],
1691
+ description: null, discounts: [], end_date: end, invoice_settings: null, items, metadata: p.metadata && typeof p.metadata === 'object' ? p.metadata : {},
1692
+ on_behalf_of: null, proration_behavior: typeof p.proration_behavior === 'string' ? p.proration_behavior : 'create_prorations', start_date: startDate,
1693
+ transfer_data: null, trial_end: null,
1694
+ };
1695
+ });
1696
+ }
1697
+
1698
+ export function end(kind: 'cancel' | 'release'): Handler {
1699
+ return async (ctx) => {
1700
+ const id = at(ctx, 'schedule');
1701
+ const sched = ctx.get(SS, id);
1702
+ if (!sched) return scheduleMissing(ctx, id);
1703
+ const refused = ctx.legal(SS, 'status', kind === 'cancel' ? 'PostSubscriptionSchedulesScheduleCancel' : 'PostSubscriptionSchedulesScheduleRelease', sched.status, undefined, id);
1704
+ if (refused) return ctx.refuse(refused);
1705
+ const now = nowUnix(ctx.occurredAt);
1706
+ const subId = typeof sched.subscription === 'string' ? sched.subscription : undefined;
1707
+ const sub = subId ? ctx.get('subscription', subId) : undefined;
1708
+ // "Cancels a subscription schedule and its associated subscription immediately (if the subscription schedule has an
1709
+ // active subscription)" (docs.stripe.com/api/subscription_schedules/cancel); releasing "will remove its subscription
1710
+ // property and set the subscription's ID to the released_subscription property", leaving the subscription in place
1711
+ // (docs.stripe.com/api/subscription_schedules/release)
1712
+ if (kind === 'cancel' && subId && sub && sub.status !== 'canceled') {
1713
+ ctx.legal('subscription', 'status', 'PostSubscriptionSchedulesScheduleCancel', String(sub.status), 'canceled', subId);
1714
+ await ctx.write('subscription', subId, { status: 'canceled', canceled_at: now, ended_at: now }, 'subscription.cancel');
1715
+ }
1716
+ if (kind === 'release' && subId && sub) await ctx.write('subscription', subId, { schedule: null }, 'subscription.update');
1717
+ const fields = kind === 'cancel'
1718
+ ? { status: 'canceled', canceled_at: now, current_phase: null }
1719
+ : { status: 'released', released_at: now, released_subscription: subId ?? null, subscription: null, current_phase: null };
1720
+ return ctx.reply(await ctx.write(SS, id, fields, `subscription_schedule.${kind}`));
1721
+ };
1722
+ }
1723
+
1724
+ /** A token asked for none of what a token holds. */
1725
+ export function noTokenSource(ctx: HandlerContext): Response {
1726
+ return fail(ctx, 'You must provide one of the following parameters: card, bank_account, pii.', 400, 'parameter_missing');
1727
+ }
1728
+
1729
+ /** A bank account token's account, as the legacy BankAccount object holds it. */
1730
+ export function bankAccountOf(ctx: HandlerContext, ba: Row): Row {
1731
+ const acct = typeof ba.account_number === 'string' ? ba.account_number.replace(/\D/g, '') : '';
1732
+ return {
1733
+ id: ctx.mint('external_account'), object: 'bank_account', account_holder_name: ba.account_holder_name ?? null,
1734
+ account_holder_type: ba.account_holder_type ?? null, bank_name: 'STRIPE TEST BANK',
1735
+ country: ba.country ?? 'US', currency: ba.currency ?? 'usd', fingerprint: 'twin_ba_fp',
1736
+ last4: acct ? acct.slice(-4) : '6789', routing_number: ba.routing_number ?? '110000000', status: 'new',
1737
+ };
1738
+ }
1739
+
1740
+ export const productMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such product: '${id}'`, 404, 'resource_missing');
1741
+
1742
+ // a product with prices cannot be deleted; Stripe says to deactivate it instead
1743
+ /** A product deleted while it has prices: "Deleting a product is only possible if it has no prices associated with it"
1744
+ * (docs.stripe.com/api/products/delete). */
1745
+ export function pricedProductRefused(ctx: HandlerContext): Response {
1746
+ return fail(ctx, 'You cannot delete the product because it has one or more prices. Deactivate the product instead.', 400, 'resource_already_exists');
1747
+ }
1748
+
1749
+ // ── features: an entitlements feature granted to a product, at most once ──
1750
+
1751
+ /** A feature attached to a product that already has it. */
1752
+ export function alreadyAttached(ctx: HandlerContext): Response {
1753
+ return fail(ctx, 'This feature is already attached to the product.', 400, 'resource_already_exists');
1754
+ }
1755
+
1756
+ export const productFeature = (ctx: HandlerContext): Row | undefined => {
1757
+ const pf = ctx.get('product_feature', at(ctx, 'id'));
1758
+ // the product a feature is attached to is its address, not a field Stripe answers
1759
+ return pf && kept(ctx, 'product_feature', pf, '_product') === at(ctx, 'product') ? pf : undefined;
1760
+ };
1761
+
1762
+ export const featureMissing = (ctx: HandlerContext): Response => fail(ctx, `No such product feature: '${at(ctx, 'id')}'`, 404, 'resource_missing');
1763
+
1764
+ // ── prices ──
1765
+
1766
+ /** A tiered price: tiers_mode and tiers, each tier with up_to and a unit or flat amount; no single unit_amount, and
1767
+ * the last tier's up_to null (∞) (docs.stripe.com/products-prices/pricing-models#tiered-pricing). */
1768
+ export async function tieredPrice(ctx: HandlerContext, params: Row): Promise<Response> {
1769
+ const mode = typeof params.tiers_mode === 'string' ? params.tiers_mode : '';
1770
+ if (mode !== 'graduated' && mode !== 'volume') return fail(ctx, 'Missing required param: tiers_mode (graduated or volume).', 400, 'parameter_missing');
1771
+ const rawTiers = Array.isArray(params.tiers) ? (params.tiers as Row[]) : [];
1772
+ if (rawTiers.length === 0) return fail(ctx, 'Missing required param: tiers.', 400, 'parameter_missing');
1773
+ const tiers = rawTiers.map((t) => {
1774
+ const upToRaw = t.up_to;
1775
+ return {
1776
+ up_to: upToRaw === 'inf' || upToRaw === undefined || upToRaw === null ? null : Math.trunc(Number(upToRaw)),
1777
+ unit_amount: t.unit_amount !== undefined ? Math.trunc(Number(t.unit_amount)) : null,
1778
+ unit_amount_decimal: t.unit_amount !== undefined ? String(Math.trunc(Number(t.unit_amount))) : null,
1779
+ flat_amount: t.flat_amount !== undefined ? Math.trunc(Number(t.flat_amount)) : null,
1780
+ flat_amount_decimal: t.flat_amount !== undefined ? String(Math.trunc(Number(t.flat_amount))) : null,
1781
+ };
1782
+ });
1783
+ if (tiers.some((t) => t.unit_amount === null && t.flat_amount === null)) return fail(ctx, 'Each tier must specify a unit_amount or flat_amount.', 400, 'parameter_invalid_empty');
1784
+ const { tiers: _t, ...rest } = params;
1785
+ return ctx.reply(await created(ctx, 'price', { ...rest, billing_scheme: 'tiered', tiers_mode: mode, tiers, unit_amount: null }, { active: true, livemode: false, type: rest.recurring ? 'recurring' : 'one_time', metadata: {} }));
1786
+ }
1787
+
1788
+ /** Whether the intent's caller named its methods: on create (TYPES_GIVEN), or by an update that set its
1789
+ * payment_method_types ("Alternatively, update the allowed payment_method_types for this PaymentIntent",
1790
+ * methodNotAllowed below), which the generic update writes as given, so the intent's history holds it. */
1791
+ export const typesGiven = (ctx: HandlerContext, id: string): boolean =>
1792
+ ctx.rowsRaw(TYPES_GIVEN).some((r) => r.id === id)
1793
+ || ctx.history(PI, id).some((e) => e.operation !== 'payment_intent.create' && Array.isArray(e.fields?.payment_method_types));
1794
+
1795
+ export const paymentIntentsSend = (ctx: HandlerContext, r: StripeResponse): Response => ctx.reply(r.body, r.status);
1796
+
1797
+ export async function mintCharge(ctx: HandlerContext, piId: string, pi: Row, amount: number): Promise<string> {
1798
+ const already = ctx.get(PI, piId)?.latest_charge;
1799
+ if (typeof already === 'string' && ctx.get('charge', already)?.status === 'succeeded') return already;
1800
+ const chargeId = ctx.mint('charge');
1801
+ const bt = await settleCharge(ctx, chargeId, amount, String(pi.currency ?? 'usd'), typeof pi.payment_method === 'string' ? pi.payment_method : undefined);
1802
+ await created(ctx, 'charge', {
1803
+ id: chargeId, amount, currency: pi.currency ?? 'usd', payment_intent: piId,
1804
+ ...(typeof pi.customer === 'string' ? { customer: pi.customer } : {}),
1805
+ ...(typeof pi.payment_method === 'string' ? { payment_method: pi.payment_method } : {}),
1806
+ ...(typeof pi.invoice === 'string' ? { invoice: pi.invoice } : {}),
1807
+ ...intentCarries(pi),
1808
+ }, { ...chargeDefaults(chargeId, amount, true, ctx.occurredAt), balance_transaction: bt, payment_method_details: paymentMethodDetails(ctx, pi.payment_method) ?? null }, { operation: 'charge.succeeded' });
1809
+ await afterCharge(ctx, chargeId, { amount, currency: String(pi.currency ?? 'usd'), payment_intent: piId, application_fee_amount: pi.application_fee_amount, destination: (pi.transfer_data as Row | undefined)?.destination }, pi.payment_method);
1810
+ return chargeId;
1811
+ }
1812
+
1813
+ /** A manual-capture intent's authorization: "Separate payment authorization and capture to create a charge now, but
1814
+ * capture funds later", and on capture "A partial capture automatically releases the remaining amount"
1815
+ * (docs.stripe.com/payments/place-a-hold-on-a-payment-method). The charge succeeded and is not captured, holding the
1816
+ * amount until capture_before, with nothing on the balance yet. Written as
1817
+ * charge.succeeded, as a charge made with capture=false is (charges.ts); its capture writes charge.captured
1818
+ * (captureAuthorization). Where the documentation stops and the twin decides: the events page names no event for an
1819
+ * authorization of its own, so the authorized charge sends charge.succeeded, its status being succeeded. */
1820
+ export async function authorizeCharge(ctx: HandlerContext, piId: string, pi: Row, amount: number): Promise<string> {
1821
+ const chargeId = ctx.mint('charge');
1822
+ await created(ctx, 'charge', {
1823
+ id: chargeId, amount, currency: pi.currency ?? 'usd', payment_intent: piId,
1824
+ ...(typeof pi.customer === 'string' ? { customer: pi.customer } : {}),
1825
+ ...(typeof pi.payment_method === 'string' ? { payment_method: pi.payment_method } : {}),
1826
+ ...(typeof pi.invoice === 'string' ? { invoice: pi.invoice } : {}),
1827
+ ...intentCarries(pi),
1828
+ }, { ...chargeDefaults(chargeId, amount, false, ctx.occurredAt), balance_transaction: null, payment_method_details: paymentMethodDetails(ctx, pi.payment_method) ?? null }, { operation: 'charge.succeeded' });
1829
+ return chargeId;
1830
+ }
1831
+
1832
+ /**
1833
+ * An intent an invoice collects through succeeded (the default_incomplete subscription flow: create
1834
+ * now, confirm client-side): its invoice is paid and, when it is a subscription's first, the
1835
+ * subscription leaves incomplete for active. Both are moves the invoice and subscription machines
1836
+ * declare under the confirming operation. No-op when the intent names no invoice, or the invoice is
1837
+ * already paid (a duplicate confirm) or void (voiding ends what it collects).
1838
+ */
1839
+ export async function payInvoiceOf(ctx: HandlerContext, pi: Row, operationId: string, actor?: 'vendor'): Promise<void> {
1840
+ const invoiceId = typeof pi.invoice === 'string' ? pi.invoice : undefined;
1841
+ const invoice = invoiceId ? ctx.get('invoice', invoiceId) : undefined;
1842
+ if (!invoiceId || !invoice || invoice.status === 'paid' || invoice.status === 'void') return;
1843
+ if (ctx.legal('invoice', 'status', operationId, invoice.status, 'paid', invoiceId, actor)) return;
1844
+ const amount = Number(invoice.total ?? invoice.amount_due) || 0;
1845
+ // `invoice.pay` is the event the standalone pay action sends: invoice.paid
1846
+ await ctx.write('invoice', invoiceId, {
1847
+ status: 'paid', paid: true, amount_paid: amount, amount_remaining: 0,
1848
+ status_transitions: { ...((invoice.status_transitions as object) ?? {}), paid_at: nowUnix(ctx.occurredAt) },
1849
+ }, 'invoice.pay');
1850
+ const subId = typeof invoice.subscription === 'string' ? invoice.subscription : undefined;
1851
+ const sub = subId ? ctx.get('subscription', subId) : undefined;
1852
+ if (subId && sub && sub.status === 'incomplete' && !ctx.legal('subscription', 'status', operationId, sub.status, 'active', subId, actor)) {
1853
+ await ctx.write('subscription', subId, { status: 'active' }, 'subscription.update');
1854
+ }
1855
+ }
1856
+
1857
+ /** The intent the path names, and the machine's refusal when this operation may not move it. */
1858
+ export function paymentIntentsLoad(ctx: HandlerContext, operationId: string): { pi: Record<string, unknown> } | { answer: Response } {
1859
+ const pi = ctx.id ? ctx.get(PI, ctx.id) : undefined;
1860
+ if (!pi) return { answer: ctx.notFound(PI, String(ctx.id)) };
1861
+ const refusal = ctx.legal(PI, 'status', operationId, pi.status);
1862
+ return refusal ? { answer: ctx.refuse(refusal) } : { pi };
1863
+ }
1864
+
1865
+ /** The type of the payment method an intent is paid with: its PaymentMethod's, or a documented test name's (pm_card_*,
1866
+ * tok_* a card; pm_usBankAccount_* a US bank account), else unknown. */
1867
+ export function methodType(ctx: HandlerContext, method: unknown): string | undefined {
1868
+ if (typeof method !== 'string' || !method) return undefined;
1869
+ const row = ctx.get('payment_method', method);
1870
+ if (row) return typeof row.type === 'string' ? row.type : undefined;
1871
+ if (/^pm_us_?bank_?account/i.test(method)) return 'us_bank_account';
1872
+ if (/^(pm_card_|tok_)/.test(method)) return 'card';
1873
+ return undefined;
1874
+ }
1875
+
1876
+ /** A confirm with a payment method of a type the intent's caller did not allow, refused as Stripe refuses it: "The
1877
+ * PaymentMethod provided (card_present) is not allowed for this PaymentIntent. Please attach a PaymentMethod of one of
1878
+ * the following types: card. Alternatively, update the allowed payment_method_types for this PaymentIntent to include
1879
+ * "card_present"" (a real answer quoted in github.com/stripe/stripe-terminal-react-native/issues/745, an intent made
1880
+ * with payment_method_types ['card']). Only a list the caller gave restricts: without one Stripe offers the methods
1881
+ * the account enables, which the twin does not model. Where the evidence stops: that answer's code is not quoted; the
1882
+ * twin answers payment_intent_invalid_parameter ("One or more provided parameters wasn't allowed for the given
1883
+ * operation on the PaymentIntent", docs.stripe.com/error-codes), param payment_method. */
1884
+ export function methodNotAllowed(ctx: HandlerContext, existing: Row, params: Row): Response | undefined {
1885
+ const types = Array.isArray(params.payment_method_types) ? params.payment_method_types.map(String)
1886
+ : Array.isArray(params.allowed_payment_method_types) ? params.allowed_payment_method_types.map(String)
1887
+ : typesGiven(ctx, String(existing.id)) && Array.isArray(existing.payment_method_types) ? (existing.payment_method_types as unknown[]).map(String) : undefined;
1888
+ if (!types) return undefined;
1889
+ const type = methodType(ctx, params.payment_method ?? existing.payment_method);
1890
+ if (!type || types.includes(type)) return undefined;
1891
+ return ctx.refuse({ status: 400, code: 'payment_intent_invalid_parameter', param: 'payment_method', message: `The PaymentMethod provided (${type}) is not allowed for this PaymentIntent. Please attach a PaymentMethod of one of the following types: ${types.join(', ')}. Alternatively, update the allowed payment_method_types for this PaymentIntent to include "${type}"` });
1892
+ }
1893
+
1894
+ /** Confirm an intent the confirm machine allows to move: the confirm action, and a create with `confirm=true`. */
1895
+ export async function confirmIntent(ctx: HandlerContext, existing: Record<string, unknown>, params: Record<string, unknown>): Promise<Response> {
1896
+ const id = String(existing.id);
1897
+ // a payment names a mandate only an active one authorizes: an inactive mandate "was rejected, revoked, or previously
1898
+ // used, and may not be used to initiate future payments" (docs.stripe.com/api/mandates/object), refused as
1899
+ // payment_intent_mandate_invalid, "The provided mandate is invalid and can't be used for the payment intent"
1900
+ // (docs.stripe.com/error-codes)
1901
+ const named = typeof params.mandate === 'string' ? params.mandate : typeof existing.mandate === 'string' ? existing.mandate : undefined;
1902
+ if (named && ctx.get('mandate', named)?.status !== 'active') return fail(ctx, 'The provided mandate is invalid and can\'t be used for the payment intent.', 400, 'payment_intent_mandate_invalid');
1903
+ const notAllowed = methodNotAllowed(ctx, existing, params);
1904
+ if (notAllowed) return notAllowed;
1905
+ // a declining test card leaves the intent needing a payment method, with the error on it and a 402
1906
+ const decline = declineFor(finder(ctx), params, existing);
1907
+ if (decline) {
1908
+ // Stripe records the attempt: a failed charge the intent's latest_charge names, the declined card on
1909
+ // last_payment_error (a test name made a real PaymentMethod), and no payment_method left on the intent
1910
+ // (docs.stripe.com/payments/paymentintents/lifecycle, docs.stripe.com/declines)
1911
+ const ref = params.payment_method ?? existing.payment_method;
1912
+ let pmId = typeof ref === 'string' ? ref : undefined;
1913
+ if (pmId && !ctx.get('payment_method', pmId) && pmId.startsWith('pm_card_')) pmId = String((await materializeTestMethod(ctx, pmId, typeof existing.customer === 'string' ? existing.customer : null)).id);
1914
+ const pm = pmId ? ctx.get('payment_method', pmId) : undefined;
1915
+ const amount = Number(params.amount ?? existing.amount) || 0;
1916
+ const chargeId = ctx.mint('charge');
1917
+ await created(ctx, 'charge', {
1918
+ id: chargeId, amount, currency: existing.currency ?? 'usd', payment_intent: id,
1919
+ ...(typeof existing.customer === 'string' ? { customer: existing.customer } : {}),
1920
+ ...(pmId ? { payment_method: pmId } : {}),
1921
+ ...intentCarries({ ...existing, ...params }),
1922
+ }, {
1923
+ ...chargeDefaults(chargeId, amount, false, ctx.occurredAt), status: 'failed', paid: false, captured: false, capture_before: null,
1924
+ failure_code: decline.code, failure_message: decline.message, balance_transaction: null,
1925
+ outcome: { type: 'issuer_declined', network_status: 'declined_by_network', reason: decline.decline_code ?? decline.code, risk_level: 'normal', seller_message: 'The bank did not return any further details with this decline.' },
1926
+ payment_method_details: pmId ? paymentMethodDetails(ctx, pmId) ?? null : null,
1927
+ }, { operation: 'charge.failed' }); // "Occurs whenever a failed charge attempt occurs." (docs.stripe.com/api/events/types)
1928
+ const { payment_method: _pm, ...rest } = params;
1929
+ const last_payment_error = { type: 'card_error', code: decline.code, ...(decline.decline_code ? { decline_code: decline.decline_code } : {}), message: decline.message, param: 'card', charge: chargeId, payment_method: pm ?? null };
1930
+ const failed = await ctx.write(PI, id, { ...rest, payment_method: null, latest_charge: chargeId, status: 'requires_payment_method', last_payment_error }, 'payment_intent.payment_failed');
1931
+ return paymentIntentsSend(ctx, cardError(decline, { payment_intent: failed, charge: chargeId }));
1932
+ }
1933
+ // a bank debit that needs micro-deposit verification waits in requires_action
1934
+ const method = typeof params.payment_method === 'string' ? params.payment_method : typeof existing.payment_method === 'string' ? existing.payment_method : undefined;
1935
+ // a bank transfer is paid from the customer's cash balance, or waits for the transfer (fundFromCashBalance)
1936
+ if (method && ctx.get('payment_method', method)?.type === 'customer_balance') return ctx.reply(ctx.expand(PI, await fundFromCashBalance(ctx, { ...existing, ...params }, params)));
1937
+ if (requiresMicrodeposits(params, existing) || microdepositsAsked(ctx, params, existing, method)) {
1938
+ return ctx.reply(ctx.expand(PI, await ctx.write(PI, id, { ...params, status: 'requires_action', next_action: microdepositsNextAction(), last_payment_error: null }, 'payment_intent.requires_action')));
1939
+ }
1940
+ // 3DS: the first confirm asks for authentication; a second one completes it
1941
+ if (existing.status !== 'requires_action' && requiresAuthentication(params, existing)) {
1942
+ return ctx.reply(ctx.expand(PI, await ctx.write(PI, id, { ...params, status: 'requires_action', next_action: threeDsNextAction(), last_payment_error: null }, 'payment_intent.requires_action')));
1943
+ }
1944
+ // manual capture authorizes and waits for /capture: the authorization is a charge, succeeded and not captured, the
1945
+ // intent's latest_charge
1946
+ if ((params.capture_method ?? existing.capture_method) === 'manual') {
1947
+ const amount = Number(existing.amount ?? params.amount ?? 0);
1948
+ const charge = await authorizeCharge(ctx, id, { ...existing, ...params }, amount);
1949
+ return ctx.reply(ctx.expand(PI, await ctx.write(PI, id, { ...params, status: 'requires_capture', amount_capturable: amount, amount_received: 0, next_action: null, last_payment_error: null, latest_charge: charge }, 'payment_intent.amount_capturable_updated')));
1950
+ }
1951
+ // a bank debit is submitted and settles later (beginBankDebit)
1952
+ if (isBankDebit(ctx, method)) return ctx.reply(ctx.expand(PI, await beginBankDebit(ctx, id, params)));
1953
+ const amount = Number(existing.amount ?? params.amount ?? 0);
1954
+ // a succeeded intent has a Charge, and latest_charge names it: what a refund of it lands on
1955
+ const charge = await mintCharge(ctx, id, { ...existing, ...params }, amount);
1956
+ const body = await ctx.write(PI, id, { ...params, status: 'succeeded', amount_received: amount, next_action: null, last_payment_error: null, latest_charge: charge }, 'payment_intent.confirm');
1957
+ await payInvoiceOf(ctx, body, 'PostPaymentIntentsIntentConfirm');
1958
+ return ctx.reply(ctx.expand(PI, body));
1959
+ }
1960
+
1961
+ /** An increment that does not raise the authorization. */
1962
+ export function incrementTooSmall(ctx: HandlerContext): Response {
1963
+ return ctx.refuse({ status: 400, code: 'parameter_invalid_integer', message: 'The new amount must be greater than the current amount of the PaymentIntent.' });
1964
+ }
1965
+
1966
+ // ── a bank debit is submitted, and settles ──
1967
+ //
1968
+ // ACH Direct Debit "is a delayed notification payment method ... The PaymentIntent you create initially has a status
1969
+ // of `processing`. After the payment has succeeded, the PaymentIntent status is updated from `processing` to
1970
+ // `succeeded`"; verification by micro-deposits returns "a status of `processing`, and sends a payment_intent.processing
1971
+ // webhook event"; and, the twin being a test-mode account: "Test transactions settle instantly and are added to your
1972
+ // available test balance. This behavior differs from live mode, where transactions can take multiple days to settle"
1973
+ // (docs.stripe.com/payments/ach-direct-debit/accept-a-payment?payment-ui=direct-api). A confirm answers processing; the
1974
+ // debit succeeds at that same instant of the World's clock, caught up before the next request is answered (as
1975
+ // renewals and payouts are). The page's test accounts give each debit its outcome: pm_usBankAccount_success
1976
+ // (000123456789) "The payment succeeds"; pm_usBankAccount_processing (000000000009) "The payment stays in processing
1977
+ // indefinitely". Where the documentation stops and the twin decides: its Charge is made when it succeeds (the page
1978
+ // names none while it processes); the failing test accounts (closed, no account, insufficient funds, debit not
1979
+ // authorized, invalid currency, dispute, weekly limit, Radar block) are not modelled and succeed.
1980
+
1981
+ /** Whether the method an intent is confirmed with is a bank debit: a us_bank_account PaymentMethod, or one of Stripe's
1982
+ * test bank accounts named as one (pm_usBankAccount_*, pm_us_bank_account). */
1983
+ export function isBankDebit(ctx: HandlerContext, method: unknown): boolean {
1984
+ if (typeof method !== 'string') return false;
1985
+ return ctx.get('payment_method', method)?.type === 'us_bank_account' || /^pm_us_?bank_?account/i.test(method);
1986
+ }
1987
+
1988
+ /** Whether a bank debit stays processing: the page's pm_usBankAccount_processing, or its account 000000000009. */
1989
+ export function staysProcessing(ctx: HandlerContext, method: unknown): boolean {
1990
+ if (method === 'pm_usBankAccount_processing') return true;
1991
+ const bank = typeof method === 'string' ? (ctx.get('payment_method', method)?.us_bank_account as Row | undefined) : undefined;
1992
+ return bank?.last4 === '0009';
1993
+ }
1994
+
1995
+ /** A bank debit submitted: the intent processes, nothing received yet, sent as payment_intent.processing; it is due to
1996
+ * settle at this instant, unless its test account stays processing. */
1997
+ export async function beginBankDebit(ctx: HandlerContext, id: string, fields: Row): Promise<Row> {
1998
+ const method = fields.payment_method ?? ctx.get(PI, id)?.payment_method;
1999
+ return ctx.write(PI, id, { ...fields, status: 'processing', amount_received: 0, next_action: null, last_payment_error: null, _settles_at: staysProcessing(ctx, method) ? null : Number(nowUnix(ctx.occurredAt)) }, 'payment_intent.processing');
2000
+ }
2001
+
2002
+ /** Time's settling of bank debits, caught up to the World's clock: each processing debit whose moment has come succeeds
2003
+ * then, its Charge made (naming the mandate it ran under) and the invoice it collects for paid. */
2004
+ export async function settleBankDebits(ctx: HandlerContext): Promise<void> {
2005
+ const now = Number(nowUnix(ctx.occurredAt));
2006
+ const due = ctx.rowsRaw(PI).filter((p) => p.status === 'processing' && typeof p._settles_at === 'number' && p._settles_at <= now).sort((a, b) => Number(a._settles_at) - Number(b._settles_at));
2007
+ for (const pi of due) {
2008
+ const id = String(pi.id);
2009
+ const c = await at_(ctx)(Number(pi._settles_at));
2010
+ c.legal(PI, 'status', ctx.call.operation.id, 'processing', 'succeeded', id, 'vendor');
2011
+ const amount = Number(pi.amount) || 0;
2012
+ const charge = await mintCharge(c, id, pi, amount);
2013
+ // the charge names the mandate its bank debit ran under (payment_method_details.us_bank_account.mandate)
2014
+ const details = (c.get('charge', charge)?.payment_method_details ?? null) as Row | null;
2015
+ const kind = typeof details?.type === 'string' ? details.type : undefined;
2016
+ if (details && kind && typeof pi.mandate === 'string') await c.write('charge', charge, { payment_method_details: { ...details, [kind]: { ...((details[kind] as Row | undefined) ?? {}), mandate: pi.mandate } } }, 'charge.mandate');
2017
+ const body = await c.write(PI, id, { status: 'succeeded', amount_received: amount, latest_charge: charge, _settles_at: null }, 'payment_intent.succeeded');
2018
+ // a single-use mandate is spent by its payment: "previously used, and may not be used to initiate future payments"
2019
+ const used = typeof pi.mandate === 'string' ? c.get('mandate', pi.mandate) : undefined;
2020
+ if (used && used.type === 'single_use' && used.status === 'active') {
2021
+ c.legal('mandate', 'status', ctx.call.operation.id, 'active', 'inactive', String(used.id), 'vendor');
2022
+ await c.write('mandate', String(used.id), { status: 'inactive' }, 'mandate.updated');
2023
+ }
2024
+ await payInvoiceOf(c, body, ctx.call.operation.id, 'vendor');
2025
+ }
2026
+ }
2027
+
2028
+ /** A customer_balance intent funded from the customer's cash balance: paid when the balance covers it ("If the customer
2029
+ * already has a balance high enough to cover the payment amount, the PaymentIntent immediately succeeds"), else
2030
+ * waiting for a transfer: "If the customer balance isn’t high enough to cover the request amount, the PaymentIntent
2031
+ * shows a requires_action status ... next_action ... display_bank_transfer_instructions" with the amount_remaining
2032
+ * (docs.stripe.com/payments/bank-transfers/accept-a-payment). Answers the intent as written. */
2033
+ export async function fundFromCashBalance(ctx: HandlerContext, pi: Row, fields: Row = {}): Promise<Row> {
2034
+ const customer = typeof pi.customer === 'string' ? pi.customer : '';
2035
+ const currency = String(pi.currency ?? 'usd');
2036
+ // what the customer's funded cash balance holds in this currency, from its ledger
2037
+ const available = customer ? ctx.rows('customer_cash_balance_transaction').filter((t) => t.customer === customer && String(t.currency) === currency).reduce((n, t) => n + (Number(t.net_amount) || 0), 0) : 0;
2038
+ const amount = Number(pi.amount) || 0;
2039
+ if (available >= amount) {
2040
+ // the balance pays the intent: its ledger records what was applied
2041
+ await created(ctx, 'customer_cash_balance_transaction', { customer }, { currency, type: 'applied_to_payment', net_amount: -amount, ending_balance: available - amount, applied_to_payment: { payment_intent: String(pi.id) }, livemode: false });
2042
+ const charge = await mintCharge(ctx, String(pi.id), { ...pi, ...fields }, amount);
2043
+ return ctx.write(PI, String(pi.id), { ...fields, status: 'succeeded', next_action: null, amount_received: amount, last_payment_error: null, latest_charge: charge }, 'payment_intent.succeeded');
2044
+ }
2045
+ // not enough yet: the intent waits for the rest, with the instructions to send it
2046
+ const next_action = { type: 'display_bank_transfer_instructions', display_bank_transfer_instructions: { amount_remaining: amount - available, currency, type: 'us_bank_transfer' } };
2047
+ return ctx.write(PI, String(pi.id), { ...fields, status: 'requires_action', next_action }, 'payment_intent.requires_action');
2048
+ }
2049
+
2050
+ /** Whether a charge's funds go straight to the available balance: a bypass card as a raw number, a test name (pm_card_*
2051
+ * or tok_*), or a stored PaymentMethod made from one (which records it as what follows its success, after-payment.ts);
2052
+ * or a US bank account, stored or one of Stripe's test bank accounts named as one (pm_usBankAccount_*). */
2053
+ export function bypassesPending(ctx: HandlerContext, card: string | undefined): boolean {
2054
+ if (!card) return false;
2055
+ const stored = ctx.row('payment_method', card);
2056
+ // the row carries what the method recorded; its type is the vendor object's (ctx.get), not the row's envelope
2057
+ if (stored) return stored._afterSuccess === 'available' || ctx.get('payment_method', card)?.type === 'us_bank_account';
2058
+ if (/^pm_us_?bank_?account/i.test(card)) return true;
2059
+ return BYPASS_NUMBERS.has(card.replace(/\D/g, '')) || card.replace(/^tok_/, 'pm_card_') in BYPASS_PENDING_CARDS;
2060
+ }
2061
+
2062
+ /** The connected account a request acts for, or undefined for the platform. */
2063
+ export const actingAccount = (ctx: HandlerContext): string | undefined => ctx.call.request.headers.get('stripe-account') ?? undefined;
2064
+
2065
+ /** A ledger entry on an account's balance: the acting account's unless one is named (null names the platform). */
2066
+ export async function write(ctx: HandlerContext, fields: Row, account: string | null | undefined = actingAccount(ctx)): Promise<string> {
2067
+ // a credit available at once waits for the drain's balance.available (settleDueEntries)
2068
+ const unsent = (fields.status ?? 'available') === 'available' && Number(fields.net) > 0 ? { [UNSENT]: true } : {};
2069
+ const bt = await created(ctx, BT, {}, { status: 'available', fee_details: [], description: null, exchange_rate: null, balance_type: 'payments', ...fields, ...unsent, ...(account ? { _account: account } : {}) });
2070
+ return String(bt.id);
2071
+ }
2072
+
2073
+ /** A captured charge's credit: its amount less the fee, pending two days unless the card bypasses the pending
2074
+ * balance (bypassesPending), when it is due at once. The
2075
+ * caller mints the charge's id first and stores the returned id as the charge's balance_transaction. */
2076
+ export async function settleCharge(ctx: HandlerContext, chargeId: string, amount: number, currency: string, card?: string): Promise<string> {
2077
+ const now = Number(nowUnix(ctx.occurredAt));
2078
+ const fee = feeOf(amount);
2079
+ const atOnce = bypassesPending(ctx, card);
2080
+ const id = await write(ctx, {
2081
+ amount, currency, fee, net: amount - fee, type: 'charge', reporting_category: 'charge', source: chargeId,
2082
+ ...(atOnce ? { status: 'available', available_on: now } : { status: 'pending', available_on: now + 2 * DAY }),
2083
+ fee_details: fee ? [{ amount: fee, application: null, currency, description: 'Stripe processing fees', type: 'stripe_fee' }] : [],
2084
+ });
2085
+ return id;
2086
+ }
2087
+
2088
+ /** A refund's debit, at once, on the acting account's balance unless one is named (null names the platform). */
2089
+ export async function settleRefund(ctx: HandlerContext, refundId: string, amount: number, currency: string, account: string | null | undefined = actingAccount(ctx)): Promise<string> {
2090
+ return write(ctx, { amount: -amount, currency, fee: 0, net: -amount, type: 'refund', reporting_category: 'refund', source: refundId, available_on: Number(nowUnix(ctx.occurredAt)) }, account);
2091
+ }
2092
+
2093
+ /** What an account had available in a currency at a moment: every entry of its payments balance whose funds had come
2094
+ * due by then. */
2095
+ export function availableAt(ctx: HandlerContext, account: string | undefined, currency: string, at: number): number {
2096
+ let sum = 0;
2097
+ for (const t of ctx.rowsRaw(BT)) {
2098
+ if (!onAccount(t, account) || t.balance_type === 'issuing' || String(t.currency ?? 'usd') !== currency) continue;
2099
+ const due = Number(t.available_on ?? t.created);
2100
+ if (Number.isFinite(due) && due <= at) sum += Number(t.net ?? 0);
2101
+ }
2102
+ return sum;
2103
+ }
2104
+
2105
+ /** The moments after `from` and up to `until` when funds of an account came due, in order: when a held refund can
2106
+ * next be covered. */
2107
+ export function fundsDueBetween(ctx: HandlerContext, account: string | undefined, currency: string, from: number, until: number): number[] {
2108
+ 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);
2109
+ return [...new Set(times)].sort((a, b) => a - b);
2110
+ }
2111
+
2112
+ /** A dispute's debit, at once: the disputed amount and the dispute fee (the twin's 1500 cents, Stripe's US $15). */
2113
+ export async function settleDispute(ctx: HandlerContext, disputeId: string, amount: number, currency: string): Promise<string> {
2114
+ const fee = 1500;
2115
+ return write(ctx, {
2116
+ amount: -amount, currency, fee, net: -amount - fee, type: 'adjustment', reporting_category: 'dispute', source: disputeId, available_on: Number(nowUnix(ctx.occurredAt)),
2117
+ fee_details: [{ amount: fee, application: null, currency, description: 'Dispute fee', type: 'stripe_fee' }],
2118
+ });
2119
+ }
2120
+
2121
+ /** A won dispute's credit, at once: the disputed amount returned (docs.stripe.com/disputes/how-disputes-work). Where the
2122
+ * documentation stops and the twin decides: the dispute fee is not returned. */
2123
+ export async function settleDisputeWon(ctx: HandlerContext, disputeId: string, amount: number, currency: string): Promise<string> {
2124
+ return write(ctx, { amount, currency, fee: 0, net: amount, type: 'adjustment', reporting_category: 'dispute_reversal', source: disputeId, available_on: Number(nowUnix(ctx.occurredAt)) });
2125
+ }
2126
+
2127
+ /** An account's ledger entries an automatic payout has not yet paid out: every entry on its payments balance that no
2128
+ * automatic payout took (the automatic payouts' own debits excluded), as stored. */
2129
+ export function unpaidEntries(ctx: HandlerContext, account: string | undefined): Row[] {
2130
+ const automatic = new Set(ctx.rowsRaw('payout').filter((p) => p.automatic === true).map((p) => p.id));
2131
+ return ctx.rowsRaw(BT).filter((t) => onAccount(t, account) && t.balance_type !== 'issuing' && !t._payout && !automatic.has(t.source));
2132
+ }
2133
+
2134
+ /** An automatic payout's debit at `at`, and the entries it pays out marked with it, so the ledger lists them under
2135
+ * the payout (docs.stripe.com/api/balance_transactions/list#balance_transaction_list-payout). */
2136
+ export async function settleAutomaticPayout(ctx: HandlerContext, payoutId: string, amount: number, currency: string, account: string | undefined, at: number, entries: Row[]): Promise<string> {
2137
+ for (const t of entries) await ctx.write(BT, String(t.id), { _payout: payoutId }, 'balance_transaction.paid_out');
2138
+ return write(ctx, { amount: -amount, currency, fee: 0, net: -amount, type: 'payout', reporting_category: 'payout', source: payoutId, available_on: at, _payout: payoutId }, account ?? null);
2139
+ }
2140
+
2141
+ /** A payout's debit (negative) or a cancellation's or reversal's credit (positive), at once, on the payout's account. */
2142
+ export async function settlePayout(ctx: HandlerContext, payoutId: string, amount: number, currency: string, account: string | null | undefined = actingAccount(ctx)): Promise<string> {
2143
+ const type = amount < 0 ? 'payout' : 'payout_cancel';
2144
+ return write(ctx, { amount, currency, fee: 0, net: amount, type, reporting_category: type === 'payout' ? 'payout' : 'payout_reversal', source: payoutId, available_on: Number(nowUnix(ctx.occurredAt)) }, account);
2145
+ }
2146
+
2147
+ /** A transfer's two entries: out of the platform's balance at once, into the destination's when `fromCharge` (its
2148
+ * charge's funds' availability) comes (a plain transfer, with no `fromCharge`, moves funds available already).
2149
+ * Answers the platform's entry. */
2150
+ export async function settleTransfer(ctx: HandlerContext, transferId: string, amount: number, currency: string, destination: string, fromCharge?: number, fromPending = false): Promise<string> {
2151
+ const availableOn = fromCharge ?? Number(nowUnix(ctx.occurredAt));
2152
+ const settled = availableOn <= Number(nowUnix(ctx.occurredAt));
2153
+ // a transfer from a charge's pending funds (source_transaction) leaves the platform when they arrive, not before
2154
+ 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(nowUnix(ctx.occurredAt)) }) }, null);
2155
+ await write(ctx, { amount, currency, fee: 0, net: amount, type: 'payment', reporting_category: 'charge', source: transferId, status: settled ? 'available' : 'pending', available_on: availableOn }, destination);
2156
+ return platform;
2157
+ }
2158
+
2159
+ /** A transfer reversal's two entries: back into the platform's balance, out of the destination's. */
2160
+ export async function settleTransferReversal(ctx: HandlerContext, reversalId: string, amount: number, currency: string, destination: string): Promise<string> {
2161
+ const platform = await write(ctx, { amount, currency, fee: 0, net: amount, type: 'transfer_refund', reporting_category: 'transfer_reversal', source: reversalId, available_on: Number(nowUnix(ctx.occurredAt)) }, null);
2162
+ await write(ctx, { amount: -amount, currency, fee: 0, net: -amount, type: 'payment_refund', reporting_category: 'refund', source: reversalId, available_on: Number(nowUnix(ctx.occurredAt)) }, destination);
2163
+ return platform;
2164
+ }
2165
+
2166
+ /** A direct charge's application fee: out of the connected account's balance, into the platform's. */
2167
+ export async function settleApplicationFee(ctx: HandlerContext, feeId: string, amount: number, currency: string, account: string): Promise<string> {
2168
+ await write(ctx, { amount: -amount, currency, fee: 0, net: -amount, type: 'application_fee', reporting_category: 'platform_earning', source: feeId, available_on: Number(nowUnix(ctx.occurredAt)) }, account);
2169
+ return write(ctx, { amount, currency, fee: 0, net: amount, type: 'application_fee', reporting_category: 'platform_earning', source: feeId, available_on: Number(nowUnix(ctx.occurredAt)) }, null);
2170
+ }
2171
+
2172
+ /** A top-up's credit, to the payments balance or, with `destination_balance=issuing`, to Issuing's
2173
+ * (docs.stripe.com/issuing/funding/balance). Where the documentation stops and the twin decides: a test-mode top-up
2174
+ * is available at once. */
2175
+ export async function settleTopup(ctx: HandlerContext, topupId: string, amount: number, currency: string, destination: string): Promise<string> {
2176
+ const issuing = destination === 'issuing';
2177
+ return write(ctx, { amount, currency, fee: 0, net: amount, type: 'topup', reporting_category: 'topup', source: topupId, available_on: Number(nowUnix(ctx.occurredAt)), balance_type: issuing ? 'issuing' : 'payments' });
2178
+ }
2179
+
2180
+ /** Time's settlements, written: each entry on the acting account's balance whose funds came due by the World's clock
2181
+ * moves pending → available (the clock's move the machine allows), so a settlement is recorded once. A read already
2182
+ * sees it (asOf); the record is what lets Stripe's balance.available be sent once (./front.ts, the drain).
2183
+ * Funds that were available at once and not yet sent are taken too, and marked sent. Answers the entries taken. */
2184
+ export async function settleDueEntries(ctx: HandlerContext, account: string | undefined = actingAccount(ctx)): Promise<Row[]> {
2185
+ const now = Number(nowUnix(ctx.occurredAt));
2186
+ const moved: Row[] = [];
2187
+ for (const t of ctx.rowsRaw(BT)) {
2188
+ if (!onAccount(t, account)) continue;
2189
+ if (t.status === 'available' && t[UNSENT] === true) {
2190
+ await ctx.write(BT, String(t.id), { [UNSENT]: false }, 'balance_transaction.available_sent');
2191
+ moved.push(t);
2192
+ continue;
2193
+ }
2194
+ if (t.status !== 'pending' || !(Number(t.available_on) <= now)) continue;
2195
+ if (ctx.legal(BT, 'status', ctx.call.operation.id, 'pending', 'available', String(t.id), 'time')) continue;
2196
+ await ctx.write(BT, String(t.id), { status: 'available' }, 'balance_transaction.available');
2197
+ moved.push(t);
2198
+ }
2199
+ return moved;
2200
+ }
2201
+
2202
+ /** An account's balance, by currency: what the clock has made available, what is still pending, and Issuing's own. */
2203
+ export function balanceOf(ctx: HandlerContext, account: string | undefined = actingAccount(ctx)): { available: Map<string, number>; pending: Map<string, number>; issuing: Map<string, number> } {
2204
+ const available = new Map<string, number>();
2205
+ const pending = new Map<string, number>();
2206
+ const issuing = new Map<string, number>();
2207
+ for (const raw of ctx.rowsRaw(BT)) {
2208
+ if (!onAccount(raw, account)) continue;
2209
+ const t = commonAsOf(ctx, raw);
2210
+ const cur = String(t.currency ?? 'usd');
2211
+ const net = Number(t.net ?? 0);
2212
+ const bucket = t.balance_type === 'issuing' ? issuing : t.status === 'available' ? available : pending;
2213
+ bucket.set(cur, (bucket.get(cur) ?? 0) + net);
2214
+ }
2215
+ return { available, pending, issuing };
2216
+ }
2217
+
2218
+ /** balance_insufficient when a payout or transfer would take more than the account has available in its currency. */
2219
+ export function refusePayout(ctx: HandlerContext, amount: number, currency: string, account: string | undefined = actingAccount(ctx)): Response | undefined {
2220
+ const have = balanceOf(ctx, account).available.get(currency) ?? 0;
2221
+ if (amount <= have) return undefined;
2222
+ 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');
2223
+ }
2224
+
2225
+ /** The ids of the ledger entries on the acting account's balance. */
2226
+ export const mine = (ctx: HandlerContext): Set<unknown> => new Set(ctx.rowsRaw(BT).filter((t) => onAccount(t, actingAccount(ctx))).map((t) => t.id));
2227
+
2228
+ export const chargeMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such charge: '${id}'`, 404, 'resource_missing');
2229
+
2230
+ /** Every egress of a charge carries its refunds, derived from the refund rows in list order. */
2231
+ export function chargeBody(ctx: HandlerContext, c: Row): Row {
2232
+ const data = newest(ctx, 'refund').filter((r) => r.charge === c.id);
2233
+ return { ...c, refunds: { object: 'list', data, has_more: false, total_count: data.length, url: `/v1/charges/${String(c.id)}/refunds` } };
2234
+ }
2235
+
2236
+ /** A Charges-API charge a declining test card refuses: a 402 card_error naming the failed charge Stripe records for the
2237
+ * attempt (docs.stripe.com/declines). */
2238
+ export async function declinedCharge(ctx: HandlerContext, decline: { code: string; decline_code?: string; message: string }): Promise<Response> {
2239
+ const params = ctx.params;
2240
+ const failedId = ctx.mint('charge');
2241
+ const amount = Number(params.amount) || 0;
2242
+ await created(ctx, 'charge', { ...withoutCard(params), id: failedId }, {
2243
+ ...chargeDefaults(failedId, amount, false, ctx.occurredAt), status: 'failed', paid: false, captured: false, capture_before: null,
2244
+ failure_code: decline.code, failure_message: decline.message, balance_transaction: null,
2245
+ outcome: { type: 'issuer_declined', network_status: 'declined_by_network', reason: decline.decline_code ?? decline.code, risk_level: 'normal', seller_message: 'The bank did not return any further details with this decline.' },
2246
+ payment_method_details: paymentMethodDetails(ctx, params.payment_method ?? params.source ?? params.card) ?? null,
2247
+ }, { operation: 'charge.failed' });
2248
+ return send(ctx, cardError(decline, { charge: failedId }));
2249
+ }
2250
+
2251
+ /** A charge's fraud report: "user_report … Assessments reported by you. If set, possible values of are `safe` and
2252
+ * `fraudulent`" (docs.stripe.com/api/charges/object, fraud_details). */
2253
+ export function fraudReport(ctx: HandlerContext, existing: Row, fd: Row): Row | Response {
2254
+ const report = String(fd.user_report);
2255
+ if (report !== 'safe' && report !== 'fraudulent') return fail(ctx, "Invalid fraud_details[user_report]: must be 'safe' or 'fraudulent'.", 400, 'parameter_invalid_string_enum');
2256
+ const prior = existing.fraud_details && typeof existing.fraud_details === 'object' ? (existing.fraud_details as Row) : {};
2257
+ return { user_report: report, stripe_report: prior.stripe_report ?? null };
2258
+ }
2259
+
2260
+ /** A capture=false charge refunded while uncaptured: its authorization is released by the refund, as it would be
2261
+ * "automatically refunded if uncaptured" (spec/openapi.json.gz, `capture_before`). The charge stays uncaptured and
2262
+ * becomes refunded in full, a Refund records the release, and no money moves: none was ever received. Written as
2263
+ * charge.refunded. Where the documentation stops and the twin decides: Stripe's basil change ("Partially capturing or
2264
+ * canceling payments no longer creates a Refund", docs.stripe.com/changelog/basil/2025-03-31/remove-refund-from-partial-
2265
+ * capture-and-payment-cancellation-flow) names partial capture and cancellation, not a refund asked for, so a refund
2266
+ * still makes one; its reason is null and it has no balance transaction. Answers the Refund. */
2267
+ export async function releaseAuthorization(ctx: HandlerContext, ch: Row, operationId: string, given: Row = {}): Promise<Row> {
2268
+ const id = String(ch.id);
2269
+ const full = Number(ch.amount) || 0;
2270
+ if (ch.refunded !== true) ctx.legal('charge', 'refunded', operationId, 'false', 'true', id);
2271
+ const refund = await created(ctx, 'refund', { ...given, charge: id, amount: full - (Number(ch.amount_refunded) || 0), currency: String(ch.currency ?? 'usd') }, {
2272
+ status: 'succeeded', metadata: {}, reason: null, receipt_number: null,
2273
+ balance_transaction: null, source_transfer_reversal: null, transfer_reversal: null, ...refundDestination(ch, 'reversal'),
2274
+ ...(typeof ch.payment_intent === 'string' ? { payment_intent: ch.payment_intent } : {}),
2275
+ });
2276
+ await ctx.write('charge', id, { amount_refunded: full, refunded: true }, 'charge.refunded');
2277
+ return refund;
2278
+ }
2279
+
2280
+ /** A PaymentIntent's authorization released by its cancel: "For PaymentIntents with a `status` of `requires_capture`, the
2281
+ * remaining `amount_capturable` is automatically refunded" (docs.stripe.com/api/payment_intents/cancel), and since basil
2282
+ * a cancellation makes no Refund: "`amount_captured` will be 0 instead of `nil` in payment cancellation flows",
2283
+ * "`amount_refunded` will no longer be updated by these actions", "`refunded` will no longer be `true` for payment
2284
+ * cancellation flows", and no charge.refunded is sent (docs.stripe.com/changelog/basil/2025-03-31/remove-refund-from-
2285
+ * partial-capture-and-payment-cancellation-flow). The charge stays uncaptured; nothing is written as an event. */
2286
+ export async function cancelAuthorization(ctx: HandlerContext, ch: Row): Promise<Row> {
2287
+ return ctx.write('charge', String(ch.id), { amount_captured: 0 }, 'charge.authorization_released');
2288
+ }
2289
+
2290
+ /** An authorized charge captured, by the charge's capture or its PaymentIntent's: what is captured credits the balance.
2291
+ * Written as charge.captured, "Occurs whenever a previously uncaptured charge is captured" (docs.stripe.com/api/events/types).
2292
+ * A partial capture releases the rest with no Refund and leaves amount_refunded and refunded as they were: "The following
2293
+ * flows no longer result in a `Refund` object created and linked to the payment: Partial capture", "`amount_refunded`
2294
+ * will no longer be updated by these actions", and "There will only be a single balance transaction for partial captures"
2295
+ * (docs.stripe.com/changelog/basil/2025-03-31/remove-refund-from-partial-capture-and-payment-cancellation-flow).
2296
+ * The caller has asked the machine whether it may capture. */
2297
+ export async function captureAuthorization(ctx: HandlerContext, ch: Row, toCapture: number, _operationId: string): Promise<Row> {
2298
+ const id = String(ch.id);
2299
+ const bt = toCapture > 0 ? await settleCharge(ctx, id, toCapture, String(ch.currency ?? 'usd'), String(ch.source ?? ch.payment_method ?? '')) : null;
2300
+ return ctx.write('charge', id, { captured: true, amount_captured: toCapture, balance_transaction: bt }, 'charge.captured');
2301
+ }
2302
+
2303
+ export const chargeRefund = (ctx: HandlerContext): Row | Response => {
2304
+ if (!ctx.get('charge', at(ctx, 'charge'))) return chargeMissing(ctx, at(ctx, 'charge'));
2305
+ const r = ctx.get('refund', at(ctx, 'refund'));
2306
+ return r && r.charge === at(ctx, 'charge') ? r : fail(ctx, `No such refund: '${at(ctx, 'refund')}'`, 404, 'resource_missing');
2307
+ };
2308
+
2309
+ export const subMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such subscription: '${id}'`, 404, 'resource_missing');
2310
+
2311
+ /** A coupon that replaces the subscription's discount, or an empty one that clears it (docs.stripe.com/api/subscriptions/update#update_subscription-discounts). */
2312
+ export function replacedDiscounts(ctx: HandlerContext, couponId: string, sub: Row): Row[] | Response {
2313
+ if (couponId === '') return [];
2314
+ const coupon = ctx.get('coupon', couponId);
2315
+ return coupon ? [buildDiscount(coupon, String(sub.customer ?? ''), Number(nowUnix(ctx.occurredAt)), { subscription: String(sub.id) })] : fail(ctx, `No such coupon: '${couponId}'`, 400, 'resource_missing');
2316
+ }
2317
+
2318
+ /** A `trial_end` Stripe refuses: the parameter is `"now" | timestamp` (docs.stripe.com/api/subscriptions/update), and a
2319
+ * timestamp that is not in the future answers "Invalid timestamp: must be an integer Unix timestamp in the future."
2320
+ * (Stripe's own message, as its SDKs' users report it: github.com/stripe/stripe-dotnet/issues/805,
2321
+ * github.com/stripe/stripe-ruby/issues/682). Where the documentation stops and the twin decides: a value that is no
2322
+ * number at all, and one more than two years on, answer that same message. */
2323
+ export function trialEndRefused(ctx: HandlerContext, value: unknown, now: number): Response | undefined {
2324
+ const t = typeof value === 'number' ? value : typeof value === 'string' && /^\d+$/.test(value.trim()) ? Number(value) : NaN;
2325
+ return value === undefined || value === 'now' || (Number.isInteger(t) && t > now && t <= now + MAX_TRIAL) ? undefined : invalidTrialEnd(ctx);
2326
+ }
2327
+
2328
+ export function invalidTrialEnd(ctx: HandlerContext): Response {
2329
+ return ctx.refuse({ status: 400, param: 'trial_end', message: 'Invalid timestamp: must be an integer Unix timestamp in the future.' });
2330
+ }
2331
+
2332
+ /** An update's `trial_end` on the subscription, into `fields`.
2333
+ *
2334
+ * `now` on a trialing subscription ends its trial at once: "The special value `now` can be provided to end the customer's
2335
+ * trial immediately" (docs.stripe.com/api/subscriptions/update#update_subscription-trial_end; the trials guide's "To end a
2336
+ * trial early … setting the `trial_end` value to … **now** to end immediately", docs.stripe.com/billing/subscriptions/
2337
+ * trials/free-trials). The update resets the billing date and charges at once: "Switching prices does not normally change
2338
+ * the billing date or generate an immediate charge unless … A trial starts or ends. In these cases, we … immediately
2339
+ * charge the customer using the new price, and reset the billing date" (docs.stripe.com/api/subscriptions/update), and
2340
+ * "Stripe immediately attempts payment when a subscription's billing cycle anchor is reset … When billing is performed
2341
+ * immediately, but the required payment fails, the subscription change request succeeds and the subscription transitions
2342
+ * to `past_due`" (docs.stripe.com/billing/subscriptions/upgrade-downgrade#immediate-payment). So a new period starts now,
2343
+ * its invoice is made (`invoice.created`) and charged to the subscription's default payment method, else the
2344
+ * customer's (paid: `invoice.paid`, the subscription `active`; declined or none: the invoice open, `past_due`), and the
2345
+ * subscription's own write sends `customer.subscription.updated`. `payment_behavior` (the same page): `error_if_incomplete`
2346
+ * answers 402 and leaves the subscription as it was, `default_incomplete` leaves the invoice open without an attempt.
2347
+ *
2348
+ * A future timestamp moves the trial's end, and the period and billing anchor with it: "The `billing_cycle_anchor` will be
2349
+ * updated to the `trial_end` value" (the same parameter); on a subscription out of its trial it starts a new one ("You can
2350
+ * add a new trial on a non-trialing subscription by updating the subscription while specifying trial_end", and for
2351
+ * classic billing mode "the `trial_start` field remains set to the start of the first trial", docs.stripe.com/billing/
2352
+ * subscriptions/trials/free-trials).
2353
+ *
2354
+ * Where the documentation stops and the twin decides: the invoice's billing_reason is `subscription_update` ("A
2355
+ * subscription was updated", docs.stripe.com/api/invoices/object#invoice_object-billing_reason); `now` on a subscription
2356
+ * that is not trialing has no trial to end and changes nothing; the credit Stripe prorates for the unused time when a new
2357
+ * trial starts mid-period is not made (as `proration_behavior=none` would have it); `pending_if_incomplete` answers as
2358
+ * `allow_incomplete` (no pending update is modelled). Answers a refusal, or the invoice to collect once the subscription is written. */
2359
+ export async function applyTrialEnd(ctx: HandlerContext, sub: Row, fields: Row, now: number): Promise<{ invoice: string; payer?: string; attempt: boolean } | undefined> {
2360
+ const value = ctx.params.trial_end;
2361
+ delete fields.trial_end;
2362
+ const id = String(sub.id);
2363
+ if (value !== 'now' || sub.status !== 'trialing') return value === 'now' ? undefined : movedTrial(sub, fields, Number(value), now);
2364
+ // the period's invoice bills the items as this update leaves them, under its discount
2365
+ const next: Row = { ...sub, ...fields, items: ctx.get(SUB, id)?.items ?? sub.items };
2366
+ const { interval, interval_count } = resolveSubscriptionBillingInterval(((next.items as { data?: Row[] } | undefined)?.data) ?? [], finder(ctx));
2367
+ const period = { start: now, end: addBillingInterval(now, interval, interval_count) };
2368
+ const invoice = await draftSubscriptionInvoice(ctx, next, { ...period, reason: 'subscription_update' });
2369
+ Object.assign(fields, { trial_end: now, billing_cycle_anchor: now, current_period_start: period.start, current_period_end: period.end, latest_invoice: invoice });
2370
+ const payer = trialPayer(ctx, sub);
2371
+ return { invoice, ...(payer ? { payer } : {}), attempt: ctx.params.payment_behavior !== 'default_incomplete' };
2372
+ }
2373
+
2374
+ /** What ending the trial charges: the update's own default payment method, else the subscription's, else its customer's. */
2375
+ export function trialPayer(ctx: HandlerContext, sub: Row): string | undefined {
2376
+ const given = ctx.params.default_payment_method;
2377
+ return typeof given === 'string' && given ? given : payerOf(ctx, sub);
2378
+ }
2379
+
2380
+ /** What an update's `trial_end` refuses before anything is written: a new trial the machine does not allow from the
2381
+ * subscription's status, or, under `error_if_incomplete`, ending a trial that cannot be paid at once ("If payment fails,
2382
+ * return an HTTP `402` status code and don't update the subscription", docs.stripe.com/api/subscriptions/update). */
2383
+ export function trialEndBlocked(ctx: HandlerContext, sub: Row, discounts: Row[] | undefined): Response | undefined {
2384
+ if (ctx.params.trial_end !== 'now') return newTrialRefused(ctx, sub);
2385
+ if (sub.status !== 'trialing') return undefined;
2386
+ const charge = trialEndCharge(ctx, sub, discounts);
2387
+ if (ctx.params.payment_behavior === 'error_if_incomplete' && charge.due > 0 && !charge.pays) return firstPaymentRefused(ctx, charge.declined);
2388
+ // the move ending the trial makes (paid or nothing due: active; else past_due) is the machine's, asked before
2389
+ // anything is written
2390
+ const refused = ctx.legal(SUB, 'status', ctx.call.operation.id, 'trialing', charge.due <= 0 || charge.pays ? 'active' : 'past_due', String(sub.id));
2391
+ return refused ? ctx.refuse(refused) : undefined;
2392
+ }
2393
+
2394
+ /** A price named by id, or given as an object. */
2395
+ export function priceRow(ctx: HandlerContext, price: unknown): Row | undefined {
2396
+ return typeof price === 'string' ? ctx.get('price', price) : price && typeof price === 'object' ? (price as Row) : undefined;
2397
+ }
2398
+
2399
+ /** One period of the subscription's items as an update's `items` would leave them, before any discount: an entry naming
2400
+ * an item changes its price and quantity (a new price resets the quantity to 1 unless one is given) or deletes it, and
2401
+ * one naming none adds an item (applyItemChanges). */
2402
+ export function dueAfter(ctx: HandlerContext, sub: Row, entries: Row[]): number {
2403
+ const lines = new Map<string, { price: Row | undefined; quantity: number }>();
2404
+ for (const it of ((sub.items as { data?: Row[] } | undefined)?.data) ?? []) lines.set(String(it.id), { price: priceRow(ctx, it.price), quantity: itemQuantity(it) });
2405
+ entries.forEach((e, i) => entryAfter(ctx, lines, e, i));
2406
+ return [...lines.values()].reduce((sum, l) => sum + priceAmount(l.price, l.quantity), 0);
2407
+ }
2408
+
2409
+ /** One entry of an update's `items` on the lines it would leave (dueAfter). */
2410
+ export function entryAfter(ctx: HandlerContext, lines: Map<string, { price: Row | undefined; quantity: number }>, e: Row, i: number): void {
2411
+ // an inline price bills as the Price inlinePrice makes of it
2412
+ const d = e.price_data && typeof e.price_data === 'object' ? (e.price_data as Row) : undefined;
2413
+ const inline: Row | undefined = d ? (d.unit_amount_decimal !== undefined ? { unit_amount_decimal: String(d.unit_amount_decimal) } : { unit_amount: Math.trunc(Number(d.unit_amount) || 0) }) : undefined;
2414
+ const price = typeof e.price === 'string' && e.price ? priceRow(ctx, e.price) : inline;
2415
+ const named = typeof e.id === 'string' && e.id;
2416
+ const key = named ? String(e.id) : `new_${i}`;
2417
+ // only a named item is deleted; an entry naming none adds one, as applyItemChanges does
2418
+ if (named && asBool(e.deleted)) { lines.delete(key); return; }
2419
+ const was = lines.get(key);
2420
+ const quantity = e.quantity !== undefined ? Math.max(0, Math.trunc(Number(e.quantity) || 0)) : price && was && price.id !== was.price?.id ? 1 : was?.quantity ?? 1;
2421
+ lines.set(key, { price: price ?? was?.price, quantity });
2422
+ }
2423
+
2424
+ /** A new trial on a subscription whose status the machine does not let start one. */
2425
+ export function newTrialRefused(ctx: HandlerContext, sub: Row): Response | undefined {
2426
+ const refused = sub.status === 'trialing' ? undefined : ctx.legal(SUB, 'status', ctx.call.operation.id, sub.status, 'trialing', String(sub.id));
2427
+ return refused ? ctx.refuse(refused) : undefined;
2428
+ }
2429
+
2430
+ /** What ending the trial charges, judged before anything is written: the period of the items as this update leaves them
2431
+ * (dueAfter) under the discount it leaves, and whether the payer pays it (an attempt made, a payer, no decline). */
2432
+ export function trialEndCharge(ctx: HandlerContext, sub: Row, discounts: Row[] | undefined): { due: number; pays: boolean; declined?: ReturnType<typeof declineFor> } {
2433
+ const subtotal = dueAfter(ctx, sub, subscriptionItemEntries(ctx.params.items));
2434
+ // the discount the subscription carries after this update takes this invoice (renewals.ts draftSubscriptionInvoice)
2435
+ const discount = (discounts ?? (sub.discounts as Row[] | undefined) ?? [])[0];
2436
+ const coupon = discount && typeof discount === 'object' ? (discount.coupon as Row | undefined) : undefined;
2437
+ const due = subtotal - (coupon ? applyCouponDiscount(subtotal, coupon) : 0);
2438
+ const payer = trialPayer(ctx, sub);
2439
+ const attempt = ctx.params.payment_behavior !== 'default_incomplete';
2440
+ const declined = payer && attempt ? declineFor(finder(ctx), { payment_method: payer }) : undefined;
2441
+ return { due, pays: attempt && !!payer && !declined, ...(declined ? { declined } : {}) };
2442
+ }
2443
+
2444
+ /** A new item named with neither `price` nor `price_data`: "One of `price` or `price_data` is required"
2445
+ * (docs.stripe.com/api/subscriptions/update). */
2446
+ export function noItemPrice(ctx: HandlerContext): Response {
2447
+ return fail(ctx, 'Missing required param: items[price].', 400, 'parameter_missing');
2448
+ }
2449
+
2450
+ /** A subscription asked to fail when its first invoice cannot be paid at once (payment_behavior=error_if_incomplete):
2451
+ * the card's decline, or no payment method to charge (docs.stripe.com/api/subscriptions/create#create_subscription-payment_behavior). */
2452
+ export function firstPaymentRefused(ctx: HandlerContext, declined: Parameters<typeof cardError>[0] | null | undefined): Response {
2453
+ return declined ? send(ctx, cardError(declined)) : fail(ctx, 'This customer has no attached payment source or default payment method.', 400, 'resource_missing');
2454
+ }
2455
+
2456
+ /** An update's `items`: "A list of up to 20 subscription items, each with an attached price"
2457
+ * (docs.stripe.com/api/subscriptions/update): an entry naming an item's `id` changes that item (its price, quantity,
2458
+ * metadata) or, with `deleted` ("A flag that, if set to `true`, will delete the specified item"), removes it; "If you
2459
+ * omit `id`, the API adds a new subscription item rather than updating the existing one". Each takes `price` or
2460
+ * `price_data`, "Data used to generate a new Price object inline. One of `price` or `price_data` is required", and
2461
+ * "When changing a subscription item's price, `quantity` is set to 1 unless a `quantity` parameter is provided". An
2462
+ * inline price is made as the manage-prices guide says: "By default, prices created with `price_data` are effectively
2463
+ * archived (they're marked as `active=false`)" (docs.stripe.com/products-prices/manage-prices).
2464
+ * Where the documentation stops and the twin decides: the update is all or nothing, every entry checked before any is
2465
+ * written (Stripe answers one error for the request); the refusals are worded by the twin. */
2466
+ export async function applyItemChanges(ctx: HandlerContext, subId: string, entries: Row[]): Promise<Response | undefined> {
2467
+ // every entry is checked first: a refusal leaves the subscription as it was
2468
+ const refused = itemChangesRefused(ctx, subId, entries);
2469
+ if (refused) return refused;
2470
+ return writeItemChanges(ctx, subId, entries);
2471
+ }
2472
+
2473
+ /** The refusal of an update's `items`, checked entry by entry before any is written (applyItemChanges). */
2474
+ export function itemChangesRefused(ctx: HandlerContext, subId: string, entries: Row[]): Response | undefined {
2475
+ for (const entry of entries) {
2476
+ const priceRef = typeof entry.price === 'string' && entry.price ? entry.price : undefined;
2477
+ if (priceRef && !ctx.get('price', priceRef)) return fail(ctx, `No such price: '${priceRef}'`, 400, 'resource_missing');
2478
+ const inline = !priceRef && entry.price_data && typeof entry.price_data === 'object' ? (entry.price_data as Row) : undefined;
2479
+ if (inline) {
2480
+ const refused = refuseInlinePrice(ctx, inline);
2481
+ if (refused) return refused;
2482
+ }
2483
+ if (typeof entry.id === 'string' && entry.id) {
2484
+ const si = ctx.get('subscription_item', entry.id);
2485
+ if (!si || si.subscription !== subId) return fail(ctx, `No such subscription_item: '${entry.id}'`, 400, 'resource_missing');
2486
+ } else if (!priceRef && !inline) return noItemPrice(ctx);
2487
+ }
2488
+ return undefined;
2489
+ }
2490
+
2491
+ /** An update's checked `items`, written. */
2492
+ export async function writeItemChanges(ctx: HandlerContext, subId: string, entries: Row[]): Promise<undefined> {
2493
+ for (const entry of entries) {
2494
+ const inline = typeof entry.price === 'string' && entry.price ? undefined : entry.price_data && typeof entry.price_data === 'object' ? (entry.price_data as Row) : undefined;
2495
+ const priceRef = typeof entry.price === 'string' && entry.price ? entry.price : inline ? await inlinePrice(ctx, inline) : undefined;
2496
+ // only a price that changes resets the quantity; one naming the item's own price leaves it
2497
+ const was = typeof entry.id === 'string' && entry.id ? ctx.get('subscription_item', entry.id)?.price : undefined;
2498
+ const wasId = typeof was === 'string' ? was : was && typeof was === 'object' ? String((was as Row).id ?? '') : undefined;
2499
+ const quantity = entry.quantity !== undefined ? { quantity: Math.max(0, Math.trunc(Number(entry.quantity) || 0)) } : priceRef && priceRef !== wasId ? { quantity: 1 } : {};
2500
+ const metadata = entry.metadata && typeof entry.metadata === 'object' ? { metadata: entry.metadata } : {};
2501
+ if (typeof entry.id === 'string' && entry.id) {
2502
+ if (asBool(entry.deleted)) { await ctx.write('subscription_item', entry.id, { deleted: true }, 'subscription_item.delete'); continue; }
2503
+ await ctx.write('subscription_item', entry.id, { ...(priceRef ? subscriptionItemPrice(priceRef, finder(ctx)) : {}), ...quantity, ...metadata }, 'subscription_item.update');
2504
+ } else {
2505
+ await created(ctx, 'subscription_item', { subscription: subId, ...subscriptionItemPrice(priceRef, finder(ctx)), quantity: 1, ...quantity, ...metadata }, { livemode: false, metadata: {}, discounts: [], tax_rates: [], billing_thresholds: null });
2506
+ }
2507
+ }
2508
+ await syncItems(ctx, subId);
2509
+ return undefined;
2510
+ }
2511
+
2512
+ /** A subscription item's `price_data` Stripe would refuse: its required `currency`, `product` (an existing one) and
2513
+ * `recurring[interval]`, and "Only one of `unit_amount` and `unit_amount_decimal` can be set". */
2514
+ export function refuseInlinePrice(ctx: HandlerContext, d: Row): Response | undefined {
2515
+ for (const name of ['currency', 'product']) if (typeof d[name] !== 'string' || !d[name]) return fail(ctx, `Missing required param: items[price_data][${name}].`, 400, 'parameter_missing');
2516
+ if (!ctx.get('product', String(d.product))) return fail(ctx, `No such product: '${String(d.product)}'`, 400, 'resource_missing');
2517
+ const interval = (d.recurring as Row | undefined)?.interval;
2518
+ if (!['day', 'week', 'month', 'year'].includes(String(interval))) return fail(ctx, 'Missing required param: items[price_data][recurring][interval].', 400, 'parameter_missing');
2519
+ if (d.unit_amount !== undefined && d.unit_amount_decimal !== undefined) return fail(ctx, 'Only one of `unit_amount` and `unit_amount_decimal` can be set.', 400, 'parameter_invalid');
2520
+ return undefined;
2521
+ }
2522
+
2523
+ /** The inline Price a `price_data` generates: recurring, archived (active=false). Answers its id. */
2524
+ export async function inlinePrice(ctx: HandlerContext, d: Row): Promise<string> {
2525
+ const r = d.recurring as Row;
2526
+ const decimal = d.unit_amount_decimal !== undefined ? String(d.unit_amount_decimal) : String(Math.trunc(Number(d.unit_amount) || 0));
2527
+ const price = await created(ctx, 'price', {
2528
+ product: d.product, currency: String(d.currency).toLowerCase(),
2529
+ // a decimal amount that is not a whole number of the smallest unit has no integer unit_amount (as semantics/plans.ts)
2530
+ unit_amount: d.unit_amount_decimal !== undefined ? (Number.isInteger(Number(d.unit_amount_decimal)) ? Number(d.unit_amount_decimal) : null) : Math.trunc(Number(d.unit_amount) || 0), unit_amount_decimal: decimal,
2531
+ recurring: { interval: r.interval, interval_count: Math.max(1, Math.trunc(Number(r.interval_count ?? 1)) || 1), usage_type: 'licensed', trial_period_days: null, meter: null },
2532
+ tax_behavior: typeof d.tax_behavior === 'string' ? d.tax_behavior : 'unspecified',
2533
+ }, { active: false, livemode: false, billing_scheme: 'per_unit', type: 'recurring', metadata: {}, lookup_key: null, nickname: null });
2534
+ return String(price.id);
2535
+ }
2536
+
2537
+ // ── items: each write keeps the parent subscription's items.data in step, rebuilt from the live items ──
2538
+
2539
+ /** A new subscription's items, each its own subscription_item as Stripe keeps it (/v1/subscription_items/{id}). */
2540
+ export async function storeItems(ctx: HandlerContext, subId: string, items: Row[]): Promise<void> {
2541
+ for (const item of items) {
2542
+ if (typeof item.id !== 'string' || ctx.get('subscription_item', item.id)) continue;
2543
+ await ctx.write('subscription_item', item.id, { ...item, subscription: subId }, 'subscription_item.create');
2544
+ }
2545
+ }
2546
+
2547
+ export async function syncItems(ctx: HandlerContext, subId: string): Promise<void> {
2548
+ if (!subId) return;
2549
+ const items = ctx.rows('subscription_item').filter((r) => r.subscription === subId);
2550
+ await ctx.write(SUB, subId, { items: { object: 'list', data: items, has_more: false, total_count: items.length, url: `/v1/subscription_items?subscription=${subId}` } }, 'subscription.items_synced');
2551
+ }
2552
+
2553
+ /** A subscription item with its billing period: its subscription's (basil moved the period onto the items). */
2554
+ export const withPeriod = (ctx: HandlerContext, si: Row): Row => {
2555
+ const sub = ctx.get(SUB, String(si.subscription));
2556
+ return { ...si, current_period_start: si.current_period_start ?? sub?.current_period_start ?? null, current_period_end: si.current_period_end ?? sub?.current_period_end ?? null };
2557
+ };
2558
+
2559
+ export const subscriptionsItemMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such subscription_item: '${id}'`, 404, 'resource_missing');
2560
+
2561
+ export const listMissing = (ctx: HandlerContext, id: string, status = 404): Response => fail(ctx, `No such radar value list: '${id}'`, status, 'resource_missing');
2562
+
2563
+ /** A value list's list_items, "List of items contained within this value list" (the served spec), kept in step with
2564
+ * its items, at the address the fixture names (/v1/radar/value_list_items?value_list=…). */
2565
+ export async function radarSyncItems(ctx: HandlerContext, listId: string): Promise<void> {
2566
+ const data = newest(ctx, VLI).filter((i) => i.value_list === listId);
2567
+ await ctx.write(VL, listId, { list_items: { object: 'list', data, has_more: false, url: `/v1/radar/value_list_items?value_list=${listId}` } }, 'radar.value_list.items_synced');
2568
+ }
2569
+
2570
+ /** A requested move of a state field the machine declares, legal or refused; a value the machine
2571
+ * does not name is written as given, as the hand-written route did. */
2572
+ export function requestedMove(ctx: HandlerContext, resource: string, operationId: string, current: unknown, values: string[]): Response | undefined {
2573
+ const to = ctx.params.status;
2574
+ if (typeof to !== 'string' || !values.includes(to)) return undefined;
2575
+ const refused = ctx.legal(resource, 'status', operationId, current, to);
2576
+ return refused ? ctx.refuse(refused) : undefined;
2577
+ }
2578
+
2579
+ // ── authorizations ──
2580
+
2581
+ /** An authorization as every egress carries it: its card embedded in full. */
2582
+ export function withCard(ctx: HandlerContext, a: Row): Row {
2583
+ const out = { ...a };
2584
+ if (typeof out.card === 'string') {
2585
+ const card = ctx.get(CARD, out.card);
2586
+ if (card) out.card = card;
2587
+ }
2588
+ return out;
2589
+ }
2590
+
2591
+ export const authMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such authorization: '${id}'`, 404, 'resource_missing');
2592
+
2593
+ /** A capture: an Issuing transaction (negative: it debits) and the issuing balance's debit. */
2594
+ export async function capture(ctx: HandlerContext, authId: string, auth: Row, amountCents: number): Promise<{ txnId: string; btId: string }> {
2595
+ const currency = typeof auth.currency === 'string' ? auth.currency : 'usd';
2596
+ const bt = await created(ctx, 'balance_transaction', {}, {
2597
+ amount: -amountCents, currency, fee: 0, net: -amountCents, type: 'issuing_transaction',
2598
+ status: 'available', balance_type: 'issuing', reporting_category: 'issuing_transaction',
2599
+ available_on: nowUnix(ctx.occurredAt), fee_details: [],
2600
+ });
2601
+ const txn = await created(ctx, TXN, { authorization: authId, card: auth.card, cardholder: auth.cardholder }, {
2602
+ type: 'capture', amount: -amountCents, currency,
2603
+ merchant_amount: -amountCents, merchant_currency: typeof auth.merchant_currency === 'string' ? auth.merchant_currency : currency,
2604
+ merchant_data: auth.merchant_data ?? merchantData(undefined),
2605
+ livemode: false, metadata: {}, dispute: null, wallet: null, network_data: null,
2606
+ amount_details: null, purchase_details: null, balance_transaction: bt.id,
2607
+ });
2608
+ return { txnId: String(txn.id), btId: String(bt.id) };
2609
+ }
2610
+
2611
+ /** Issuing refusals of a request no story sends: an unknown card status or authorization method, and a capture of an
2612
+ * authorization that is not approved and pending. */
2613
+ export function issuingRefusal(ctx: HandlerContext, what: 'card_status' | 'authorization_method' | 'not_capturable', auth?: Row): Response {
2614
+ switch (what) {
2615
+ case 'card_status': return fail(ctx, "Invalid status: must be one of 'active', 'inactive', or 'canceled'.", 400, 'parameter_invalid_string_enum');
2616
+ case 'authorization_method': return fail(ctx, "Invalid authorization_method: must be one of 'chip', 'contactless', 'keyed_in', 'online', or 'swipe'.", 400, 'parameter_invalid_string_enum');
2617
+ case 'not_capturable': return fail(ctx, `This authorization cannot be captured because it is not an approved pending authorization (status: ${String(auth?.status)}, approved: ${auth?.approved === true}).`, 400);
2618
+ }
2619
+ }
2620
+
2621
+ /** A partial approval's refusal: "You can specify the amount you want to approve by setting the amount in the webhook
2622
+ * response body or the approve call" only "When an authorization is partially authorized, the is_amount_controllable
2623
+ * field on the authorization request is set to true" (docs.stripe.com/issuing/purchases/authorizations), and never a
2624
+ * credit. Answers the refusal, or undefined when the amount may be approved. */
2625
+ export function partialApprovalRefused(ctx: HandlerContext, auth: Row): Response | undefined {
2626
+ if (Math.trunc(Number(ctx.params.amount) || 0) <= 0) return fail(ctx, 'Invalid integer: amount must be a positive integer.', 400, 'parameter_invalid_integer');
2627
+ if ((auth.pending_request as Row | null | undefined)?.is_amount_controllable !== true) return fail(ctx, 'amount may only be provided when the authorization was presented with is_amount_controllable.', 400);
2628
+ return undefined;
2629
+ }
2630
+
2631
+ // the (deprecated but real) API decision on a pending authorization: it lands in request_history
2632
+ // as the webhook's answer would, consumes the pending request, and an approval captures
2633
+ export function issuingDecide(approved: boolean): Handler {
2634
+ return async (ctx) => {
2635
+ const id = at(ctx, 'authorization');
2636
+ const auth = ctx.get(AUTH, id);
2637
+ if (!auth) return authMissing(ctx, id);
2638
+ const finalized = { status: 400, code: 'authorization_already_finalized', message: `This authorization has already been finalized (status ${String(auth.status)}).` };
2639
+ // a webhook-approved authorization is decided, though still pending
2640
+ if (auth.approved === true) return ctx.refuse(finalized);
2641
+ const refused = ctx.legal(AUTH, 'status', approved ? 'PostIssuingAuthorizationsAuthorizationApprove' : 'PostIssuingAuthorizationsAuthorizationDecline', auth.status, undefined, id);
2642
+ if (refused) return ctx.refuse(refused);
2643
+ // a partial approval only for an amount-controllable presentment, and never a credit
2644
+ const badAmount = approved && ctx.params.amount !== undefined ? partialApprovalRefused(ctx, auth) : undefined;
2645
+ if (badAmount) return badAmount;
2646
+ const decidedAmount = approved && ctx.params.amount !== undefined ? Math.trunc(Number(ctx.params.amount) || 0) : Number(auth.amount) || 0;
2647
+ const currency = typeof auth.currency === 'string' ? auth.currency : 'usd';
2648
+ const history = Array.isArray(auth.request_history) ? (auth.request_history as Row[]) : [];
2649
+ // an approval holds the funds and waits for the merchant's capture; a decline closes it
2650
+ // (docs.stripe.com/issuing/purchases/authorizations, docs.stripe.com/issuing/funding/balance)
2651
+ const hold = approved ? await holdFor(ctx, id, decidedAmount, currency) : null;
2652
+ return ctx.reply(withCard(ctx, await ctx.write(AUTH, id, {
2653
+ ...(approved ? {} : { status: 'closed' }), approved, pending_request: null,
2654
+ ...(approved && ctx.params.amount !== undefined ? { amount: decidedAmount } : {}),
2655
+ request_history: [...history, historyEntry({
2656
+ amount: decidedAmount, currency, approved, reason: approved ? 'webhook_approved' : 'webhook_declined', reasonMessage: null,
2657
+ createdSec: Number(nowUnix(ctx.occurredAt)), merchantAmount: Number(auth.merchant_amount) || decidedAmount,
2658
+ merchantCurrency: typeof auth.merchant_currency === 'string' ? auth.merchant_currency : currency,
2659
+ })],
2660
+ ...(hold ? { balance_transactions: [...(Array.isArray(auth.balance_transactions) ? auth.balance_transactions : []), hold.id] } : {}),
2661
+ }, 'issuing_authorization.updated'),
2662
+ ));
2663
+ };
2664
+ }
2665
+
2666
+ /** Time's decision on a real-time request no one answered, caught up to the World's clock: once its window has ended,
2667
+ * a pending authorization whose issuing_authorization.request went unanswered, and that no approve or decline decided,
2668
+ * is decided automatically, its request_history reason webhook_timeout ("webhook_timeout for all other failure modes",
2669
+ * the same page, beside webhook_error for a response Stripe cannot process).
2670
+ * Where the documentation stops and the twin decides: the timeout setting is the Dashboard's, which the API does not
2671
+ * answer, and the twin's is to decline; the window is measured in World time from the authorization's created. */
2672
+ export async function lapseRealtimeRequests(ctx: HandlerContext): Promise<void> {
2673
+ const now = Number(nowUnix(ctx.occurredAt));
2674
+ const requested = new Set(ctx.rows('event').filter((e) => e.type === 'issuing_authorization.request').map((e) => String(((e.data as Row | undefined)?.object as Row | undefined)?.id ?? '')));
2675
+ for (const a of ctx.rowsRaw(AUTH)) {
2676
+ if (a.status !== 'pending' || a.approved === true || !a.pending_request || !requested.has(String(a.id))) continue;
2677
+ const at = Number(a.created) + REALTIME_WINDOW_SECONDS;
2678
+ if (now < at) continue;
2679
+ const id = String(a.id);
2680
+ const currency = typeof a.currency === 'string' ? a.currency : 'usd';
2681
+ const amount = Number(a.amount) || 0;
2682
+ ctx.legal(AUTH, 'status', ctx.call.operation.id, 'pending', 'closed', id, 'time');
2683
+ await ctx.write(AUTH, id, {
2684
+ status: 'closed', approved: false, pending_request: null,
2685
+ request_history: [...(Array.isArray(a.request_history) ? (a.request_history as Row[]) : []), historyEntry({
2686
+ amount, currency, approved: false, reason: 'webhook_timeout', reasonMessage: null, createdSec: at,
2687
+ merchantAmount: Number(a.merchant_amount) || amount, merchantCurrency: typeof a.merchant_currency === 'string' ? a.merchant_currency : currency,
2688
+ })],
2689
+ }, 'issuing_authorization.updated');
2690
+ }
2691
+ }
2692
+
2693
+ /** An approval's hold: "If you approve the authorization, we deduct the `amount` from your Issuing balance and hold it
2694
+ * in reserve until the authorization is either captured, voided, or expired without capture"
2695
+ * (docs.stripe.com/issuing/purchases/authorizations). */
2696
+ export async function holdFor(ctx: HandlerContext, authId: string, amount: number, currency: string): Promise<Row> {
2697
+ return created(ctx, 'balance_transaction', {}, {
2698
+ amount: -amount, currency, fee: 0, net: -amount, type: 'issuing_authorization_hold',
2699
+ status: 'available', balance_type: 'issuing', reporting_category: 'issuing_authorization_hold',
2700
+ available_on: nowUnix(ctx.occurredAt), fee_details: [], source: authId,
2701
+ });
2702
+ }
2703
+
2704
+ /** An authorization approved as it is presented, its amount held: approved and pending until the merchant captures. */
2705
+ export async function approvedAtOnce(ctx: HandlerContext, subject: Row, fields: Row, held: number, entry: Row): Promise<Response> {
2706
+ const hold = await holdFor(ctx, String(subject.id), held, String(fields.currency ?? 'usd'));
2707
+ return ctx.reply(withCard(ctx, await created(ctx, AUTH, subject, { ...fields, amount: held, status: 'pending', approved: true, pending_request: null, request_history: [entry], balance_transactions: [hold.id] })));
2708
+ }
2709
+
2710
+ /** An authorization as the platform's real-time answer makes it: approved (in part, only when the request was
2711
+ * amount-controllable), declined, or declined for an answer Stripe cannot read (docs.stripe.com/issuing/controls/
2712
+ * real-time-authorizations: the response's `approved` and `amount`; webhook_error "if we can't process your response"). */
2713
+ export async function answeredByEndpoint(ctx: HandlerContext, outcome: { kind: 'approved'; amount?: number } | { kind: 'declined' } | { kind: 'error'; message: string }, o: {
2714
+ subject: Row; fields: Row; amount: number; controllable: boolean; entry: (e: { amount: number; approved: boolean; reason: string; reasonMessage: string | null }) => Row;
2715
+ decline: (reason: string, message: string | null) => Promise<Response>;
2716
+ }): Promise<Response> {
2717
+ if (outcome.kind === 'approved') {
2718
+ const held = o.controllable && outcome.amount !== undefined ? outcome.amount : o.amount;
2719
+ return approvedAtOnce(ctx, o.subject, o.fields, held, o.entry({ amount: held, approved: true, reason: 'webhook_approved', reasonMessage: null }));
2720
+ }
2721
+ return outcome.kind === 'declined' ? o.decline('webhook_declined', null) : o.decline('webhook_error', outcome.message);
2722
+ }
2723
+
2724
+ // ── disputes: opened against a transaction, unsubmitted until submitted ──
2725
+
2726
+ export const disputeMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such dispute: '${id}'`, 404, 'resource_missing');
2727
+
2728
+ // ── personalization designs: in review until Stripe's review (the test helpers in test mode) decides ──
2729
+
2730
+ export const designMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such personalization design: '${id}'`, 404, 'resource_missing');
2731
+
2732
+ export function review(action: 'activate' | 'deactivate' | 'reject', operationId: string): Handler {
2733
+ return async (ctx) => {
2734
+ const id = at(ctx, 'personalization_design');
2735
+ const d = ctx.get(PD, id);
2736
+ if (!d) return designMissing(ctx, id);
2737
+ const refused = ctx.legal(PD, 'status', operationId, d.status, undefined, id);
2738
+ if (refused) return ctx.refuse(refused);
2739
+ const status = action === 'activate' ? 'active' : action === 'deactivate' ? 'inactive' : 'rejected';
2740
+ // a rejection records its reasons: the reject helper's required rejection_reasons, "The reason(s) the
2741
+ // personalization design was rejected" (the served spec), per card_logo and carrier_text
2742
+ const given = ctx.params.rejection_reasons && typeof ctx.params.rejection_reasons === 'object' ? (ctx.params.rejection_reasons as Row) : undefined;
2743
+ if (action === 'reject' && !given) return fail(ctx, 'Missing required param: rejection_reasons.', 400, 'parameter_missing');
2744
+ const reasons = action === 'reject' ? { rejection_reasons: { card_logo: Array.isArray(given!.card_logo) ? given!.card_logo : [], carrier_text: Array.isArray(given!.carrier_text) ? given!.carrier_text : [] } } : {};
2745
+ return ctx.reply(await ctx.write(PD, id, { status, ...reasons }, `personalization_design.${action}`));
2746
+ };
2747
+ }
2748
+
2749
+ /**
2750
+ * Create a refund and land it on its charge. An omitted amount is the whole remaining balance. The
2751
+ * charge's write records `charge.refunded`, the event Stripe sends carrying the charge's new totals;
2752
+ * `refunded` is true only at the full amount.
2753
+ */
2754
+ /** A reason Stripe does not take (docs.stripe.com/api/refunds/create#create_refund-reason). */
2755
+ export function badReason(ctx: HandlerContext): Response {
2756
+ return fail(ctx, `Invalid refund reason: must be one of ${[...REFUND_REASONS].join(', ')}.`, 400, 'parameter_invalid_string_enum');
2757
+ }
2758
+
2759
+ /** A bank-transfer payment refunded with origin=customer_balance goes back to the cash balance
2760
+ * (docs.stripe.com/payments/customer-balance/refunding). */
2761
+ export async function backToCashBalance(ctx: HandlerContext, customer: string, currency: string, amount: number, refundId: string): Promise<void> {
2762
+ const before = ctx.rows('customer_cash_balance_transaction').filter((t) => t.customer === customer && String(t.currency) === currency).reduce((n, t) => n + (Number(t.net_amount) || 0), 0);
2763
+ await created(ctx, 'customer_cash_balance_transaction', { customer }, { currency, type: 'refunded_from_payment', net_amount: amount, ending_balance: before + amount, refunded_from_payment: { refund: refundId }, livemode: false });
2764
+ }
2765
+
2766
+ /** A capture=false charge's refund, which releases its whole authorization (see the header). */
2767
+ export async function refundUncaptured(ctx: HandlerContext, charge: Row, amount: number, remaining: number, params: Row): Promise<Response> {
2768
+ if (amount < remaining) return fail(ctx, `Charge ${String(charge.id)} is uncaptured: refunding it releases the whole authorization (${remaining}).`, 400, 'amount_too_small');
2769
+ const { reason, metadata } = params;
2770
+ return ctx.reply(await releaseAuthorization(ctx, charge, ctx.call.operation.id, { ...(reason !== undefined ? { reason } : {}), ...(metadata !== undefined ? { metadata } : {}) }));
2771
+ }
2772
+
2773
+ export async function refundCharge(ctx: HandlerContext, charge: Row, params: Row): Promise<Response> {
2774
+ const chargeId = String(charge.id);
2775
+ const total = Number(charge.amount) || 0;
2776
+ const already = Number(charge.amount_refunded) || 0;
2777
+ const remaining = Math.max(0, total - already);
2778
+ const amount = params.amount === undefined ? remaining : Math.trunc(Number(params.amount));
2779
+ if (!Number.isFinite(amount) || amount <= 0) return fail(ctx, 'Invalid integer: amount must be a positive integer.', 400, 'parameter_invalid_integer');
2780
+ if (amount > remaining) return fail(ctx, `Refund amount (${amount}) is greater than unrefunded amount on charge (${remaining}).`, 400, 'amount_too_large');
2781
+ if (params.reason !== undefined && !REFUND_REASONS.has(String(params.reason))) return badReason(ctx);
2782
+ // an authorization is released, never refunded out of the balance: a PaymentIntent's by cancelling the intent, a
2783
+ // capture=false charge's by its refund (refundUncaptured)
2784
+ if (charge.captured === false && typeof charge.payment_intent === 'string') return fail(ctx, `Charge ${chargeId} is uncaptured and can't be refunded directly; cancel its PaymentIntent (${charge.payment_intent}) to release the authorization.`, 400, 'payment_intent_unexpected_state');
2785
+ if (charge.captured === false) return refundUncaptured(ctx, charge, amount, remaining, params);
2786
+ const refunded = already + amount;
2787
+ // the refund that takes the rest refunds the charge: the charge machine's move under this operation
2788
+ if (refunded >= total && charge.refunded !== true) {
2789
+ const refused = ctx.legal('charge', 'refunded', ctx.call.operation.id, 'false', 'true', chargeId);
2790
+ if (refused) return ctx.refuse(refused);
2791
+ }
2792
+ // a refund has no `livemode` field; it debits the balance at once
2793
+ const refundId = ctx.mint('refund');
2794
+ const currency = String(charge.currency ?? 'usd');
2795
+ const pi = typeof charge.payment_intent === 'string' ? ctx.get('payment_intent', charge.payment_intent) : undefined;
2796
+ const byTransfer = ((pi?.payment_method_types as unknown[] | undefined) ?? []).includes('customer_balance');
2797
+ const toCashBalance = byTransfer && params.origin === 'customer_balance';
2798
+ const awaitsBank = byTransfer && !toCashBalance;
2799
+ const now = Number(nowUnix(ctx.occurredAt));
2800
+ const customer = typeof charge.customer === 'string' ? charge.customer : typeof pi?.customer === 'string' ? pi.customer : undefined;
2801
+ const emailTo = typeof params.instructions_email === 'string' ? params.instructions_email : (customer ? ctx.get('customer', customer)?.email : undefined) ?? null;
2802
+ // "Refunds use your available Stripe balance (not including pending amounts). If your available balance doesn't
2803
+ // cover the amount of the refund, Stripe holds the refund as pending for card transactions ... until your Stripe
2804
+ // balance becomes sufficient" (docs.stripe.com/refunds): the refund waits, moving no money, until the balance covers
2805
+ // it (settleHeldRefunds). Where the documentation stops and the twin decides: a refund of another payment method
2806
+ // short of balance is not modelled (Stripe fails it); the twin makes it as a card's.
2807
+ const account = actingAccount(ctx);
2808
+ const isCard = (charge.payment_method_details as Row | null | undefined)?.type === 'card';
2809
+ const held = !awaitsBank && !toCashBalance && isCard && availableAt(ctx, account, currency, now) < amount;
2810
+ if (held) ctx.legal('refund', 'status', ctx.call.operation.id, 'succeeded', 'pending', refundId);
2811
+ const bt = awaitsBank || held ? null : await settleRefund(ctx, refundId, amount, currency);
2812
+ if (toCashBalance && customer) await backToCashBalance(ctx, customer, currency, amount, refundId);
2813
+ const { reverse_transfer: reverseTransfer, refund_application_fee: refundFee, instructions_email: _email, origin: _origin, ...stored } = params;
2814
+ const share = (whole: number): number => Math.round((whole * amount) / (total || 1));
2815
+ let transferReversal: string | null = null;
2816
+ const transfer = typeof charge.transfer === 'string' ? ctx.get('transfer', charge.transfer) : undefined;
2817
+ if (reverseTransfer !== undefined && asBool(reverseTransfer) && transfer) {
2818
+ const back = Math.min(share(Number(transfer.amount) || 0), (Number(transfer.amount) || 0) - (Number(transfer.amount_reversed) || 0));
2819
+ const trr = await created(ctx, 'transfer_reversal', { amount: back, currency, transfer: transfer.id }, { balance_transaction: null, destination_payment_refund: null, source_refund: refundId, metadata: {} });
2820
+ const trrBt = await settleTransferReversal(ctx, String(trr.id), back, currency, String(transfer.destination));
2821
+ const reversal = await ctx.write('transfer_reversal', String(trr.id), { balance_transaction: trrBt }, 'transfer_reversal.updated');
2822
+ const reversed = (Number(transfer.amount_reversed) || 0) + back;
2823
+ const list = (transfer.reversals as Row | undefined) ?? { object: 'list', data: [], has_more: false, total_count: 0 };
2824
+ const data = [...(((list.data as unknown[]) ?? [])), reversal];
2825
+ await ctx.write('transfer', String(transfer.id), { amount_reversed: reversed, reversed: reversed >= (Number(transfer.amount) || 0), reversals: { ...list, data, total_count: data.length, url: `/v1/transfers/${String(transfer.id)}/reversals` } }, 'transfer.reversed');
2826
+ transferReversal = String(trr.id);
2827
+ }
2828
+ const fee = typeof charge.application_fee === 'string' ? ctx.get('application_fee', charge.application_fee) : undefined;
2829
+ if (refundFee !== undefined && asBool(refundFee) && fee) {
2830
+ const feeTotal = Number(fee.amount) || 0;
2831
+ const back = Math.min(share(feeTotal), feeTotal - (Number(fee.amount_refunded) || 0));
2832
+ const done = (Number(fee.amount_refunded) || 0) + back;
2833
+ if (!(done >= feeTotal && fee.refunded !== true && ctx.legal('application_fee', 'refunded', ctx.call.operation.id, 'false', 'true', String(fee.id)))) {
2834
+ const fr = await created(ctx, 'fee_refund', { amount: back, currency, fee: fee.id }, { balance_transaction: null, metadata: {} });
2835
+ const list = (fee.refunds as Row | undefined) ?? { object: 'list', data: [], has_more: false, total_count: 0 };
2836
+ const data = [...(((list.data as unknown[]) ?? [])), fr];
2837
+ await ctx.write('application_fee', String(fee.id), { amount_refunded: done, refunded: done >= feeTotal, refunds: { ...list, data, total_count: data.length, url: `/v1/application_fees/${String(fee.id)}/refunds` } }, 'application_fee.refunded');
2838
+ }
2839
+ }
2840
+ const body = await created(ctx, 'refund', {
2841
+ ...stored, id: refundId, charge: chargeId, amount, currency, transfer_reversal: transferReversal,
2842
+ ...(typeof charge.payment_intent === 'string' ? { payment_intent: charge.payment_intent } : {}),
2843
+ }, {
2844
+ status: awaitsBank ? 'requires_action' : held ? 'pending' : 'succeeded', metadata: {}, reason: null, receipt_number: null,
2845
+ ...(held ? { pending_reason: 'insufficient_funds', _account: account ?? null } : {}),
2846
+ balance_transaction: bt, source_transfer_reversal: null,
2847
+ // a bank transfer's refund goes to the customer's bank (a us_bank_transfer) or back to its cash balance
2848
+ // (customer_cash_balance): "If this is a `us_bank_transfer` refund, this hash contains the transaction specific details",
2849
+ // "If this is a `customer_cash_balance` refund ..." (docs.stripe.com/api/refunds/object, destination_details)
2850
+ ...(byTransfer
2851
+ ? { destination_details: toCashBalance ? { type: 'customer_cash_balance', customer_cash_balance: {} } : { type: 'us_bank_transfer', us_bank_transfer: { reference: null, reference_status: null } } }
2852
+ : refundDestination(charge, 'refund')),
2853
+ ...(awaitsBank ? { next_action: { type: 'display_details', display_details: { email_sent: { email_sent_at: now, email_sent_to: emailTo }, expires_at: now + 30 * 86_400 } } } : {}),
2854
+ });
2855
+ await ctx.write('charge', chargeId, { amount_refunded: refunded, refunded: refunded >= total }, 'charge.refunded');
2856
+ return ctx.reply(body);
2857
+ }
2858
+
2859
+ /** Time's settling of held refunds, caught up to the World's clock: each refund held for want of balance, oldest first,
2860
+ * is made at the first moment the account's available balance covers it (the funds that come due then), its debit
2861
+ * written then, as `refund.updated`. Where the documentation stops and the twin decides: a held refund is made the
2862
+ * moment the balance covers it. */
2863
+ export async function settleHeldRefunds(ctx: HandlerContext): Promise<void> {
2864
+ const now = Number(nowUnix(ctx.occurredAt));
2865
+ const heldRefunds = ctx.rowsRaw('refund').filter((r) => r.status === 'pending' && r.pending_reason === 'insufficient_funds').sort((a, b) => Number(a.created) - Number(b.created));
2866
+ for (const r of heldRefunds) {
2867
+ const account = typeof r._account === 'string' ? r._account : undefined;
2868
+ const currency = String(r.currency ?? 'usd');
2869
+ const amount = Number(r.amount) || 0;
2870
+ const when = [Number(r.created), ...fundsDueBetween(ctx, account, currency, Number(r.created), now)].find((t) => availableAt(ctx, account, currency, t) >= amount);
2871
+ if (when === undefined) continue;
2872
+ const c = await at_(ctx)(when);
2873
+ c.legal('refund', 'status', ctx.call.operation.id, 'pending', 'succeeded', String(r.id), 'vendor');
2874
+ const bt = await settleRefund(c, String(r.id), amount, currency, account ?? null);
2875
+ await c.write('refund', String(r.id), { status: 'succeeded', pending_reason: null, balance_transaction: bt }, 'refund.updated');
2876
+ }
2877
+ }
2878
+
2879
+ /** The charge a refund aims at: named directly, or reached through its PaymentIntent. */
2880
+ export function target(ctx: HandlerContext): Row | Response {
2881
+ const chargeId = typeof ctx.params.charge === 'string' ? ctx.params.charge : '';
2882
+ const piId = typeof ctx.params.payment_intent === 'string' ? ctx.params.payment_intent : '';
2883
+ if (!chargeId && !piId) return fail(ctx, 'One of `charge` or `payment_intent` is required.', 400, 'parameter_missing');
2884
+ if (chargeId) return ctx.get('charge', chargeId) ?? fail(ctx, `No such charge: '${chargeId}'`, 404, 'resource_missing');
2885
+ const pi = ctx.get('payment_intent', piId);
2886
+ if (!pi) return fail(ctx, `No such payment_intent: '${piId}'`, 404, 'resource_missing');
2887
+ const latest = typeof pi.latest_charge === 'string' ? pi.latest_charge : undefined;
2888
+ const ch = (latest ? ctx.get('charge', latest) : undefined) ?? newest(ctx, 'charge').find((c) => c.payment_intent === piId);
2889
+ return ch ?? fail(ctx, `This PaymentIntent does not have a successful charge to refund. Its status is ${String(pi.status)}.`, 400, 'payment_intent_unexpected_state');
2890
+ }
2891
+
2892
+ export const refundMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such refund: '${id}'`, 404, 'resource_missing');
2893
+
2894
+ /** Each advancing clock whose advance has taken its time reaches its target, caught up before anything is answered:
2895
+ * its frozen_time moves, it is ready, and its customers' trials and periods that ended by then end
2896
+ * (./renewals.ts advanceBilling). The advance's own write is when it began (the kernel's updatedAt). */
2897
+ export async function finishClockAdvances(ctx: HandlerContext): Promise<void> {
2898
+ const now = Number(nowUnix(ctx.occurredAt));
2899
+ for (const clock of ctx.rowsRaw(CLOCK)) {
2900
+ if (clock.status !== 'advancing') continue;
2901
+ if (Date.parse(String(clock.updatedAt)) / 1000 + ADVANCE_SECONDS > now) continue;
2902
+ const id = String(clock.id);
2903
+ const target = Number((clock.status_details as { advancing?: { target_frozen_time?: number } } | undefined)?.advancing?.target_frozen_time);
2904
+ ctx.legal(CLOCK, 'status', ctx.call.operation.id, 'advancing', 'ready', id, 'vendor');
2905
+ await ctx.write(CLOCK, id, { frozen_time: target, status: 'ready', status_details: {} }, 'test_clock.ready');
2906
+ await advanceBilling(ctx, (sub) => typeof sub.customer === 'string' && ctx.get('customer', sub.customer)?.test_clock === id);
2907
+ }
2908
+ }
2909
+
2910
+ /** What the platform saved, or the settings a new platform starts with (OAuth off, no redirect URI). */
2911
+ export function connectOAuthSettings(ctx: Pick<HandlerContext, 'rowsRaw'>): ConnectOAuthSettings {
2912
+ const row = ctx.rowsRaw(SETTINGS).find((r) => r.id === PLATFORM_CLIENT_ID);
2913
+ return { oauth_enabled: row?.oauth_enabled === true, redirect_uris: Array.isArray(row?.redirect_uris) ? (row!.redirect_uris as string[]) : [] };
2914
+ }
2915
+
2916
+ export const accountMissing = (ctx: HandlerContext, id: string, status = 404): Response => fail(ctx, `No such account: '${id}'`, status, 'resource_missing');
2917
+
2918
+ /** The account, tombstones included where the hand-written routes looked past a deletion. */
2919
+ export const accountRow = (ctx: HandlerContext, id: string): Row | undefined => ctx.row('account', id, { withDeleted: true });
2920
+
2921
+ /** Stripe's review of a Custom account once the platform gives it something: with nothing left due, its requested
2922
+ * capabilities become active and it can take charges and receive payouts; with something due again (its bank account
2923
+ * removed), they stop. Where the documentation stops and the twin decides: test-mode verification is immediate, and
2924
+ * it owes what customRequirements lists. An Express or Standard account is onboarded on Stripe's own pages. */
2925
+ export async function connectReview(ctx: HandlerContext, id: string): Promise<void> {
2926
+ const account = ctx.get('account', id);
2927
+ if (account && account.type === 'custom') await reviewCustom(ctx, id, account);
2928
+ }
2929
+
2930
+ /** The review of a Custom account (see review). */
2931
+ export async function reviewCustom(ctx: HandlerContext, id: string, account: Row): Promise<void> {
2932
+ const bank = ctx.rows('external_account').some((e) => e.account === id);
2933
+ const persons = ctx.rows('person').filter((p) => p.account === id);
2934
+ const { now: due, later } = customRequirements(account, bank, persons);
2935
+ // one account, one review: "If a connected account has both card_payments and transfers, and the status of either one
2936
+ // is inactive, then both capabilities are disabled" (docs.stripe.com/connect/account-capabilities)
2937
+ const ready = due.length === 0;
2938
+ const capabilities: Row = {};
2939
+ for (const [key, was] of Object.entries((account.capabilities as Row | undefined) ?? {})) {
2940
+ const to = ready ? 'active' : 'inactive';
2941
+ // Stripe's review moves each capability, as the machine declares it may
2942
+ if (was !== to) ctx.legal('capability', 'status', ctx.call.operation.id, String(was), to, key, 'vendor');
2943
+ capabilities[key] = to;
2944
+ }
2945
+ const requirements = { ...((account.requirements as Row | undefined) ?? {}), currently_due: due, eventually_due: [...due, ...later], past_due: [], disabled_reason: ready ? null : 'requirements.past_due', current_deadline: null };
2946
+ await ctx.write('account', id, { capabilities, requirements, charges_enabled: ready, payouts_enabled: ready, details_submitted: ready }, ready ? 'account.updated' : 'account.update');
2947
+ }
2948
+
2949
+ // ── persons on an account ──
2950
+
2951
+ export const personMissing = (ctx: HandlerContext): Response => fail(ctx, `No such person: '${at(ctx, 'person')}'`, 404, 'resource_missing');
2952
+
2953
+ export const accountPerson = (ctx: HandlerContext): Row | undefined => {
2954
+ const p = ctx.get('person', at(ctx, 'person'));
2955
+ return p && p.account === at(ctx, 'account') ? p : undefined;
2956
+ };
2957
+
2958
+ // ── external accounts: a payout destination from a token or a bank_account hash ──
2959
+
2960
+ export const externalMissing = (ctx: HandlerContext): Response => fail(ctx, `No such external account: '${at(ctx, 'id')}'`, 404, 'resource_missing');
2961
+
2962
+ export const accountExternal = (ctx: HandlerContext): Row | undefined => {
2963
+ const e = ctx.get('external_account', at(ctx, 'id'));
2964
+ return e && e.account === at(ctx, 'account') ? e : undefined;
2965
+ };
2966
+
2967
+ /** Whether the platform may create, update or delete an account's external accounts: "A platform can create, update, or
2968
+ * delete external accounts only for connected accounts without access to either the full Stripe or Express Dashboard
2969
+ * and where the platform is responsible for negative balances" (docs.stripe.com/connect/payouts-bank-accounts); it can
2970
+ * still view an Express account's ("A platform can view the external accounts of connected accounts that don’t have
2971
+ * access to the full Stripe Dashboard"). Where the documentation stops and the twin decides: the refusal. Stripe's
2972
+ * pages give no error code for it; the twin answers 403, which the errors page gives as "The API key doesn’t have
2973
+ * permissions to perform the request" (docs.stripe.com/api/errors), with the twin's own wording. The create page says
2974
+ * it too: "You can only specify connected accounts where account.controller.requirement_collection is `application`"
2975
+ * (docs.stripe.com/api/external_account_bank_accounts/create). */
2976
+ export function refuseExternalWrite(ctx: HandlerContext, account: string): Response | undefined {
2977
+ const row = accountRow(ctx, account);
2978
+ const controller = (row?.controller as Row | undefined) ?? controllerOf(String(row?.type ?? 'standard'));
2979
+ const dashboard = String(((controller.stripe_dashboard as Row | undefined)?.type) ?? '');
2980
+ const losses = String(((controller.losses as Row | undefined)?.payments) ?? '');
2981
+ if (dashboard === 'none' && losses === 'application') return undefined;
2982
+ return ctx.refuse({ status: 403, message: `This application does not have the required permissions to manage the external accounts of account '${account}': they can only be managed through the account's ${dashboard === 'express' ? 'Express' : 'Stripe'} Dashboard.` });
2983
+ }
2984
+
2985
+ /** Update and delete by id, finding tombstones as the hand-written routes did, with Stripe's own operation names. */
2986
+ export function patch(resource: string, param: string, missing: string, op: string): Handler {
2987
+ return (ctx) => patchRow(ctx, resource, param, missing, op);
2988
+ }
2989
+
2990
+ export async function patchRow(ctx: HandlerContext, resource: string, param: string, missing: string, op: string): Promise<Response> {
2991
+ const id = at(ctx, param);
2992
+ if (!ctx.row(resource, id, { withDeleted: true })) return fail(ctx, `No such ${missing}: '${id}'`, 404, 'resource_missing');
2993
+ return ctx.reply(await ctx.write(resource, id, ctx.params, op));
2994
+ }
2995
+
2996
+ // A reader's update takes its label and metadata only; it moves to another location by registering it
2997
+ // there again (https://docs.stripe.com/api/terminal/readers/update, docs.stripe.com/terminal/fleet/locations-and-zones)
2998
+ // (the parameter check refuses anything else, as Stripe does: ./params.ts)
2999
+ export const updateReader: Handler = patch(READER, 'reader', 'reader', 'terminal_reader.updated');
3000
+
3001
+ export function remove(resource: string, param: string, missing: string, op: string, object: string): Handler {
3002
+ return async (ctx) => {
3003
+ const id = at(ctx, param);
3004
+ if (!ctx.row(resource, id, { withDeleted: true })) return fail(ctx, `No such ${missing}: '${id}'`, 404, 'resource_missing');
3005
+ const row = ctx.get(resource, id);
3006
+ await ctx.write(resource, id, { deleted: true }, op);
3007
+ // a deleted reader still says what device it was
3008
+ return ctx.reply({ id, object, deleted: true, ...(object === 'terminal.reader' && row ? { device_type: row.device_type, serial_number: row.serial_number } : {}) });
3009
+ };
3010
+ }
3011
+
3012
+ export const readerMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such reader: '${id}'`, 404, 'resource_missing');
3013
+
3014
+ /** A card presented to a reader with no payment in progress. */
3015
+ export function nothingToPresent(ctx: HandlerContext): Response {
3016
+ return fail(ctx, 'This reader has no in-progress payment to present a payment method to.', 400, 'terminal_reader_invalid_state');
3017
+ }
3018
+
3019
+ /** Under manual capture the presented card only holds the amount (docs.stripe.com/terminal/payments/collect-card-payment#capture-payment):
3020
+ * the hold is an uncaptured charge, as an online authorization's is (authorizeCharge), which the intent's capture takes. */
3021
+ export async function holdForCapture(ctx: HandlerContext, piId: string, pi: Record<string, unknown>, pm: string, amount: number): Promise<void> {
3022
+ const charge = await authorizeCharge(ctx, piId, { ...pi, payment_method: pm }, amount);
3023
+ await ctx.write('payment_intent', piId, { status: 'requires_capture', payment_method: pm, amount_capturable: amount, latest_charge: charge }, 'payment_intent.amount_capturable_updated');
3024
+ }
3025
+
3026
+ /** Time's settling of top-ups, caught up to the World's clock: a pending top-up succeeds on its expected_availability_date,
3027
+ * its funds entered then in the balance it names. */
3028
+ export async function settleTopups(ctx: HandlerContext): Promise<void> {
3029
+ const now = Number(nowUnix(ctx.occurredAt));
3030
+ for (const t of ctx.rowsRaw('topup')) {
3031
+ if (t.status !== 'pending' || Number(t.expected_availability_date) > now) continue;
3032
+ const c = await at_(ctx)(Number(t.expected_availability_date));
3033
+ c.legal('topup', 'status', ctx.call.operation.id, 'pending', 'succeeded', String(t.id), 'vendor');
3034
+ const bt = await settleTopup(c, String(t.id), Number(t.amount), String(t.currency), t.destination_balance === 'issuing' ? 'issuing' : 'payments');
3035
+ await c.write('topup', String(t.id), { status: 'succeeded', balance_transaction: bt }, 'topup.succeeded');
3036
+ }
3037
+ }
3038
+
3039
+ export const disputesDisputeMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such dispute: '${id}'`, 404, 'resource_missing');
3040
+
3041
+ /** Evidence staged without submitting it (submit=false), or on a dispute already under review or decided. */
3042
+ export async function keepEvidence(ctx: HandlerContext, id: string, fields: Row): Promise<Response> {
3043
+ return ctx.reply(await ctx.write('dispute', id, fields, 'dispute.update'));
3044
+ }
3045
+
3046
+ export const meterMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such meter: '${id}'`, 404, 'resource_missing');
3047
+
3048
+ export function activation(kind: 'deactivate' | 'reactivate'): Handler {
3049
+ return async (ctx) => {
3050
+ const id = at(ctx, 'id');
3051
+ const m = ctx.get(METER, id);
3052
+ if (!m) return meterMissing(ctx, id);
3053
+ const refused = ctx.legal(METER, 'status', kind === 'deactivate' ? 'PostBillingMetersIdDeactivate' : 'PostBillingMetersIdReactivate', m.status, undefined, id);
3054
+ if (refused) return ctx.refuse(refused);
3055
+ const fields = { ...(kind === 'deactivate' ? { status: 'inactive', status_transitions: { deactivated_at: nowUnix(ctx.occurredAt) } } : { status: 'active', status_transitions: { deactivated_at: null } }), updated: nowUnix(ctx.occurredAt) };
3056
+ return ctx.reply(await ctx.write(METER, id, fields, `billing_meter.${kind}`));
3057
+ };
3058
+ }
3059
+
3060
+ export const grantMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such credit grant: '${id}'`, 404, 'resource_missing');
3061
+
3062
+ // expiring or voiding a grant stamps the instant; it no longer counts toward the balance
3063
+ export function endGrant(kind: 'expire' | 'void'): Handler {
3064
+ return async (ctx) => {
3065
+ const id = at(ctx, 'id');
3066
+ if (!ctx.get(GRANT, id)) return grantMissing(ctx, id);
3067
+ return ctx.reply(await ctx.write(GRANT, id, { ...(kind === 'void' ? { voided_at: nowUnix(ctx.occurredAt) } : { expires_at: nowUnix(ctx.occurredAt) }), updated: nowUnix(ctx.occurredAt) }, `credit_grant.${kind}`));
3068
+ };
3069
+ }
3070
+
3071
+ export function alertMove(kind: 'activate' | 'deactivate' | 'archive', operationId: string): Handler {
3072
+ return async (ctx) => {
3073
+ const id = at(ctx, 'id');
3074
+ const a = ctx.get(ALERT, id);
3075
+ if (!a) return fail(ctx, `No such alert: '${id}'`, 404, 'resource_missing');
3076
+ const refused = ctx.legal(ALERT, 'status', operationId, a.status, undefined, id);
3077
+ if (refused) return ctx.refuse(refused);
3078
+ const status = kind === 'activate' ? 'active' : kind === 'deactivate' ? 'inactive' : 'archived';
3079
+ return ctx.reply(await ctx.write(ALERT, id, { status }, `billing_alert.${kind}`));
3080
+ };
3081
+ }
3082
+
3083
+ export const transferMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such transfer: '${id}'`, 404, 'resource_missing');
3084
+
3085
+ /** A transfer to an account whose transfers capability is not active. */
3086
+ export function transfersInactive(ctx: HandlerContext): Response {
3087
+ 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' });
3088
+ }
3089
+
3090
+ /** A transfer from a charge whose funds have settled: "With a source_transaction, the transfer request returns success
3091
+ * regardless of your available balance if the related charge hasn't settled yet" (docs.stripe.com/connect/separate-
3092
+ * charges-and-transfers), so a settled one comes out of the available balance. */
3093
+ export function settledSourceRefused(ctx: HandlerContext, amount: number, currency: string): Response | undefined {
3094
+ return refusePayout(ctx, amount, currency, undefined);
3095
+ }
3096
+
3097
+ /** An application fee refunded to its whole through its own refunds endpoint: the fee machine's move, or its refusal. */
3098
+ export function feeFullyRefunded(ctx: HandlerContext, resource: string, flag: string, id: string): Response | undefined {
3099
+ const refused = ctx.legal(resource, flag, ctx.call.operation.id, 'false', 'true', id);
3100
+ return refused ? ctx.refuse(refused) : undefined;
3101
+ }
3102
+
3103
+ /** Take `amount` (the remainder by default) back out of a parent's total, as a child row appended to its list. */
3104
+ export async function giveBack(ctx: HandlerContext, o: {
3105
+ parent: Row; parentResource: string; child: string; childFields: (amount: number) => Row; childDefaults: Row;
3106
+ doneField: string; flag: string; listUrl: string; op: string; tooLarge: (remaining: number) => string;
3107
+ /** what the money movement itself writes, once the child exists */
3108
+ settle?: (child: Row, amount: number) => Promise<void>;
3109
+ }): Promise<Response> {
3110
+ const id = String(o.parent.id);
3111
+ const total = Number(o.parent.amount ?? 0);
3112
+ const already = Number(o.parent[o.doneField] ?? 0);
3113
+ const remaining = total - already;
3114
+ const amount = ctx.params.amount !== undefined ? Math.trunc(Number(ctx.params.amount) || 0) : remaining;
3115
+ if (amount <= 0 || amount > remaining) return fail(ctx, o.tooLarge(remaining), 400, 'amount_too_large');
3116
+ const done = already + amount;
3117
+ // a fee refunded in full is `refunded`: the application fee machine's move (a transfer's `reversed` is no state)
3118
+ const feeRefusal = o.parentResource === 'application_fee' && done >= total && o.parent[o.flag] !== true ? feeFullyRefunded(ctx, o.parentResource, o.flag, id) : undefined;
3119
+ if (feeRefusal) return feeRefusal;
3120
+ // the `metadata` a reversal or a fee refund is created with is its own ("Set of key-value pairs that you can attach to
3121
+ // an object", docs.stripe.com/api/transfer_reversals/create, docs.stripe.com/api/fee_refunds/create)
3122
+ const metadata = ctx.params.metadata && typeof ctx.params.metadata === 'object' ? { metadata: ctx.params.metadata } : {};
3123
+ const child = await created(ctx, o.child, { ...o.childFields(amount), ...metadata }, o.childDefaults);
3124
+ if (o.settle) await o.settle(child, amount);
3125
+ const existing = (o.parent[o.flag === 'reversed' ? 'reversals' : 'refunds'] as Row) ?? { object: 'list', data: [], has_more: false, total_count: 0 };
3126
+ const data = [...((existing.data as unknown[]) ?? []), child];
3127
+ await ctx.write(o.parentResource, id, {
3128
+ [o.doneField]: done, [o.flag]: done >= total,
3129
+ [o.flag === 'reversed' ? 'reversals' : 'refunds']: { ...existing, data, total_count: data.length, url: o.listUrl },
3130
+ }, o.op);
3131
+ return ctx.reply(child);
3132
+ }
3133
+
3134
+ export const feeMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such application fee: '${id}'`, 404, 'resource_missing');
3135
+
3136
+ /** An earlier version's payment_method_types refused: the first value that names no payment method type the
3137
+ * operation takes, in the intent's words or (a Checkout Session) the enum's. */
3138
+ export function unknownMethodType(ctx: HandlerContext, opId: string, given: unknown): Response | undefined {
3139
+ const values = Array.isArray(given) ? given : given && typeof given === 'object' ? Object.values(given) : [given];
3140
+ const checkout = opId === 'PostCheckoutSessions';
3141
+ const known = checkout ? CHECKOUT_METHOD_TYPES : PAYMENT_METHOD_TYPES;
3142
+ const i = values.findIndex((v) => !known.includes(String(v)));
3143
+ if (i < 0) return undefined;
3144
+ if (checkout) {
3145
+ const param = `payment_method_types[${i}]`;
3146
+ return ctx.refuse({ status: 400, param, message: `Invalid ${param}: must be one of ${oneOf(known)}` });
3147
+ }
3148
+ const doc = TYPES_DOC[opId.startsWith('PostSetupIntents') ? 'setup_intents' : 'payment_intents'];
3149
+ return ctx.refuse({ status: 400, param: 'payment_method_types', message: `The payment method type "${String(values[i])}" is invalid. See ${doc} for the full list of supported payment method types.` });
3150
+ }
3151
+
3152
+ /** payment_method_types refused where the caller's version removed it. */
3153
+ export const noLongerSupported = (ctx: HandlerContext, version: string): Response =>
3154
+ ctx.refuse({ status: 400, code: 'payment_method_types_no_longer_supported', param: 'payment_method_types', message: `payment_method_types is no longer supported in API version ${version}. Use allowed_payment_method_types, or dynamic payment methods, instead.` });
3155
+
3156
+ /** Stripe's refusal of a request whose top-level parameters the operation does not take, or undefined. */
3157
+ export function refuseParameters(ctx: HandlerContext): Response | undefined {
3158
+ const op = OPS.get(ctx.call.operation.id);
3159
+ if (!op) return undefined;
3160
+ const pinned = ctx.call.request.headers.get('stripe-version');
3161
+ const params = ctx.params;
3162
+ if (pinned && pinned < SERVED_VERSION) {
3163
+ if (!TYPED.has(op.id)) return undefined;
3164
+ if (params.payment_method_types === undefined) return undefined;
3165
+ if (REMOVED_TYPES.has(op.id) && methodTypesRemoved(pinned)) return noLongerSupported(ctx, pinned);
3166
+ return unknownMethodType(ctx, op.id, params.payment_method_types);
3167
+ }
3168
+ const method = ctx.call.request.method.toUpperCase();
3169
+ const known = new Set([...(op.query ?? []), ...(op.body ?? [])].map((p) => p.name).concat(DOCUMENTED[op.id] ?? []));
3170
+ if (REMOVED_TYPES.has(op.id) && params.payment_method_types !== undefined) return noLongerSupported(ctx, pinned ?? SERVED_VERSION);
3171
+ for (const name of Object.keys(params)) {
3172
+ if (!known.has(name)) return ctx.refuse({ status: 400, code: 'parameter_unknown', param: name, message: `Received unknown parameter: ${name}` });
3173
+ }
3174
+ const required = method === 'GET' || method === 'DELETE' ? (op.query ?? []) : (op.body ?? []);
3175
+ for (const p of required) {
3176
+ if (p.required && params[p.name] === undefined) return ctx.refuse({ status: 400, code: 'parameter_missing', param: p.name, message: `Missing required param: ${p.name}.` });
3177
+ }
3178
+ return undefined;
3179
+ }
3180
+
3181
+ /** A file's links, kept in step with the links made to it, at the address Stripe lists them
3182
+ * (/v1/file_links?file=…, the File object's example). */
3183
+ export async function syncLinks(ctx: HandlerContext, fileId: string): Promise<void> {
3184
+ const data = newest(ctx, 'file_link').filter((l) => l.file === fileId);
3185
+ await ctx.write('file', fileId, { links: { object: 'list', data, has_more: false, url: `/v1/file_links?file=${fileId}` } }, 'file.links_synced');
3186
+ }
3187
+
3188
+ // ── calculations: each line's tax on top of its amount; no `created`, a tax_date instead ──
3189
+
3190
+ export const calcMissing = (ctx: HandlerContext, id: string): Response => fail(ctx, `No such tax calculation: '${id}'`, 404, 'resource_missing');
3191
+
3192
+ /** A page of the line items a stored object carries. */
3193
+ export function taxLinePage(ctx: HandlerContext, holder: Row): Response {
3194
+ const li = holder.line_items as { data?: Row[] } | undefined;
3195
+ const { page, hasMore } = paginate(Array.isArray(li?.data) ? li!.data! : [], ctx.params);
3196
+ return ctx.reply({ object: 'list', url: path(ctx), has_more: hasMore, data: page });
3197
+ }
3198
+
3199
+ export const txMissing = (ctx: HandlerContext, id: string, status = 404): Response => fail(ctx, `No such tax transaction: '${id}'`, status, 'resource_missing');
3200
+
3201
+ /** An answer in the shape of the API version the caller is served (./version.ts), a webhook endpoint's `secret` shown
3202
+ * only at its creation ("Only returned at creation", docs.stripe.com/api/webhook_endpoints/object). */
3203
+ export async function rendered(request: Request, res: Response): Promise<Response> {
3204
+ const creates = request.method === 'POST' && new URL(request.url).pathname.replace(/\/+$/, '') === '/v1/webhook_endpoints';
3205
+ const pinned = request.headers.get('stripe-version');
3206
+ if (!(res.headers.get('content-type') ?? '').includes('json')) return res;
3207
+ if (!servesCurrent(pinned) && creates) return res;
3208
+ const expand = await expandOf(request.clone());
3209
+ const body = await res.json();
3210
+ const answered = creates ? body : withoutEndpointSecret(body);
3211
+ return new Response(JSON.stringify(servesCurrent(pinned) ? render(answered, pinned, expand) : answered), { status: res.status, statusText: res.statusText, headers: res.headers });
3212
+ }