@volter/twin-stripe 2.0.38 → 3.0.1

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 (402) hide show
  1. package/README.md +112 -207
  2. package/dist/generated/pack-facts.json +94 -0
  3. package/dist/journeys/coverage.json +596 -0
  4. package/dist/journeys/customer-life.json +6108 -0
  5. package/dist/journeys/customer-life.outline.md +371 -0
  6. package/dist/journeys/decisions.json +677 -0
  7. package/dist/journeys/demand.json +706 -0
  8. package/dist/journeys/score.json +853 -0
  9. package/dist/journeys/unreachable.json +102 -0
  10. package/dist/journeys/vendor-examples.json +8010 -0
  11. package/dist/spec/SOURCE.md +18 -0
  12. package/dist/spec/doc-examples.json +445 -0
  13. package/dist/spec/fixtures3.json.gz +0 -0
  14. package/dist/spec/openapi.json.gz +0 -0
  15. package/dist/spec/patches.json +34 -0
  16. package/dist/spec/sources.json +306 -0
  17. package/dist/src/cli.d.ts +0 -1
  18. package/dist/src/cli.js +11 -31
  19. package/dist/src/engine/after-payment.d.ts +8 -0
  20. package/dist/src/engine/after-payment.js +27 -0
  21. package/dist/src/engine/apps-secrets.d.ts +1 -0
  22. package/dist/src/engine/apps-secrets.js +3 -0
  23. package/dist/src/engine/balance.d.ts +5 -0
  24. package/dist/src/engine/balance.js +15 -0
  25. package/dist/src/engine/checkout.d.ts +24 -0
  26. package/dist/src/engine/checkout.js +30 -0
  27. package/dist/src/engine/common.d.ts +19 -0
  28. package/dist/src/engine/common.js +34 -0
  29. package/dist/src/engine/connect.d.ts +45 -0
  30. package/dist/src/engine/connect.js +108 -0
  31. package/dist/src/engine/customers.d.ts +4 -0
  32. package/dist/src/engine/customers.js +8 -0
  33. package/dist/src/engine/display.d.ts +11 -0
  34. package/dist/src/engine/display.js +13 -0
  35. package/dist/src/engine/files.d.ts +11 -0
  36. package/dist/src/engine/files.js +23 -0
  37. package/dist/src/engine/invoices.d.ts +21 -0
  38. package/dist/src/engine/invoices.js +84 -0
  39. package/dist/src/engine/issuing.d.ts +33 -0
  40. package/dist/src/engine/issuing.js +54 -0
  41. package/dist/src/engine/ledger.d.ts +8 -0
  42. package/dist/src/engine/ledger.js +8 -0
  43. package/dist/src/engine/oauth.d.ts +4 -0
  44. package/dist/src/engine/oauth.js +24 -0
  45. package/dist/src/engine/onboarding.d.ts +13 -0
  46. package/dist/src/engine/onboarding.js +42 -0
  47. package/dist/src/{stripe-params.d.ts → engine/params.d.ts} +20 -3
  48. package/dist/src/{stripe-params.js → engine/params.js} +7 -60
  49. package/dist/src/engine/payment-intents.d.ts +10 -0
  50. package/dist/src/engine/payment-intents.js +27 -0
  51. package/dist/src/engine/payment-methods.d.ts +16 -0
  52. package/dist/src/engine/payment-methods.js +22 -0
  53. package/dist/src/engine/radar.d.ts +2 -0
  54. package/dist/src/engine/radar.js +5 -0
  55. package/dist/src/engine/refunds.d.ts +1 -0
  56. package/dist/src/engine/refunds.js +3 -0
  57. package/dist/src/engine/renewals.d.ts +36 -0
  58. package/dist/src/engine/renewals.js +65 -0
  59. package/dist/src/{stripe-twin.d.ts → engine/stripe.d.ts} +12 -45
  60. package/dist/src/{stripe-twin.js → engine/stripe.js} +53 -387
  61. package/dist/src/engine/subscriptions.d.ts +11 -0
  62. package/dist/src/engine/subscriptions.js +30 -0
  63. package/dist/src/engine/transfers.d.ts +2 -0
  64. package/dist/src/engine/transfers.js +1 -0
  65. package/dist/src/{stripe-version.d.ts → engine/version.d.ts} +0 -2
  66. package/dist/src/{stripe-version.js → engine/version.js} +21 -9
  67. package/dist/src/engine/webhook-endpoints.d.ts +1 -0
  68. package/dist/src/engine/webhook-endpoints.js +12 -0
  69. package/dist/src/engine/webhooks.d.ts +31 -0
  70. package/dist/src/engine/webhooks.js +68 -0
  71. package/dist/src/fetch.d.ts +2 -0
  72. package/dist/src/fetch.js +26 -0
  73. package/dist/src/generated/surface.gen.json +1 -1
  74. package/dist/src/generated/ui.gen.json +1 -1
  75. package/dist/src/index.d.ts +5 -14
  76. package/dist/src/index.js +10 -75
  77. package/dist/src/manifest.js +478 -876
  78. package/dist/src/screens/billing-portal.d.ts +3 -0
  79. package/dist/src/screens/{portal.js → billing-portal.js} +32 -58
  80. package/dist/src/screens/checkout-js.d.ts +2 -0
  81. package/dist/src/screens/checkout-js.js +84 -0
  82. package/dist/src/screens/checkout.d.ts +2 -31
  83. package/dist/src/screens/checkout.js +32 -121
  84. package/dist/src/screens/connect-onboarding.d.ts +3 -0
  85. package/dist/src/screens/{onboarding.js → connect-onboarding.js} +38 -104
  86. package/dist/src/screens/dashboard.d.ts +3 -0
  87. package/dist/src/screens/dashboard.js +116 -0
  88. package/dist/src/screens/shared.d.ts +27 -0
  89. package/dist/src/screens/shared.js +87 -0
  90. package/dist/src/screens/stripe-js.d.ts +3 -0
  91. package/dist/src/screens/stripe-js.js +95 -0
  92. package/dist/src/semantics/account.d.ts +2 -0
  93. package/dist/src/semantics/account.js +8 -0
  94. package/dist/src/semantics/account_links.d.ts +2 -0
  95. package/dist/src/semantics/account_links.js +22 -0
  96. package/dist/src/semantics/accounts.d.ts +4 -0
  97. package/dist/src/semantics/accounts.js +40 -0
  98. package/dist/src/semantics/apps.d.ts +4 -0
  99. package/dist/src/semantics/{apps-secrets.js → apps.js} +14 -26
  100. package/dist/src/semantics/around.d.ts +2 -0
  101. package/dist/src/semantics/around.js +13 -0
  102. package/dist/src/semantics/balance.d.ts +2 -11
  103. package/dist/src/semantics/balance.js +3 -194
  104. package/dist/src/semantics/balance_transactions.d.ts +2 -0
  105. package/dist/src/semantics/balance_transactions.js +15 -0
  106. package/dist/src/semantics/billing_portal.d.ts +4 -0
  107. package/dist/src/semantics/billing_portal.js +36 -0
  108. package/dist/src/semantics/charges.d.ts +3 -28
  109. package/dist/src/semantics/charges.js +5 -202
  110. package/dist/src/semantics/checkout.d.ts +3 -20
  111. package/dist/src/semantics/checkout.js +21 -271
  112. package/dist/src/semantics/clock.d.ts +2 -0
  113. package/dist/src/semantics/clock.js +15 -0
  114. package/dist/src/semantics/coupons.d.ts +2 -6
  115. package/dist/src/semantics/coupons.js +2 -60
  116. package/dist/src/semantics/customers.d.ts +5 -6
  117. package/dist/src/semantics/customers.js +47 -413
  118. package/dist/src/semantics/doors.d.ts +23 -0
  119. package/dist/src/semantics/doors.js +73 -0
  120. package/dist/src/semantics/entitlements.d.ts +0 -2
  121. package/dist/src/semantics/entitlements.js +4 -95
  122. package/dist/src/semantics/events.d.ts +11 -0
  123. package/dist/src/semantics/events.js +31 -0
  124. package/dist/src/semantics/index.d.ts +2 -0
  125. package/dist/src/semantics/index.js +85 -0
  126. package/dist/src/semantics/invoice_payments.d.ts +2 -0
  127. package/dist/src/semantics/invoice_payments.js +12 -0
  128. package/dist/src/semantics/invoices.d.ts +11 -18
  129. package/dist/src/semantics/invoices.js +121 -440
  130. package/dist/src/semantics/issuing.d.ts +6 -13
  131. package/dist/src/semantics/issuing.js +58 -556
  132. package/dist/src/semantics/payment_intents.d.ts +3 -0
  133. package/dist/src/semantics/payment_intents.js +71 -0
  134. package/dist/src/semantics/payment_methods.d.ts +3 -0
  135. package/dist/src/semantics/payment_methods.js +15 -0
  136. package/dist/src/semantics/payouts.d.ts +3 -0
  137. package/dist/src/semantics/payouts.js +28 -0
  138. package/dist/src/semantics/prices.d.ts +4 -0
  139. package/dist/src/semantics/prices.js +37 -0
  140. package/dist/src/semantics/products.d.ts +4 -2
  141. package/dist/src/semantics/products.js +12 -138
  142. package/dist/src/semantics/promotion_codes.d.ts +3 -0
  143. package/dist/src/semantics/promotion_codes.js +35 -0
  144. package/dist/src/semantics/radar.d.ts +2 -2
  145. package/dist/src/semantics/radar.js +5 -74
  146. package/dist/src/semantics/refunds.d.ts +2 -9
  147. package/dist/src/semantics/refunds.js +3 -193
  148. package/dist/src/semantics/shared.d.ts +558 -55
  149. package/dist/src/semantics/shared.js +2070 -114
  150. package/dist/src/semantics/states.d.ts +462 -0
  151. package/dist/src/semantics/states.js +634 -0
  152. package/dist/src/semantics/subscriptions.d.ts +6 -11
  153. package/dist/src/semantics/subscriptions.js +37 -530
  154. package/dist/src/semantics/test_helpers.d.ts +3 -0
  155. package/dist/src/semantics/test_helpers.js +125 -0
  156. package/dist/src/semantics/transfers.d.ts +2 -2
  157. package/dist/src/semantics/transfers.js +6 -101
  158. package/dist/src/semantics/webhook_endpoints.d.ts +2 -0
  159. package/dist/src/semantics/webhook_endpoints.js +26 -0
  160. package/dist/src/server.d.ts +7 -0
  161. package/dist/src/server.js +7 -0
  162. package/generated/pack-facts.json +94 -0
  163. package/journeys/coverage.json +596 -0
  164. package/journeys/customer-life.json +6108 -0
  165. package/journeys/customer-life.outline.md +371 -0
  166. package/journeys/decisions.json +677 -0
  167. package/journeys/demand.json +706 -0
  168. package/journeys/score.json +853 -0
  169. package/journeys/unreachable.json +102 -0
  170. package/journeys/vendor-examples.json +8010 -0
  171. package/package.json +11 -20
  172. package/spec/SOURCE.md +18 -0
  173. package/spec/doc-examples.json +445 -0
  174. package/spec/fixtures3.json.gz +0 -0
  175. package/spec/openapi.json.gz +0 -0
  176. package/spec/patches.json +34 -0
  177. package/spec/sources.json +306 -0
  178. package/src/cli.ts +11 -28
  179. package/src/engine/after-payment.ts +29 -0
  180. package/src/engine/apps-secrets.ts +4 -0
  181. package/src/engine/balance.ts +32 -0
  182. package/src/engine/checkout.ts +39 -0
  183. package/src/engine/common.ts +49 -0
  184. package/src/engine/connect.ts +106 -0
  185. package/src/engine/customers.ts +10 -0
  186. package/src/engine/display.ts +18 -0
  187. package/src/engine/files.ts +28 -0
  188. package/src/engine/invoices.ts +102 -0
  189. package/src/engine/issuing.ts +66 -0
  190. package/src/engine/ledger.ts +48 -0
  191. package/src/engine/oauth.ts +18 -0
  192. package/src/engine/onboarding.ts +53 -0
  193. package/src/{stripe-params.ts → engine/params.ts} +7 -56
  194. package/src/engine/payment-intents.ts +32 -0
  195. package/src/engine/payment-methods.ts +24 -0
  196. package/src/engine/radar.ts +6 -0
  197. package/src/engine/refunds.ts +3 -0
  198. package/src/engine/renewals.ts +72 -0
  199. package/src/{stripe-twin.ts → engine/stripe.ts} +57 -400
  200. package/src/engine/subscriptions.ts +37 -0
  201. package/src/engine/transfers.ts +22 -0
  202. package/src/{stripe-version.ts → engine/version.ts} +19 -10
  203. package/src/engine/webhook-endpoints.ts +14 -0
  204. package/src/engine/webhooks.ts +70 -0
  205. package/src/fetch.ts +27 -0
  206. package/src/generated/surface.gen.json +1 -1
  207. package/src/generated/ui.gen.json +1 -1
  208. package/src/index.ts +10 -116
  209. package/src/manifest.ts +480 -904
  210. package/src/screens/{portal.tsx → billing-portal.tsx} +35 -42
  211. package/src/screens/checkout-js.ts +80 -0
  212. package/src/screens/checkout.tsx +32 -96
  213. package/src/screens/{onboarding.tsx → connect-onboarding.tsx} +39 -85
  214. package/src/screens/dashboard.tsx +178 -0
  215. package/src/screens/shared.tsx +84 -0
  216. package/src/screens/stripe-js.ts +102 -0
  217. package/src/semantics/account.ts +10 -0
  218. package/src/semantics/account_links.ts +20 -0
  219. package/src/semantics/accounts.ts +44 -0
  220. package/src/semantics/{apps-secrets.ts → apps.ts} +17 -33
  221. package/src/semantics/around.ts +17 -0
  222. package/src/semantics/balance.ts +6 -208
  223. package/src/semantics/balance_transactions.ts +18 -0
  224. package/src/semantics/billing_portal.ts +45 -0
  225. package/src/semantics/charges.ts +8 -212
  226. package/src/semantics/checkout.ts +25 -276
  227. package/src/semantics/clock.ts +19 -0
  228. package/src/semantics/coupons.ts +5 -68
  229. package/src/semantics/customers.ts +48 -414
  230. package/src/semantics/doors.ts +79 -0
  231. package/src/semantics/entitlements.ts +3 -94
  232. package/src/semantics/events.ts +37 -0
  233. package/src/semantics/index.ts +89 -0
  234. package/src/semantics/invoice_payments.ts +16 -0
  235. package/src/semantics/invoices.ts +112 -441
  236. package/src/semantics/issuing.ts +57 -573
  237. package/src/semantics/payment_intents.ts +76 -0
  238. package/src/semantics/payment_methods.ts +20 -0
  239. package/src/semantics/payouts.ts +29 -0
  240. package/src/semantics/prices.ts +41 -0
  241. package/src/semantics/products.ts +12 -146
  242. package/src/semantics/promotion_codes.ts +38 -0
  243. package/src/semantics/radar.ts +8 -79
  244. package/src/semantics/refunds.ts +4 -216
  245. package/src/semantics/shared.ts +2089 -135
  246. package/src/semantics/states.ts +662 -0
  247. package/src/semantics/subscriptions.ts +39 -542
  248. package/src/semantics/test_helpers.ts +119 -0
  249. package/src/semantics/transfers.ts +10 -132
  250. package/src/semantics/webhook_endpoints.ts +27 -0
  251. package/src/server.ts +7 -0
  252. package/client/dashboard-api.ts +0 -286
  253. package/client/stripe-mirror.css +0 -277
  254. package/client/stripe-mirror.tsx +0 -1559
  255. package/dist/client/dashboard-api.d.ts +0 -107
  256. package/dist/client/dashboard-api.js +0 -238
  257. package/dist/client/dashboard-api.ts +0 -286
  258. package/dist/client/stripe-mirror.bundle.js +0 -236
  259. package/dist/client/stripe-mirror.css +0 -277
  260. package/dist/client/stripe-mirror.d.ts +0 -134
  261. package/dist/client/stripe-mirror.js +0 -859
  262. package/dist/client/stripe-mirror.tsx +0 -1559
  263. package/dist/src/screens/connect-oauth.d.ts +0 -27
  264. package/dist/src/screens/connect-oauth.js +0 -414
  265. package/dist/src/screens/connect-settings.d.ts +0 -22
  266. package/dist/src/screens/connect-settings.js +0 -103
  267. package/dist/src/screens/consent-skin.d.ts +0 -4
  268. package/dist/src/screens/consent-skin.js +0 -18
  269. package/dist/src/screens/financial-connections.d.ts +0 -5
  270. package/dist/src/screens/financial-connections.js +0 -90
  271. package/dist/src/screens/identity.d.ts +0 -5
  272. package/dist/src/screens/identity.js +0 -86
  273. package/dist/src/screens/onboarding.d.ts +0 -13
  274. package/dist/src/screens/portal.d.ts +0 -5
  275. package/dist/src/screens/public-details.d.ts +0 -5
  276. package/dist/src/screens/public-details.js +0 -90
  277. package/dist/src/semantics/after-payment.d.ts +0 -22
  278. package/dist/src/semantics/after-payment.js +0 -99
  279. package/dist/src/semantics/apps-secrets.d.ts +0 -2
  280. package/dist/src/semantics/billing.d.ts +0 -2
  281. package/dist/src/semantics/billing.js +0 -220
  282. package/dist/src/semantics/connect.d.ts +0 -5
  283. package/dist/src/semantics/connect.js +0 -493
  284. package/dist/src/semantics/credit-notes.d.ts +0 -2
  285. package/dist/src/semantics/credit-notes.js +0 -172
  286. package/dist/src/semantics/disputes.d.ts +0 -2
  287. package/dist/src/semantics/disputes.js +0 -51
  288. package/dist/src/semantics/ephemeral-keys.d.ts +0 -2
  289. package/dist/src/semantics/ephemeral-keys.js +0 -34
  290. package/dist/src/semantics/files.d.ts +0 -2
  291. package/dist/src/semantics/files.js +0 -125
  292. package/dist/src/semantics/ledger.d.ts +0 -59
  293. package/dist/src/semantics/ledger.js +0 -200
  294. package/dist/src/semantics/payment-intents.d.ts +0 -18
  295. package/dist/src/semantics/payment-intents.js +0 -452
  296. package/dist/src/semantics/payment-links.d.ts +0 -2
  297. package/dist/src/semantics/payment-links.js +0 -133
  298. package/dist/src/semantics/payment-methods.d.ts +0 -20
  299. package/dist/src/semantics/payment-methods.js +0 -140
  300. package/dist/src/semantics/plans.d.ts +0 -5
  301. package/dist/src/semantics/plans.js +0 -121
  302. package/dist/src/semantics/platform.d.ts +0 -9
  303. package/dist/src/semantics/platform.js +0 -206
  304. package/dist/src/semantics/renewals.d.ts +0 -47
  305. package/dist/src/semantics/renewals.js +0 -281
  306. package/dist/src/semantics/setup-intents.d.ts +0 -2
  307. package/dist/src/semantics/setup-intents.js +0 -84
  308. package/dist/src/semantics/subscription-schedules.d.ts +0 -2
  309. package/dist/src/semantics/subscription-schedules.js +0 -119
  310. package/dist/src/semantics/tax.d.ts +0 -2
  311. package/dist/src/semantics/tax.js +0 -197
  312. package/dist/src/semantics/terminal.d.ts +0 -5
  313. package/dist/src/semantics/terminal.js +0 -182
  314. package/dist/src/semantics/test-clocks.d.ts +0 -6
  315. package/dist/src/semantics/test-clocks.js +0 -73
  316. package/dist/src/semantics/tokens.d.ts +0 -4
  317. package/dist/src/semantics/tokens.js +0 -44
  318. package/dist/src/semantics/treasury.d.ts +0 -2
  319. package/dist/src/semantics/treasury.js +0 -377
  320. package/dist/src/semantics/webhook-endpoints.d.ts +0 -3
  321. package/dist/src/semantics/webhook-endpoints.js +0 -85
  322. package/dist/src/stripe-budget.d.ts +0 -55
  323. package/dist/src/stripe-budget.js +0 -155
  324. package/dist/src/stripe-capabilities.d.ts +0 -3
  325. package/dist/src/stripe-capabilities.js +0 -5836
  326. package/dist/src/stripe-conformance.d.ts +0 -43
  327. package/dist/src/stripe-conformance.js +0 -105
  328. package/dist/src/stripe-connector.d.ts +0 -161
  329. package/dist/src/stripe-connector.js +0 -414
  330. package/dist/src/stripe-emit.d.ts +0 -2
  331. package/dist/src/stripe-emit.js +0 -145
  332. package/dist/src/stripe-events.d.ts +0 -93
  333. package/dist/src/stripe-events.js +0 -392
  334. package/dist/src/stripe-js.d.ts +0 -4
  335. package/dist/src/stripe-js.js +0 -70
  336. package/dist/src/stripe-mirror-ui.d.ts +0 -15
  337. package/dist/src/stripe-mirror-ui.js +0 -87
  338. package/dist/src/stripe-perform-harness.d.ts +0 -9
  339. package/dist/src/stripe-perform-harness.js +0 -26
  340. package/dist/src/stripe-server.d.ts +0 -33
  341. package/dist/src/stripe-server.js +0 -429
  342. package/dist/src/stripe-shared.d.ts +0 -109
  343. package/dist/src/stripe-shared.js +0 -276
  344. package/dist/src/stripe-ui-conformance.d.ts +0 -5
  345. package/dist/src/stripe-ui-conformance.js +0 -79
  346. package/dist/src/stripe-ui-structure.d.ts +0 -3
  347. package/dist/src/stripe-ui-structure.js +0 -168
  348. package/dist/test-fixtures/stripe-known-deviations.json +0 -110
  349. package/dist/test-fixtures/stripe-openapi-operations.SOURCE.md +0 -14
  350. package/dist/test-fixtures/stripe-openapi-operations.json +0 -4717
  351. package/dist/test-fixtures/stripe-schemas.SOURCE.md +0 -35
  352. package/dist/test-fixtures/stripe-schemas.json +0 -3813
  353. package/src/screens/connect-oauth.tsx +0 -400
  354. package/src/screens/connect-settings.tsx +0 -121
  355. package/src/screens/consent-skin.ts +0 -20
  356. package/src/screens/financial-connections.tsx +0 -101
  357. package/src/screens/identity.tsx +0 -96
  358. package/src/screens/public-details.tsx +0 -105
  359. package/src/semantics/after-payment.ts +0 -118
  360. package/src/semantics/billing.ts +0 -216
  361. package/src/semantics/connect.ts +0 -487
  362. package/src/semantics/credit-notes.ts +0 -168
  363. package/src/semantics/disputes.ts +0 -62
  364. package/src/semantics/ephemeral-keys.ts +0 -34
  365. package/src/semantics/files.ts +0 -143
  366. package/src/semantics/ledger.ts +0 -253
  367. package/src/semantics/payment-intents.ts +0 -463
  368. package/src/semantics/payment-links.ts +0 -148
  369. package/src/semantics/payment-methods.ts +0 -145
  370. package/src/semantics/plans.ts +0 -131
  371. package/src/semantics/platform.ts +0 -220
  372. package/src/semantics/renewals.ts +0 -279
  373. package/src/semantics/setup-intents.ts +0 -87
  374. package/src/semantics/subscription-schedules.ts +0 -129
  375. package/src/semantics/tax.ts +0 -220
  376. package/src/semantics/terminal.ts +0 -195
  377. package/src/semantics/test-clocks.ts +0 -77
  378. package/src/semantics/tokens.ts +0 -52
  379. package/src/semantics/treasury.ts +0 -383
  380. package/src/semantics/webhook-endpoints.ts +0 -87
  381. package/src/stripe-budget.ts +0 -181
  382. package/src/stripe-capabilities.ts +0 -5651
  383. package/src/stripe-conformance.ts +0 -124
  384. package/src/stripe-connector.ts +0 -462
  385. package/src/stripe-emit.ts +0 -157
  386. package/src/stripe-events.ts +0 -434
  387. package/src/stripe-js.ts +0 -70
  388. package/src/stripe-mirror-ui.ts +0 -90
  389. package/src/stripe-perform-harness.ts +0 -29
  390. package/src/stripe-server.ts +0 -393
  391. package/src/stripe-shared.ts +0 -297
  392. package/src/stripe-ui-conformance.ts +0 -88
  393. package/src/stripe-ui-structure.ts +0 -182
  394. package/test-fixtures/stripe-known-deviations.json +0 -110
  395. package/test-fixtures/stripe-openapi-operations.json +0 -4717
  396. package/test-fixtures/stripe-schemas.json +0 -3813
  397. /package/dist/src/{screens → engine}/industries.d.ts +0 -0
  398. /package/dist/src/{screens → engine}/industries.js +0 -0
  399. /package/dist/src/{semantics → engine}/test-cards.d.ts +0 -0
  400. /package/dist/src/{semantics → engine}/test-cards.js +0 -0
  401. /package/src/{screens → engine}/industries.ts +0 -0
  402. /package/src/{semantics → engine}/test-cards.ts +0 -0
@@ -1,58 +1,802 @@
1
- import surface from '../generated/surface.gen.json' with { type: 'json' };
2
- import { manifest } from "../manifest.js";
3
- import { OBJECT_NAME, paginate, searchOver, stashVendorType, view } from "../stripe-twin.js";
4
- export const send = (ctx, r) => ctx.reply(r.body, r.status);
5
- /** Stripe's error body: an invalid_request_error with the message, and the code when there is one. */
6
- export const fail = (ctx, message, status = 404, code) => ctx.refuse({ status, message, ...(code ? { code } : {}) });
7
- /** A file parameter whose description requires a purpose refuses a file of another one. The served spec requires it
8
- * on every such parameter ("Must have a `purpose` value of `issuing_logo`", personalization designs' card_logo;
9
- * "The file's `purpose` must be one of the following: …", file links' file). Where the documentation stops and the
10
- * twin decides: Stripe documents no error for it (docs.stripe.com/error-codes names none), so the twin answers the
11
- * 400 invalid_request_error it answers for an unknown file, naming the parameter and the purposes allowed. */
12
- export function filePurposeRefused(ctx, param, allowed) {
13
- const given = ctx.params[param];
14
- if (given === undefined || given === '')
1
+ import { NAMED_EVENTS, readDecision, STRIPE_EVENT_TYPES, STRIPE_REALTIME_AUTH_TIMEOUT_MS, stripeSignature } from "../engine/webhooks.js";
2
+ import { redactKey, requestKey } from "../engine/oauth.js";
3
+ import { HOUR, INV, itemQuantity, itemsOf, keptAfter, oneTimeLines, RENEWING, SUB } from "../engine/renewals.js";
4
+ import { DAY, payoutDay } from "../engine/balance.js";
5
+ import { AFTER_SUCCESS_CARDS, BY_NUMBER } from "../engine/after-payment.js";
6
+ import { accountSettings, addBillingInterval, applyCouponDiscount, asBool, buildDiscount, buildSubscriptionItemsList, cardError, chargeDefaults, declineFor, disputeEvidence, microdepositsNextAction, mintClientSecret, nowUnix, OBJECT_NAME, paginate, paymentMethodSubObject, PLATFORM_ACCOUNT_ID, priceAmount, requiresAuthentication, requiresMicrodeposits, resolveSubscriptionBillingInterval, resolveTrial, searchOver, subscriptionItemEntries, subscriptionItemPrice, TEST_TOKEN_DECLINES, threeDsNextAction, view } from "../engine/stripe.js";
7
+ import { SECRET } from "../engine/apps-secrets.js";
8
+ import { collectsThroughIntent, invoicePrefix, transitions } from "../engine/invoices.js";
9
+ import { CS, isOneTime, nestedMetadata } from "../engine/checkout.js";
10
+ import { externalList, SPEC_FIELDS } from "../engine/common.js";
11
+ import { noBilling, PM, TEST_PM_CARDS, testCardOf } from "../engine/payment-methods.js";
12
+ import { intentCarries, PI, TYPES_GIVEN } from "../engine/payment-intents.js";
13
+ import { BT, BYPASS_NUMBERS, feeOf, onAccount, UNSENT } from "../engine/ledger.js";
14
+ import { MAX_TRIAL, movedTrial } from "../engine/subscriptions.js";
15
+ import { VL, VLI } from "../engine/radar.js";
16
+ import { AUTH, historyEntry, merchantData, REALTIME_WINDOW_SECONDS, TXN } from "../engine/issuing.js";
17
+ import { BYPASS_PENDING_CARDS } from "../engine/test-cards.js";
18
+ import { customRequirements } from "../engine/connect.js";
19
+ import { expandOf, render, SERVED_VERSION, servesCurrent, withoutEndpointSecret } from "../engine/version.js";
20
+ import { CHECKOUT_METHOD_TYPES, DOCUMENTED, methodTypesRemoved, oneOf, OPS, PAYMENT_METHOD_TYPES, REMOVED_TYPES, TYPED, TYPES_DOC } from "../engine/params.js";
21
+ import { linesOf, sumLines } from "../engine/invoices.js";
22
+ import { refundDestination } from "../engine/common.js";
23
+ import { REFUND_REASONS } from "../engine/refunds.js";
24
+ /** Stripe's events: `Stripe-Signature: t=…,v1=…` over `${t}.${body}` keyed by the endpoint's secret
25
+ * (docs.stripe.com/webhooks#verify-manually); the Event object (docs.stripe.com/api/events/object) kept as the account's
26
+ * own (`GET /v1/events`), whether or not an endpoint takes it; an endpoint live while `enabled`, taking the types its
27
+ * `enabled_events` names (`*` all, `<family>.*` a family), and a Connect endpoint (`connect: true`) its connected
28
+ * accounts' events ("Connected accounts" scope, docs.stripe.com/connect/webhooks), any other the account's own. */
29
+ export const STRIPE_EVENTS = {
30
+ scheme: { kind: 'timestamp-v1', header: 'Stripe-Signature' },
31
+ types: NAMED_EVENTS,
32
+ known: STRIPE_EVENT_TYPES,
33
+ store: 'event',
34
+ envelope: {
35
+ id: '$id', object: 'event', account: '$account', api_version: '$version', created: '$time.s', data: '$data', livemode: false,
36
+ pending_webhooks: 0, request: { id: null, idempotency_key: null }, type: '$type',
37
+ },
38
+ endpoints: { storedAs: 'webhook_endpoint', url: 'url', secret: 'secret', filter: 'enabled_events', status: { field: 'status', live: 'enabled' }, scope: { field: 'connect', value: '$account' } },
39
+ };
40
+ /** A customer's now: its test clock's frozen time when it is on one (docs.stripe.com/billing/testing/test-clocks), the
41
+ * World's otherwise. */
42
+ export function clockNow(ctx, customer) {
43
+ const clock = typeof customer === 'string' ? ctx.get('customer', customer)?.test_clock : undefined;
44
+ const frozen = typeof clock === 'string' ? ctx.get('test_helpers.test_clock', clock)?.frozen_time : undefined;
45
+ return frozen !== undefined ? Number(frozen) : Number(nowUnix(ctx.occurredAt));
46
+ }
47
+ /** What a subscription's invoices charge: its own default payment method, else its customer's. */
48
+ export function payerOf(ctx, sub) {
49
+ return typeof sub.default_payment_method === 'string' && sub.default_payment_method ? sub.default_payment_method : customerDefault(ctx, sub);
50
+ }
51
+ /** The customer's default for invoices, charged when the subscription names none of its own. */
52
+ export function customerDefault(ctx, sub) {
53
+ const customer = typeof sub.customer === 'string' ? ctx.get('customer', sub.customer) : undefined;
54
+ const settings = customer?.invoice_settings;
55
+ return typeof settings?.default_payment_method === 'string' && settings.default_payment_method ? settings.default_payment_method : undefined;
56
+ }
57
+ /** A subscription whose invoice has just been finalized: the `once` coupon that invoice took is spent, and a once coupon
58
+ * it did not take (added after it was drafted) stays for the next (unspentDiscounts). */
59
+ export async function spendOnceCoupon(ctx, invoice) {
60
+ const subId = typeof invoice.subscription === 'string' ? invoice.subscription : undefined;
61
+ const sub = subId ? resourceView(ctx, SUB, subId) : undefined;
62
+ if (!sub || !subId)
63
+ return;
64
+ const all = sub.discounts ?? [];
65
+ const kept = keptAfter(all, invoice);
66
+ if (kept.length !== all.length)
67
+ await ctx.write(SUB, subId, { discounts: kept }, 'subscription.discount_spent');
68
+ }
69
+ /** A draft invoice for one period of a subscription, its lines the subscription's items and any one-time lines `once`
70
+ * gives it (a Checkout session's one-time prices, "on the initial invoice only", docs.stripe.com/api/checkout/sessions/
71
+ * create#create_checkout_session-line_items), under the subscription's discount. Answers the invoice id. */
72
+ export async function draftSubscriptionInvoice(ctx, sub, o) {
73
+ const id = o.id ?? ctx.mint(INV);
74
+ const currency = String(sub.currency ?? 'usd');
75
+ const lines = itemsOf(sub).map((it, i) => {
76
+ const price = it.price && typeof it.price === 'object' ? it.price : ctx.get('price', String(it.price ?? ''));
77
+ const quantity = itemQuantity(it);
78
+ return {
79
+ id: `il_twin_${id}_${i + 1}`, object: 'line_item', type: 'subscription',
80
+ // a trial's first invoice bills nothing for the trial period (docs.stripe.com/billing/subscriptions/trials)
81
+ amount: o.trial ? 0 : priceAmount(price, quantity), currency, quantity, proration: false,
82
+ price: price ?? null, subscription: sub.id, subscription_item: it.id ?? null, invoice_item: null,
83
+ period: { start: o.start, end: o.end }, description: o.trial ? `Trial period for ${String(ctx.get('product', String(price?.product ?? ''))?.name ?? 'the plan')}` : null,
84
+ };
85
+ });
86
+ if (o.once?.length)
87
+ lines.push(...oneTimeLines(id, sub, o.once, lines.length, o.start, currency));
88
+ const subtotal = lines.reduce((s, l) => s + l.amount, 0);
89
+ // a discount the subscription still carries applies; a `once` coupon is removed once an invoice finalizes
90
+ // (spendOnceCoupon), so it discounts one invoice (docs.stripe.com/billing/subscriptions/coupons#coupon-duration)
91
+ const discount = (sub.discounts ?? [])[0];
92
+ const coupon = discount && typeof discount === 'object' ? discount.coupon : undefined;
93
+ const off = coupon ? applyCouponDiscount(subtotal, coupon) : 0;
94
+ const total = Math.max(0, subtotal - off);
95
+ await created(ctx, INV, { id, customer: sub.customer, subscription: sub.id }, {
96
+ created: o.start, status: 'draft', livemode: false, currency, collection_method: 'charge_automatically',
97
+ billing_reason: o.reason, auto_advance: true, attempt_count: 0, attempted: false, next_payment_attempt: null,
98
+ amount_due: total, amount_paid: 0, amount_remaining: total, amount_overpaid: 0, amount_paid_off_stripe: 0, amount_shipping: 0,
99
+ subtotal, total, starting_balance: 0, post_payment_credit_notes_amount: 0, pre_payment_credit_notes_amount: 0,
100
+ // "The invoice that consumed the coupon still shows the applied discount" (docs.stripe.com/billing/subscriptions/coupons)
101
+ period_start: o.start, period_end: o.end, default_tax_rates: [], discounts: coupon && discount ? [discount] : [],
102
+ lines: { object: 'list', data: lines, has_more: false, total_count: lines.length, url: `/v1/invoices/${id}/lines` },
103
+ automatic_tax: { enabled: false, liability: null, status: null },
104
+ status_transitions: { finalized_at: null, marked_uncollectible_at: null, paid_at: null, voided_at: null },
105
+ issuer: { type: 'self' }, payment_settings: { default_mandate: null, payment_method_options: null, payment_method_types: null },
106
+ payment_intent: null, charge: null,
107
+ });
108
+ return id;
109
+ }
110
+ /** Finalize a subscription's draft invoice at `at` and charge what its subscription pays with. The move is time's (a
111
+ * renewal), the customer's (the Checkout page they paid on) or the API's (an update that ends a trial, which names the
112
+ * payer, may ask for no attempt, and moves the subscription itself: semantics/subscriptions.ts applyTrialEnd). Answers
113
+ * whether it was paid. */
114
+ export async function collectSubscriptionInvoice(ctx, invoiceId, at, actor, opts = {}) {
115
+ const inv = ctx.get(INV, invoiceId);
116
+ const sub = inv && typeof inv.subscription === 'string' ? resourceView(ctx, SUB, inv.subscription) : undefined;
117
+ if (!inv || !sub || inv.status !== 'draft')
118
+ return false;
119
+ const total = Number(inv.total) || 0;
120
+ const numbered = { ...finalizedFields(ctx, inv, at), status_transitions: { ...inv.status_transitions, finalized_at: at } };
121
+ const op = ctx.call.operation.id;
122
+ // nothing due (a trial's first invoice) is paid as it is finalized; finalizing spends a `once` coupon
123
+ if (total <= 0) {
124
+ if (ctx.legal(INV, 'status', op, 'draft', 'paid', invoiceId, actor))
125
+ return false;
126
+ await spendOnceCoupon(ctx, inv);
127
+ await ctx.write(INV, invoiceId, { ...numbered, status: 'paid', paid: true, auto_advance: false, status_transitions: { ...numbered.status_transitions, paid_at: at } }, 'invoice.paid');
128
+ return true;
129
+ }
130
+ const payer = actor === 'api' ? opts.payer : payerOf(ctx, sub);
131
+ // default_incomplete finalizes the invoice without attempting payment (docs.stripe.com/api/subscriptions/update#update_subscription-payment_behavior)
132
+ const attempt = opts.attempt !== false;
133
+ const decline = payer && attempt ? declineFor(finder(ctx), { payment_method: payer }) : undefined;
134
+ const pays = attempt && !!payer && !decline;
135
+ if (ctx.legal(INV, 'status', op, 'draft', pays ? 'paid' : 'open', invoiceId, actor))
136
+ return false;
137
+ await spendOnceCoupon(ctx, inv);
138
+ const piId = ctx.mint('payment_intent');
139
+ const currency = String(inv.currency ?? 'usd');
140
+ const chargeId = pays ? await mintCharge(ctx, piId, { currency, customer: inv.customer, payment_method: payer, invoice: invoiceId }, total) : null;
141
+ const intent = await created(ctx, 'payment_intent', { id: piId, amount: total, currency, customer: inv.customer, invoice: invoiceId, payment_method: pays ? payer : null }, {
142
+ status: pays ? 'succeeded' : 'requires_payment_method', client_secret: mintClientSecret(piId, await ctx.secret(`client-secret:${piId}`)), livemode: false,
143
+ capture_method: 'automatic', amount_capturable: 0, amount_received: pays ? total : 0, next_action: null, latest_charge: chargeId,
144
+ last_payment_error: decline ? { type: 'card_error', code: decline.code, decline_code: decline.decline_code ?? null, message: decline.message, payment_method: { id: payer } } : null,
145
+ automatic_payment_methods: null, payment_method_types: ['card'], payment_method_options: {},
146
+ });
147
+ await ctx.write(INV, invoiceId, {
148
+ ...numbered, status: pays ? 'paid' : 'open', paid: pays, attempt_count: attempt ? 1 : 0, attempted: attempt, payment_intent: piId, charge: chargeId,
149
+ // source: spec:/components/schemas/invoice/properties/confirmation_secret/description "client_secret of the PaymentIntent"
150
+ confirmation_secret: { type: 'payment_intent', client_secret: intent.client_secret },
151
+ amount_paid: pays ? total : 0, amount_remaining: pays ? 0 : total, auto_advance: attempt && !pays, next_payment_attempt: null,
152
+ status_transitions: { ...numbered.status_transitions, paid_at: pays ? at : null },
153
+ }, pays ? 'invoice.paid' : attempt ? 'invoice.payment_failed' : 'invoice.finalized');
154
+ if (actor !== 'api' && !pays && sub.status !== 'past_due' && !ctx.legal(SUB, 'status', op, sub.status, 'past_due', String(sub.id), 'time')) {
155
+ await ctx.write(SUB, String(sub.id), { status: 'past_due' }, 'customer.subscription.updated');
156
+ }
157
+ return pays;
158
+ }
159
+ /** Pay a subscription's open invoice with `paymentMethod` (the customer on the portal, `external`): the charge on the
160
+ * invoice's PaymentIntent, the invoice paid, a past_due subscription active. Answers the decline, if the card is refused. */
161
+ export async function payOpenInvoice(ctx, invoiceId, paymentMethod) {
162
+ const inv = ctx.get(INV, invoiceId);
163
+ if (!inv || inv.status !== 'open')
164
+ return { code: 'invoice_not_open', message: 'This invoice is no longer open.' };
165
+ const decline = declineFor(finder(ctx), { payment_method: paymentMethod });
166
+ if (decline)
167
+ return decline;
168
+ const op = ctx.call.operation.id;
169
+ const refused = ctx.legal(INV, 'status', op, 'open', 'paid', invoiceId, 'external');
170
+ if (refused)
171
+ return { code: String(refused.code ?? 'invoice_not_open'), message: refused.message };
172
+ const total = Number(inv.amount_remaining ?? inv.total) || 0;
173
+ const now = Number(nowUnix(ctx.occurredAt));
174
+ const piId = typeof inv.payment_intent === 'string' ? inv.payment_intent : undefined;
175
+ let chargeId = null;
176
+ const pi = piId ? ctx.get('payment_intent', piId) : undefined;
177
+ if (piId && pi && !ctx.legal('payment_intent', 'status', op, pi.status, 'succeeded', piId, 'external')) {
178
+ chargeId = await mintCharge(ctx, piId, { ...pi, payment_method: paymentMethod, invoice: invoiceId }, total);
179
+ await ctx.write('payment_intent', piId, { status: 'succeeded', payment_method: paymentMethod, amount_received: total, last_payment_error: null, latest_charge: chargeId }, 'payment_intent.succeeded');
180
+ }
181
+ await ctx.write(INV, invoiceId, {
182
+ status: 'paid', paid: true, amount_paid: total, amount_remaining: 0, charge: chargeId, auto_advance: false,
183
+ attempt_count: (Number(inv.attempt_count) || 0) + 1, attempted: true,
184
+ status_transitions: { ...inv.status_transitions, paid_at: now },
185
+ }, 'invoice.paid');
186
+ const sub = typeof inv.subscription === 'string' ? resourceView(ctx, SUB, inv.subscription) : undefined;
187
+ if (sub && sub.status === 'past_due' && !ctx.legal(SUB, 'status', op, 'past_due', 'active', String(sub.id), 'external')) {
188
+ await ctx.write(SUB, String(sub.id), { status: 'active' }, 'customer.subscription.updated');
189
+ }
190
+ return undefined;
191
+ }
192
+ /** Time's moves on subscriptions, caught up to each customer's clock in the order they fell due, each made at the
193
+ * moment it was due: a period that ended renews (a trial's end among them) or, set to cancel, cancels; a renewal
194
+ * drafted an hour or more ago is finalized and charged. */
195
+ export async function advanceBilling(ctx, only) {
196
+ // Stripe's own move wherever a handler reaches it: a read that catches a renewal up records it with no caller
197
+ await ctx.asVendor(async () => {
198
+ const at = at_(ctx);
199
+ for (let guard = 0; guard < 10_000 && (await billingStep(ctx, at, only)); guard++)
200
+ ;
201
+ });
202
+ }
203
+ /** The earliest move that has come due, made at its moment; false when none has. */
204
+ export async function billingStep(ctx, at, only) {
205
+ // the earliest move that has come due, of any subscription
206
+ let next;
207
+ for (const sub of ctx.rows(SUB).map((s) => ctx.expand(SUB, s))) {
208
+ if (only && !only(sub))
209
+ continue;
210
+ if (!RENEWING.includes(String(sub.status)) || typeof sub.current_period_end !== 'number' || sub.pause_collection)
211
+ continue;
212
+ if (sub.current_period_end <= clockNow(ctx, sub.customer) && (!next || sub.current_period_end < next.t))
213
+ next = { t: sub.current_period_end, kind: 'period', id: String(sub.id) };
214
+ }
215
+ for (const inv of ctx.rows(INV)) {
216
+ if (inv.status !== 'draft' || inv.billing_reason !== 'subscription_cycle' || inv.auto_advance !== true)
217
+ continue;
218
+ const sub = typeof inv.subscription === 'string' ? resourceView(ctx, SUB, inv.subscription) : undefined;
219
+ if (!sub || (only && !only(sub)))
220
+ continue;
221
+ const t = Number(inv.created) + HOUR;
222
+ if (t <= clockNow(ctx, sub.customer) && (!next || t < next.t))
223
+ next = { t, kind: 'collect', id: String(inv.id) };
224
+ }
225
+ if (!next)
226
+ return false;
227
+ const c = await at(next.t);
228
+ if (next.kind === 'collect') {
229
+ await collectSubscriptionInvoice(c, next.id, next.t, 'time');
230
+ return true;
231
+ }
232
+ const id = next.id;
233
+ const sub = resourceView(c, SUB, id);
234
+ const op = c.call.operation.id;
235
+ // one set to cancel at its period's end is canceled then, with no renewal
236
+ // (docs.stripe.com/billing/subscriptions/cancel#cancel-at-end-of-cycle)
237
+ if (sub.cancel_at_period_end === true) {
238
+ if (c.legal(SUB, 'status', op, sub.status, 'canceled', id, 'time'))
239
+ return false;
240
+ await c.write(SUB, id, { status: 'canceled', ended_at: next.t, canceled_at: sub.canceled_at ?? next.t }, 'customer.subscription.deleted');
241
+ return true;
242
+ }
243
+ const start = next.t;
244
+ const { interval, interval_count } = resolveSubscriptionBillingInterval(itemsOf(sub), finder(c));
245
+ const end = addBillingInterval(start, interval, interval_count);
246
+ const trialEnds = sub.status === 'trialing';
247
+ if (trialEnds && c.legal(SUB, 'status', op, 'trialing', 'active', id, 'time'))
248
+ return false;
249
+ const invoiceId = await draftSubscriptionInvoice(c, sub, { start, end, reason: 'subscription_cycle' });
250
+ await c.write(SUB, id, { current_period_start: start, current_period_end: end, latest_invoice: invoiceId, ...(trialEnds ? { status: 'active' } : {}) }, 'customer.subscription.updated');
251
+ return true;
252
+ }
253
+ export const account = (ctx) => actingAccount(ctx);
254
+ /** The acting account's Balance object (docs.stripe.com/api/balance/balance_object). */
255
+ export function balanceBody(ctx, acct = account(ctx)) {
256
+ const { available, pending, issuing } = balanceOf(ctx, acct);
257
+ const toArr = (m) => {
258
+ const out = [...m.entries()].map(([currency, amount]) => ({ amount, currency, source_types: { card: amount } }));
259
+ return out.length ? out : [{ amount: 0, currency: 'usd', source_types: { card: 0 } }];
260
+ };
261
+ // a platform's balance holds its connected accounts' reserve, "Funds held due to negative balances on connected accounts
262
+ // where account.controller.requirement_collection is `application`" (docs.stripe.com/api/balance/balance_object, whose
263
+ // example answers `[{"amount": 0, "currency": "usd"}]`); the twin models no such reserve, so it is zero in each currency
264
+ const reserved = acct ? {} : { connect_reserved: toArr(available).map((b) => ({ amount: 0, currency: b.currency })) };
265
+ return {
266
+ object: 'balance', available: toArr(available), pending: toArr(pending), ...reserved, livemode: false,
267
+ ...(issuing.size ? { issuing: { available: [...issuing.entries()].map(([currency, amount]) => ({ amount, currency, source_types: { card: amount } })) } } : {}),
268
+ };
269
+ }
270
+ /** Time's arrivals, written: each of the acting account's payouts whose arrival date has come moves pending → paid
271
+ * (the clock's move, as asOf reads it), written as `payout.paid`, the event Stripe sends for it. Answers their ids. */
272
+ export async function payDuePayouts(ctx, acct = account(ctx)) {
273
+ const now = Number(nowUnix(ctx.occurredAt));
274
+ const paid = [];
275
+ for (const p of newest(ctx, 'payout')) {
276
+ if ((acct ? kept(ctx, 'payout', p, '_account') !== acct : !!kept(ctx, 'payout', p, '_account')) || p.status !== 'pending' || Number(p.arrival_date) > now)
277
+ continue;
278
+ if (ctx.legal('payout', 'status', ctx.call.operation.id, 'pending', 'paid', String(p.id), 'time'))
279
+ continue;
280
+ await ctx.write('payout', String(p.id), { status: 'paid' }, 'payout.paid');
281
+ paid.push(String(p.id));
282
+ }
283
+ return paid;
284
+ }
285
+ /** Where a connected account's payout goes: "ID of the bank account or card the payout is sent to" (served spec,
286
+ * payout.destination), its default external account for the currency, "When multiple accounts are available for a given
287
+ * currency, Stripe uses the one set as `default_for_currency`" (docs.stripe.com/connect/payouts-bank-accounts), the
288
+ * newest such. Where the documentation stops and the twin decides: the platform's own bank account is not modelled, so
289
+ * its payouts name none. */
290
+ export function payoutBank(ctx, account, currency) {
291
+ const banks = newest(ctx, 'external_account').filter((e) => e.account === account && String(e.currency ?? currency) === currency);
292
+ return String((banks.find((e) => e.default_for_currency === true) ?? banks[0])?.id ?? '') || null;
293
+ }
294
+ export const payoutDefaults = (ctx) => ({
295
+ method: 'standard', type: 'bank_account', source_type: 'card', automatic: false,
296
+ reconciliation_status: 'not_applicable', arrival_date: Number(nowUnix(ctx.occurredAt)) + 2 * DAY, livemode: false, metadata: {},
297
+ });
298
+ /** A payout as the clock reads it: paid once its arrival date has come, the clock's move, asked of the
299
+ * machine as a write asks it. */
300
+ export function asOf(ctx, p) {
301
+ if (p.status !== 'pending' || Number(p.arrival_date) > Number(nowUnix(ctx.occurredAt)))
302
+ return p;
303
+ ctx.legal('payout', 'status', ctx.call.operation.id, 'pending', 'paid', String(p.id), 'time');
304
+ return { ...p, status: 'paid' };
305
+ }
306
+ /** A connected account's payout in a currency none of its bank accounts takes. */
307
+ export function noExternalAccount(ctx, currency) {
308
+ return fail(ctx, `Sorry, you don't have any external accounts in that currency (${currency}).`, 400);
309
+ }
310
+ /** Time's payouts, caught up to the World's clock: each account on an automatic schedule is paid out, on each of its
311
+ * scheduled days that has come, what became available by then. */
312
+ export async function advancePayouts(ctx) {
313
+ const now = Number(nowUnix(ctx.occurredAt));
314
+ const platform = ctx.get('account', PLATFORM_ACCOUNT_ID);
315
+ const accounts = [{ id: undefined, settings: platform?.settings }];
316
+ for (const a of ctx.rows('account')) {
317
+ if (a.id === PLATFORM_ACCOUNT_ID || a.payouts_enabled !== true)
318
+ continue;
319
+ if (!ctx.rows('external_account').some((e) => e.account === a.id))
320
+ continue;
321
+ accounts.push({ id: String(a.id), settings: a.settings });
322
+ }
323
+ for (const acct of accounts) {
324
+ const schedule = (accountSettings(acct.settings, acct.settings ?? undefined).payouts.schedule ?? {});
325
+ if (schedule.interval === 'manual')
326
+ continue;
327
+ const unpaid = unpaidEntries(ctx, acct.id);
328
+ const days = [...new Set(unpaid.map((t) => payoutDay(Number(t.available_on) || 0, schedule)))].filter((d) => d <= now).sort((x, y) => x - y);
329
+ const paid = new Set();
330
+ for (const day of days) {
331
+ const due = unpaid.filter((t) => !paid.has(t.id) && (Number(t.available_on) || 0) <= day);
332
+ const byCurrency = new Map();
333
+ for (const t of due)
334
+ byCurrency.set(String(t.currency ?? 'usd'), [...(byCurrency.get(String(t.currency ?? 'usd')) ?? []), t]);
335
+ for (const [currency, entries] of byCurrency) {
336
+ const amount = entries.reduce((n, t) => n + (Number(t.net) || 0), 0);
337
+ // nothing to pay yet: what came due is carried to the next payout
338
+ if (amount <= 0)
339
+ continue;
340
+ // made on its day, as Stripe makes it, whenever the request that catches it up comes
341
+ const c = await at_(ctx)(day);
342
+ const id = c.mint('payout');
343
+ const bt = await settleAutomaticPayout(c, id, amount, currency, acct.id, day, entries);
344
+ await created(c, 'payout', { id, amount, currency }, {
345
+ status: 'pending', ...payoutDefaults(c), arrival_date: day + 2 * DAY, automatic: true, balance_transaction: bt, destination: acct.id ? payoutBank(c, String(acct.id), currency) : null,
346
+ description: 'STRIPE PAYOUT', ...(acct.id ? { _account: acct.id } : {}),
347
+ });
348
+ for (const t of entries)
349
+ paid.add(t.id);
350
+ }
351
+ }
352
+ }
353
+ }
354
+ /** What Stripe does after a card succeeds: from a raw number, a test name (pm_card_* or tok_*), or a stored
355
+ * PaymentMethod that recorded it when it was made. */
356
+ export function afterSuccessOf(ctx, ref) {
357
+ // a card given as a token (card[token], payment_method_data[card][token]) is the card the token names
358
+ if (ref && typeof ref === 'object' && typeof ref.token === 'string')
359
+ return afterSuccessOf(ctx, ref.token);
360
+ if (ref && typeof ref === 'object')
361
+ return BY_NUMBER[String(ref.number ?? '').replace(/\D/g, '')];
362
+ if (typeof ref !== 'string' || !ref)
363
+ return undefined;
364
+ const stored = ctx.row('payment_method', ref);
365
+ if (stored)
366
+ return stored._afterSuccess ?? undefined;
367
+ return AFTER_SUCCESS_CARDS[ref.replace(/^tok_/, 'pm_card_')]?.outcome ?? BY_NUMBER[ref.replace(/\D/g, '')];
368
+ }
369
+ /** Stripe's acts on a charge that just succeeded: a dispute or a review its card brings, and the platform's fee. */
370
+ export async function afterCharge(ctx, chargeId, charge, ref) {
371
+ const outcome = afterSuccessOf(ctx, ref);
372
+ const pi = charge.payment_intent ? { payment_intent: charge.payment_intent } : { payment_intent: null };
373
+ const now = Number(nowUnix(ctx.occurredAt));
374
+ if (outcome === 'dispute' || outcome === 'dispute_not_received' || outcome === 'inquiry') {
375
+ const dispute = await created(ctx, 'dispute', { charge: chargeId, ...pi, amount: charge.amount, currency: charge.currency }, {
376
+ reason: outcome === 'dispute_not_received' ? 'product_not_received' : 'fraudulent', status: outcome === 'inquiry' ? 'warning_needs_response' : 'needs_response', is_charge_refundable: false,
377
+ evidence: disputeEvidence(), evidence_details: { due_by: now + 7 * DAY, has_evidence: false, past_due: false, submission_count: 0, enhanced_eligibility: {} },
378
+ balance_transactions: [], livemode: false, metadata: {}, enhanced_eligibility_types: [],
379
+ });
380
+ // an inquiry moves no money; a dispute takes the amount and its fee until it is decided
381
+ if (outcome !== 'inquiry') {
382
+ const bt = await settleDispute(ctx, String(dispute.id), charge.amount, charge.currency);
383
+ await ctx.write('dispute', String(dispute.id), { balance_transactions: [ctx.get('balance_transaction', bt) ?? bt] }, 'dispute.funds_withdrawn');
384
+ }
385
+ await ctx.write('charge', chargeId, { disputed: true }, 'charge.dispute.created');
386
+ }
387
+ if (outcome === 'review')
388
+ await openReview(ctx, chargeId, pi);
389
+ const feeAmount = Math.trunc(Number(charge.application_fee_amount) || 0);
390
+ const destination = typeof charge.destination === 'string' && charge.destination ? charge.destination : undefined;
391
+ const direct = actingAccount(ctx);
392
+ const account = destination ?? direct;
393
+ // a destination charge transfers what it collected, less the platform's fee, available when the charge's funds are
394
+ if (destination) {
395
+ const amount = charge.amount - feeAmount;
396
+ const chargeBt = ctx.get('charge', chargeId)?.balance_transaction;
397
+ const availableOn = Number(ctx.get('balance_transaction', String(chargeBt))?.available_on ?? nowUnix(ctx.occurredAt));
398
+ const tr = await created(ctx, 'transfer', { amount, currency: charge.currency, destination }, {
399
+ amount_reversed: 0, balance_transaction: null, livemode: false, metadata: {}, reversed: false, source_type: 'card', source_transaction: chargeId,
400
+ reversals: { object: 'list', data: [], has_more: false, total_count: 0, url: '' },
401
+ });
402
+ const bt = await settleTransfer(ctx, String(tr.id), amount, charge.currency, destination, availableOn);
403
+ 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');
404
+ await ctx.write('charge', chargeId, { transfer: tr.id }, 'charge.updated');
405
+ }
406
+ if (feeAmount > 0 && account) {
407
+ const fee = await created(ctx, 'application_fee', { account, amount: feeAmount, charge: chargeId, currency: charge.currency }, {
408
+ amount_refunded: 0, application: 'ca_twin', balance_transaction: null, originating_transaction: null, refunded: false, livemode: false,
409
+ });
410
+ // a direct charge's fee moves from the connected account to the platform (a destination charge kept it back)
411
+ const bt = !destination && direct ? await settleApplicationFee(ctx, String(fee.id), feeAmount, charge.currency, direct) : null;
412
+ 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');
413
+ await ctx.write('charge', chargeId, { application_fee: fee.id, application_fee_amount: feeAmount }, 'charge.updated');
414
+ }
415
+ }
416
+ /** Radar places an elevated-risk card's charge in review (docs.stripe.com/radar/reviews). */
417
+ export async function openReview(ctx, chargeId, pi) {
418
+ const review = await created(ctx, 'review', { charge: chargeId, ...pi }, {
419
+ open: true, opened_reason: 'rule', reason: 'rule', closed_reason: null, billing_zip: null, ip_address: null, ip_address_location: null, session: null, livemode: false,
420
+ });
421
+ const existing = ctx.get('charge', chargeId)?.outcome ?? {};
422
+ await ctx.write('charge', chargeId, {
423
+ review: review.id,
424
+ 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.' },
425
+ }, 'review.opened');
426
+ }
427
+ export const customerMissing = (ctx, id) => fail(ctx, `No such customer: '${id}'`, 404, 'resource_missing');
428
+ /** The request event asked of the endpoint, signed with its secret and rendered in the event's API version, and its
429
+ * answer read as the decision. */
430
+ export async function askForAuthorization(ctx, url, event, secret) {
431
+ const payload = JSON.stringify(render(event, typeof event.api_version === 'string' ? event.api_version : undefined));
432
+ const signature = stripeSignature(payload, secret, Math.floor(Date.parse(ctx.occurredAt) / 1000));
433
+ const answer = await ctx.ask(url, { method: 'POST', headers: { 'content-type': 'application/json', 'stripe-signature': signature }, body: payload }, STRIPE_REALTIME_AUTH_TIMEOUT_MS);
434
+ if (answer.missed === 'timeout')
435
+ return { kind: 'timeout', message: 'Webhook endpoint did not respond within the real-time authorization window.' };
436
+ if (answer.missed === 'unreachable')
437
+ return { kind: 'timeout', message: 'Webhook endpoint was unreachable within the real-time authorization window.' };
438
+ return readDecision(answer);
439
+ }
440
+ /** Stripe's refusal of a call a publishable key may not make, or undefined when the key may make it. */
441
+ export function publishableKeyRefused(ctx) {
442
+ // the key however it is sent, Bearer or Basic's user (requestKey): a publishable key is public, and sent as Basic it
443
+ // is still one
444
+ if (!requestKey(ctx.call.request).startsWith('pk_'))
445
+ return undefined;
446
+ return ctx.refuse({ status: 403, code: 'secret_key_required', message: 'The API key provided is a publishable key, but a secret key is required.' });
447
+ }
448
+ /** The platform's own keys, as the dashboard's API keys page makes them (the `appCredentials` door): a secret key and a
449
+ * publishable key, held by their SHA-256. A request with no key is refused, as is a platform key Stripe never issued
450
+ * ("Invalid API Key provided"). */
451
+ // source: https://docs.stripe.com/api/authentication "API requests without authentication also fail."
452
+ export function platformKeyRefused(ctx, request) {
453
+ const key = requestKey(request);
454
+ if (!key)
455
+ 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/." });
456
+ const held = ctx.rowsRaw('_platform_key').some((k) => k._sha256 === ctx.crypto.sha256(key) && k.deleted !== true);
457
+ return held ? undefined : ctx.refuse({ status: 401, message: `Invalid API Key provided: ${redactKey(key)}` });
458
+ }
459
+ // ── metadata ──
460
+ // "This parameter uses a merge mechanism, which allows you to add new key-value pairs to an object in an update call
461
+ // without affecting any existing metadata"; "Pass in the key with an empty string as the value to remove the key from the
462
+ // metadata"; "Pass an empty string as the value for the metadata attribute to delete all of the keys simultaneously"
463
+ // (docs.stripe.com/metadata), and "Individual keys can be unset by posting an empty value to them" holds on a create
464
+ // too: an object never holds a key set to "" (stripe-node encodes a `null` value as `metadata[key]=`). The derived core
465
+ // merges a nested hash on an update (dropping keys set to ""), so for it only a clear-all is rewritten; where a handler
466
+ // stores the request's metadata whole, the request carries the merged hash, its removed keys as "". The rewritten
467
+ // request is JSON.
468
+ export function withMetadata(ctx, request) {
469
+ if (request.method !== 'POST' || (request.headers.get('content-type') ?? '').includes('multipart'))
470
+ return request;
471
+ if (!('metadata' in ctx.params))
472
+ return request;
473
+ const op = ctx.call.operation;
474
+ const given = ctx.params.metadata;
475
+ let metadata;
476
+ if (op.class === 'create') {
477
+ if (given === '')
478
+ metadata = {};
479
+ else if (given && typeof given === 'object' && !Array.isArray(given) && Object.values(given).includes(''))
480
+ metadata = Object.fromEntries(Object.entries(given).filter(([, v]) => v !== ''));
481
+ else
482
+ return request;
483
+ }
484
+ else if (op.class === 'update' && op.resource) {
485
+ const resource = op.resource;
486
+ const id = Object.values(ctx.call.params).at(-1) ?? '';
487
+ const held = ctx.get(resource, id)?.metadata;
488
+ const prior = held && typeof held === 'object' ? held : {};
489
+ // the merged hash, a key removed carried as "" so a merging update (the derived core's) drops it too; an object
490
+ // never answers a key set to "" (../engine/version.ts render)
491
+ if (given === '')
492
+ metadata = Object.fromEntries(Object.keys(prior).map((k) => [k, '']));
493
+ else if (given && typeof given === 'object' && !Array.isArray(given))
494
+ metadata = { ...prior, ...given };
495
+ else
496
+ return request;
497
+ }
498
+ else
499
+ return request;
500
+ const headers = new Headers(request.headers);
501
+ headers.set('content-type', 'application/json');
502
+ return new Request(request.url, { method: request.method, headers, body: JSON.stringify({ ...ctx.params, metadata }) });
503
+ }
504
+ export function scopeKeyOf(ctx) {
505
+ const scope = ctx.params.scope && typeof ctx.params.scope === 'object' ? ctx.params.scope : undefined;
506
+ const scopeType = scope && typeof scope.type === 'string' ? scope.type : 'account';
507
+ return scopeType === 'user' ? `user:${String(scope.user)}` : 'account';
508
+ }
509
+ export const named = (ctx, name) => ctx.rows(SECRET).find((s) => s.name === name && kept(ctx, SECRET, s, '_scope_key') === scopeKeyOf(ctx));
510
+ export const invoiceMissing = (ctx, id) => fail(ctx, `No such invoice: '${id}'`, 404, 'resource_missing');
511
+ /** Paying an invoice with nothing to pay it: "If not set, defaults to the subscription's default payment method, if any,
512
+ * or to the default payment method in the customer's invoice settings" (docs.stripe.com/api/invoices/object,
513
+ * default_payment_method), and none of them is set. */
514
+ export function nothingToPayWith(ctx) {
515
+ return fail(ctx, 'This customer has no attached payment source or default payment method. Please consider adding a default payment method.', 400, 'missing');
516
+ }
517
+ /** A subscription waiting on the invoice paid through the invoice's own pay (incomplete on its first, past_due on a
518
+ * failed renewal) is active again. */
519
+ export async function activatedByPayment(ctx, subId) {
520
+ await ctx.write('subscription', subId, { status: 'active' }, 'subscription.update');
521
+ }
522
+ /** The invoice the path names, and the machine's refusal when this operation may not move it. */
523
+ export function invoicesLoad(ctx, operationId) {
524
+ const id = at(ctx, 'invoice');
525
+ const inv = ctx.get(INV, id);
526
+ if (!inv)
527
+ return { answer: invoiceMissing(ctx, id) };
528
+ const refused = ctx.legal(INV, 'status', operationId, inv.status, undefined, id);
529
+ return refused ? { answer: ctx.refuse(refused) } : { inv };
530
+ }
531
+ /** A draft finalized on its way to being paid: numbered, open, its PaymentIntent opened (PostInvoicesInvoiceFinalize). */
532
+ export async function finalizeForPayment(ctx, inv, id) {
533
+ const piId = collectsThroughIntent(inv) ? ctx.mint('payment_intent') : null;
534
+ const now = nowUnix(ctx.occurredAt);
535
+ ctx.legal(INV, 'status', 'PostInvoicesInvoicePay', 'draft', 'open', id);
536
+ const body = await ctx.write(INV, id, { ...finalizedFields(ctx, inv, Number(now)), status: 'open', status_transitions: { ...transitions(inv), finalized_at: now }, payment_intent: piId }, 'invoice.finalize');
537
+ if (piId)
538
+ await openPaymentIntent(ctx, piId, inv, id);
539
+ await spendOnceCoupon(ctx, inv);
540
+ return ctx.get(INV, id) ?? body;
541
+ }
542
+ /** The PaymentIntent a charge_automatically invoice with a balance gets when it is finalized; it
543
+ * waits for confirmation when the invoice already names a default payment method. */
544
+ export async function openPaymentIntent(ctx, piId, inv, invoiceId) {
545
+ const defaultPaymentMethod = typeof inv.default_payment_method === 'string' ? inv.default_payment_method : undefined;
546
+ const intent = await created(ctx, 'payment_intent', {
547
+ id: piId, amount: Number(inv.amount_due) || 0, currency: String(inv.currency ?? 'usd'), customer: inv.customer, invoice: invoiceId,
548
+ ...(defaultPaymentMethod ? { payment_method: defaultPaymentMethod } : {}),
549
+ }, {
550
+ status: defaultPaymentMethod ? 'requires_confirmation' : 'requires_payment_method',
551
+ client_secret: mintClientSecret(piId, await ctx.secret(`client-secret:${piId}`)), livemode: false,
552
+ capture_method: 'automatic', amount_capturable: 0, amount_received: 0, next_action: null,
553
+ automatic_payment_methods: null, payment_method_types: ['card', 'link'], payment_method_options: {},
554
+ });
555
+ // source: spec:/components/schemas/invoice/properties/confirmation_secret/description "client_secret of the PaymentIntent"
556
+ await ctx.write(INV, invoiceId, { confirmation_secret: { type: 'payment_intent', client_secret: intent.client_secret } }, 'invoice.updated');
557
+ }
558
+ export function finalizedFields(ctx, inv, now) {
559
+ const customerId = typeof inv.customer === 'string' ? inv.customer : '';
560
+ const customer = customerId ? ctx.get('customer', customerId) : undefined;
561
+ const prefix = typeof customer?.invoice_prefix === 'string' && customer.invoice_prefix
562
+ ? customer.invoice_prefix
563
+ : invoicePrefix(customerId);
564
+ const numbered = ctx.rows(INV).filter((i) => i.customer === customerId && typeof i.number === 'string' && i.id !== inv.id).length;
565
+ const fields = { number: typeof inv.number === 'string' && inv.number ? inv.number : `${prefix}-${String(numbered + 1).padStart(4, '0')}` };
566
+ const days = Number(inv.days_until_due);
567
+ if (inv.collection_method === 'send_invoice' && inv.due_date == null && Number.isFinite(days) && days > 0)
568
+ fields.due_date = now + days * 86400;
569
+ return fields;
570
+ }
571
+ /** A coupon for a fixed amount off, in its currency (docs.stripe.com/api/coupons/create#create_coupon-amount_off). */
572
+ export function amountOffOf(ctx, params) {
573
+ const amountOff = Number(params.amount_off);
574
+ if (!Number.isInteger(amountOff) || amountOff <= 0)
575
+ return fail(ctx, 'Invalid integer: amount_off must be a positive integer.', 400, 'parameter_invalid_integer');
576
+ if (params.currency === undefined || params.currency === '')
577
+ return fail(ctx, 'Missing required param: currency.', 400, 'parameter_missing');
578
+ return amountOff;
579
+ }
580
+ /** Time's lapsing of coupons, caught up to the World's clock: a valid coupon whose redeem_by has passed is no longer
581
+ * valid from that moment (manifest.ts). Where the documentation stops and the twin decides: the lapse sends no event
582
+ * (the events page names none for it). */
583
+ export async function lapseCoupons(ctx) {
584
+ const now = Number(nowUnix(ctx.occurredAt));
585
+ for (const c of ctx.rowsRaw('coupon')) {
586
+ if (c.valid !== true || typeof c.redeem_by !== 'number' || c.redeem_by > now)
587
+ continue;
588
+ const t = await at_(ctx)(c.redeem_by);
589
+ t.legal('coupon', 'valid', ctx.call.operation.id, 'true', 'false', String(c.id), 'time');
590
+ await t.write('coupon', String(c.id), { valid: false }, 'coupon.lapsed');
591
+ }
592
+ }
593
+ export const sessionMissing = (ctx, id) => fail(ctx, `No such checkout.session: '${id}'`, 404, 'resource_missing');
594
+ // Stripe normalizes the create input into the Session: line_items become the list envelope, and
595
+ // subscription_data (create-only) is kept aside for completion to copy onto the subscription
596
+ /** The discount a session is created with (discounts[0][promotion_code] or [coupon]), or Stripe's refusal: an unknown
597
+ * code or coupon, and one that has expired or been deactivated, are refused at create
598
+ * (docs.stripe.com/api/checkout/sessions/create#create_checkout_session-discounts, docs.stripe.com/error-codes#coupon-expired).
599
+ * Where the documentation stops and the twin decides: the refusals' wording. */
600
+ export function discountOf(ctx, params, now) {
601
+ const first = Array.isArray(params.discounts) ? params.discounts[0] : undefined;
602
+ if (!first || typeof first !== 'object')
15
603
  return undefined;
16
- const file = ctx.get('file', String(given));
17
- if (!file)
18
- return fail(ctx, `No such file upload: '${String(given)}'`, 400, 'resource_missing');
19
- if (allowed.includes(String(file.purpose)))
604
+ const expired = (what) => ctx.refuse({ status: 400, code: 'coupon_expired', param: 'discounts', message: `This ${what} has expired.` });
605
+ let promotion;
606
+ let couponId = typeof first.coupon === 'string' ? first.coupon : undefined;
607
+ if (typeof first.promotion_code === 'string') {
608
+ const pc = ctx.get('promotion_code', first.promotion_code);
609
+ if (!pc)
610
+ return ctx.refuse({ status: 400, code: 'resource_missing', param: 'discounts[0][promotion_code]', message: `No such promotion code: '${first.promotion_code}'` });
611
+ if (typeof pc.expires_at === 'number' && pc.expires_at <= now)
612
+ return expired('promotion code');
613
+ if (pc.active === false)
614
+ return ctx.refuse({ status: 400, param: 'discounts[0][promotion_code]', message: 'This promotion code is inactive.' });
615
+ promotion = String(pc.id);
616
+ couponId = typeof pc.coupon === 'string' ? pc.coupon : String(pc.coupon?.id ?? '');
617
+ }
618
+ const coupon = couponId ? ctx.get('coupon', couponId) : undefined;
619
+ if (!coupon)
620
+ return ctx.refuse({ status: 400, code: 'resource_missing', param: 'discounts[0][coupon]', message: `No such coupon: '${couponId ?? ''}'` });
621
+ if (coupon.valid === false || (typeof coupon.redeem_by === 'number' && coupon.redeem_by <= now))
622
+ return expired('coupon');
623
+ return { coupon, ...(promotion ? { promotion } : {}) };
624
+ }
625
+ /** A payment or subscription session with nothing to sell (docs.stripe.com/api/checkout/sessions/create#create_checkout_session-line_items). */
626
+ export function noLineItems(ctx) {
627
+ 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');
628
+ }
629
+ /** A destination charge to an account the platform does not have (docs.stripe.com/connect/destination-charges). */
630
+ export function checkoutNoDestination(ctx, destination) {
631
+ return ctx.refuse({ status: 400, code: 'resource_missing', param: 'payment_intent_data[transfer_data][destination]', message: `No such destination: '${String(destination)}'` });
632
+ }
633
+ /** A session's trial Stripe refuses: `subscription_data.trial_end` "Has to be at least 48 hours in the future", and
634
+ * `subscription_data.trial_period_days` "Has to be at least 1" (docs.stripe.com/api/checkout/sessions/create). Where the
635
+ * documentation stops and the twin decides: the refusals' wording. */
636
+ export function sessionTrialRefused(ctx, data, now) {
637
+ if (!data || typeof data !== 'object')
20
638
  return undefined;
21
- const need = allowed.length === 1 ? `a \`purpose\` value of \`${allowed[0]}\`` : `a \`purpose\` of one of: ${allowed.map((a) => `\`${a}\``).join(', ')}`;
22
- return fail(ctx, `Invalid ${param}: the file '${String(given)}' has a \`purpose\` of \`${String(file.purpose)}\`, but it must have ${need}.`, 400);
639
+ const { trial_end: end, trial_period_days: days } = data;
640
+ const endRefused = end !== undefined && !(Number.isInteger(Number(end)) && Number(end) >= now + 48 * 3600);
641
+ const daysRefused = days !== undefined && !(Number.isInteger(Number(days)) && Number(days) >= 1);
642
+ return endRefused || daysRefused ? sessionTrialRefusal(ctx, endRefused ? 'trial_end' : 'trial_period_days') : undefined;
643
+ }
644
+ export function sessionTrialRefusal(ctx, param) {
645
+ 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.';
646
+ return ctx.refuse({ status: 400, param: `subscription_data[${param}]`, message });
647
+ }
648
+ /** What completing a session makes, by its mode, as the fields that link it: a payment is a PaymentIntent paid with
649
+ * the entered card, its charge in the ledger as any payment's is. */
650
+ export async function complete(ctx, id, existing, card) {
651
+ const link = { status: 'complete' };
652
+ const customer = typeof existing.customer === 'string' ? existing.customer : undefined;
653
+ const currency = typeof existing.currency === 'string' ? existing.currency : 'usd';
654
+ // the entered card becomes a PaymentMethod carrying what a later charge to it answers and what Stripe does after it
655
+ // succeeds (docs.stripe.com/testing#declined-payments, #disputes)
656
+ 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;
657
+ // and Checkout attaches it to the customer when it saves it: a subscription's card ("If your Checkout Session uses
658
+ // subscription mode, Stripe saves the payment method by default", docs.stripe.com/payments/checkout/how-checkout-works),
659
+ // a setup session's (it exists to save one), and a payment's only under payment_intent_data.setup_future_usage ("to have
660
+ // Checkout automatically attach the payment method to the Customer you pass in", docs.stripe.com/api/checkout/sessions/
661
+ // create#create_checkout_session-customer). Attaching is its own write, so payment_method.attached is delivered ("Occurs
662
+ // whenever a new payment method is attached to a customer", docs.stripe.com/api/events/types) before what the card then
663
+ // pays for. Where the documentation stops and the twin decides: the order of the events, which Stripe does not
664
+ // guarantee (docs.stripe.com/webhooks#event-ordering). A gap: the customer's own opt-in to save a payment's card
665
+ // (saved_payment_method_options.payment_method_save) is not modelled; the page offers no such box.
666
+ const saves = existing.mode !== 'payment' || !!(ctx.row(CS, id)?._payment_intent_data ?? {}).setup_future_usage;
667
+ const pm = made && customer && saves ? await ctx.write('payment_method', String(made.id), { customer }, 'payment_method.attach') : made;
668
+ if (existing.mode === 'payment') {
669
+ const amount = Number(existing.amount_total) || 0;
670
+ const piId = ctx.mint('payment_intent');
671
+ const pid = (ctx.row(CS, id)?._payment_intent_data ?? {});
672
+ const connect = {
673
+ ...(pid.application_fee_amount !== undefined ? { application_fee_amount: Math.trunc(Number(pid.application_fee_amount) || 0) } : {}),
674
+ ...(pid.transfer_data && typeof pid.transfer_data === 'object' ? { transfer_data: { destination: pid.transfer_data.destination } } : {}),
675
+ ...(typeof pid.description === 'string' ? { description: pid.description } : {}),
676
+ // the session's setup_future_usage is its PaymentIntent's (payment_intent_data: "A subset of parameters to be passed to PaymentIntent creation")
677
+ ...(typeof pid.setup_future_usage === 'string' ? { setup_future_usage: pid.setup_future_usage } : {}),
678
+ ...(nestedMetadata(pid.metadata) ? { metadata: nestedMetadata(pid.metadata) } : {}),
679
+ };
680
+ const fields = { amount, currency, id: piId, ...(customer ? { customer } : {}), ...(pm ? { payment_method: pm.id } : {}), ...connect };
681
+ 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'] });
682
+ const charge = await mintCharge(ctx, piId, fields, amount);
683
+ await ctx.write('payment_intent', piId, { latest_charge: charge }, 'payment_intent.succeeded');
684
+ link.payment_intent = piId;
685
+ link.payment_status = 'paid';
686
+ }
687
+ else if (existing.mode === 'subscription') {
688
+ if (customer) {
689
+ // the subscription bills the session's own (already resolved) line items, and takes the
690
+ // session's subscription_data: metadata, description, and a trial as its first period
691
+ const now = Number(nowUnix(ctx.occurredAt));
692
+ // "Line items with one-time Prices will be on the initial invoice only" (docs.stripe.com/api/checkout/sessions/
693
+ // create#create_checkout_session-line_items): the subscription's items are the recurring ones
694
+ const inline = ctx.row(CS, id)?._price_data ?? [];
695
+ const lines = existing.line_items?.data ?? [];
696
+ const allLineItems = inline.some(Boolean) ? await sessionPrices(ctx, lines, inline) : lines;
697
+ const sessionLineItems = allLineItems.filter((it) => !isOneTime(it));
698
+ const oneTime = allLineItems.filter((it) => isOneTime(it));
699
+ const { interval, interval_count } = resolveSubscriptionBillingInterval(sessionLineItems, finder(ctx));
700
+ const subId = ctx.mint('subscription');
701
+ // the session's view never carries its create-only subscription_data: read the stored row
702
+ const raw = ctx.row(CS, id)?._subscription_data;
703
+ const subData = (raw && typeof raw === 'object' ? raw : {});
704
+ const subMetadata = nestedMetadata(subData.metadata) ?? {};
705
+ // a trial of `trial_period_days` from now, or to `trial_end` (docs.stripe.com/payments/checkout/free-trials)
706
+ const trialEnd = resolveTrial(subData, now)?.end ?? null;
707
+ const sub = await created(ctx, 'subscription', { customer, id: subId }, {
708
+ status: trialEnd === null ? 'active' : 'trialing', livemode: false, currency, collection_method: 'charge_automatically',
709
+ // a trial's end is the billing anchor (docs.stripe.com/api/subscriptions/create#create_subscription-trial_end)
710
+ cancel_at_period_end: false, start_date: now, billing_cycle_anchor: trialEnd ?? now, metadata: subMetadata,
711
+ description: typeof subData.description === 'string' ? subData.description : null,
712
+ // the session's discount is the subscription's (docs.stripe.com/payments/checkout/discounts)
713
+ discounts: sessionDiscount(ctx, id, customer, now), billing_schedules: [],
714
+ trial_start: trialEnd === null ? null : now, trial_end: trialEnd,
715
+ current_period_start: now, current_period_end: trialEnd ?? addBillingInterval(now, interval, interval_count),
716
+ // Checkout saves the card as the subscription's default payment method (docs.stripe.com/payments/checkout/how-checkout-works)
717
+ default_payment_method: pm?.id ?? null,
718
+ items: buildSubscriptionItemsList(sessionLineItems, subId, now, finder(ctx)),
719
+ automatic_tax: { enabled: false, liability: null }, billing_mode: { type: 'classic' },
720
+ invoice_settings: { issuer: { type: 'self' } },
721
+ });
722
+ await storeItems(ctx, subId, sub.items?.data ?? []);
723
+ // its first invoice, paid on the page by the card just entered (nothing is due on a trial's)
724
+ // (docs.stripe.com/billing/subscriptions/overview#how-payments-work-subscriptions)
725
+ const invoice = await draftSubscriptionInvoice(ctx, sub, { start: now, end: Number(sub.current_period_end), reason: 'subscription_create', trial: trialEnd !== null, once: oneTime });
726
+ await collectSubscriptionInvoice(ctx, invoice, now, 'external');
727
+ await ctx.write('subscription', subId, { latest_invoice: invoice }, 'subscription.update');
728
+ link.subscription = sub.id;
729
+ link.invoice = invoice;
730
+ }
731
+ link.payment_status = 'paid';
732
+ }
733
+ else
734
+ link.setup_intent = await completeSetup(ctx, customer, pm);
735
+ return link;
23
736
  }
737
+ /** A subscription session's lines at completion, each inline `price_data` made the Price it generates ("Data used to
738
+ * generate a new Price object inline", the same page), under the product it names or one made from its product_data,
739
+ * so the subscription's items bill it. Where the documentation stops and the twin decides: such a Price is archived
740
+ * (active=false), as a subscription item's price_data makes one (docs.stripe.com/products-prices/manage-prices). */
741
+ export async function sessionPrices(ctx, lines, inline) {
742
+ const out = [];
743
+ for (const [i, line] of lines.entries()) {
744
+ const d = inline[i];
745
+ if (!d) {
746
+ out.push(line);
747
+ continue;
748
+ }
749
+ const pd = d.product_data && typeof d.product_data === 'object' ? d.product_data : undefined;
750
+ 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);
751
+ const r = d.recurring && typeof d.recurring === 'object' ? d.recurring : undefined;
752
+ const price = await created(ctx, 'price', {
753
+ product, currency: String(d.currency ?? line.currency ?? 'usd').toLowerCase(),
754
+ unit_amount: d.unit_amount_decimal !== undefined ? null : Math.trunc(Number(d.unit_amount) || 0),
755
+ unit_amount_decimal: d.unit_amount_decimal !== undefined ? String(d.unit_amount_decimal) : String(Math.trunc(Number(d.unit_amount) || 0)),
756
+ ...(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 }),
757
+ }, { active: false, livemode: false, billing_scheme: 'per_unit', type: r ? 'recurring' : 'one_time', metadata: {}, lookup_key: null, nickname: null, tax_behavior: 'unspecified' });
758
+ out.push({ ...line, price });
759
+ }
760
+ return out;
761
+ }
762
+ /** A setup session saves the card through a succeeded SetupIntent (docs.stripe.com/payments/save-and-reuse?platform=checkout). */
763
+ export async function completeSetup(ctx, customer, pm) {
764
+ const siId = ctx.mint('setup_intent');
765
+ 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 });
766
+ return si.id;
767
+ }
768
+ /** The discount a completed subscription session gives its subscription. */
769
+ export function sessionDiscount(ctx, id, customer, now) {
770
+ const d = ctx.row(CS, id)?._discount;
771
+ const coupon = d && typeof d.coupon === 'string' ? ctx.get('coupon', d.coupon) : undefined;
772
+ return coupon ? [{ ...buildDiscount(coupon, customer, now), promotion_code: d?.promotion_code ?? null, checkout_session: id }] : [];
773
+ }
774
+ /** The customer paying on the hosted page (src/screens/checkout.tsx): the external actor's move on the
775
+ * session's machine, then what the payment made, linked, and the session stored complete. */
776
+ export async function completeSession(ctx, id, existing, details = {}, card) {
777
+ const refused = ctx.legal(CS, 'status', 'PostCheckoutSessionsSession', existing.status, 'complete', id, 'external');
778
+ if (refused)
779
+ return ctx.refuse(refused);
780
+ const link = await complete(ctx, id, existing, card);
781
+ // the discount the buyer took is redeemed (shared.ts redeemCoupon)
782
+ const d = ctx.row(CS, id)?._discount;
783
+ if (d)
784
+ await redeemCoupon(ctx, d.coupon, d.promotion_code);
785
+ // the session's url "is only present when the session is active" (docs.stripe.com/api/checkout/sessions/object)
786
+ if (link.payment_status !== undefined)
787
+ ctx.legal(CS, 'payment_status', 'PostCheckoutSessionsSession', existing.payment_status, String(link.payment_status), id, 'external');
788
+ return ctx.write(CS, id, { ...details, ...link, url: null }, 'checkout.session.completed');
789
+ }
790
+ export const send = (ctx, r) => ctx.reply(r.body, r.status);
791
+ /** Stripe's error body: an invalid_request_error with the message, and the code when there is one. */
792
+ export const fail = (ctx, message, status = 404, code) => ctx.refuse({ status, message, ...(code ? { code } : {}) });
24
793
  /** The request's path, as the list envelope's `url` carries it. */
25
794
  export const path = (ctx) => new URL(ctx.call.request.url).pathname.replace(/\/+$/, '') || '/';
26
795
  /** A path parameter, by the name the spec gives it. */
27
796
  export const at = (ctx, name) => ctx.call.params[name] ?? '';
28
- /** An update's fields laid over what is stored, as the derived core does: a nested hash is merged into the stored one,
29
- * not put in its place (Stripe updates only the keys a request names; docs.stripe.com/api/metadata and each update
30
- * reference), and an empty string unsets a key. */
31
- export function mergeUpdate(ctx, resource, id, fields) {
32
- const current = ctx.get(resource, id) ?? {};
33
- const out = {};
34
- for (const [k, v] of Object.entries(fields)) {
35
- const prior = current[k];
36
- out[k] = v && typeof v === 'object' && !Array.isArray(v) && prior && typeof prior === 'object' && !Array.isArray(prior)
37
- ? Object.fromEntries(Object.entries({ ...prior, ...v }).filter(([, x]) => x !== ''))
38
- : v;
39
- }
40
- return out;
41
- }
42
- /** The tree's type for a resource: what its rows are stored under. */
43
- export const stored = (resource) => manifest.resources[resource]?.storedAs ?? resource;
44
797
  /** A resource's rows in Stripe's list order: newest first by `timeField`, ties by mint order (as the derived core breaks them). */
45
798
  /** A subject's bookkeeping field (`_…`): kept on the stored row, never in the wire view ctx.get and ctx.rows answer. */
46
799
  export const kept = (ctx, resource, row, key) => ctx.row(resource, String(row.id), { withDeleted: true })?.[key];
47
- /** A removed discount as Stripe answers it: the discount, marked deleted (docs.stripe.com/api/discounts/delete). */
48
- export function deletedDiscount(d, now) {
49
- const coupon = d.coupon && typeof d.coupon === 'object' ? String(d.coupon.id) : typeof d.coupon === 'string' ? d.coupon : null;
50
- return {
51
- id: d.id ?? `di_${coupon ?? 'twin'}`, object: 'discount', deleted: true, checkout_session: d.checkout_session ?? null, customer: d.customer ?? null,
52
- invoice: d.invoice ?? null, invoice_item: d.invoice_item ?? null, promotion_code: d.promotion_code ?? null, subscription: d.subscription ?? null,
53
- subscription_item: d.subscription_item ?? null, source: d.source ?? { type: 'coupon', coupon }, start: d.start ?? now,
54
- };
55
- }
56
800
  /** A create's parameter that describes a confirmation, sent without confirm=true: the served spec gives each "This
57
801
  * parameter can only be used with `confirm=true`" (off_session: "can only be used when confirm=true"); the message's
58
802
  * wording is the twin's. Answers the refusal, or undefined. */
@@ -76,19 +820,15 @@ export function newest(ctx, resource, timeField = 'created') {
76
820
  // an object Stripe gives no creation time is ordered by the one the twin keeps for it
77
821
  const raw = new Map(ctx.rowsRaw(resource).map((r) => [String(r.id), r]));
78
822
  const when = (r) => Number(r[timeField] ?? raw.get(String(r.id))?._created ?? 0);
79
- return ctx.rows(resource).sort((a, b) => {
823
+ // ties by the order the World made them (an event's id is a digest, not a count)
824
+ const rows = ctx.rows(resource);
825
+ const made = new Map(rows.map((r, i) => [r, i]));
826
+ return rows.sort((a, b) => {
80
827
  const ta = when(a), tb = when(b);
81
828
  if (tb !== ta)
82
829
  return tb - ta;
83
- return String(b.id).localeCompare(String(a.id), undefined, { numeric: true });
84
- });
85
- }
86
- /** Keep the rows whose field equals the request's parameter of the same name, for each name given. */
87
- /** A list's range filter on a unix time (`created[gte]=…&created[lt]=…`, or one exact time). */
88
- export function inRange(t, v) {
89
- const at = Number(t);
90
- const r = (v && typeof v === 'object' ? v : { gte: v, lte: v });
91
- 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));
830
+ return made.get(b) - made.get(a);
831
+ }).map((r) => ctx.expand(resource, r));
92
832
  }
93
833
  /** A context at the moment Stripe would have made a move time makes (a renewal, a payout on its schedule), so what
94
834
  * the move writes carries that moment (its events' occurredAt, `created`, a charge's funds' available_on), not the
@@ -105,99 +845,1315 @@ export function where(ctx, items, spec) {
105
845
  }
106
846
  return out;
107
847
  }
108
- function expandPaths(ctx) {
848
+ export function expandPaths(ctx) {
109
849
  const expand = ctx.params.expand;
110
850
  return Array.isArray(expand) ? expand.map((p) => String(p).split('.')) : [];
111
851
  }
112
852
  /** A balance transaction as the clock reads it: available once its available_on has passed, the clock's move,
113
- * asked of the machine as a write asks it (semantics/ledger.ts). */
114
- export function asOf(ctx, t) {
853
+ * asked of the machine as a write asks it (./ledger.ts). */
854
+ export function commonAsOf(ctx, t) {
115
855
  const due = Number(t.available_on);
116
- if (t.status !== 'pending' || !Number.isFinite(due) || due > Number(ctx.now()))
856
+ if (t.status !== 'pending' || !Number.isFinite(due) || due > Number(nowUnix(ctx.occurredAt)))
117
857
  return t;
118
858
  ctx.legal('balance_transaction', 'status', ctx.call.operation.id, 'pending', 'available', String(t.id), 'time');
119
859
  return { ...t, status: 'available' };
120
860
  }
121
- /** Stripe's expand walk: each dotted path replaces an id with the resource the manifest says it
122
- * holds, one segment at a time; an id the tree lacks stays an id. A balance transaction reads as the clock has it
123
- * (asOf), as its own retrieve does. */
861
+ /** Stripe's expand walk (the kernel's, over the manifest's `embeds`): each dotted path replaces an id with the resource
862
+ * it holds, one segment at a time; an id the tree lacks stays an id. An embedded balance transaction reads as the clock
863
+ * has it (asOf), as its own retrieve does. */
124
864
  export function expandRow(ctx, resource, body, paths) {
125
- const embeds = manifest.resources[resource]?.embeds;
126
- if (!embeds || paths.length === 0)
127
- return body;
128
- let out = body;
129
- const byHead = new Map();
130
- for (const p of paths) {
131
- if (p.length === 0)
132
- continue;
133
- const list = byHead.get(p[0]) ?? [];
134
- list.push(p.slice(1));
135
- byHead.set(p[0], list);
136
- }
137
- for (const [head, tails] of byHead) {
138
- const target = embeds[head];
139
- if (!target)
140
- continue;
141
- const cur = out[head];
142
- const found = typeof cur === 'string' && cur ? ctx.get(target, cur) : cur && typeof cur === 'object' && !Array.isArray(cur) ? cur : undefined;
143
- if (!found)
144
- continue;
145
- const sub = target === 'balance_transaction' ? asOf(ctx, found) : found;
146
- const deeper = tails.filter((t) => t.length > 0);
147
- out = { ...out, [head]: deeper.length ? expandRow(ctx, target, sub, deeper) : sub };
148
- }
149
- return out;
865
+ const asOf = (v) => {
866
+ if (Array.isArray(v))
867
+ return v.map(asOf);
868
+ if (!v || typeof v !== 'object')
869
+ return v;
870
+ const o = Object.fromEntries(Object.entries(v).map(([k, x]) => [k, asOf(x)]));
871
+ return o.object === 'balance_transaction' ? commonAsOf(ctx, o) : o;
872
+ };
873
+ const out = ctx.expand(resource, body, paths.map((p) => p.join('.')));
874
+ return Object.fromEntries(Object.entries(out).map(([k, v]) => [k, asOf(v)]));
150
875
  }
151
876
  /** One resource with the request's `expand[]` applied. */
152
877
  export const expanded = (ctx, resource, body) => expandRow(ctx, resource, body, expandPaths(ctx));
878
+ export const resourceView = (ctx, resource, id) => {
879
+ const row = ctx.get(resource, id);
880
+ return row ? ctx.expand(resource, row) : undefined;
881
+ };
153
882
  /** Stripe's list envelope over rows already in list order: a page, `has_more`, and `expand[]=data.*`. */
154
883
  export function list(ctx, resource, items) {
155
884
  const { page, hasMore } = paginate(items, ctx.params);
156
885
  const paths = expandPaths(ctx).filter((p) => p[0] === 'data').map((p) => p.slice(1)).filter((p) => p.length > 0);
157
- return ctx.reply({ object: 'list', url: path(ctx), has_more: hasMore, data: paths.length ? page.map((r) => expandRow(ctx, resource, r, paths)) : page });
886
+ return ctx.reply({ object: 'list', url: path(ctx), has_more: hasMore, data: page.map((r) => expandRow(ctx, resource, r, paths)) });
158
887
  }
159
888
  /** Stripe's search over a resource's rows (`query` in its search language). */
160
889
  export const search = (ctx, resource, timeField = 'created') => send(ctx, searchOver(newest(ctx, resource, timeField), ctx.params, path(ctx)));
161
- const SPEC_FIELDS = new Map(surface.resources.map((r) => [r.name, new Set(r.fields.map((f) => f.name))]));
162
890
  /** A create as Stripe stamps it: the caller's id when it gave one (seeding uses real ids), else a
163
891
  * minted one; `object`, the creation time, the defaults, then the request's own fields. An object
164
892
  * Stripe gives no creation time keeps the twin's as `_created`, for ordering. (A request parameter the
165
893
  * object has no field for stays on the row, where the rules read it; the wire answer leaves it out,
166
- * stripe-version.ts.) */
894
+ * ./version.ts.) */
167
895
  export async function created(ctx, resource, params, defaults, opts = {}) {
168
896
  const { id: provided, ...rest } = params;
169
- const type = stored(resource);
897
+ const type = ctx.storedType(resource);
170
898
  const id = typeof provided === 'string' && provided ? provided : ctx.mint(resource);
171
899
  const known = SPEC_FIELDS.get(resource);
172
900
  const timeField = opts.timeField ?? 'created';
173
901
  const stamped = !known || known.has(timeField) || timeField in defaults || timeField in rest ? timeField : '_created';
174
- const fields = stashVendorType(type, { object: OBJECT_NAME[type] ?? type, [stamped]: ctx.now(), ...defaults, ...rest });
175
- return ctx.write(resource, id, fields, opts.operation ?? `${type}.create`);
176
- }
177
- export const finder = (ctx) => {
178
- const tree = ctx.tree();
179
- return (storedType, id) => {
180
- const r = tree.find((x) => x.type === storedType && x.id === id);
181
- return r ? view(storedType, r) : undefined;
182
- };
902
+ const fields = { object: OBJECT_NAME[type] ?? type, [stamped]: nowUnix(ctx.occurredAt), ...defaults, ...rest };
903
+ // source: spec:/components/schemas/subscription/properties/items/description "List of subscription items, each with an attached price."
904
+ const children = resource === SUB ? (fields.items?.data ?? []) : [];
905
+ if (resource === SUB)
906
+ delete fields.items;
907
+ // source: spec:/components/schemas/subscription_item/properties/price "price"
908
+ if (resource === 'subscription_item') {
909
+ const item = fields;
910
+ if (item.price && typeof item.price === 'object')
911
+ item.price = item.price.id;
912
+ delete item.plan; // the served subscription_item schema has no plan field
913
+ }
914
+ // source: spec:/components/schemas/account/properties/individual "person"
915
+ if (resource === 'account' && fields.individual && typeof fields.individual === 'object') {
916
+ const person = await created(ctx, 'person', { ...fields.individual, account: id }, { metadata: {}, relationship: { representative: true } });
917
+ fields.individual = person.id;
918
+ }
919
+ const row = await ctx.write(resource, id, fields, opts.operation ?? `${type}.create`);
920
+ if (children.length)
921
+ await storeItems(ctx, id, children);
922
+ return ctx.expand(resource, row);
923
+ }
924
+ export const finder = (ctx) => (storedType, id) => {
925
+ const r = ctx.rowsRaw(storedType, { withDeleted: true }).find((x) => x.id === id);
926
+ // source: https://docs.stripe.com/testing "Generic decline 4000 0000 0000 0002"
927
+ // Private test-card behavior is used for subsequent charges, never sent as a vendor field.
928
+ return r ? { ...view(storedType, r), ...(r._declineOutcome !== undefined ? { _declineOutcome: r._declineOutcome } : {}) } : undefined;
183
929
  };
184
- /** A refund's destination_details for a card charge: "If this is a `card` refund, this hash contains the transaction
185
- * specific details" and its `type` "can be `refund`, `reversal`, or `pending`" — a reversal, where "The original charge
186
- * will drop off the bank statement altogether", for an authorization released uncaptured, else a refund, "a credit entry
187
- * on the bank statement" (docs.stripe.com/api/refunds/object). The network's reference number the twin never has. A
188
- * charge not paid by card answers none. */
189
- export function refundDestination(charge, type) {
190
- const pmd = charge.payment_method_details;
191
- if (pmd && pmd.type !== 'card')
192
- return {};
193
- return { destination_details: { type: 'card', card: { reference: null, reference_status: null, reference_type: null, type } } };
194
- }
195
- /** An account's external_accounts, "External accounts (bank accounts and debit cards) currently attached to this
196
- * account" (docs.stripe.com/api/accounts/object), as the list its example answers. */
197
- export const externalList = (account, data) => ({ object: 'list', data, has_more: false, total_count: data.length, url: `/v1/accounts/${account}/external_accounts` });
198
930
  /** The account's external_accounts list, rewritten from its external accounts after one is added or removed. */
199
931
  export async function syncExternals(ctx, account) {
200
932
  if (!ctx.get('account', account))
201
933
  return;
202
934
  await ctx.write('account', account, { external_accounts: externalList(account, newest(ctx, 'external_account').filter((e) => e.account === account)) }, 'account.external_accounts');
203
935
  }
936
+ export const pmMissing = (ctx, id) => fail(ctx, `No such payment_method: '${id}'`, 404, 'resource_missing');
937
+ /** The card a charge was paid with, as its payment_method_details reports it
938
+ * (docs.stripe.com/api/charges/object#charge_object-payment_method_details): a stored PaymentMethod's card, a
939
+ * documented test name (pm_card_* or tok_*, the same cards), or a raw card; undefined for anything else. */
940
+ export function paymentMethodDetails(ctx, ref) {
941
+ let card;
942
+ // a payment method of another kind (a US bank account) is described by its own block, as the charge reports it
943
+ const stored = typeof ref === 'string' && ref ? ctx.get(PM, ref) : undefined;
944
+ // Stripe's US bank account test methods (pm_us_bank_account, pm_usBankAccount_*) are its test bank's account
945
+ const pm = stored ?? (typeof ref === 'string' && /^pm_us_?bank_?account/i.test(ref) ? { type: 'us_bank_account', ...paymentMethodSubObject('us_bank_account', {}) } : undefined);
946
+ if (pm && typeof pm.type === 'string' && pm.type !== 'card') {
947
+ const own = pm[pm.type] ?? {};
948
+ const pick = ['account_holder_type', 'account_type', 'bank_name', 'fingerprint', 'last4', 'routing_number'];
949
+ return { type: pm.type, [pm.type]: Object.fromEntries(pick.filter((k) => own[k] !== undefined).map((k) => [k, own[k]])) };
950
+ }
951
+ if (typeof ref === 'string' && ref) {
952
+ const stored = ctx.get(PM, ref)?.card;
953
+ if (stored)
954
+ card = stored;
955
+ else
956
+ card = testCardOf(ref);
957
+ }
958
+ else if (ref && typeof ref === 'object')
959
+ card = paymentMethodSubObject('card', { card: ref }).card;
960
+ if (!card)
961
+ return undefined;
962
+ return {
963
+ type: 'card',
964
+ card: {
965
+ brand: card.brand, last4: card.last4, exp_month: card.exp_month, exp_year: card.exp_year, funding: card.funding ?? 'credit',
966
+ country: card.country ?? 'US', network: card.brand, fingerprint: card.fingerprint ?? null,
967
+ checks: card.checks ?? { address_line1_check: null, address_postal_code_check: null, cvc_check: 'pass' },
968
+ three_d_secure: null, wallet: null, installments: null, mandate: null,
969
+ },
970
+ };
971
+ }
972
+ // attaching needs an existing customer; a well-known test token (pm_card_visa, …) is a template:
973
+ // attaching it mints a new PaymentMethod on the customer carrying that card's outcome
974
+ /** Whether a payment method can be attached: a stored one, or a documented test name that attaching mints. */
975
+ export const attachable = (ctx, id) => !!ctx.get(PM, id) || (id.startsWith('pm_card_') && (id in TEST_TOKEN_DECLINES || id in AFTER_SUCCESS_CARDS));
976
+ export async function attachPaymentMethod(ctx, id, customer) {
977
+ if (!ctx.get(PM, id))
978
+ return materializeTestMethod(ctx, id, customer);
979
+ return ctx.write(PM, id, { customer }, 'payment_method.attach');
980
+ }
981
+ /** A documented test name (pm_card_visa, pm_card_visa_chargeDeclined, …) made a real PaymentMethod, as Stripe
982
+ * does when one is used: the brand and number it stands for (docs.stripe.com/testing#cards) and its outcome. */
983
+ export async function materializeTestMethod(ctx, id, customer) {
984
+ const card = TEST_PM_CARDS[id] ?? { brand: 'visa', number: '4242424242424242' };
985
+ const sub = paymentMethodSubObject('card', { card: { number: card.number } });
986
+ sub.card.brand = card.brand;
987
+ const afterSuccess = AFTER_SUCCESS_CARDS[id]?.outcome;
988
+ return created(ctx, PM, { type: 'card', customer, livemode: false, billing_details: noBilling, ...sub, _declineOutcome: TEST_TOKEN_DECLINES[id] ?? null, ...(afterSuccess ? { _afterSuccess: afterSuccess } : {}) }, {});
989
+ }
990
+ /** A PaymentMethod made from a confirm's `payment_method_data` ("If provided, this hash will be used to create a
991
+ * PaymentMethod", docs.stripe.com/api/setup_intents/confirm, docs.stripe.com/api/payment_intents/confirm), or none. */
992
+ export async function methodFromData(ctx, data) {
993
+ if (!data || typeof data !== 'object')
994
+ return undefined;
995
+ const d = data;
996
+ const type = typeof d.type === 'string' ? d.type : 'card';
997
+ const made = await created(ctx, PM, {}, {
998
+ type, customer: null, livemode: false,
999
+ // source: spec:/paths/~1v1~1setup_intents~1{intent}~1confirm/post/requestBody/content/application~1x-www-form-urlencoded/schema/properties/payment_method_data/description "this hash creates a PaymentMethod"
1000
+ metadata: d.metadata && typeof d.metadata === 'object' ? d.metadata : {},
1001
+ billing_details: { ...noBilling, ...(d.billing_details ?? {}) },
1002
+ ...paymentMethodSubObject(type, d),
1003
+ // what follows its card's success (a dispute, funds straight to available), as a PaymentMethod created directly carries
1004
+ ...(type === 'card' && afterSuccessOf(ctx, d.card) ? { _afterSuccess: afterSuccessOf(ctx, d.card) } : {}),
1005
+ // and what a payment with its card answers: a test card the issuer declines, or one that asks the cardholder to
1006
+ // authenticate, entered as its number (Stripe.js sends it so), as the same card made a PaymentMethod directly does
1007
+ // source: https://docs.stripe.com/testing "Generic decline 4000 0000 0000 0002"
1008
+ // source: https://docs.stripe.com/testing "This card requires authentication on all transactions, regardless of how the card is set up."
1009
+ ...(type === 'card' ? { _declineOutcome: declineFor(() => undefined, { card: d.card }) ?? null, ...(requiresAuthentication({ card: d.card }) ? { _requiresAuthentication: true } : {}) } : {}),
1010
+ });
1011
+ return String(made.id);
1012
+ }
1013
+ /** Whether an intent sets up or pays with a bank account by micro-deposits because it asks for them:
1014
+ * payment_method_options[us_bank_account][verification_method]=microdeposits with a us_bank_account method
1015
+ * ("Microdeposit only verification", docs.stripe.com/payments/ach-direct-debit/set-up-payment). */
1016
+ export function microdepositsAsked(ctx, params, intent, pm) {
1017
+ const options = (params.payment_method_options ?? intent.payment_method_options)?.us_bank_account;
1018
+ return options?.verification_method === 'microdeposits' && !!pm && ctx.get(PM, pm)?.type === 'us_bank_account';
1019
+ }
1020
+ // ── features: an entitlements feature granted to a product, at most once ──
1021
+ /** A tiered price: tiers_mode and tiers, each tier with up_to and a unit or flat amount; no single unit_amount, and
1022
+ * the last tier's up_to null (∞) (docs.stripe.com/products-prices/pricing-models#tiered-pricing). */
1023
+ export async function tieredPrice(ctx, params) {
1024
+ const mode = typeof params.tiers_mode === 'string' ? params.tiers_mode : '';
1025
+ if (mode !== 'graduated' && mode !== 'volume')
1026
+ return fail(ctx, 'Missing required param: tiers_mode (graduated or volume).', 400, 'parameter_missing');
1027
+ const rawTiers = Array.isArray(params.tiers) ? params.tiers : [];
1028
+ if (rawTiers.length === 0)
1029
+ return fail(ctx, 'Missing required param: tiers.', 400, 'parameter_missing');
1030
+ const tiers = rawTiers.map((t) => {
1031
+ const upToRaw = t.up_to;
1032
+ return {
1033
+ up_to: upToRaw === 'inf' || upToRaw === undefined || upToRaw === null ? null : Math.trunc(Number(upToRaw)),
1034
+ unit_amount: t.unit_amount !== undefined ? Math.trunc(Number(t.unit_amount)) : null,
1035
+ unit_amount_decimal: t.unit_amount !== undefined ? String(Math.trunc(Number(t.unit_amount))) : null,
1036
+ flat_amount: t.flat_amount !== undefined ? Math.trunc(Number(t.flat_amount)) : null,
1037
+ flat_amount_decimal: t.flat_amount !== undefined ? String(Math.trunc(Number(t.flat_amount))) : null,
1038
+ };
1039
+ });
1040
+ if (tiers.some((t) => t.unit_amount === null && t.flat_amount === null))
1041
+ return fail(ctx, 'Each tier must specify a unit_amount or flat_amount.', 400, 'parameter_invalid_empty');
1042
+ const { tiers: _t, ...rest } = params;
1043
+ 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: {} }));
1044
+ }
1045
+ /** Whether the intent's caller named its methods: on create (TYPES_GIVEN), or by an update that set its
1046
+ * payment_method_types ("Alternatively, update the allowed payment_method_types for this PaymentIntent",
1047
+ * methodNotAllowed below), which the generic update writes as given, so the intent's history holds it. */
1048
+ export const typesGiven = (ctx, id) => ctx.rowsRaw(TYPES_GIVEN).some((r) => r.id === id)
1049
+ || ctx.history(PI, id).some((e) => e.operation !== 'payment_intent.create' && Array.isArray(e.fields?.payment_method_types));
1050
+ export const paymentIntentsSend = (ctx, r) => ctx.reply(r.body, r.status);
1051
+ export async function mintCharge(ctx, piId, pi, amount) {
1052
+ const already = ctx.get(PI, piId)?.latest_charge;
1053
+ if (typeof already === 'string' && ctx.get('charge', already)?.status === 'succeeded')
1054
+ return already;
1055
+ const chargeId = ctx.mint('charge');
1056
+ const bt = await settleCharge(ctx, chargeId, amount, String(pi.currency ?? 'usd'), typeof pi.payment_method === 'string' ? pi.payment_method : undefined);
1057
+ await created(ctx, 'charge', {
1058
+ id: chargeId, amount, currency: pi.currency ?? 'usd', payment_intent: piId,
1059
+ ...(typeof pi.customer === 'string' ? { customer: pi.customer } : {}),
1060
+ ...(typeof pi.payment_method === 'string' ? { payment_method: pi.payment_method } : {}),
1061
+ ...(typeof pi.invoice === 'string' ? { invoice: pi.invoice } : {}),
1062
+ ...intentCarries(pi),
1063
+ }, { ...chargeDefaults(chargeId, amount, true, ctx.occurredAt), balance_transaction: bt, payment_method_details: paymentMethodDetails(ctx, pi.payment_method) ?? null }, { operation: 'charge.succeeded' });
1064
+ await afterCharge(ctx, chargeId, { amount, currency: String(pi.currency ?? 'usd'), payment_intent: piId, application_fee_amount: pi.application_fee_amount, destination: pi.transfer_data?.destination }, pi.payment_method);
1065
+ return chargeId;
1066
+ }
1067
+ /** A manual-capture intent's authorization: "Separate payment authorization and capture to create a charge now, but
1068
+ * capture funds later", and on capture "A partial capture automatically releases the remaining amount"
1069
+ * (docs.stripe.com/payments/place-a-hold-on-a-payment-method). The charge succeeded and is not captured, holding the
1070
+ * amount until capture_before, with nothing on the balance yet. Written as
1071
+ * charge.succeeded, as a charge made with capture=false is (charges.ts); its capture writes charge.captured
1072
+ * (captureAuthorization). Where the documentation stops and the twin decides: the events page names no event for an
1073
+ * authorization of its own, so the authorized charge sends charge.succeeded, its status being succeeded. */
1074
+ export async function authorizeCharge(ctx, piId, pi, amount) {
1075
+ const chargeId = ctx.mint('charge');
1076
+ await created(ctx, 'charge', {
1077
+ id: chargeId, amount, currency: pi.currency ?? 'usd', payment_intent: piId,
1078
+ ...(typeof pi.customer === 'string' ? { customer: pi.customer } : {}),
1079
+ ...(typeof pi.payment_method === 'string' ? { payment_method: pi.payment_method } : {}),
1080
+ ...(typeof pi.invoice === 'string' ? { invoice: pi.invoice } : {}),
1081
+ ...intentCarries(pi),
1082
+ }, { ...chargeDefaults(chargeId, amount, false, ctx.occurredAt), balance_transaction: null, payment_method_details: paymentMethodDetails(ctx, pi.payment_method) ?? null }, { operation: 'charge.succeeded' });
1083
+ return chargeId;
1084
+ }
1085
+ /**
1086
+ * An intent an invoice collects through succeeded (the default_incomplete subscription flow: create
1087
+ * now, confirm client-side): its invoice is paid and, when it is a subscription's first, the
1088
+ * subscription leaves incomplete for active. Both are moves the invoice and subscription machines
1089
+ * declare under the confirming operation. No-op when the intent names no invoice, or the invoice is
1090
+ * already paid (a duplicate confirm) or void (voiding ends what it collects).
1091
+ */
1092
+ export async function payInvoiceOf(ctx, pi, operationId, actor) {
1093
+ const invoiceId = typeof pi.invoice === 'string' ? pi.invoice : undefined;
1094
+ const invoice = invoiceId ? ctx.get('invoice', invoiceId) : undefined;
1095
+ if (!invoiceId || !invoice || invoice.status === 'paid' || invoice.status === 'void')
1096
+ return;
1097
+ await finishInvoiceIntent(ctx, invoice, invoiceId, operationId, actor);
1098
+ }
1099
+ /** An invoice-linked intent read back from a live account; the served create API cannot set invoice. */
1100
+ export async function finishInvoiceIntent(ctx, invoice, invoiceId, operationId, actor) {
1101
+ if (ctx.legal('invoice', 'status', operationId, invoice.status, 'paid', invoiceId, actor))
1102
+ return;
1103
+ const amount = Number(invoice.total ?? invoice.amount_due) || 0;
1104
+ // `invoice.pay` is the event the standalone pay action sends: invoice.paid
1105
+ await ctx.write('invoice', invoiceId, {
1106
+ status: 'paid', paid: true, amount_paid: amount, amount_remaining: 0,
1107
+ status_transitions: { ...(invoice.status_transitions ?? {}), paid_at: nowUnix(ctx.occurredAt) },
1108
+ }, 'invoice.pay');
1109
+ const subId = typeof invoice.subscription === 'string' ? invoice.subscription : undefined;
1110
+ const sub = subId ? resourceView(ctx, 'subscription', subId) : undefined;
1111
+ if (subId && sub && sub.status === 'incomplete' && !ctx.legal('subscription', 'status', operationId, sub.status, 'active', subId, actor)) {
1112
+ await ctx.write('subscription', subId, { status: 'active' }, 'subscription.update');
1113
+ }
1114
+ }
1115
+ /** The type of the payment method an intent is paid with: its PaymentMethod's, or a documented test name's (pm_card_*,
1116
+ * tok_* a card; pm_usBankAccount_* a US bank account), else unknown. */
1117
+ export function methodType(ctx, method) {
1118
+ if (typeof method !== 'string' || !method)
1119
+ return undefined;
1120
+ const row = ctx.get('payment_method', method);
1121
+ if (row)
1122
+ return typeof row.type === 'string' ? row.type : undefined;
1123
+ if (/^pm_us_?bank_?account/i.test(method))
1124
+ return 'us_bank_account';
1125
+ if (/^(pm_card_|tok_)/.test(method))
1126
+ return 'card';
1127
+ return undefined;
1128
+ }
1129
+ /** A confirm with a payment method of a type the intent's caller did not allow, refused as Stripe refuses it: "The
1130
+ * PaymentMethod provided (card_present) is not allowed for this PaymentIntent. Please attach a PaymentMethod of one of
1131
+ * the following types: card. Alternatively, update the allowed payment_method_types for this PaymentIntent to include
1132
+ * "card_present"" (a real answer quoted in github.com/stripe/stripe-terminal-react-native/issues/745, an intent made
1133
+ * with payment_method_types ['card']). Only a list the caller gave restricts: without one Stripe offers the methods
1134
+ * the account enables, which the twin does not model. Where the evidence stops: that answer's code is not quoted; the
1135
+ * twin answers payment_intent_invalid_parameter ("One or more provided parameters wasn't allowed for the given
1136
+ * operation on the PaymentIntent", docs.stripe.com/error-codes), param payment_method. */
1137
+ export function methodNotAllowed(ctx, existing, params) {
1138
+ const types = Array.isArray(params.payment_method_types) ? params.payment_method_types.map(String)
1139
+ : Array.isArray(params.allowed_payment_method_types) ? params.allowed_payment_method_types.map(String)
1140
+ : typesGiven(ctx, String(existing.id)) && Array.isArray(existing.payment_method_types) ? existing.payment_method_types.map(String) : undefined;
1141
+ if (!types)
1142
+ return undefined;
1143
+ const type = methodType(ctx, params.payment_method ?? existing.payment_method);
1144
+ if (!type || types.includes(type))
1145
+ return undefined;
1146
+ 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}"` });
1147
+ }
1148
+ // Confirmation controls are request instructions, absent from the pinned PaymentIntent object.
1149
+ // source: spec:/paths/~1v1~1payment_intents~1{intent}~1confirm/post/requestBody/content/application~1x-www-form-urlencoded/schema/properties/return_url/description "The URL to redirect your customer back to after they authenticate or cancel their payment"
1150
+ export function intentFields(params) {
1151
+ const { confirm: _confirm, amount_to_confirm: _amount, confirmation_token: _token, error_on_requires_action: _error, expand: _expand, mandate: _mandate, mandate_data: _mandateData, off_session: _offSession, payment_method_data: _methodData, radar_options: _radar, return_url: _returnUrl, use_stripe_sdk: _sdk, ...fields } = params;
1152
+ return fields;
1153
+ }
1154
+ /** Confirm an intent the confirm machine allows to move: the confirm action, and a create with `confirm=true`. */
1155
+ export async function confirmIntent(ctx, existing, params) {
1156
+ const id = String(existing.id);
1157
+ // a payment names a mandate only an active one authorizes: an inactive mandate "was rejected, revoked, or previously
1158
+ // used, and may not be used to initiate future payments" (docs.stripe.com/api/mandates/object), refused as
1159
+ // payment_intent_mandate_invalid, "The provided mandate is invalid and can't be used for the payment intent"
1160
+ // (docs.stripe.com/error-codes)
1161
+ const named = typeof params.mandate === 'string' ? params.mandate : typeof existing.mandate === 'string' ? existing.mandate : undefined;
1162
+ if (named && ctx.get('mandate', named)?.status !== 'active')
1163
+ return fail(ctx, 'The provided mandate is invalid and can\'t be used for the payment intent.', 400, 'payment_intent_mandate_invalid');
1164
+ const notAllowed = methodNotAllowed(ctx, existing, params);
1165
+ if (notAllowed)
1166
+ return notAllowed;
1167
+ // a declining test card leaves the intent needing a payment method, with the error on it and a 402
1168
+ const decline = declineFor(finder(ctx), params, existing);
1169
+ if (decline) {
1170
+ // Stripe records the attempt: a failed charge the intent's latest_charge names, the declined card on
1171
+ // last_payment_error (a test name made a real PaymentMethod), and no payment_method left on the intent
1172
+ // (docs.stripe.com/payments/paymentintents/lifecycle, docs.stripe.com/declines)
1173
+ const ref = params.payment_method ?? existing.payment_method;
1174
+ let pmId = typeof ref === 'string' ? ref : undefined;
1175
+ if (pmId && !ctx.get('payment_method', pmId) && pmId.startsWith('pm_card_'))
1176
+ pmId = String((await materializeTestMethod(ctx, pmId, typeof existing.customer === 'string' ? existing.customer : null)).id);
1177
+ const pm = pmId ? ctx.get('payment_method', pmId) : undefined;
1178
+ const amount = Number(params.amount ?? existing.amount) || 0;
1179
+ const chargeId = ctx.mint('charge');
1180
+ await created(ctx, 'charge', {
1181
+ id: chargeId, amount, currency: existing.currency ?? 'usd', payment_intent: id,
1182
+ ...(typeof existing.customer === 'string' ? { customer: existing.customer } : {}),
1183
+ ...(pmId ? { payment_method: pmId } : {}),
1184
+ ...intentCarries({ ...existing, ...intentFields(params) }),
1185
+ }, {
1186
+ ...chargeDefaults(chargeId, amount, false, ctx.occurredAt), status: 'failed', paid: false, captured: false, capture_before: null,
1187
+ failure_code: decline.code, failure_message: decline.message, balance_transaction: null,
1188
+ 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.' },
1189
+ payment_method_details: pmId ? paymentMethodDetails(ctx, pmId) ?? null : null,
1190
+ }, { operation: 'charge.failed' }); // "Occurs whenever a failed charge attempt occurs." (docs.stripe.com/api/events/types)
1191
+ const { payment_method: _pm, ...rest } = params;
1192
+ 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 };
1193
+ const failed = await ctx.write(PI, id, { ...intentFields(rest), payment_method: null, latest_charge: chargeId, status: 'requires_payment_method', last_payment_error }, 'payment_intent.payment_failed');
1194
+ return paymentIntentsSend(ctx, cardError(decline, { payment_intent: failed, charge: chargeId }));
1195
+ }
1196
+ // a bank debit that needs micro-deposit verification waits in requires_action
1197
+ const method = typeof params.payment_method === 'string' ? params.payment_method : typeof existing.payment_method === 'string' ? existing.payment_method : undefined;
1198
+ // a bank transfer is paid from the customer's cash balance, or waits for the transfer (fundFromCashBalance)
1199
+ if (method && ctx.get('payment_method', method)?.type === 'customer_balance')
1200
+ return ctx.reply(ctx.expand(PI, await fundFromCashBalance(ctx, { ...existing, ...intentFields(params) }, intentFields(params))));
1201
+ if (requiresMicrodeposits(params, existing) || microdepositsAsked(ctx, params, existing, method)) {
1202
+ return ctx.reply(ctx.expand(PI, await ctx.write(PI, id, { ...intentFields(params), status: 'requires_action', next_action: microdepositsNextAction(), last_payment_error: null }, 'payment_intent.requires_action')));
1203
+ }
1204
+ // 3DS: the first confirm asks for authentication; a second one completes it
1205
+ if (existing.status !== 'requires_action' && (requiresAuthentication(params, existing) || (!!method && ctx.row(PM, method)?._requiresAuthentication === true))) {
1206
+ return ctx.reply(ctx.expand(PI, await ctx.write(PI, id, { ...intentFields(params), status: 'requires_action', next_action: threeDsNextAction(), last_payment_error: null }, 'payment_intent.requires_action')));
1207
+ }
1208
+ // manual capture authorizes and waits for /capture: the authorization is a charge, succeeded and not captured, the
1209
+ // intent's latest_charge
1210
+ if ((params.capture_method ?? existing.capture_method) === 'manual') {
1211
+ const amount = Number(existing.amount ?? params.amount ?? 0);
1212
+ const charge = await authorizeCharge(ctx, id, { ...existing, ...intentFields(params) }, amount);
1213
+ return ctx.reply(ctx.expand(PI, await ctx.write(PI, id, { ...intentFields(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')));
1214
+ }
1215
+ // a bank debit is submitted and settles later (beginBankDebit)
1216
+ if (isBankDebit(ctx, method))
1217
+ return ctx.reply(ctx.expand(PI, await beginBankDebit(ctx, id, intentFields(params))));
1218
+ const amount = Number(existing.amount ?? params.amount ?? 0);
1219
+ // a succeeded intent has a Charge, and latest_charge names it: what a refund of it lands on
1220
+ const charge = await mintCharge(ctx, id, { ...existing, ...intentFields(params) }, amount);
1221
+ const body = await ctx.write(PI, id, { ...intentFields(params), status: 'succeeded', amount_received: amount, next_action: null, last_payment_error: null, latest_charge: charge }, 'payment_intent.confirm');
1222
+ await payInvoiceOf(ctx, body, 'PostPaymentIntentsIntentConfirm');
1223
+ return ctx.reply(ctx.expand(PI, body));
1224
+ }
1225
+ /** Whether the method an intent is confirmed with is a bank debit: a us_bank_account PaymentMethod, or one of Stripe's
1226
+ * test bank accounts named as one (pm_usBankAccount_*, pm_us_bank_account). */
1227
+ export function isBankDebit(ctx, method) {
1228
+ if (typeof method !== 'string')
1229
+ return false;
1230
+ return ctx.get('payment_method', method)?.type === 'us_bank_account' || /^pm_us_?bank_?account/i.test(method);
1231
+ }
1232
+ /** Whether a bank debit stays processing: the page's pm_usBankAccount_processing, or its account 000000000009. */
1233
+ export function staysProcessing(ctx, method) {
1234
+ if (method === 'pm_usBankAccount_processing')
1235
+ return true;
1236
+ const bank = typeof method === 'string' ? ctx.get('payment_method', method)?.us_bank_account : undefined;
1237
+ return bank?.last4 === '0009';
1238
+ }
1239
+ /** A bank debit submitted: the intent processes, nothing received yet, sent as payment_intent.processing; it is due to
1240
+ * settle at this instant, unless its test account stays processing. */
1241
+ export async function beginBankDebit(ctx, id, fields) {
1242
+ const method = fields.payment_method ?? ctx.get(PI, id)?.payment_method;
1243
+ 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');
1244
+ }
1245
+ /** Time's settling of bank debits, caught up to the World's clock: each processing debit whose moment has come succeeds
1246
+ * then, its Charge made and the invoice it collects for paid. */
1247
+ export async function settleBankDebits(ctx) {
1248
+ const now = Number(nowUnix(ctx.occurredAt));
1249
+ 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));
1250
+ for (const pi of due) {
1251
+ const id = String(pi.id);
1252
+ const c = await at_(ctx)(Number(pi._settles_at));
1253
+ c.legal(PI, 'status', ctx.call.operation.id, 'processing', 'succeeded', id, 'vendor');
1254
+ const amount = Number(pi.amount) || 0;
1255
+ const charge = await mintCharge(c, id, pi, amount);
1256
+ const body = await c.write(PI, id, { status: 'succeeded', amount_received: amount, latest_charge: charge, _settles_at: null }, 'payment_intent.succeeded');
1257
+ // (a debit run under a mandate names it on its charge, and a single-use mandate is spent by it, at Stripe; the twin
1258
+ // makes no mandate: micro-deposit verification, which accepts one, is the gap here, ../manifest.ts unmodeled)
1259
+ await payInvoiceOf(c, body, ctx.call.operation.id, 'vendor');
1260
+ }
1261
+ }
1262
+ /** A customer_balance intent funded from the customer's cash balance: paid when the balance covers it ("If the customer
1263
+ * already has a balance high enough to cover the payment amount, the PaymentIntent immediately succeeds"), else
1264
+ * waiting for a transfer: "If the customer balance isn’t high enough to cover the request amount, the PaymentIntent
1265
+ * shows a requires_action status ... next_action ... display_bank_transfer_instructions" with the amount_remaining
1266
+ * (docs.stripe.com/payments/bank-transfers/accept-a-payment). Answers the intent as written. */
1267
+ export async function fundFromCashBalance(ctx, pi, fields = {}) {
1268
+ const customer = typeof pi.customer === 'string' ? pi.customer : '';
1269
+ const currency = String(pi.currency ?? 'usd');
1270
+ // what the customer's funded cash balance holds in this currency, from its ledger
1271
+ 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;
1272
+ const amount = Number(pi.amount) || 0;
1273
+ if (available >= amount)
1274
+ return payFromCashBalance(ctx, pi, fields, { customer, currency, available, amount });
1275
+ // not enough yet: the intent waits for the rest, with the instructions to send it
1276
+ const next_action = { type: 'display_bank_transfer_instructions', display_bank_transfer_instructions: { amount_remaining: amount - available, currency, type: 'us_bank_transfer' } };
1277
+ return ctx.write(PI, String(pi.id), { ...fields, status: 'requires_action', next_action }, 'payment_intent.requires_action');
1278
+ }
1279
+ /** A customer_balance intent the customer's funded cash balance pays: its ledger records what was applied, and the intent
1280
+ * succeeds with its charge. */
1281
+ export async function payFromCashBalance(ctx, pi, fields, o) {
1282
+ await created(ctx, 'customer_cash_balance_transaction', { customer: o.customer }, { currency: o.currency, type: 'applied_to_payment', net_amount: -o.amount, ending_balance: o.available - o.amount, applied_to_payment: { payment_intent: String(pi.id) }, livemode: false });
1283
+ const charge = await mintCharge(ctx, String(pi.id), { ...pi, ...fields }, o.amount);
1284
+ return ctx.write(PI, String(pi.id), { ...fields, status: 'succeeded', next_action: null, amount_received: o.amount, last_payment_error: null, latest_charge: charge }, 'payment_intent.succeeded');
1285
+ }
1286
+ /** Whether a charge's funds go straight to the available balance: a bypass card as a raw number, a test name (pm_card_*
1287
+ * or tok_*), or a stored PaymentMethod made from one (which records it as what follows its success, after-payment.ts);
1288
+ * or a US bank account, stored or one of Stripe's test bank accounts named as one (pm_usBankAccount_*). */
1289
+ export function bypassesPending(ctx, card) {
1290
+ if (!card)
1291
+ return false;
1292
+ const stored = ctx.row('payment_method', card);
1293
+ // the row carries what the method recorded; its type is the vendor object's (ctx.get), not the row's envelope
1294
+ if (stored)
1295
+ return stored._afterSuccess === 'available' || ctx.get('payment_method', card)?.type === 'us_bank_account';
1296
+ if (/^pm_us_?bank_?account/i.test(card))
1297
+ return true;
1298
+ return BYPASS_NUMBERS.has(card.replace(/\D/g, '')) || card.replace(/^tok_/, 'pm_card_') in BYPASS_PENDING_CARDS;
1299
+ }
1300
+ /** The connected account a request acts for, or undefined for the platform. */
1301
+ // The platform's own account ID denotes the same balance as an omitted Stripe-Account header.
1302
+ export const actingAccount = (ctx) => { const id = ctx.call.request.headers.get('stripe-account'); return id && id !== PLATFORM_ACCOUNT_ID ? id : undefined; };
1303
+ /** A ledger entry on an account's balance: the acting account's unless one is named (null names the platform). */
1304
+ export async function write(ctx, fields, account = actingAccount(ctx)) {
1305
+ // a credit available at once waits for the drain's balance.available (settleDueEntries)
1306
+ const unsent = (fields.status ?? 'available') === 'available' && Number(fields.net) > 0 ? { [UNSENT]: true } : {};
1307
+ const bt = await created(ctx, BT, {}, { status: 'available', fee_details: [], description: null, exchange_rate: null, balance_type: 'payments', ...fields, ...unsent, ...(account ? { _account: account } : {}) });
1308
+ return String(bt.id);
1309
+ }
1310
+ /** A captured charge's credit: its amount less the fee, pending two days unless the card bypasses the pending
1311
+ * balance (bypassesPending), when it is due at once. The
1312
+ * caller mints the charge's id first and stores the returned id as the charge's balance_transaction. */
1313
+ export async function settleCharge(ctx, chargeId, amount, currency, card) {
1314
+ const now = Number(nowUnix(ctx.occurredAt));
1315
+ const fee = feeOf(amount);
1316
+ const atOnce = bypassesPending(ctx, card);
1317
+ const id = await write(ctx, {
1318
+ amount, currency, fee, net: amount - fee, type: 'charge', reporting_category: 'charge', source: chargeId,
1319
+ ...(atOnce ? { status: 'available', available_on: now } : { status: 'pending', available_on: now + 2 * DAY }),
1320
+ fee_details: fee ? [{ amount: fee, application: null, currency, description: 'Stripe processing fees', type: 'stripe_fee' }] : [],
1321
+ });
1322
+ return id;
1323
+ }
1324
+ /** A refund's debit, at once, on the acting account's balance unless one is named (null names the platform). */
1325
+ export async function settleRefund(ctx, refundId, amount, currency, account = actingAccount(ctx)) {
1326
+ return write(ctx, { amount: -amount, currency, fee: 0, net: -amount, type: 'refund', reporting_category: 'refund', source: refundId, available_on: Number(nowUnix(ctx.occurredAt)) }, account);
1327
+ }
1328
+ /** What an account had available in a currency at a moment: every entry of its payments balance whose funds had come
1329
+ * due by then. */
1330
+ export function availableAt(ctx, account, currency, at) {
1331
+ let sum = 0;
1332
+ for (const t of ctx.rowsRaw(BT)) {
1333
+ if (!onAccount(t, account) || t.balance_type === 'issuing' || String(t.currency ?? 'usd') !== currency)
1334
+ continue;
1335
+ const due = Number(t.available_on ?? t.created);
1336
+ if (Number.isFinite(due) && due <= at)
1337
+ sum += Number(t.net ?? 0);
1338
+ }
1339
+ return sum;
1340
+ }
1341
+ /** The moments after `from` and up to `until` when funds of an account came due, in order: when a held refund can
1342
+ * next be covered. */
1343
+ export function fundsDueBetween(ctx, account, currency, from, until) {
1344
+ 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);
1345
+ return [...new Set(times)].sort((a, b) => a - b);
1346
+ }
1347
+ /** A dispute's debit, at once: the disputed amount and the dispute fee (the twin's 1500 cents, Stripe's US $15). */
1348
+ export async function settleDispute(ctx, disputeId, amount, currency) {
1349
+ const fee = 1500;
1350
+ return write(ctx, {
1351
+ amount: -amount, currency, fee, net: -amount - fee, type: 'adjustment', reporting_category: 'dispute', source: disputeId, available_on: Number(nowUnix(ctx.occurredAt)),
1352
+ fee_details: [{ amount: fee, application: null, currency, description: 'Dispute fee', type: 'stripe_fee' }],
1353
+ });
1354
+ }
1355
+ /** An account's ledger entries an automatic payout has not yet paid out: every entry on its payments balance that no
1356
+ * automatic payout took (the automatic payouts' own debits excluded), as stored. */
1357
+ export function unpaidEntries(ctx, account) {
1358
+ const automatic = new Set(ctx.rowsRaw('payout').filter((p) => p.automatic === true).map((p) => p.id));
1359
+ return ctx.rowsRaw(BT).filter((t) => onAccount(t, account) && t.balance_type !== 'issuing' && !t._payout && !automatic.has(t.source));
1360
+ }
1361
+ /** An automatic payout's debit at `at`, and the entries it pays out marked with it, so the ledger lists them under
1362
+ * the payout (docs.stripe.com/api/balance_transactions/list#balance_transaction_list-payout). */
1363
+ export async function settleAutomaticPayout(ctx, payoutId, amount, currency, account, at, entries) {
1364
+ for (const t of entries)
1365
+ await ctx.write(BT, String(t.id), { _payout: payoutId }, 'balance_transaction.paid_out');
1366
+ return write(ctx, { amount: -amount, currency, fee: 0, net: -amount, type: 'payout', reporting_category: 'payout', source: payoutId, available_on: at, _payout: payoutId }, account ?? null);
1367
+ }
1368
+ /** A payout's debit (negative) or a cancellation's or reversal's credit (positive), at once, on the payout's account. */
1369
+ export async function settlePayout(ctx, payoutId, amount, currency, account = actingAccount(ctx)) {
1370
+ const type = amount < 0 ? 'payout' : 'payout_cancel';
1371
+ 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);
1372
+ }
1373
+ /** A transfer's two entries: out of the platform's balance at once, into the destination's when `fromCharge` (its
1374
+ * charge's funds' availability) comes (a plain transfer, with no `fromCharge`, moves funds available already).
1375
+ * Answers the platform's entry. */
1376
+ export async function settleTransfer(ctx, transferId, amount, currency, destination, fromCharge, fromPending = false) {
1377
+ const availableOn = fromCharge ?? Number(nowUnix(ctx.occurredAt));
1378
+ const settled = availableOn <= Number(nowUnix(ctx.occurredAt));
1379
+ // a transfer from a charge's pending funds (source_transaction) leaves the platform when they arrive, not before
1380
+ 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);
1381
+ await write(ctx, { amount, currency, fee: 0, net: amount, type: 'payment', reporting_category: 'charge', source: transferId, status: settled ? 'available' : 'pending', available_on: availableOn }, destination);
1382
+ return platform;
1383
+ }
1384
+ /** A direct charge's application fee: out of the connected account's balance, into the platform's. */
1385
+ export async function settleApplicationFee(ctx, feeId, amount, currency, account) {
1386
+ 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);
1387
+ 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);
1388
+ }
1389
+ /** Time's settlements, written: each entry on the acting account's balance whose funds came due by the World's clock
1390
+ * moves pending → available (the clock's move the machine allows), so a settlement is recorded once. A read already
1391
+ * sees it (asOf); the record is what lets Stripe's balance.available be sent once (./front.ts, the drain).
1392
+ * Funds that were available at once and not yet sent are taken too, and marked sent. Answers the entries taken. */
1393
+ export async function settleDueEntries(ctx, account = actingAccount(ctx)) {
1394
+ const now = Number(nowUnix(ctx.occurredAt));
1395
+ const moved = [];
1396
+ for (const t of ctx.rowsRaw(BT)) {
1397
+ if (!onAccount(t, account))
1398
+ continue;
1399
+ if (t.status === 'available' && t[UNSENT] === true) {
1400
+ await ctx.write(BT, String(t.id), { [UNSENT]: false }, 'balance_transaction.available_sent');
1401
+ moved.push(t);
1402
+ continue;
1403
+ }
1404
+ if (t.status !== 'pending' || !(Number(t.available_on) <= now))
1405
+ continue;
1406
+ if (ctx.legal(BT, 'status', ctx.call.operation.id, 'pending', 'available', String(t.id), 'time'))
1407
+ continue;
1408
+ await ctx.write(BT, String(t.id), { status: 'available' }, 'balance_transaction.available');
1409
+ moved.push(t);
1410
+ }
1411
+ return moved;
1412
+ }
1413
+ /** An account's balance, by currency: what the clock has made available, what is still pending, and Issuing's own. */
1414
+ export function balanceOf(ctx, account = actingAccount(ctx)) {
1415
+ const available = new Map();
1416
+ const pending = new Map();
1417
+ const issuing = new Map();
1418
+ for (const raw of ctx.rowsRaw(BT)) {
1419
+ if (!onAccount(raw, account))
1420
+ continue;
1421
+ const t = commonAsOf(ctx, raw);
1422
+ const cur = String(t.currency ?? 'usd');
1423
+ const net = Number(t.net ?? 0);
1424
+ const bucket = t.balance_type === 'issuing' ? issuing : t.status === 'available' ? available : pending;
1425
+ bucket.set(cur, (bucket.get(cur) ?? 0) + net);
1426
+ }
1427
+ return { available, pending, issuing };
1428
+ }
1429
+ /** balance_insufficient when a payout or transfer would take more than the account has available in its currency. */
1430
+ export function refusePayout(ctx, amount, currency, account = actingAccount(ctx)) {
1431
+ const have = balanceOf(ctx, account).available.get(currency) ?? 0;
1432
+ if (amount <= have)
1433
+ return undefined;
1434
+ 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');
1435
+ }
1436
+ /** The ids of the ledger entries on the acting account's balance. */
1437
+ export const mine = (ctx) => new Set(ctx.rowsRaw(BT).filter((t) => onAccount(t, actingAccount(ctx))).map((t) => t.id));
1438
+ export const chargeMissing = (ctx, id) => fail(ctx, `No such charge: '${id}'`, 404, 'resource_missing');
1439
+ /** Every egress of a charge carries its refunds, derived from the refund rows in list order. */
1440
+ export function chargeBody(ctx, c) {
1441
+ const data = newest(ctx, 'refund').filter((r) => r.charge === c.id);
1442
+ return { ...c, refunds: { object: 'list', data, has_more: false, total_count: data.length, url: `/v1/charges/${String(c.id)}/refunds` } };
1443
+ }
1444
+ export const subMissing = (ctx, id) => fail(ctx, `No such subscription: '${id}'`, 404, 'resource_missing');
1445
+ /** A coupon that replaces the subscription's discount, or an empty one that clears it (docs.stripe.com/api/subscriptions/update#update_subscription-discounts). */
1446
+ export function replacedDiscounts(ctx, couponId, sub) {
1447
+ if (couponId === '')
1448
+ return [];
1449
+ const coupon = ctx.get('coupon', couponId);
1450
+ return coupon ? [buildDiscount(coupon, String(sub.customer ?? ''), Number(nowUnix(ctx.occurredAt)), { subscription: String(sub.id) })] : fail(ctx, `No such coupon: '${couponId}'`, 400, 'resource_missing');
1451
+ }
1452
+ /** A `trial_end` Stripe refuses: the parameter is `"now" | timestamp` (docs.stripe.com/api/subscriptions/update), and a
1453
+ * timestamp that is not in the future answers "Invalid timestamp: must be an integer Unix timestamp in the future."
1454
+ * (Stripe's own message, as its SDKs' users report it: github.com/stripe/stripe-dotnet/issues/805,
1455
+ * github.com/stripe/stripe-ruby/issues/682). Where the documentation stops and the twin decides: a value that is no
1456
+ * number at all, and one more than two years on, answer that same message. */
1457
+ export function trialEndRefused(ctx, value, now) {
1458
+ const t = typeof value === 'number' ? value : typeof value === 'string' && /^\d+$/.test(value.trim()) ? Number(value) : NaN;
1459
+ return value === undefined || value === 'now' || (Number.isInteger(t) && t > now && t <= now + MAX_TRIAL) ? undefined : invalidTrialEnd(ctx);
1460
+ }
1461
+ export function invalidTrialEnd(ctx) {
1462
+ return ctx.refuse({ status: 400, param: 'trial_end', message: 'Invalid timestamp: must be an integer Unix timestamp in the future.' });
1463
+ }
1464
+ /** An update's `trial_end` on the subscription, into `fields`.
1465
+ *
1466
+ * `now` on a trialing subscription ends its trial at once: "The special value `now` can be provided to end the customer's
1467
+ * trial immediately" (docs.stripe.com/api/subscriptions/update#update_subscription-trial_end; the trials guide's "To end a
1468
+ * trial early … setting the `trial_end` value to … **now** to end immediately", docs.stripe.com/billing/subscriptions/
1469
+ * trials/free-trials). The update resets the billing date and charges at once: "Switching prices does not normally change
1470
+ * the billing date or generate an immediate charge unless … A trial starts or ends. In these cases, we … immediately
1471
+ * charge the customer using the new price, and reset the billing date" (docs.stripe.com/api/subscriptions/update), and
1472
+ * "Stripe immediately attempts payment when a subscription's billing cycle anchor is reset … When billing is performed
1473
+ * immediately, but the required payment fails, the subscription change request succeeds and the subscription transitions
1474
+ * to `past_due`" (docs.stripe.com/billing/subscriptions/upgrade-downgrade#immediate-payment). So a new period starts now,
1475
+ * its invoice is made (`invoice.created`) and charged to the subscription's default payment method, else the
1476
+ * customer's (paid: `invoice.paid`, the subscription `active`; declined or none: the invoice open, `past_due`), and the
1477
+ * subscription's own write sends `customer.subscription.updated`. `payment_behavior` (the same page): `error_if_incomplete`
1478
+ * answers 402 and leaves the subscription as it was, `default_incomplete` leaves the invoice open without an attempt.
1479
+ *
1480
+ * A future timestamp moves the trial's end, and the period and billing anchor with it: "The `billing_cycle_anchor` will be
1481
+ * updated to the `trial_end` value" (the same parameter); on a subscription out of its trial it starts a new one ("You can
1482
+ * add a new trial on a non-trialing subscription by updating the subscription while specifying trial_end", and for
1483
+ * classic billing mode "the `trial_start` field remains set to the start of the first trial", docs.stripe.com/billing/
1484
+ * subscriptions/trials/free-trials).
1485
+ *
1486
+ * Where the documentation stops and the twin decides: the invoice's billing_reason is `subscription_update` ("A
1487
+ * subscription was updated", docs.stripe.com/api/invoices/object#invoice_object-billing_reason); `now` on a subscription
1488
+ * that is not trialing has no trial to end and changes nothing; the credit Stripe prorates for the unused time when a new
1489
+ * trial starts mid-period is not made (as `proration_behavior=none` would have it); `pending_if_incomplete` answers as
1490
+ * `allow_incomplete` (no pending update is modelled). Answers a refusal, or the invoice to collect once the subscription is written. */
1491
+ export async function applyTrialEnd(ctx, sub, fields, now) {
1492
+ const value = ctx.params.trial_end;
1493
+ delete fields.trial_end;
1494
+ const id = String(sub.id);
1495
+ if (value !== 'now' || sub.status !== 'trialing')
1496
+ return value === 'now' ? undefined : movedTrial(sub, fields, Number(value), now);
1497
+ // the period's invoice bills the items as this update leaves them, under its discount
1498
+ const next = { ...sub, ...fields, items: resourceView(ctx, SUB, id)?.items ?? sub.items };
1499
+ const { interval, interval_count } = resolveSubscriptionBillingInterval((next.items?.data) ?? [], finder(ctx));
1500
+ const period = { start: now, end: addBillingInterval(now, interval, interval_count) };
1501
+ const invoice = await draftSubscriptionInvoice(ctx, next, { ...period, reason: 'subscription_update' });
1502
+ Object.assign(fields, { trial_end: now, billing_cycle_anchor: now, current_period_start: period.start, current_period_end: period.end, latest_invoice: invoice });
1503
+ const payer = trialPayer(ctx, sub);
1504
+ return { invoice, ...(payer ? { payer } : {}), attempt: ctx.params.payment_behavior !== 'default_incomplete' };
1505
+ }
1506
+ /** What ending the trial charges: the update's own default payment method, else the subscription's, else its customer's. */
1507
+ export function trialPayer(ctx, sub) {
1508
+ const given = ctx.params.default_payment_method;
1509
+ return typeof given === 'string' && given ? given : payerOf(ctx, sub);
1510
+ }
1511
+ /** What an update's `trial_end` refuses before anything is written: a new trial the machine does not allow from the
1512
+ * subscription's status, or, under `error_if_incomplete`, ending a trial that cannot be paid at once ("If payment fails,
1513
+ * return an HTTP `402` status code and don't update the subscription", docs.stripe.com/api/subscriptions/update). */
1514
+ export function trialEndBlocked(ctx, sub, discounts) {
1515
+ if (ctx.params.trial_end !== 'now')
1516
+ return newTrialRefused(ctx, sub);
1517
+ if (sub.status !== 'trialing')
1518
+ return undefined;
1519
+ const charge = trialEndCharge(ctx, sub, discounts);
1520
+ if (ctx.params.payment_behavior === 'error_if_incomplete' && charge.due > 0 && !charge.pays)
1521
+ return firstPaymentRefused(ctx, charge.declined);
1522
+ // the move ending the trial makes (paid or nothing due: active; else past_due) is the machine's, asked before
1523
+ // anything is written
1524
+ const refused = ctx.legal(SUB, 'status', ctx.call.operation.id, 'trialing', charge.due <= 0 || charge.pays ? 'active' : 'past_due', String(sub.id));
1525
+ return refused ? ctx.refuse(refused) : undefined;
1526
+ }
1527
+ /** A price named by id, or given as an object. */
1528
+ export function priceRow(ctx, price) {
1529
+ return typeof price === 'string' ? ctx.get('price', price) : price && typeof price === 'object' ? price : undefined;
1530
+ }
1531
+ /** One period of the subscription's items as an update's `items` would leave them, before any discount: an entry naming
1532
+ * an item changes its price and quantity (a new price resets the quantity to 1 unless one is given) or deletes it, and
1533
+ * one naming none adds an item (applyItemChanges). */
1534
+ export function dueAfter(ctx, sub, entries) {
1535
+ const lines = new Map();
1536
+ for (const it of (sub.items?.data) ?? [])
1537
+ lines.set(String(it.id), { price: priceRow(ctx, it.price), quantity: itemQuantity(it) });
1538
+ entries.forEach((e, i) => entryAfter(ctx, lines, e, i));
1539
+ return [...lines.values()].reduce((sum, l) => sum + priceAmount(l.price, l.quantity), 0);
1540
+ }
1541
+ /** One entry of an update's `items` on the lines it would leave (dueAfter). */
1542
+ export function entryAfter(ctx, lines, e, i) {
1543
+ // an inline price bills as the Price inlinePrice makes of it
1544
+ const d = e.price_data && typeof e.price_data === 'object' ? e.price_data : undefined;
1545
+ const inline = d ? (d.unit_amount_decimal !== undefined ? { unit_amount_decimal: String(d.unit_amount_decimal) } : { unit_amount: Math.trunc(Number(d.unit_amount) || 0) }) : undefined;
1546
+ const price = typeof e.price === 'string' && e.price ? priceRow(ctx, e.price) : inline;
1547
+ const named = typeof e.id === 'string' && e.id;
1548
+ const key = named ? String(e.id) : `new_${i}`;
1549
+ // only a named item is deleted; an entry naming none adds one, as applyItemChanges does
1550
+ if (named && asBool(e.deleted)) {
1551
+ lines.delete(key);
1552
+ return;
1553
+ }
1554
+ const was = lines.get(key);
1555
+ 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;
1556
+ lines.set(key, { price: price ?? was?.price, quantity });
1557
+ }
1558
+ /** A new trial on a subscription whose status the machine does not let start one. */
1559
+ export function newTrialRefused(ctx, sub) {
1560
+ const refused = sub.status === 'trialing' ? undefined : ctx.legal(SUB, 'status', ctx.call.operation.id, sub.status, 'trialing', String(sub.id));
1561
+ return refused ? ctx.refuse(refused) : undefined;
1562
+ }
1563
+ /** What ending the trial charges, judged before anything is written: the period of the items as this update leaves them
1564
+ * (dueAfter) under the discount it leaves, and whether the payer pays it (an attempt made, a payer, no decline). */
1565
+ export function trialEndCharge(ctx, sub, discounts) {
1566
+ const subtotal = dueAfter(ctx, sub, subscriptionItemEntries(ctx.params.items));
1567
+ // the discount the subscription carries after this update takes this invoice (renewals.ts draftSubscriptionInvoice)
1568
+ const discount = (discounts ?? sub.discounts ?? [])[0];
1569
+ const coupon = discount && typeof discount === 'object' ? discount.coupon : undefined;
1570
+ const due = subtotal - (coupon ? applyCouponDiscount(subtotal, coupon) : 0);
1571
+ const payer = trialPayer(ctx, sub);
1572
+ const attempt = ctx.params.payment_behavior !== 'default_incomplete';
1573
+ const declined = payer && attempt ? declineFor(finder(ctx), { payment_method: payer }) : undefined;
1574
+ return { due, pays: attempt && !!payer && !declined, ...(declined ? { declined } : {}) };
1575
+ }
1576
+ /** A new item named with neither `price` nor `price_data`: "One of `price` or `price_data` is required"
1577
+ * (docs.stripe.com/api/subscriptions/update). */
1578
+ export function noItemPrice(ctx) {
1579
+ return fail(ctx, 'Missing required param: items[price].', 400, 'parameter_missing');
1580
+ }
1581
+ /** A subscription asked to fail when its first invoice cannot be paid at once (payment_behavior=error_if_incomplete):
1582
+ * the card's decline, or no payment method to charge (docs.stripe.com/api/subscriptions/create#create_subscription-payment_behavior). */
1583
+ export function firstPaymentRefused(ctx, declined) {
1584
+ return declined ? send(ctx, cardError(declined)) : fail(ctx, 'This customer has no attached payment source or default payment method.', 400, 'resource_missing');
1585
+ }
1586
+ /** An update's `items`: "A list of up to 20 subscription items, each with an attached price"
1587
+ * (docs.stripe.com/api/subscriptions/update): an entry naming an item's `id` changes that item (its price, quantity,
1588
+ * metadata) or, with `deleted` ("A flag that, if set to `true`, will delete the specified item"), removes it; "If you
1589
+ * omit `id`, the API adds a new subscription item rather than updating the existing one". Each takes `price` or
1590
+ * `price_data`, "Data used to generate a new Price object inline. One of `price` or `price_data` is required", and
1591
+ * "When changing a subscription item's price, `quantity` is set to 1 unless a `quantity` parameter is provided". An
1592
+ * inline price is made as the manage-prices guide says: "By default, prices created with `price_data` are effectively
1593
+ * archived (they're marked as `active=false`)" (docs.stripe.com/products-prices/manage-prices).
1594
+ * Where the documentation stops and the twin decides: the update is all or nothing, every entry checked before any is
1595
+ * written (Stripe answers one error for the request); the refusals are worded by the twin. */
1596
+ export async function applyItemChanges(ctx, subId, entries) {
1597
+ // every entry is checked first: a refusal leaves the subscription as it was
1598
+ const refused = itemChangesRefused(ctx, subId, entries);
1599
+ if (refused)
1600
+ return refused;
1601
+ return writeItemChanges(ctx, subId, entries);
1602
+ }
1603
+ /** The refusal of an update's `items`, checked entry by entry before any is written (applyItemChanges). */
1604
+ export function itemChangesRefused(ctx, subId, entries) {
1605
+ for (const entry of entries) {
1606
+ const priceRef = typeof entry.price === 'string' && entry.price ? entry.price : undefined;
1607
+ if (priceRef && !ctx.get('price', priceRef))
1608
+ return fail(ctx, `No such price: '${priceRef}'`, 400, 'resource_missing');
1609
+ const inline = !priceRef && entry.price_data && typeof entry.price_data === 'object' ? entry.price_data : undefined;
1610
+ if (inline) {
1611
+ const refused = refuseInlinePrice(ctx, inline);
1612
+ if (refused)
1613
+ return refused;
1614
+ }
1615
+ if (typeof entry.id === 'string' && entry.id) {
1616
+ const si = ctx.get('subscription_item', entry.id);
1617
+ if (!si || si.subscription !== subId)
1618
+ return fail(ctx, `No such subscription_item: '${entry.id}'`, 400, 'resource_missing');
1619
+ }
1620
+ else if (!priceRef && !inline)
1621
+ return noItemPrice(ctx);
1622
+ }
1623
+ return undefined;
1624
+ }
1625
+ /** An update's checked `items`, written. */
1626
+ export async function writeItemChanges(ctx, subId, entries) {
1627
+ for (const entry of entries) {
1628
+ const inline = typeof entry.price === 'string' && entry.price ? undefined : entry.price_data && typeof entry.price_data === 'object' ? entry.price_data : undefined;
1629
+ const priceRef = typeof entry.price === 'string' && entry.price ? entry.price : inline ? await inlinePrice(ctx, inline) : undefined;
1630
+ // only a price that changes resets the quantity; one naming the item's own price leaves it
1631
+ const was = typeof entry.id === 'string' && entry.id ? ctx.get('subscription_item', entry.id)?.price : undefined;
1632
+ const wasId = typeof was === 'string' ? was : was && typeof was === 'object' ? String(was.id ?? '') : undefined;
1633
+ const quantity = entry.quantity !== undefined ? { quantity: Math.max(0, Math.trunc(Number(entry.quantity) || 0)) } : priceRef && priceRef !== wasId ? { quantity: 1 } : {};
1634
+ const metadata = entry.metadata && typeof entry.metadata === 'object' ? { metadata: entry.metadata } : {};
1635
+ if (typeof entry.id === 'string' && entry.id) {
1636
+ if (asBool(entry.deleted)) {
1637
+ await ctx.write('subscription_item', entry.id, { deleted: true }, 'subscription_item.delete');
1638
+ continue;
1639
+ }
1640
+ await ctx.write('subscription_item', entry.id, { ...(priceRef ? { price: priceRef } : {}), ...quantity, ...metadata }, 'subscription_item.update');
1641
+ }
1642
+ else {
1643
+ await created(ctx, 'subscription_item', { subscription: subId, ...subscriptionItemPrice(priceRef, finder(ctx)), quantity: 1, ...quantity, ...metadata }, { livemode: false, metadata: {}, discounts: [], tax_rates: [], billing_thresholds: null });
1644
+ }
1645
+ }
1646
+ await syncItems(ctx, subId);
1647
+ return undefined;
1648
+ }
1649
+ /** A subscription item's `price_data` Stripe would refuse: its required `currency`, `product` (an existing one) and
1650
+ * `recurring[interval]`, and "Only one of `unit_amount` and `unit_amount_decimal` can be set". */
1651
+ export function refuseInlinePrice(ctx, d) {
1652
+ for (const name of ['currency', 'product'])
1653
+ if (typeof d[name] !== 'string' || !d[name])
1654
+ return fail(ctx, `Missing required param: items[price_data][${name}].`, 400, 'parameter_missing');
1655
+ if (!ctx.get('product', String(d.product)))
1656
+ return fail(ctx, `No such product: '${String(d.product)}'`, 400, 'resource_missing');
1657
+ const interval = d.recurring?.interval;
1658
+ if (!['day', 'week', 'month', 'year'].includes(String(interval)))
1659
+ return fail(ctx, 'Missing required param: items[price_data][recurring][interval].', 400, 'parameter_missing');
1660
+ if (d.unit_amount !== undefined && d.unit_amount_decimal !== undefined)
1661
+ return fail(ctx, 'Only one of `unit_amount` and `unit_amount_decimal` can be set.', 400, 'parameter_invalid');
1662
+ return undefined;
1663
+ }
1664
+ /** The inline Price a `price_data` generates: recurring, archived (active=false). Answers its id. */
1665
+ export async function inlinePrice(ctx, d) {
1666
+ const r = d.recurring;
1667
+ const decimal = d.unit_amount_decimal !== undefined ? String(d.unit_amount_decimal) : String(Math.trunc(Number(d.unit_amount) || 0));
1668
+ const price = await created(ctx, 'price', {
1669
+ product: d.product, currency: String(d.currency).toLowerCase(),
1670
+ // a decimal amount that is not a whole number of the smallest unit has no integer unit_amount (as semantics/plans.ts)
1671
+ 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,
1672
+ 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 },
1673
+ tax_behavior: typeof d.tax_behavior === 'string' ? d.tax_behavior : 'unspecified',
1674
+ }, { active: false, livemode: false, billing_scheme: 'per_unit', type: 'recurring', metadata: {}, lookup_key: null, nickname: null });
1675
+ return String(price.id);
1676
+ }
1677
+ // ── items: each write keeps the parent subscription's items.data in step, rebuilt from the live items ──
1678
+ /** A new subscription's items, each its own subscription_item as Stripe keeps it (/v1/subscription_items/{id}). */
1679
+ export async function storeItems(ctx, subId, items) {
1680
+ for (const item of items) {
1681
+ if (typeof item.id !== 'string' || ctx.get('subscription_item', item.id))
1682
+ continue;
1683
+ const { plan: _plan, price, ...fields } = item;
1684
+ await ctx.write('subscription_item', item.id, { ...fields, price: typeof price === 'object' && price ? price.id : price, subscription: subId }, 'subscription_item.create');
1685
+ }
1686
+ }
1687
+ export async function syncItems(ctx, subId) {
1688
+ if (!subId)
1689
+ return;
1690
+ await ctx.write(SUB, subId, {}, 'subscription.items_synced');
1691
+ }
1692
+ export const listMissing = (ctx, id, status = 404) => fail(ctx, `No such radar value list: '${id}'`, status, 'resource_missing');
1693
+ /** A value list's list_items, "List of items contained within this value list" (the served spec), kept in step with
1694
+ * its items, at the address the fixture names (/v1/radar/value_list_items?value_list=…). */
1695
+ export async function radarSyncItems(ctx, listId) {
1696
+ const data = newest(ctx, VLI).filter((i) => i.value_list === listId);
1697
+ 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');
1698
+ }
1699
+ /** An authorization as every egress carries it: its card embedded in full. */
1700
+ export function withCard(ctx, a) {
1701
+ return ctx.expand(AUTH, a);
1702
+ }
1703
+ export const authMissing = (ctx, id) => fail(ctx, `No such authorization: '${id}'`, 404, 'resource_missing');
1704
+ /** A capture: an Issuing transaction (negative: it debits) and the issuing balance's debit. */
1705
+ export async function capture(ctx, authId, auth, amountCents) {
1706
+ const currency = typeof auth.currency === 'string' ? auth.currency : 'usd';
1707
+ const bt = await created(ctx, 'balance_transaction', {}, {
1708
+ amount: -amountCents, currency, fee: 0, net: -amountCents, type: 'issuing_transaction',
1709
+ status: 'available', balance_type: 'issuing', reporting_category: 'issuing_transaction',
1710
+ available_on: nowUnix(ctx.occurredAt), fee_details: [],
1711
+ });
1712
+ const txn = await created(ctx, TXN, { authorization: authId, card: auth.card, cardholder: auth.cardholder }, {
1713
+ type: 'capture', amount: -amountCents, currency,
1714
+ merchant_amount: -amountCents, merchant_currency: typeof auth.merchant_currency === 'string' ? auth.merchant_currency : currency,
1715
+ merchant_data: auth.merchant_data ?? merchantData(undefined),
1716
+ livemode: false, metadata: {}, dispute: null, wallet: null, network_data: null,
1717
+ amount_details: null, purchase_details: null, balance_transaction: bt.id,
1718
+ });
1719
+ return { txnId: String(txn.id), btId: String(bt.id) };
1720
+ }
1721
+ /** Issuing refusals of a request no story sends: an unknown card status or authorization method, and a capture of an
1722
+ * authorization that is not approved and pending. */
1723
+ export function issuingRefusal(ctx, what, auth) {
1724
+ switch (what) {
1725
+ case 'card_status': return fail(ctx, "Invalid status: must be one of 'active', 'inactive', or 'canceled'.", 400, 'parameter_invalid_string_enum');
1726
+ 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');
1727
+ 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);
1728
+ }
1729
+ }
1730
+ /** A partial approval's refusal: "You can specify the amount you want to approve by setting the amount in the webhook
1731
+ * response body or the approve call" only "When an authorization is partially authorized, the is_amount_controllable
1732
+ * field on the authorization request is set to true" (docs.stripe.com/issuing/purchases/authorizations), and never a
1733
+ * credit. Answers the refusal, or undefined when the amount may be approved. */
1734
+ export function partialApprovalRefused(ctx, auth) {
1735
+ if (Math.trunc(Number(ctx.params.amount) || 0) <= 0)
1736
+ return fail(ctx, 'Invalid integer: amount must be a positive integer.', 400, 'parameter_invalid_integer');
1737
+ if (auth.pending_request?.is_amount_controllable !== true)
1738
+ return fail(ctx, 'amount may only be provided when the authorization was presented with is_amount_controllable.', 400);
1739
+ return undefined;
1740
+ }
1741
+ // the (deprecated but real) API decision on a pending authorization: it lands in request_history
1742
+ // as the webhook's answer would, consumes the pending request, and an approval captures
1743
+ export function issuingDecide(approved) {
1744
+ return async (ctx) => {
1745
+ const id = at(ctx, 'authorization');
1746
+ const auth = ctx.get(AUTH, id);
1747
+ if (!auth)
1748
+ return authMissing(ctx, id);
1749
+ const finalized = { status: 400, code: 'authorization_already_finalized', message: `This authorization has already been finalized (status ${String(auth.status)}).` };
1750
+ // a webhook-approved authorization is decided, though still pending
1751
+ if (auth.approved === true && auth.status === 'pending')
1752
+ return ctx.refuse(finalized);
1753
+ const refused = ctx.legal(AUTH, 'status', approved ? 'PostIssuingAuthorizationsAuthorizationApprove' : 'PostIssuingAuthorizationsAuthorizationDecline', auth.status, undefined, id);
1754
+ if (refused)
1755
+ return ctx.refuse(refused);
1756
+ // a partial approval only for an amount-controllable presentment, and never a credit
1757
+ const badAmount = approved && ctx.params.amount !== undefined ? partialApprovalRefused(ctx, auth) : undefined;
1758
+ if (badAmount)
1759
+ return badAmount;
1760
+ const decidedAmount = approved && ctx.params.amount !== undefined ? Math.trunc(Number(ctx.params.amount) || 0) : Number(auth.amount) || 0;
1761
+ const currency = typeof auth.currency === 'string' ? auth.currency : 'usd';
1762
+ const history = Array.isArray(auth.request_history) ? auth.request_history : [];
1763
+ // an approval holds the funds and waits for the merchant's capture; a decline closes it
1764
+ // (docs.stripe.com/issuing/purchases/authorizations, docs.stripe.com/issuing/funding/balance)
1765
+ const hold = approved ? await holdFor(ctx, id, decidedAmount, currency) : null;
1766
+ return ctx.reply(withCard(ctx, await ctx.write(AUTH, id, {
1767
+ status: approved ? 'pending' : 'closed', approved, pending_request: null,
1768
+ ...(approved && ctx.params.amount !== undefined ? { amount: decidedAmount } : {}),
1769
+ request_history: [...history, historyEntry({
1770
+ amount: decidedAmount, currency, approved, reason: approved ? 'webhook_approved' : 'webhook_declined', reasonMessage: null,
1771
+ createdSec: Number(nowUnix(ctx.occurredAt)), merchantAmount: Number(auth.merchant_amount) || decidedAmount,
1772
+ merchantCurrency: typeof auth.merchant_currency === 'string' ? auth.merchant_currency : currency,
1773
+ })],
1774
+ ...(hold ? { balance_transactions: [...(Array.isArray(auth.balance_transactions) ? auth.balance_transactions : []), hold.id] } : {}),
1775
+ }, 'issuing_authorization.updated')));
1776
+ };
1777
+ }
1778
+ /** Time's decision on a real-time request no one answered, caught up to the World's clock: once its window has ended,
1779
+ * a pending authorization whose issuing_authorization.request went unanswered, and that no approve or decline decided,
1780
+ * is decided automatically, its request_history reason webhook_timeout ("webhook_timeout for all other failure modes",
1781
+ * the same page, beside webhook_error for a response Stripe cannot process).
1782
+ * Where the documentation stops and the twin decides: the timeout setting is the Dashboard's, which the API does not
1783
+ * answer, and the twin's is to decline; the window is measured in World time from the authorization's created. */
1784
+ export async function lapseRealtimeRequests(ctx) {
1785
+ const now = Number(nowUnix(ctx.occurredAt));
1786
+ const requested = new Set(ctx.rows('event').filter((e) => e.type === 'issuing_authorization.request').map((e) => String(e.data?.object?.id ?? '')));
1787
+ for (const a of ctx.rowsRaw(AUTH)) {
1788
+ if (a.status !== 'pending' || a.approved === true || !a.pending_request || !requested.has(String(a.id)))
1789
+ continue;
1790
+ const at = Number(a.created) + REALTIME_WINDOW_SECONDS;
1791
+ if (now < at)
1792
+ continue;
1793
+ const id = String(a.id);
1794
+ const currency = typeof a.currency === 'string' ? a.currency : 'usd';
1795
+ const amount = Number(a.amount) || 0;
1796
+ ctx.legal(AUTH, 'status', ctx.call.operation.id, 'pending', 'closed', id, 'time');
1797
+ await ctx.write(AUTH, id, {
1798
+ status: 'closed', approved: false, pending_request: null,
1799
+ request_history: [...(Array.isArray(a.request_history) ? a.request_history : []), historyEntry({
1800
+ amount, currency, approved: false, reason: 'webhook_timeout', reasonMessage: null, createdSec: at,
1801
+ merchantAmount: Number(a.merchant_amount) || amount, merchantCurrency: typeof a.merchant_currency === 'string' ? a.merchant_currency : currency,
1802
+ })],
1803
+ }, 'issuing_authorization.updated');
1804
+ }
1805
+ }
1806
+ /** An approval's hold: "If you approve the authorization, we deduct the `amount` from your Issuing balance and hold it
1807
+ * in reserve until the authorization is either captured, voided, or expired without capture"
1808
+ * (docs.stripe.com/issuing/purchases/authorizations). */
1809
+ export async function holdFor(ctx, authId, amount, currency) {
1810
+ return created(ctx, 'balance_transaction', {}, {
1811
+ amount: -amount, currency, fee: 0, net: -amount, type: 'issuing_authorization_hold',
1812
+ status: 'available', balance_type: 'issuing', reporting_category: 'issuing_authorization_hold',
1813
+ available_on: nowUnix(ctx.occurredAt), fee_details: [], source: authId,
1814
+ });
1815
+ }
1816
+ /** An authorization approved as it is presented, its amount held: approved and pending until the merchant captures. */
1817
+ export async function approvedAtOnce(ctx, subject, fields, held, entry) {
1818
+ const hold = await holdFor(ctx, String(subject.id), held, String(fields.currency ?? 'usd'));
1819
+ 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] })));
1820
+ }
1821
+ /** An authorization as the platform's real-time answer makes it: approved (in part, only when the request was
1822
+ * amount-controllable), declined, or declined for an answer Stripe cannot read (docs.stripe.com/issuing/controls/
1823
+ * real-time-authorizations: the response's `approved` and `amount`; webhook_error "if we can't process your response"). */
1824
+ export async function answeredByEndpoint(ctx, outcome, o) {
1825
+ if (outcome.kind === 'approved') {
1826
+ const held = o.controllable && outcome.amount !== undefined ? outcome.amount : o.amount;
1827
+ return approvedAtOnce(ctx, o.subject, o.fields, held, o.entry({ amount: held, approved: true, reason: 'webhook_approved', reasonMessage: null }));
1828
+ }
1829
+ return outcome.kind === 'declined' ? o.decline('webhook_declined', null) : o.decline('webhook_error', outcome.message);
1830
+ }
1831
+ /** Time's settling of held refunds, caught up to the World's clock: each refund held for want of balance, oldest first,
1832
+ * is made at the first moment the account's available balance covers it (the funds that come due then), its debit
1833
+ * written then, as `refund.updated`. Where the documentation stops and the twin decides: a held refund is made the
1834
+ * moment the balance covers it. */
1835
+ export async function settleHeldRefunds(ctx) {
1836
+ const now = Number(nowUnix(ctx.occurredAt));
1837
+ const heldRefunds = ctx.rowsRaw('refund').filter((r) => r.status === 'pending' && r.pending_reason === 'insufficient_funds').sort((a, b) => Number(a.created) - Number(b.created));
1838
+ for (const r of heldRefunds)
1839
+ await settleOneHeldRefund(ctx, r, now);
1840
+ }
1841
+ /** A pending refund can enter this surface only through the vendor-backed refund refresh. */
1842
+ export async function settleOneHeldRefund(ctx, r, now) {
1843
+ const account = typeof r._account === 'string' ? r._account : undefined;
1844
+ const currency = String(r.currency ?? 'usd');
1845
+ const amount = Number(r.amount) || 0;
1846
+ const when = [Number(r.created), ...fundsDueBetween(ctx, account, currency, Number(r.created), now)].find((t) => availableAt(ctx, account, currency, t) >= amount);
1847
+ if (when === undefined)
1848
+ return;
1849
+ const c = await at_(ctx)(when);
1850
+ c.legal('refund', 'status', ctx.call.operation.id, 'pending', 'succeeded', String(r.id), 'vendor');
1851
+ const bt = await settleRefund(c, String(r.id), amount, currency, account ?? null);
1852
+ await c.write('refund', String(r.id), { status: 'succeeded', pending_reason: null, balance_transaction: bt }, 'refund.updated');
1853
+ }
1854
+ export const accountMissing = (ctx, id, status = 404) => fail(ctx, `No such account: '${id}'`, status, 'resource_missing');
1855
+ /** The account, tombstones included where the hand-written routes looked past a deletion. */
1856
+ export const accountRow = (ctx, id) => ctx.row('account', id, { withDeleted: true });
1857
+ /** Stripe's review of a Custom account once the platform gives it something: with nothing left due, its requested
1858
+ * capabilities become active and it can take charges and receive payouts; with something due again (its bank account
1859
+ * removed), they stop. Where the documentation stops and the twin decides: test-mode verification is immediate, and
1860
+ * it owes what customRequirements lists. An Express or Standard account is onboarded on Stripe's own pages. */
1861
+ export async function connectReview(ctx, id) {
1862
+ const account = resourceView(ctx, 'account', id);
1863
+ if (account && account.type === 'custom')
1864
+ await reviewCustom(ctx, id, account);
1865
+ }
1866
+ /** The review of a Custom account (see review). */
1867
+ export async function reviewCustom(ctx, id, account) {
1868
+ const bank = ctx.rows('external_account').some((e) => e.account === id);
1869
+ const persons = ctx.rows('person').filter((p) => p.account === id);
1870
+ const { now: due, later } = customRequirements(account, bank, persons);
1871
+ // one account, one review: "If a connected account has both card_payments and transfers, and the status of either one
1872
+ // is inactive, then both capabilities are disabled" (docs.stripe.com/connect/account-capabilities)
1873
+ const ready = due.length === 0;
1874
+ const capabilities = {};
1875
+ for (const [key, was] of Object.entries(account.capabilities ?? {})) {
1876
+ const to = ready ? 'active' : 'inactive';
1877
+ // Capabilities are entries of the account's map, not standalone stored subjects.
1878
+ capabilities[key] = to;
1879
+ }
1880
+ const requirements = { ...(account.requirements ?? {}), currently_due: due, eventually_due: [...due, ...later], past_due: [], disabled_reason: ready ? null : 'requirements.past_due', current_deadline: null };
1881
+ await ctx.write('account', id, { capabilities, requirements, charges_enabled: ready, payouts_enabled: ready, details_submitted: ready }, ready ? 'account.updated' : 'account.update');
1882
+ }
1883
+ /** A transfer to an account whose transfers capability is not active. */
1884
+ export function transfersInactive(ctx) {
1885
+ 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' });
1886
+ }
1887
+ /** A transfer from a charge whose funds have settled: "With a source_transaction, the transfer request returns success
1888
+ * regardless of your available balance if the related charge hasn't settled yet" (docs.stripe.com/connect/separate-
1889
+ * charges-and-transfers), so a settled one comes out of the available balance. */
1890
+ export function settledSourceRefused(ctx, amount, currency) {
1891
+ return refusePayout(ctx, amount, currency, undefined);
1892
+ }
1893
+ /** An earlier version's payment_method_types refused: the first value that names no payment method type the
1894
+ * operation takes, in the intent's words or (a Checkout Session) the enum's. */
1895
+ export function unknownMethodType(ctx, opId, given) {
1896
+ const values = Array.isArray(given) ? given : given && typeof given === 'object' ? Object.values(given) : [given];
1897
+ const checkout = opId === 'PostCheckoutSessions';
1898
+ const known = checkout ? CHECKOUT_METHOD_TYPES : PAYMENT_METHOD_TYPES;
1899
+ const i = values.findIndex((v) => !known.includes(String(v)));
1900
+ if (i < 0)
1901
+ return undefined;
1902
+ if (checkout) {
1903
+ const param = `payment_method_types[${i}]`;
1904
+ return ctx.refuse({ status: 400, param, message: `Invalid ${param}: must be one of ${oneOf(known)}` });
1905
+ }
1906
+ const doc = TYPES_DOC[opId.startsWith('PostSetupIntents') ? 'setup_intents' : 'payment_intents'];
1907
+ 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.` });
1908
+ }
1909
+ /** payment_method_types refused where the caller's version removed it. */
1910
+ export const noLongerSupported = (ctx, version) => 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.` });
1911
+ /** Stripe's refusal of a request whose top-level parameters the operation does not take, or undefined. */
1912
+ export function refuseParameters(ctx) {
1913
+ const op = OPS.get(ctx.call.operation.id);
1914
+ if (!op)
1915
+ return undefined;
1916
+ const pinned = ctx.call.request.headers.get('stripe-version');
1917
+ const params = ctx.params;
1918
+ if (pinned && pinned < SERVED_VERSION) {
1919
+ if (!TYPED.has(op.id))
1920
+ return undefined;
1921
+ if (params.payment_method_types === undefined)
1922
+ return undefined;
1923
+ if (REMOVED_TYPES.has(op.id) && methodTypesRemoved(pinned))
1924
+ return noLongerSupported(ctx, pinned);
1925
+ return unknownMethodType(ctx, op.id, params.payment_method_types);
1926
+ }
1927
+ const method = ctx.call.request.method.toUpperCase();
1928
+ const known = new Set([...(op.query ?? []), ...(op.body ?? [])].map((p) => p.name).concat(DOCUMENTED[op.id] ?? []));
1929
+ if (REMOVED_TYPES.has(op.id) && params.payment_method_types !== undefined)
1930
+ return noLongerSupported(ctx, pinned ?? SERVED_VERSION);
1931
+ for (const name of Object.keys(params)) {
1932
+ if (!known.has(name))
1933
+ return ctx.refuse({ status: 400, code: 'parameter_unknown', param: name, message: `Received unknown parameter: ${name}` });
1934
+ }
1935
+ const required = method === 'GET' || method === 'DELETE' ? (op.query ?? []) : (op.body ?? []);
1936
+ for (const p of required) {
1937
+ if (p.required && params[p.name] === undefined)
1938
+ return ctx.refuse({ status: 400, code: 'parameter_missing', param: p.name, message: `Missing required param: ${p.name}.` });
1939
+ }
1940
+ return undefined;
1941
+ }
1942
+ /** An answer in the shape of the API version the caller is served (./version.ts), a webhook endpoint's `secret` shown
1943
+ * only at its creation ("Only returned at creation", docs.stripe.com/api/webhook_endpoints/object). */
1944
+ export async function rendered(request, res) {
1945
+ const creates = request.method === 'POST' && new URL(request.url).pathname.replace(/\/+$/, '') === '/v1/webhook_endpoints';
1946
+ const pinned = request.headers.get('stripe-version');
1947
+ if (!(res.headers.get('content-type') ?? '').includes('json'))
1948
+ return res;
1949
+ if (!servesCurrent(pinned) && creates)
1950
+ return res;
1951
+ const expand = await expandOf(request.clone());
1952
+ const body = await res.json();
1953
+ const answered = creates ? body : withoutEndpointSecret(body);
1954
+ return new Response(JSON.stringify(servesCurrent(pinned) ? render(answered, pinned, expand) : answered), { status: res.status, statusText: res.statusText, headers: res.headers });
1955
+ }
1956
+ /** Write a draft's line list and the totals derived from it. */
1957
+ export async function writeLines(ctx, invoiceId, next) {
1958
+ const subtotal = sumLines(next);
1959
+ const lines = { object: 'list', data: next, has_more: false, total_count: next.length, url: `/v1/invoices/${invoiceId}/lines` };
1960
+ return ctx.write(INV, invoiceId, { lines, subtotal, total: subtotal, amount_due: subtotal, amount_remaining: subtotal }, 'invoice.update');
1961
+ }
1962
+ /** 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). */
1963
+ export async function pullPendingItem(ctx, invoiceId, inv, item, now) {
1964
+ const current = ctx.get(INV, invoiceId) ?? inv;
1965
+ await writeLines(ctx, invoiceId, [...linesOf(current), {
1966
+ id: `il_${String(item.id)}`, object: 'line_item', type: 'invoiceitem', amount: Number(item.amount) || 0, currency: String(current.currency ?? item.currency ?? 'usd'),
1967
+ quantity: Number(item.quantity) || 1, proration: false, invoice_item: item.id, price: item.price ?? null,
1968
+ period: item.period ?? { start: now, end: now }, description: item.description ?? null,
1969
+ discountable: item.discountable ?? true, discounts: [], livemode: false, metadata: item.metadata ?? {}, tax_amounts: [], tax_rates: [],
1970
+ }]);
1971
+ await ctx.write('invoiceitem', String(item.id), { invoice: invoiceId }, 'invoiceitem.update');
1972
+ }
1973
+ /** The intent the path names, and the machine's refusal when this operation may not move it. */
1974
+ export function paymentIntentsLoad(ctx, operationId) {
1975
+ const pi = ctx.id ? ctx.get(PI, ctx.id) : undefined;
1976
+ if (!pi)
1977
+ return { answer: ctx.notFound(PI, String(ctx.id)) };
1978
+ const refusal = ctx.legal(PI, 'status', operationId, pi.status);
1979
+ return refusal ? { answer: ctx.refuse(refusal) } : { pi };
1980
+ }
1981
+ /** A transfer reversal's two entries: back into the platform's balance, out of the destination's. */
1982
+ export async function settleTransferReversal(ctx, reversalId, amount, currency, destination) {
1983
+ 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);
1984
+ 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);
1985
+ return platform;
1986
+ }
1987
+ /** A capture=false charge refunded while uncaptured: its authorization is released by the refund, as it would be
1988
+ * "automatically refunded if uncaptured" (spec/openapi.json.gz, `capture_before`). The charge stays uncaptured and
1989
+ * becomes refunded in full, a Refund records the release, and no money moves: none was ever received. Written as
1990
+ * charge.refunded. Where the documentation stops and the twin decides: Stripe's basil change ("Partially capturing or
1991
+ * canceling payments no longer creates a Refund", docs.stripe.com/changelog/basil/2025-03-31/remove-refund-from-partial-
1992
+ * capture-and-payment-cancellation-flow) names partial capture and cancellation, not a refund asked for, so a refund
1993
+ * still makes one; its reason is null and it has no balance transaction. Answers the Refund. */
1994
+ export async function releaseAuthorization(ctx, ch, operationId, given = {}) {
1995
+ const id = String(ch.id);
1996
+ const full = Number(ch.amount) || 0;
1997
+ if (ch.refunded !== true)
1998
+ ctx.legal('charge', 'refunded', operationId, 'false', 'true', id);
1999
+ const refund = await created(ctx, 'refund', { ...given, charge: id, amount: full - (Number(ch.amount_refunded) || 0), currency: String(ch.currency ?? 'usd') }, {
2000
+ status: 'succeeded', metadata: {}, reason: null, receipt_number: null,
2001
+ balance_transaction: null, source_transfer_reversal: null, transfer_reversal: null, ...refundDestination(ch, 'reversal'),
2002
+ ...(typeof ch.payment_intent === 'string' ? { payment_intent: ch.payment_intent } : {}),
2003
+ });
2004
+ await ctx.write('charge', id, { amount_refunded: full, refunded: true }, 'charge.refunded');
2005
+ return refund;
2006
+ }
2007
+ /** A PaymentIntent's authorization released by its cancel: "For PaymentIntents with a `status` of `requires_capture`, the
2008
+ * remaining `amount_capturable` is automatically refunded" (docs.stripe.com/api/payment_intents/cancel), and since basil
2009
+ * a cancellation makes no Refund: "`amount_captured` will be 0 instead of `nil` in payment cancellation flows",
2010
+ * "`amount_refunded` will no longer be updated by these actions", "`refunded` will no longer be `true` for payment
2011
+ * cancellation flows", and no charge.refunded is sent (docs.stripe.com/changelog/basil/2025-03-31/remove-refund-from-
2012
+ * partial-capture-and-payment-cancellation-flow). The charge stays uncaptured; nothing is written as an event. */
2013
+ export async function cancelAuthorization(ctx, ch) {
2014
+ return ctx.write('charge', String(ch.id), { amount_captured: 0 }, 'charge.authorization_released');
2015
+ }
2016
+ /**
2017
+ * Create a refund and land it on its charge. An omitted amount is the whole remaining balance. The
2018
+ * charge's write records `charge.refunded`, the event Stripe sends carrying the charge's new totals;
2019
+ * `refunded` is true only at the full amount.
2020
+ */
2021
+ /** A reason Stripe does not take (docs.stripe.com/api/refunds/create#create_refund-reason). */
2022
+ export function badReason(ctx) {
2023
+ return fail(ctx, `Invalid refund reason: must be one of ${[...REFUND_REASONS].join(', ')}.`, 400, 'parameter_invalid_string_enum');
2024
+ }
2025
+ /** A bank-transfer payment refunded with origin=customer_balance goes back to the cash balance
2026
+ * (docs.stripe.com/payments/customer-balance/refunding). */
2027
+ export async function backToCashBalance(ctx, customer, currency, amount, refundId) {
2028
+ 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);
2029
+ 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 });
2030
+ }
2031
+ /** A capture=false charge's refund, which releases its whole authorization (see the header). */
2032
+ export async function refundUncaptured(ctx, charge, amount, remaining, params) {
2033
+ if (amount < remaining)
2034
+ return fail(ctx, `Charge ${String(charge.id)} is uncaptured: refunding it releases the whole authorization (${remaining}).`, 400, 'amount_too_small');
2035
+ const { reason, metadata } = params;
2036
+ return ctx.reply(await releaseAuthorization(ctx, charge, ctx.call.operation.id, { ...(reason !== undefined ? { reason } : {}), ...(metadata !== undefined ? { metadata } : {}) }));
2037
+ }
2038
+ export async function refundCharge(ctx, charge, params) {
2039
+ const chargeId = String(charge.id);
2040
+ const total = Number(charge.amount) || 0;
2041
+ const already = Number(charge.amount_refunded) || 0;
2042
+ const remaining = Math.max(0, total - already);
2043
+ const amount = params.amount === undefined ? remaining : Math.trunc(Number(params.amount));
2044
+ if (!Number.isFinite(amount) || amount <= 0)
2045
+ return fail(ctx, 'Invalid integer: amount must be a positive integer.', 400, 'parameter_invalid_integer');
2046
+ if (amount > remaining)
2047
+ return fail(ctx, `Refund amount (${amount}) is greater than unrefunded amount on charge (${remaining}).`, 400, 'amount_too_large');
2048
+ if (params.reason !== undefined && !REFUND_REASONS.has(String(params.reason)))
2049
+ return badReason(ctx);
2050
+ // an authorization is released, never refunded out of the balance: a PaymentIntent's by cancelling the intent, a
2051
+ // capture=false charge's by its refund (refundUncaptured)
2052
+ if (charge.captured === false && typeof charge.payment_intent === 'string')
2053
+ 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');
2054
+ if (charge.captured === false)
2055
+ return refundUncaptured(ctx, charge, amount, remaining, params);
2056
+ const refunded = already + amount;
2057
+ // the refund that takes the rest refunds the charge: the charge machine's move under this operation
2058
+ if (refunded >= total && charge.refunded !== true) {
2059
+ const refused = ctx.legal('charge', 'refunded', ctx.call.operation.id, 'false', 'true', chargeId);
2060
+ if (refused)
2061
+ return ctx.refuse(refused);
2062
+ }
2063
+ // a refund has no `livemode` field; it debits the balance at once
2064
+ const refundId = ctx.mint('refund');
2065
+ const currency = String(charge.currency ?? 'usd');
2066
+ const pi = typeof charge.payment_intent === 'string' ? ctx.get('payment_intent', charge.payment_intent) : undefined;
2067
+ const byTransfer = (pi?.payment_method_types ?? []).includes('customer_balance');
2068
+ const toCashBalance = byTransfer && params.origin === 'customer_balance';
2069
+ const awaitsBank = byTransfer && !toCashBalance;
2070
+ const now = Number(nowUnix(ctx.occurredAt));
2071
+ const customer = typeof charge.customer === 'string' ? charge.customer : typeof pi?.customer === 'string' ? pi.customer : undefined;
2072
+ const emailTo = typeof params.instructions_email === 'string' ? params.instructions_email : (customer ? ctx.get('customer', customer)?.email : undefined) ?? null;
2073
+ // "Refunds use your available Stripe balance (not including pending amounts). If your available balance doesn't
2074
+ // cover the amount of the refund, Stripe holds the refund as pending for card transactions ... until your Stripe
2075
+ // balance becomes sufficient" (docs.stripe.com/refunds): the refund waits, moving no money, until the balance covers
2076
+ // it (settleHeldRefunds). Where the documentation stops and the twin decides: a refund of another payment method
2077
+ // short of balance is not modelled (Stripe fails it); the twin makes it as a card's.
2078
+ const account = actingAccount(ctx);
2079
+ const isCard = charge.payment_method_details?.type === 'card';
2080
+ const held = !awaitsBank && !toCashBalance && isCard && availableAt(ctx, account, currency, now) < amount;
2081
+ if (held)
2082
+ ctx.legal('refund', 'status', ctx.call.operation.id, 'succeeded', 'pending', refundId);
2083
+ const bt = awaitsBank || held ? null : await settleRefund(ctx, refundId, amount, currency);
2084
+ if (toCashBalance && customer)
2085
+ await backToCashBalance(ctx, customer, currency, amount, refundId);
2086
+ const { reverse_transfer: reverseTransfer, refund_application_fee: refundFee, instructions_email: _email, origin: _origin, ...stored } = params;
2087
+ const share = (whole) => Math.round((whole * amount) / (total || 1));
2088
+ let transferReversal = null;
2089
+ const transfer = typeof charge.transfer === 'string' ? ctx.get('transfer', charge.transfer) : undefined;
2090
+ if (reverseTransfer !== undefined && asBool(reverseTransfer) && transfer) {
2091
+ const back = Math.min(share(Number(transfer.amount) || 0), (Number(transfer.amount) || 0) - (Number(transfer.amount_reversed) || 0));
2092
+ const trr = await created(ctx, 'transfer_reversal', { amount: back, currency, transfer: transfer.id }, { balance_transaction: null, destination_payment_refund: null, source_refund: refundId, metadata: {} });
2093
+ const trrBt = await settleTransferReversal(ctx, String(trr.id), back, currency, String(transfer.destination));
2094
+ const reversal = await ctx.write('transfer_reversal', String(trr.id), { balance_transaction: trrBt }, 'transfer_reversal.updated');
2095
+ const reversed = (Number(transfer.amount_reversed) || 0) + back;
2096
+ const list = transfer.reversals ?? { object: 'list', data: [], has_more: false, total_count: 0 };
2097
+ const data = [...((list.data ?? [])), reversal];
2098
+ 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');
2099
+ transferReversal = String(trr.id);
2100
+ }
2101
+ const fee = typeof charge.application_fee === 'string' ? ctx.get('application_fee', charge.application_fee) : undefined;
2102
+ if (refundFee !== undefined && asBool(refundFee) && fee) {
2103
+ const feeTotal = Number(fee.amount) || 0;
2104
+ const back = Math.min(share(feeTotal), feeTotal - (Number(fee.amount_refunded) || 0));
2105
+ const done = (Number(fee.amount_refunded) || 0) + back;
2106
+ if (!(done >= feeTotal && fee.refunded !== true && ctx.legal('application_fee', 'refunded', ctx.call.operation.id, 'false', 'true', String(fee.id)))) {
2107
+ const fr = await created(ctx, 'fee_refund', { amount: back, currency, fee: fee.id }, { balance_transaction: null, metadata: {} });
2108
+ const list = fee.refunds ?? { object: 'list', data: [], has_more: false, total_count: 0 };
2109
+ const data = [...((list.data ?? [])), fr];
2110
+ 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');
2111
+ }
2112
+ }
2113
+ const body = await created(ctx, 'refund', {
2114
+ ...stored, id: refundId, charge: chargeId, amount, currency, transfer_reversal: transferReversal,
2115
+ ...(typeof charge.payment_intent === 'string' ? { payment_intent: charge.payment_intent } : {}),
2116
+ }, {
2117
+ status: awaitsBank ? 'requires_action' : held ? 'pending' : 'succeeded', metadata: {}, reason: null, receipt_number: null,
2118
+ ...(held ? { pending_reason: 'insufficient_funds', _account: account ?? null } : {}),
2119
+ balance_transaction: bt, source_transfer_reversal: null,
2120
+ // a bank transfer's refund goes to the customer's bank (a us_bank_transfer) or back to its cash balance
2121
+ // (customer_cash_balance): "If this is a `us_bank_transfer` refund, this hash contains the transaction specific details",
2122
+ // "If this is a `customer_cash_balance` refund ..." (docs.stripe.com/api/refunds/object, destination_details)
2123
+ ...(byTransfer
2124
+ ? { destination_details: toCashBalance ? { type: 'customer_cash_balance', customer_cash_balance: {} } : { type: 'us_bank_transfer', us_bank_transfer: { reference: null, reference_status: null } } }
2125
+ : refundDestination(charge, 'refund')),
2126
+ ...(awaitsBank ? { next_action: { type: 'display_details', display_details: { email_sent: { email_sent_at: now, email_sent_to: emailTo }, expires_at: now + 30 * 86_400 } } } : {}),
2127
+ });
2128
+ await ctx.write('charge', chargeId, { amount_refunded: refunded, refunded: refunded >= total }, 'charge.refunded');
2129
+ return ctx.reply(body);
2130
+ }
2131
+ /** The charge a refund aims at: named directly, or reached through its PaymentIntent. */
2132
+ export function target(ctx) {
2133
+ const chargeId = typeof ctx.params.charge === 'string' ? ctx.params.charge : '';
2134
+ const piId = typeof ctx.params.payment_intent === 'string' ? ctx.params.payment_intent : '';
2135
+ if (!chargeId && !piId)
2136
+ return fail(ctx, 'One of `charge` or `payment_intent` is required.', 400, 'parameter_missing');
2137
+ if (chargeId)
2138
+ return ctx.get('charge', chargeId) ?? fail(ctx, `No such charge: '${chargeId}'`, 404, 'resource_missing');
2139
+ const pi = ctx.get('payment_intent', piId);
2140
+ if (!pi)
2141
+ return fail(ctx, `No such payment_intent: '${piId}'`, 404, 'resource_missing');
2142
+ const latest = typeof pi.latest_charge === 'string' ? pi.latest_charge : undefined;
2143
+ const ch = (latest ? ctx.get('charge', latest) : undefined) ?? newest(ctx, 'charge').find((c) => c.payment_intent === piId);
2144
+ 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');
2145
+ }
2146
+ /** A pending invoice item contributes to a preview only on its customer's next invoice. */
2147
+ // source: spec:PostInvoicesCreatePreview "including subscription renewal charges, invoice item charges, etc."
2148
+ export function pendingPreviewItem(ii, customer, currency, now) {
2149
+ if (ii.customer !== customer || ii.invoice)
2150
+ return undefined;
2151
+ return {
2152
+ id: `il_${String(ii.id)}`, object: 'line_item', type: 'invoiceitem', amount: Number(ii.amount) || 0, currency,
2153
+ quantity: Number(ii.quantity) || 1, proration: false, invoice_item: ii.id,
2154
+ period: ii.period ?? { start: now, end: now }, description: ii.description ?? null,
2155
+ };
2156
+ }
2157
+ export function pendingPreviewLines(ctx, customer, currency, now) {
2158
+ return newest(ctx, 'invoiceitem', 'date').flatMap(ii => { const line = pendingPreviewItem(ii, customer, currency, now); return line ? [line] : []; });
2159
+ }