@volter/twin-stripe 0.1.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/README.md +64 -27
  2. package/client/dashboard-api.ts +286 -0
  3. package/client/stripe-mirror.css +272 -159
  4. package/client/stripe-mirror.tsx +1384 -541
  5. package/dist/client/dashboard-api.d.ts +107 -0
  6. package/dist/client/dashboard-api.js +238 -0
  7. package/dist/client/dashboard-api.ts +286 -0
  8. package/dist/client/stripe-mirror.bundle.js +236 -0
  9. package/dist/client/stripe-mirror.css +275 -0
  10. package/dist/client/stripe-mirror.d.ts +134 -0
  11. package/dist/client/stripe-mirror.js +823 -0
  12. package/dist/client/stripe-mirror.tsx +1534 -0
  13. package/dist/src/cli.d.ts +2 -0
  14. package/dist/src/cli.js +39 -0
  15. package/dist/src/generated/events.gen.json +1 -0
  16. package/dist/src/generated/surface.gen.json +1 -0
  17. package/dist/src/generated/ui.gen.json +1 -0
  18. package/dist/src/index.d.ts +14 -0
  19. package/dist/src/index.js +73 -0
  20. package/dist/src/manifest.d.ts +2 -0
  21. package/dist/src/manifest.js +1065 -0
  22. package/dist/src/screens/checkout.d.ts +31 -0
  23. package/dist/src/screens/checkout.js +241 -0
  24. package/dist/src/screens/consent-skin.d.ts +4 -0
  25. package/dist/src/screens/consent-skin.js +18 -0
  26. package/dist/src/screens/financial-connections.d.ts +5 -0
  27. package/dist/src/screens/financial-connections.js +90 -0
  28. package/dist/src/screens/identity.d.ts +5 -0
  29. package/dist/src/screens/identity.js +86 -0
  30. package/dist/src/screens/industries.d.ts +1 -0
  31. package/dist/src/screens/industries.js +267 -0
  32. package/dist/src/screens/onboarding.d.ts +13 -0
  33. package/dist/src/screens/onboarding.js +225 -0
  34. package/dist/src/screens/portal.d.ts +5 -0
  35. package/dist/src/screens/portal.js +214 -0
  36. package/dist/src/screens/public-details.d.ts +5 -0
  37. package/dist/src/screens/public-details.js +90 -0
  38. package/dist/src/semantics/after-payment.d.ts +22 -0
  39. package/dist/src/semantics/after-payment.js +93 -0
  40. package/dist/src/semantics/apps-secrets.d.ts +2 -0
  41. package/dist/src/semantics/apps-secrets.js +54 -0
  42. package/dist/src/semantics/balance.d.ts +11 -0
  43. package/dist/src/semantics/balance.js +195 -0
  44. package/dist/src/semantics/billing.d.ts +2 -0
  45. package/dist/src/semantics/billing.js +220 -0
  46. package/dist/src/semantics/charges.d.ts +28 -0
  47. package/dist/src/semantics/charges.js +201 -0
  48. package/dist/src/semantics/checkout.d.ts +15 -0
  49. package/dist/src/semantics/checkout.js +303 -0
  50. package/dist/src/semantics/connect.d.ts +5 -0
  51. package/dist/src/semantics/connect.js +476 -0
  52. package/dist/src/semantics/coupons.d.ts +6 -0
  53. package/dist/src/semantics/coupons.js +92 -0
  54. package/dist/src/semantics/credit-notes.d.ts +2 -0
  55. package/dist/src/semantics/credit-notes.js +172 -0
  56. package/dist/src/semantics/customers.d.ts +6 -0
  57. package/dist/src/semantics/customers.js +429 -0
  58. package/dist/src/semantics/disputes.d.ts +2 -0
  59. package/dist/src/semantics/disputes.js +51 -0
  60. package/dist/src/semantics/entitlements.d.ts +2 -0
  61. package/dist/src/semantics/entitlements.js +95 -0
  62. package/dist/src/semantics/ephemeral-keys.d.ts +2 -0
  63. package/dist/src/semantics/ephemeral-keys.js +34 -0
  64. package/dist/src/semantics/files.d.ts +2 -0
  65. package/dist/src/semantics/files.js +125 -0
  66. package/dist/src/semantics/invoices.d.ts +18 -0
  67. package/dist/src/semantics/invoices.js +541 -0
  68. package/dist/src/semantics/issuing.d.ts +13 -0
  69. package/dist/src/semantics/issuing.js +570 -0
  70. package/dist/src/semantics/ledger.d.ts +54 -0
  71. package/dist/src/semantics/ledger.js +181 -0
  72. package/dist/src/semantics/payment-intents.d.ts +18 -0
  73. package/dist/src/semantics/payment-intents.js +404 -0
  74. package/dist/src/semantics/payment-links.d.ts +2 -0
  75. package/dist/src/semantics/payment-links.js +133 -0
  76. package/dist/src/semantics/payment-methods.d.ts +20 -0
  77. package/dist/src/semantics/payment-methods.js +138 -0
  78. package/dist/src/semantics/plans.d.ts +5 -0
  79. package/dist/src/semantics/plans.js +121 -0
  80. package/dist/src/semantics/platform.d.ts +9 -0
  81. package/dist/src/semantics/platform.js +206 -0
  82. package/dist/src/semantics/products.d.ts +2 -0
  83. package/dist/src/semantics/products.js +140 -0
  84. package/dist/src/semantics/radar.d.ts +2 -0
  85. package/dist/src/semantics/radar.js +83 -0
  86. package/dist/src/semantics/refunds.d.ts +9 -0
  87. package/dist/src/semantics/refunds.js +195 -0
  88. package/dist/src/semantics/renewals.d.ts +47 -0
  89. package/dist/src/semantics/renewals.js +251 -0
  90. package/dist/src/semantics/setup-intents.d.ts +2 -0
  91. package/dist/src/semantics/setup-intents.js +84 -0
  92. package/dist/src/semantics/shared.d.ts +78 -0
  93. package/dist/src/semantics/shared.js +192 -0
  94. package/dist/src/semantics/subscription-schedules.d.ts +2 -0
  95. package/dist/src/semantics/subscription-schedules.js +119 -0
  96. package/dist/src/semantics/subscriptions.d.ts +11 -0
  97. package/dist/src/semantics/subscriptions.js +605 -0
  98. package/dist/src/semantics/tax.d.ts +2 -0
  99. package/dist/src/semantics/tax.js +197 -0
  100. package/dist/src/semantics/terminal.d.ts +5 -0
  101. package/dist/src/semantics/terminal.js +182 -0
  102. package/dist/src/semantics/test-clocks.d.ts +6 -0
  103. package/dist/src/semantics/test-clocks.js +73 -0
  104. package/dist/src/semantics/tokens.d.ts +4 -0
  105. package/dist/src/semantics/tokens.js +44 -0
  106. package/dist/src/semantics/transfers.d.ts +2 -0
  107. package/dist/src/semantics/transfers.js +154 -0
  108. package/dist/src/semantics/treasury.d.ts +2 -0
  109. package/dist/src/semantics/treasury.js +377 -0
  110. package/dist/src/semantics/webhook-endpoints.d.ts +3 -0
  111. package/dist/src/semantics/webhook-endpoints.js +85 -0
  112. package/dist/src/stripe-budget.d.ts +55 -0
  113. package/dist/src/stripe-budget.js +155 -0
  114. package/dist/src/stripe-capabilities.d.ts +3 -0
  115. package/dist/src/stripe-capabilities.js +5052 -0
  116. package/dist/src/stripe-conformance.d.ts +41 -0
  117. package/dist/src/stripe-conformance.js +96 -0
  118. package/dist/src/stripe-connector.d.ts +161 -0
  119. package/dist/src/stripe-connector.js +414 -0
  120. package/dist/src/stripe-emit.d.ts +2 -0
  121. package/dist/src/stripe-emit.js +145 -0
  122. package/dist/src/stripe-events.d.ts +93 -0
  123. package/dist/src/stripe-events.js +388 -0
  124. package/dist/src/stripe-js.d.ts +4 -0
  125. package/dist/src/stripe-js.js +70 -0
  126. package/dist/src/stripe-mirror-ui.d.ts +15 -0
  127. package/dist/src/stripe-mirror-ui.js +87 -0
  128. package/dist/src/stripe-params.d.ts +3 -0
  129. package/dist/src/stripe-params.js +43 -0
  130. package/dist/src/stripe-perform-harness.d.ts +9 -0
  131. package/dist/src/stripe-perform-harness.js +26 -0
  132. package/dist/src/stripe-server.d.ts +33 -0
  133. package/dist/src/stripe-server.js +326 -0
  134. package/dist/src/stripe-shared.d.ts +106 -0
  135. package/dist/src/stripe-shared.js +273 -0
  136. package/dist/src/stripe-twin.d.ts +155 -0
  137. package/dist/src/stripe-twin.js +1226 -0
  138. package/dist/src/stripe-ui-conformance.d.ts +5 -0
  139. package/dist/src/stripe-ui-conformance.js +79 -0
  140. package/dist/src/stripe-ui-structure.d.ts +3 -0
  141. package/dist/src/stripe-ui-structure.js +168 -0
  142. package/dist/src/stripe-version.d.ts +10 -0
  143. package/dist/src/stripe-version.js +285 -0
  144. package/dist/test-fixtures/stripe-known-deviations.json +105 -0
  145. package/dist/test-fixtures/stripe-openapi-operations.SOURCE.md +14 -0
  146. package/dist/test-fixtures/stripe-openapi-operations.json +4717 -0
  147. package/dist/test-fixtures/stripe-schemas.SOURCE.md +35 -0
  148. package/dist/test-fixtures/stripe-schemas.json +3740 -0
  149. package/package.json +18 -10
  150. package/src/cli.ts +7 -7
  151. package/src/generated/events.gen.json +1 -0
  152. package/src/generated/surface.gen.json +1 -0
  153. package/src/generated/ui.gen.json +1 -0
  154. package/src/index.ts +31 -9
  155. package/src/manifest.ts +1097 -0
  156. package/src/screens/checkout.tsx +252 -0
  157. package/src/screens/consent-skin.ts +20 -0
  158. package/src/screens/financial-connections.tsx +101 -0
  159. package/src/screens/identity.tsx +96 -0
  160. package/src/screens/industries.ts +267 -0
  161. package/src/screens/onboarding.tsx +243 -0
  162. package/src/screens/portal.tsx +218 -0
  163. package/src/screens/public-details.tsx +105 -0
  164. package/src/semantics/after-payment.ts +113 -0
  165. package/src/semantics/apps-secrets.ts +58 -0
  166. package/src/semantics/balance.ts +209 -0
  167. package/src/semantics/billing.ts +216 -0
  168. package/src/semantics/charges.ts +211 -0
  169. package/src/semantics/checkout.ts +297 -0
  170. package/src/semantics/connect.ts +471 -0
  171. package/src/semantics/coupons.ts +97 -0
  172. package/src/semantics/credit-notes.ts +168 -0
  173. package/src/semantics/customers.ts +432 -0
  174. package/src/semantics/disputes.ts +62 -0
  175. package/src/semantics/entitlements.ts +94 -0
  176. package/src/semantics/ephemeral-keys.ts +34 -0
  177. package/src/semantics/files.ts +143 -0
  178. package/src/semantics/invoices.ts +541 -0
  179. package/src/semantics/issuing.ts +585 -0
  180. package/src/semantics/ledger.ts +216 -0
  181. package/src/semantics/payment-intents.ts +420 -0
  182. package/src/semantics/payment-links.ts +148 -0
  183. package/src/semantics/payment-methods.ts +143 -0
  184. package/src/semantics/plans.ts +131 -0
  185. package/src/semantics/platform.ts +220 -0
  186. package/src/semantics/products.ts +154 -0
  187. package/src/semantics/radar.ts +85 -0
  188. package/src/semantics/refunds.ts +218 -0
  189. package/src/semantics/renewals.ts +274 -0
  190. package/src/semantics/setup-intents.ts +87 -0
  191. package/src/semantics/shared.ts +215 -0
  192. package/src/semantics/subscription-schedules.ts +129 -0
  193. package/src/semantics/subscriptions.ts +610 -0
  194. package/src/semantics/tax.ts +220 -0
  195. package/src/semantics/terminal.ts +195 -0
  196. package/src/semantics/test-clocks.ts +77 -0
  197. package/src/semantics/tokens.ts +52 -0
  198. package/src/semantics/transfers.ts +174 -0
  199. package/src/semantics/treasury.ts +383 -0
  200. package/src/semantics/webhook-endpoints.ts +87 -0
  201. package/src/stripe-budget.ts +4 -4
  202. package/src/stripe-capabilities.ts +1456 -222
  203. package/src/stripe-conformance.ts +6 -5
  204. package/src/stripe-connector.ts +68 -40
  205. package/src/stripe-emit.ts +14 -7
  206. package/src/stripe-events.ts +94 -36
  207. package/src/stripe-js.ts +70 -0
  208. package/src/stripe-mirror-ui.ts +28 -298
  209. package/src/stripe-params.ts +44 -0
  210. package/src/stripe-perform-harness.ts +29 -0
  211. package/src/stripe-server.ts +263 -38
  212. package/src/stripe-shared.ts +294 -0
  213. package/src/stripe-twin.ts +429 -5325
  214. package/src/stripe-ui-conformance.ts +70 -107
  215. package/src/stripe-ui-structure.ts +124 -348
  216. package/src/stripe-version.ts +278 -0
  217. package/test-fixtures/stripe-known-deviations.json +2 -7
  218. package/test-fixtures/stripe-openapi-operations.json +1188 -2855
  219. package/src/stripe-form.ts +0 -35
@@ -0,0 +1,420 @@
1
+ // PaymentIntent semantics. The machine in ../manifest.ts says which moves of `status` are legal and
2
+ // what Stripe answers otherwise; these handlers compute what each move does. List, retrieve and
3
+ // update are the derived core's; search is Stripe's query language over the intents.
4
+ import type { Semantics, SemanticsContext } from '@volter/world-core';
5
+ import {
6
+ asBool,
7
+ cardError,
8
+ chargeDefaults,
9
+ declineFor,
10
+ microdepositsNextAction,
11
+ mintClientSecret,
12
+ requiresAuthentication,
13
+ requiresMicrodeposits,
14
+ threeDsNextAction,
15
+ validateMoney,
16
+ verifyMicrodeposits,
17
+ type StripeResponse,
18
+ } from '../stripe-twin.ts';
19
+ import { afterCharge, mintMandate } from './after-payment.ts';
20
+ import { cancelAuthorization, captureAuthorization } from './charges.ts';
21
+ import { settleCharge } from './ledger.ts';
22
+ import { materializeTestMethod, methodFromData, microdepositsAsked, paymentMethodDetails } from './payment-methods.ts';
23
+ import { at_, confirmOnly, created, fail, finder, search, type Row } from './shared.ts';
24
+
25
+ const PI = 'payment_intent';
26
+
27
+ const send = (ctx: SemanticsContext, r: StripeResponse): Response => ctx.reply(r.body, r.status);
28
+
29
+ // ── THE MONEY MODEL, continued: a succeeded intent has a Charge ──
30
+ //
31
+ // Real Stripe always materializes a Charge when a PaymentIntent succeeds and points the intent's
32
+ // `latest_charge` at it: the charge is what a refund lands on, so an intent that succeeds without
33
+ // one cannot answer "refund this payment" at all. Idempotent against a repeated confirm: an intent
34
+ // that already names a successful charge keeps it (a second one would double the money collected); a
35
+ // declined attempt's failed charge is history, and the payment that succeeds makes its own. The id is
36
+ // returned so the caller folds `latest_charge` into the same intent write (one write, one event). The
37
+ // charge is written as the event Stripe sends for it, `charge.succeeded` ("Occurs whenever a charge is
38
+ // successful", docs.stripe.com/api/events/types); Stripe has no `charge.created`.
39
+ /** What every charge an intent makes carries of it: its transfer_group, which "identifies the resulting payment as part
40
+ * of a group" (docs.stripe.com/api/payment_intents/object), its description and its metadata. */
41
+ function intentCarries(pi: Row): Row {
42
+ return {
43
+ ...(typeof pi.transfer_group === 'string' ? { transfer_group: pi.transfer_group } : {}),
44
+ ...(typeof pi.description === 'string' ? { description: pi.description } : {}),
45
+ // "When a PaymentIntent creates a Charge, the metadata copies to the Charge in a one-time snapshot"
46
+ // (docs.stripe.com/metadata, "Copy metadata to another object")
47
+ ...(pi.metadata && typeof pi.metadata === 'object' ? { metadata: { ...(pi.metadata as Row) } } : {}),
48
+ };
49
+ }
50
+
51
+ export async function mintCharge(ctx: SemanticsContext, piId: string, pi: Row, amount: number): Promise<string> {
52
+ const already = ctx.get(PI, piId)?.latest_charge;
53
+ if (typeof already === 'string' && ctx.get('charge', already)?.status === 'succeeded') return already;
54
+ const chargeId = ctx.mint('charge');
55
+ const bt = await settleCharge(ctx, chargeId, amount, String(pi.currency ?? 'usd'), typeof pi.payment_method === 'string' ? pi.payment_method : undefined);
56
+ await created(ctx, 'charge', {
57
+ id: chargeId, amount, currency: pi.currency ?? 'usd', payment_intent: piId,
58
+ ...(typeof pi.customer === 'string' ? { customer: pi.customer } : {}),
59
+ ...(typeof pi.payment_method === 'string' ? { payment_method: pi.payment_method } : {}),
60
+ ...(typeof pi.invoice === 'string' ? { invoice: pi.invoice } : {}),
61
+ ...intentCarries(pi),
62
+ }, { ...chargeDefaults(chargeId, amount, true, ctx.occurredAt), balance_transaction: bt, payment_method_details: paymentMethodDetails(ctx, pi.payment_method) ?? null }, { operation: 'charge.succeeded' });
63
+ await afterCharge(ctx, chargeId, { amount, currency: String(pi.currency ?? 'usd'), payment_intent: piId, application_fee_amount: pi.application_fee_amount, destination: (pi.transfer_data as Row | undefined)?.destination }, pi.payment_method);
64
+ return chargeId;
65
+ }
66
+
67
+ /** A manual-capture intent's authorization: "Separate payment authorization and capture to create a charge now, but
68
+ * capture funds later", and on capture "A partial capture automatically releases the remaining amount"
69
+ * (docs.stripe.com/payments/place-a-hold-on-a-payment-method). The charge succeeded and is not captured, holding the
70
+ * amount until capture_before, with nothing on the balance yet. Written as
71
+ * charge.succeeded, as a charge made with capture=false is (charges.ts); its capture writes charge.captured
72
+ * (captureAuthorization). Where the documentation stops and the twin decides: the events page names no event for an
73
+ * authorization of its own, so the authorized charge sends charge.succeeded, its status being succeeded. */
74
+ export async function authorizeCharge(ctx: SemanticsContext, piId: string, pi: Row, amount: number): Promise<string> {
75
+ const chargeId = ctx.mint('charge');
76
+ await created(ctx, 'charge', {
77
+ id: chargeId, amount, currency: pi.currency ?? 'usd', payment_intent: piId,
78
+ ...(typeof pi.customer === 'string' ? { customer: pi.customer } : {}),
79
+ ...(typeof pi.payment_method === 'string' ? { payment_method: pi.payment_method } : {}),
80
+ ...(typeof pi.invoice === 'string' ? { invoice: pi.invoice } : {}),
81
+ ...intentCarries(pi),
82
+ }, { ...chargeDefaults(chargeId, amount, false, ctx.occurredAt), balance_transaction: null, payment_method_details: paymentMethodDetails(ctx, pi.payment_method) ?? null }, { operation: 'charge.succeeded' });
83
+ return chargeId;
84
+ }
85
+
86
+ /**
87
+ * An intent an invoice collects through succeeded (the default_incomplete subscription flow: create
88
+ * now, confirm client-side): its invoice is paid and, when it is a subscription's first, the
89
+ * subscription leaves incomplete for active. Both are moves the invoice and subscription machines
90
+ * declare under the confirming operation. No-op when the intent names no invoice, or the invoice is
91
+ * already paid (a duplicate confirm) or void (voiding ends what it collects).
92
+ */
93
+ async function payInvoiceOf(ctx: SemanticsContext, pi: Row, operationId: string, actor?: 'vendor'): Promise<void> {
94
+ const invoiceId = typeof pi.invoice === 'string' ? pi.invoice : undefined;
95
+ const invoice = invoiceId ? ctx.get('invoice', invoiceId) : undefined;
96
+ if (!invoiceId || !invoice || invoice.status === 'paid' || invoice.status === 'void') return;
97
+ if (ctx.legal('invoice', 'status', operationId, invoice.status, 'paid', invoiceId, actor)) return;
98
+ const amount = Number(invoice.total ?? invoice.amount_due) || 0;
99
+ // `invoice.pay` is the event the standalone pay action sends: invoice.paid
100
+ await ctx.write('invoice', invoiceId, {
101
+ status: 'paid', paid: true, amount_paid: amount, amount_remaining: 0,
102
+ status_transitions: { ...((invoice.status_transitions as object) ?? {}), paid_at: ctx.now() },
103
+ }, 'invoice.pay');
104
+ const subId = typeof invoice.subscription === 'string' ? invoice.subscription : undefined;
105
+ const sub = subId ? ctx.get('subscription', subId) : undefined;
106
+ if (subId && sub && sub.status === 'incomplete' && !ctx.legal('subscription', 'status', operationId, sub.status, 'active', subId, actor)) {
107
+ await ctx.write('subscription', subId, { status: 'active' }, 'subscription.update');
108
+ }
109
+ }
110
+
111
+ /** The intent the path names, and the machine's refusal when this operation may not move it. */
112
+ function load(ctx: SemanticsContext, operationId: string): { pi: Record<string, unknown> } | { answer: Response } {
113
+ const pi = ctx.id ? ctx.get(PI, ctx.id) : undefined;
114
+ if (!pi) return { answer: ctx.notFound(PI, String(ctx.id)) };
115
+ const refusal = ctx.legal(PI, 'status', operationId, pi.status);
116
+ return refusal ? { answer: ctx.refuse(refusal) } : { pi };
117
+ }
118
+
119
+ const create: Semantics = async (ctx) => {
120
+ const params = ctx.params;
121
+ const bad = validateMoney(params);
122
+ if (bad) return send(ctx, bad);
123
+ // what describes a confirmation needs one: error_on_requires_action, mandate, mandate_data, off_session and return_url
124
+ // are each, in the served spec, a parameter that "can only be used with `confirm=true`" (shared.ts confirmOnly)
125
+ const unconfirmed = confirmOnly(ctx, ['error_on_requires_action', 'mandate', 'mandate_data', 'off_session', 'return_url'], asBool(params.confirm));
126
+ if (unconfirmed) return unconfirmed;
127
+ // automatic_payment_methods: when enabled, Stripe selects eligible methods and answers the
128
+ // normalized { enabled, allow_redirects } object
129
+ const apmIn = params.automatic_payment_methods;
130
+ const apmEnabled = apmIn && typeof apmIn === 'object' ? asBool((apmIn as Record<string, unknown>).enabled) : false;
131
+ const automatic_payment_methods = apmEnabled ? { enabled: true, allow_redirects: ((apmIn as Record<string, unknown>).allow_redirects as string) ?? 'always' } : null;
132
+ // the methods it may be paid with: allowed_payment_method_types in the served version, payment_method_types for a
133
+ // caller pinned to an earlier one (docs.stripe.com/api/payment_intents/create)
134
+ const given = Array.isArray(params.allowed_payment_method_types) ? params.allowed_payment_method_types : params.payment_method_types;
135
+ const payment_method_types = Array.isArray(given) ? given.map(String) : ['card'];
136
+ // `confirm` is an instruction, not a field: `confirm=true` attempts to confirm the intent at once
137
+ // (https://docs.stripe.com/api/payment_intents/create#create_payment_intent-confirm)
138
+ const { automatic_payment_methods: _a, payment_method_types: _p, allowed_payment_method_types: _ap, id: provided, expand: _e, confirm: confirmNow, payment_method_data: data, mandate_data: _mandate, ...rest } = params;
139
+ // a create's payment_method_data makes its method, as a confirm's does (payment-methods.ts methodFromData)
140
+ const made = await methodFromData(ctx, data);
141
+ if (made) rest.payment_method = made;
142
+ // the id is minted first so the client secret can carry it: Stripe.js parses the id back out
143
+ const id = typeof provided === 'string' && provided ? provided : ctx.mint(PI);
144
+ // it waits for a payment method until it has one, then for its confirmation (manifest.ts)
145
+ const hasMethod = typeof rest.payment_method === 'string' && rest.payment_method !== '';
146
+ if (hasMethod) ctx.legal(PI, 'status', 'PostPaymentIntents', 'requires_payment_method', 'requires_confirmation', id);
147
+ const body = await ctx.write(
148
+ PI,
149
+ id,
150
+ {
151
+ object: 'payment_intent',
152
+ created: ctx.now(),
153
+ status: hasMethod ? 'requires_confirmation' : 'requires_payment_method',
154
+ client_secret: mintClientSecret(id),
155
+ livemode: false,
156
+ capture_method: 'automatic',
157
+ amount_capturable: 0,
158
+ amount_received: 0,
159
+ next_action: null,
160
+ automatic_payment_methods,
161
+ payment_method_types,
162
+ ...(Array.isArray(params.allowed_payment_method_types) ? { allowed_payment_method_types: payment_method_types } : {}),
163
+ payment_method_options: (params.payment_method_options as object) ?? {},
164
+ ...rest,
165
+ },
166
+ 'payment_intent.create',
167
+ );
168
+ if (asBool(confirmNow)) return confirmIntent(ctx, body, {});
169
+ return ctx.reply(ctx.expand(PI, body));
170
+ };
171
+
172
+ const confirm: Semantics = async (ctx) => {
173
+ const loaded = load(ctx, 'PostPaymentIntentsIntentConfirm');
174
+ if ('answer' in loaded) return loaded.answer;
175
+ const { expand: _e, payment_method_data: data, mandate_data: _mandate, ...params } = ctx.params;
176
+ // a confirm's payment_method_data makes the method it pays with; neither it nor mandate_data is a field of the intent
177
+ const made = await methodFromData(ctx, data);
178
+ return confirmIntent(ctx, loaded.pi, made ? { ...params, payment_method: made } : params);
179
+ };
180
+
181
+ /** Confirm an intent the confirm machine allows to move: the confirm action, and a create with `confirm=true`. */
182
+ async function confirmIntent(ctx: SemanticsContext, existing: Record<string, unknown>, params: Record<string, unknown>): Promise<Response> {
183
+ const id = String(existing.id);
184
+ // a payment names a mandate only an active one authorizes: an inactive mandate "was rejected, revoked, or previously
185
+ // used, and may not be used to initiate future payments" (docs.stripe.com/api/mandates/object), refused as
186
+ // payment_intent_mandate_invalid, "The provided mandate is invalid and can't be used for the payment intent"
187
+ // (docs.stripe.com/error-codes)
188
+ const named = typeof params.mandate === 'string' ? params.mandate : typeof existing.mandate === 'string' ? existing.mandate : undefined;
189
+ if (named && ctx.get('mandate', named)?.status !== 'active') return fail(ctx, 'The provided mandate is invalid and can\'t be used for the payment intent.', 400, 'payment_intent_mandate_invalid');
190
+ // a declining test card leaves the intent needing a payment method, with the error on it and a 402
191
+ const decline = declineFor(finder(ctx), params, existing);
192
+ if (decline) {
193
+ // Stripe records the attempt: a failed charge the intent's latest_charge names, the declined card on
194
+ // last_payment_error (a test name made a real PaymentMethod), and no payment_method left on the intent
195
+ // (docs.stripe.com/payments/paymentintents/lifecycle, docs.stripe.com/declines)
196
+ const ref = params.payment_method ?? existing.payment_method;
197
+ let pmId = typeof ref === 'string' ? ref : undefined;
198
+ if (pmId && !ctx.get('payment_method', pmId) && pmId.startsWith('pm_card_')) pmId = String((await materializeTestMethod(ctx, pmId, typeof existing.customer === 'string' ? existing.customer : null)).id);
199
+ const pm = pmId ? ctx.get('payment_method', pmId) : undefined;
200
+ const amount = Number(params.amount ?? existing.amount) || 0;
201
+ const chargeId = ctx.mint('charge');
202
+ await created(ctx, 'charge', {
203
+ id: chargeId, amount, currency: existing.currency ?? 'usd', payment_intent: id,
204
+ ...(typeof existing.customer === 'string' ? { customer: existing.customer } : {}),
205
+ ...(pmId ? { payment_method: pmId } : {}),
206
+ ...intentCarries({ ...existing, ...params }),
207
+ }, {
208
+ ...chargeDefaults(chargeId, amount, false, ctx.occurredAt), status: 'failed', paid: false, captured: false, capture_before: null,
209
+ failure_code: decline.code, failure_message: decline.message, balance_transaction: null,
210
+ 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.' },
211
+ payment_method_details: pmId ? paymentMethodDetails(ctx, pmId) ?? null : null,
212
+ }, { operation: 'charge.failed' }); // "Occurs whenever a failed charge attempt occurs." (docs.stripe.com/api/events/types)
213
+ const { payment_method: _pm, ...rest } = params;
214
+ 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 };
215
+ const failed = await ctx.write(PI, id, { ...rest, payment_method: null, latest_charge: chargeId, status: 'requires_payment_method', last_payment_error }, 'payment_intent.payment_failed');
216
+ return send(ctx, cardError(decline, { payment_intent: failed, charge: chargeId }));
217
+ }
218
+ // a bank debit that needs micro-deposit verification waits in requires_action
219
+ const method = typeof params.payment_method === 'string' ? params.payment_method : typeof existing.payment_method === 'string' ? existing.payment_method : undefined;
220
+ // a bank transfer is paid from the customer's cash balance, or waits for the transfer (fundFromCashBalance)
221
+ if (method && ctx.get('payment_method', method)?.type === 'customer_balance') return ctx.reply(ctx.expand(PI, await fundFromCashBalance(ctx, { ...existing, ...params }, params)));
222
+ if (requiresMicrodeposits(params, existing) || microdepositsAsked(ctx, params, existing, method)) {
223
+ return ctx.reply(ctx.expand(PI, await ctx.write(PI, id, { ...params, status: 'requires_action', next_action: microdepositsNextAction(), last_payment_error: null }, 'payment_intent.requires_action')));
224
+ }
225
+ // 3DS: the first confirm asks for authentication; a second one completes it
226
+ if (existing.status !== 'requires_action' && requiresAuthentication(params, existing)) {
227
+ return ctx.reply(ctx.expand(PI, await ctx.write(PI, id, { ...params, status: 'requires_action', next_action: threeDsNextAction(), last_payment_error: null }, 'payment_intent.requires_action')));
228
+ }
229
+ // manual capture authorizes and waits for /capture: the authorization is a charge, succeeded and not captured, the
230
+ // intent's latest_charge
231
+ if ((params.capture_method ?? existing.capture_method) === 'manual') {
232
+ const amount = Number(existing.amount ?? params.amount ?? 0);
233
+ const charge = await authorizeCharge(ctx, id, { ...existing, ...params }, amount);
234
+ return ctx.reply(ctx.expand(PI, await ctx.write(PI, id, { ...params, status: 'requires_capture', amount_capturable: amount, amount_received: 0, next_action: null, last_payment_error: null, latest_charge: charge }, 'payment_intent.amount_capturable_updated')));
235
+ }
236
+ // a bank debit is submitted and settles later (beginBankDebit)
237
+ if (isBankDebit(ctx, method)) return ctx.reply(ctx.expand(PI, await beginBankDebit(ctx, id, params)));
238
+ const amount = Number(existing.amount ?? params.amount ?? 0);
239
+ // a succeeded intent has a Charge, and latest_charge names it: what a refund of it lands on
240
+ const charge = await mintCharge(ctx, id, { ...existing, ...params }, amount);
241
+ const body = await ctx.write(PI, id, { ...params, status: 'succeeded', amount_received: amount, next_action: null, last_payment_error: null, latest_charge: charge }, 'payment_intent.confirm');
242
+ await payInvoiceOf(ctx, body, 'PostPaymentIntentsIntentConfirm');
243
+ return ctx.reply(ctx.expand(PI, body));
244
+ }
245
+
246
+ const capture: Semantics = async (ctx) => {
247
+ const loaded = load(ctx, 'PostPaymentIntentsIntentCapture');
248
+ if ('answer' in loaded) return loaded.answer;
249
+ const pi = loaded.pi;
250
+ const authorized = Number(pi.amount_capturable ?? pi.amount ?? 0);
251
+ // amount_to_capture lowers the captured amount (a partial capture); it never raises it
252
+ const asked = ctx.params.amount_to_capture !== undefined ? Math.max(0, Math.trunc(Number(ctx.params.amount_to_capture) || 0)) : authorized;
253
+ const captured = Math.min(asked, authorized);
254
+ // the authorization confirm made is captured; an intent authorized before it was kept is charged as before
255
+ const auth = typeof pi.latest_charge === 'string' ? ctx.get('charge', pi.latest_charge) : undefined;
256
+ const held = auth && auth.status === 'succeeded' && auth.captured === false ? auth : undefined;
257
+ if (held) {
258
+ const refused = ctx.legal('charge', 'captured', 'PostPaymentIntentsIntentCapture', 'false', 'true', String(held.id));
259
+ if (refused) return ctx.refuse(refused);
260
+ await captureAuthorization(ctx, held, captured, 'PostPaymentIntentsIntentCapture');
261
+ await afterCharge(ctx, String(held.id), { amount: captured, currency: String(pi.currency ?? 'usd'), payment_intent: String(pi.id), application_fee_amount: pi.application_fee_amount, destination: (pi.transfer_data as Row | undefined)?.destination }, pi.payment_method);
262
+ }
263
+ const charge = held ? String(held.id) : await mintCharge(ctx, String(pi.id), pi, captured);
264
+ const body = await ctx.write(PI, String(pi.id), { status: 'succeeded', amount_received: captured, amount_capturable: 0, latest_charge: charge }, 'payment_intent.succeeded');
265
+ await payInvoiceOf(ctx, body, 'PostPaymentIntentsIntentCapture');
266
+ return ctx.reply(ctx.expand(PI, body));
267
+ };
268
+
269
+ /** An increment that does not raise the authorization. */
270
+ function incrementTooSmall(ctx: SemanticsContext): Response {
271
+ return ctx.refuse({ status: 400, code: 'parameter_invalid_integer', message: 'The new amount must be greater than the current amount of the PaymentIntent.' });
272
+ }
273
+
274
+ const incrementAuthorization: Semantics = async (ctx) => {
275
+ const loaded = load(ctx, 'PostPaymentIntentsIntentIncrementAuthorization');
276
+ if ('answer' in loaded) return loaded.answer;
277
+ const pi = loaded.pi;
278
+ if (ctx.params.amount === undefined) return ctx.refuse({ status: 400, code: 'parameter_missing', message: 'Missing required param: amount.' });
279
+ const amount = Math.trunc(Number(ctx.params.amount) || 0);
280
+ if (!Number.isInteger(amount) || amount <= Number(pi.amount ?? 0)) return incrementTooSmall(ctx);
281
+ // the authorization the charge holds grows with it: "If the incremental authorization fails ... no other fields on
282
+ // the PaymentIntent or Charge update" (docs.stripe.com/api/payment_intents/increment_authorization), so on success the
283
+ // charge's amount is the new authorized amount. Where the documentation stops and the twin decides: the charge's
284
+ // update sends no event of its own (the events page names none for it).
285
+ const held = typeof pi.latest_charge === 'string' ? ctx.get('charge', pi.latest_charge) : undefined;
286
+ if (held && held.captured === false) await ctx.write('charge', String(held.id), { amount }, 'charge.authorization_incremented');
287
+ return ctx.reply(ctx.expand(PI, await ctx.write(PI, String(pi.id), { amount, amount_capturable: amount }, 'payment_intent.amount_capturable_updated')));
288
+ };
289
+
290
+ const cancel: Semantics = async (ctx) => {
291
+ const loaded = load(ctx, 'PostPaymentIntentsIntentCancel');
292
+ if ('answer' in loaded) return loaded.answer;
293
+ const cancellation_reason = typeof ctx.params.cancellation_reason === 'string' ? ctx.params.cancellation_reason : 'requested_by_customer';
294
+ // "For PaymentIntents with a `status` of `requires_capture`, the remaining `amount_capturable` is automatically
295
+ // refunded" (docs.stripe.com/api/payment_intents/cancel): the authorization is released (charges.ts)
296
+ const held = loaded.pi.status === 'requires_capture' && typeof loaded.pi.latest_charge === 'string' ? ctx.get('charge', loaded.pi.latest_charge) : undefined;
297
+ if (held && held.captured === false && held.refunded !== true) await cancelAuthorization(ctx, held);
298
+ return ctx.reply(ctx.expand(PI, await ctx.write(PI, String(loaded.pi.id), { status: 'canceled', cancellation_reason, amount_capturable: 0 }, 'payment_intent.canceled')));
299
+ };
300
+
301
+ const verifyMicrodepositsHandler: Semantics = async (ctx) => {
302
+ const pi = ctx.id ? ctx.get(PI, ctx.id) : undefined;
303
+ if (!pi) return ctx.notFound(PI, String(ctx.id));
304
+ // the deposit amounts are checked before the intent's state, as Stripe does
305
+ const wrong = verifyMicrodeposits(ctx.params, pi);
306
+ if (wrong) return send(ctx, wrong);
307
+ const refusal = ctx.legal(PI, 'status', 'PostPaymentIntentsIntentVerifyMicrodeposits', pi.status);
308
+ if (refusal) return ctx.refuse(refusal);
309
+ const amount = Number(pi.amount) || 0;
310
+ // a debit saved for reuse ("If you want to reuse the payment method in the future, provide the setup_future_usage
311
+ // parameter with the value of off_session", the ACH page) is authorized for many payments (multi_use, "Represents
312
+ // permission given for multiple payments"); else for this one (single_use, "a one-time permission given for a single
313
+ // payment", docs.stripe.com/api/mandates/object)
314
+ const reuse = pi.setup_future_usage === 'off_session' || pi.setup_future_usage === 'on_session';
315
+ const mandate = reuse ? await mintMandate(ctx, pi.payment_method, 'multi_use') : await mintMandate(ctx, pi.payment_method, 'single_use', amount, String(pi.currency ?? 'usd'));
316
+ // "When the bank account is successfully verified, Stripe returns the PaymentIntent object with a status of
317
+ // `processing`" (docs.stripe.com/payments/ach-direct-debit/accept-a-payment?payment-ui=direct-api)
318
+ return ctx.reply(ctx.expand(PI, await beginBankDebit(ctx, String(pi.id), { mandate })));
319
+ };
320
+
321
+ // ── a bank debit is submitted, and settles ──
322
+ //
323
+ // ACH Direct Debit "is a delayed notification payment method ... The PaymentIntent you create initially has a status
324
+ // of `processing`. After the payment has succeeded, the PaymentIntent status is updated from `processing` to
325
+ // `succeeded`"; verification by micro-deposits returns "a status of `processing`, and sends a payment_intent.processing
326
+ // webhook event"; and, the twin being a test-mode account: "Test transactions settle instantly and are added to your
327
+ // available test balance. This behavior differs from live mode, where transactions can take multiple days to settle"
328
+ // (docs.stripe.com/payments/ach-direct-debit/accept-a-payment?payment-ui=direct-api). A confirm answers processing; the
329
+ // debit succeeds at that same instant of the World's clock, caught up before the next request is answered (as
330
+ // renewals and payouts are). The page's test accounts give each debit its outcome: pm_usBankAccount_success
331
+ // (000123456789) "The payment succeeds"; pm_usBankAccount_processing (000000000009) "The payment stays in processing
332
+ // indefinitely". Where the documentation stops and the twin decides: its Charge is made when it succeeds (the page
333
+ // names none while it processes); the failing test accounts (closed, no account, insufficient funds, debit not
334
+ // authorized, invalid currency, dispute, weekly limit, Radar block) are not modelled and succeed.
335
+
336
+ /** Whether the method an intent is confirmed with is a bank debit: a us_bank_account PaymentMethod, or one of Stripe's
337
+ * test bank accounts named as one (pm_usBankAccount_*, pm_us_bank_account). */
338
+ export function isBankDebit(ctx: SemanticsContext, method: unknown): boolean {
339
+ if (typeof method !== 'string') return false;
340
+ return ctx.get('payment_method', method)?.type === 'us_bank_account' || /^pm_us_?bank_?account/i.test(method);
341
+ }
342
+
343
+ /** Whether a bank debit stays processing: the page's pm_usBankAccount_processing, or its account 000000000009. */
344
+ function staysProcessing(ctx: SemanticsContext, method: unknown): boolean {
345
+ if (method === 'pm_usBankAccount_processing') return true;
346
+ const bank = typeof method === 'string' ? (ctx.get('payment_method', method)?.us_bank_account as Row | undefined) : undefined;
347
+ return bank?.last4 === '0009';
348
+ }
349
+
350
+ /** A bank debit submitted: the intent processes, nothing received yet, sent as payment_intent.processing; it is due to
351
+ * settle at this instant, unless its test account stays processing. */
352
+ async function beginBankDebit(ctx: SemanticsContext, id: string, fields: Row): Promise<Row> {
353
+ const method = fields.payment_method ?? ctx.get(PI, id)?.payment_method;
354
+ 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(ctx.now()) }, 'payment_intent.processing');
355
+ }
356
+
357
+ /** Time's settling of bank debits, caught up to the World's clock: each processing debit whose moment has come succeeds
358
+ * then, its Charge made (naming the mandate it ran under) and the invoice it collects for paid. */
359
+ export async function settleBankDebits(ctx: SemanticsContext): Promise<void> {
360
+ const now = Number(ctx.now());
361
+ 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));
362
+ for (const pi of due) {
363
+ const id = String(pi.id);
364
+ const c = await at_(ctx)(Number(pi._settles_at));
365
+ c.legal(PI, 'status', ctx.call.operation.id, 'processing', 'succeeded', id, 'vendor');
366
+ const amount = Number(pi.amount) || 0;
367
+ const charge = await mintCharge(c, id, pi, amount);
368
+ // the charge names the mandate its bank debit ran under (payment_method_details.us_bank_account.mandate)
369
+ const details = (c.get('charge', charge)?.payment_method_details ?? null) as Row | null;
370
+ const kind = typeof details?.type === 'string' ? details.type : undefined;
371
+ if (details && kind && typeof pi.mandate === 'string') await c.write('charge', charge, { payment_method_details: { ...details, [kind]: { ...((details[kind] as Row | undefined) ?? {}), mandate: pi.mandate } } }, 'charge.mandate');
372
+ const body = await c.write(PI, id, { status: 'succeeded', amount_received: amount, latest_charge: charge, _settles_at: null }, 'payment_intent.succeeded');
373
+ // a single-use mandate is spent by its payment: "previously used, and may not be used to initiate future payments"
374
+ const used = typeof pi.mandate === 'string' ? c.get('mandate', pi.mandate) : undefined;
375
+ if (used && used.type === 'single_use' && used.status === 'active') {
376
+ c.legal('mandate', 'status', ctx.call.operation.id, 'active', 'inactive', String(used.id), 'vendor');
377
+ await c.write('mandate', String(used.id), { status: 'inactive' }, 'mandate.updated');
378
+ }
379
+ await payInvoiceOf(c, body, ctx.call.operation.id, 'vendor');
380
+ }
381
+ }
382
+
383
+ /** A customer_balance intent funded from the customer's cash balance: paid when the balance covers it ("If the customer
384
+ * already has a balance high enough to cover the payment amount, the PaymentIntent immediately succeeds"), else
385
+ * waiting for a transfer: "If the customer balance isn’t high enough to cover the request amount, the PaymentIntent
386
+ * shows a requires_action status ... next_action ... display_bank_transfer_instructions" with the amount_remaining
387
+ * (docs.stripe.com/payments/bank-transfers/accept-a-payment). Answers the intent as written. */
388
+ async function fundFromCashBalance(ctx: SemanticsContext, pi: Row, fields: Row = {}): Promise<Row> {
389
+ const customer = typeof pi.customer === 'string' ? pi.customer : '';
390
+ const currency = String(pi.currency ?? 'usd');
391
+ // what the customer's funded cash balance holds in this currency, from its ledger
392
+ 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;
393
+ const amount = Number(pi.amount) || 0;
394
+ if (available >= amount) {
395
+ // the balance pays the intent: its ledger records what was applied
396
+ await created(ctx, 'customer_cash_balance_transaction', { customer }, { currency, type: 'applied_to_payment', net_amount: -amount, ending_balance: available - amount, applied_to_payment: { payment_intent: String(pi.id) }, livemode: false });
397
+ const charge = await mintCharge(ctx, String(pi.id), { ...pi, ...fields }, amount);
398
+ return ctx.write(PI, String(pi.id), { ...fields, status: 'succeeded', next_action: null, amount_received: amount, last_payment_error: null, latest_charge: charge }, 'payment_intent.succeeded');
399
+ }
400
+ // not enough yet: the intent waits for the rest, with the instructions to send it
401
+ const next_action = { type: 'display_bank_transfer_instructions', display_bank_transfer_instructions: { amount_remaining: amount - available, currency, type: 'us_bank_transfer' } };
402
+ return ctx.write(PI, String(pi.id), { ...fields, status: 'requires_action', next_action }, 'payment_intent.requires_action');
403
+ }
404
+
405
+ const applyCustomerBalance: Semantics = async (ctx) => {
406
+ const loaded = load(ctx, 'PostPaymentIntentsIntentApplyCustomerBalance');
407
+ if ('answer' in loaded) return loaded.answer;
408
+ return ctx.reply(ctx.expand(PI, await fundFromCashBalance(ctx, loaded.pi)));
409
+ };
410
+
411
+ export const paymentIntents: Record<string, Semantics> = {
412
+ PostPaymentIntents: create,
413
+ GetPaymentIntentsSearch: async (ctx) => search(ctx, PI),
414
+ PostPaymentIntentsIntentConfirm: confirm,
415
+ PostPaymentIntentsIntentCapture: capture,
416
+ PostPaymentIntentsIntentIncrementAuthorization: incrementAuthorization,
417
+ PostPaymentIntentsIntentCancel: cancel,
418
+ PostPaymentIntentsIntentVerifyMicrodeposits: verifyMicrodepositsHandler,
419
+ PostPaymentIntentsIntentApplyCustomerBalance: applyCustomerBalance,
420
+ };
@@ -0,0 +1,148 @@
1
+ // Payment Link and Quote semantics. Both carry line items resolved from existing prices. A payment
2
+ // link is a reusable hosted-checkout URL, active until switched off; a quote moves draft → open
3
+ // (finalize) → accepted or canceled, the machine in ../manifest.ts. Link retrieve and update
4
+ // (`active`, its machine), quote retrieve and the quote list are the derived core's.
5
+ import type { Semantics, SemanticsContext } from '@volter/world-core';
6
+ import { asBool, lineItemEntries, paginate, resolveLineItem, type CheckoutItem } from '../stripe-twin.ts';
7
+ import { draftInvoiceFor } from './invoices.ts';
8
+ import { at, created, fail, finder, list, newest, path, where, type Row } from './shared.ts';
9
+
10
+ /** The request's line items resolved against their prices, or the refusal for a missing price. */
11
+ function resolved(ctx: SemanticsContext): CheckoutItem[] | Response {
12
+ const entries = lineItemEntries(ctx.params);
13
+ const items: CheckoutItem[] = [];
14
+ for (let i = 0; i < entries.length; i++) {
15
+ const { item, priceMissing } = resolveLineItem(entries[i]!, i, 'usd', finder(ctx));
16
+ if (priceMissing) return fail(ctx, `No such price: '${priceMissing}'`, 400, 'resource_missing');
17
+ items.push(item);
18
+ }
19
+ return items;
20
+ }
21
+
22
+ /** A page of the line items a stored object carries. */
23
+ function linePage(ctx: SemanticsContext, holder: Row): Response {
24
+ const li = holder.line_items as { data?: Row[] } | undefined;
25
+ const { page, hasMore } = paginate(Array.isArray(li?.data) ? li!.data! : [], ctx.params);
26
+ return ctx.reply({ object: 'list', url: path(ctx), has_more: hasMore, data: page });
27
+ }
28
+
29
+ const PL = 'payment_link';
30
+ const linkMissing = (ctx: SemanticsContext, id: string): Response => fail(ctx, `No such payment link: '${id}'`, 404, 'resource_missing');
31
+
32
+ const createLink: Semantics = async (ctx) => {
33
+ if (lineItemEntries(ctx.params).length === 0) return fail(ctx, 'Missing required param: line_items.', 400, 'parameter_missing');
34
+ const items = resolved(ctx);
35
+ if (items instanceof Response) return items;
36
+ const id = ctx.mint(PL);
37
+ const { line_items: _li, ...rest } = ctx.params;
38
+ return ctx.reply(
39
+ await created(ctx, PL, { ...rest, id }, {
40
+ active: ctx.params.active !== undefined ? asBool(ctx.params.active) : true,
41
+ url: `https://buy.twin.local/${id}`, livemode: false, metadata: {},
42
+ // Stripe's defaults for what the link was not given (docs.stripe.com/api/payment-link/create)
43
+ allow_promotion_codes: false, automatic_tax: { enabled: false, liability: null }, billing_address_collection: 'auto',
44
+ custom_fields: [], custom_text: { after_submit: null, shipping_address: null, submit: null, terms_of_service_acceptance: null },
45
+ customer_creation: 'if_required', payment_method_collection: 'always', phone_number_collection: { enabled: false },
46
+ shipping_options: [], submit_type: 'auto', tax_id_collection: { enabled: false, required: 'never' },
47
+ line_items: { object: 'list', data: items, has_more: false, url: `/v1/payment_links/${id}/line_items` },
48
+ currency: items[0]?.currency ?? 'usd',
49
+ after_completion: { type: 'redirect', redirect: typeof ctx.params.after_completion === 'object' ? ctx.params.after_completion : null },
50
+ }),
51
+ );
52
+ };
53
+
54
+ const listLinks: Semantics = async (ctx) => list(ctx, PL, where(ctx, newest(ctx, PL), { active: (p, v) => asBool(p.active) === asBool(v) }));
55
+
56
+ const linkLines: Semantics = async (ctx) => {
57
+ const p = ctx.get(PL, at(ctx, 'payment_link'));
58
+ return p ? linePage(ctx, p) : linkMissing(ctx, at(ctx, 'payment_link'));
59
+ };
60
+
61
+ // ── quotes ──
62
+
63
+ const quoteMissing = (ctx: SemanticsContext, id: string): Response => fail(ctx, `No such quote: '${id}'`, 404, 'resource_missing');
64
+
65
+ const createQuote: Semantics = async (ctx) => {
66
+ const customer = typeof ctx.params.customer === 'string' ? ctx.params.customer : '';
67
+ if (!customer) return fail(ctx, 'Missing required param: customer.', 400, 'parameter_missing');
68
+ if (!ctx.row('customer', customer, { withDeleted: true })) return fail(ctx, `No such customer: '${customer}'`, 400, 'resource_missing');
69
+ const items = resolved(ctx);
70
+ if (items instanceof Response) return items;
71
+ const subtotal = items.reduce((s, it) => s + it.amount_subtotal, 0);
72
+ const id = ctx.mint('quote');
73
+ const { line_items: _li, ...rest } = ctx.params;
74
+ return ctx.reply(
75
+ await created(ctx, 'quote', { ...rest, id }, {
76
+ status: 'draft', customer, currency: items[0]?.currency ?? 'usd', livemode: false, metadata: {},
77
+ amount_subtotal: subtotal, amount_total: subtotal,
78
+ // Stripe's defaults (docs.stripe.com/api/quotes/create); what is paid up front is the whole quote, and the twin bills in classic mode
79
+ automatic_tax: { enabled: false, liability: null, provider: null, status: null }, collection_method: 'charge_automatically', discounts: [],
80
+ invoice_settings: { days_until_due: null, issuer: { type: 'self' } },
81
+ subscription_data: { billing_mode: { type: 'classic' }, description: null, effective_date: null, metadata: null, trial_period_days: null },
82
+ computed: { recurring: null, upfront: { amount_subtotal: subtotal, amount_total: subtotal, total_details: { amount_discount: 0, amount_shipping: 0, amount_tax: 0 } } },
83
+ line_items: { object: 'list', data: items, has_more: false, url: `/v1/quotes/${id}/line_items` },
84
+ total_details: { amount_discount: 0, amount_shipping: 0, amount_tax: 0 },
85
+ expires_at: Number(ctx.now()) + 30 * 24 * 3600,
86
+ number: null, invoice: null, subscription: null,
87
+ status_transitions: { accepted_at: null, canceled_at: null, finalized_at: null },
88
+ }),
89
+ );
90
+ };
91
+
92
+ const quoteLines: Semantics = async (ctx) => {
93
+ const q = ctx.get('quote', at(ctx, 'quote'));
94
+ return q ? linePage(ctx, q) : quoteMissing(ctx, at(ctx, 'quote'));
95
+ };
96
+
97
+ // Stripe streams the PDF; the twin answers a stable reference to it
98
+ const pdf: Semantics = async (ctx) => {
99
+ const id = at(ctx, 'quote');
100
+ if (!ctx.get('quote', id)) return quoteMissing(ctx, id);
101
+ return ctx.reply({ object: 'quote_pdf', url: `https://files.twin.local/quotes/${id}.pdf` });
102
+ };
103
+
104
+ function move(action: 'finalize' | 'accept' | 'cancel', operationId: string): Semantics {
105
+ return async (ctx) => {
106
+ const id = at(ctx, 'quote');
107
+ const q = ctx.get('quote', id);
108
+ if (!q) return quoteMissing(ctx, id);
109
+ const refused = ctx.legal('quote', 'status', operationId, q.status, undefined, id);
110
+ if (refused) return ctx.refuse(refused);
111
+ const now = ctx.now();
112
+ const stamp = action === 'finalize' ? { finalized_at: now } : action === 'accept' ? { accepted_at: now } : { canceled_at: now };
113
+ // "Accepted quotes automatically generate an invoice, subscription, or subscription schedule"; "Quotes without
114
+ // recurring prices: A draft invoice is created with auto_advance set to false" (docs.stripe.com/quotes/overview),
115
+ // the quote its parent ("Details about the quote that generated this invoice", the served spec). Where the
116
+ // documentation stops and the twin decides: a quote with recurring prices makes no subscription yet.
117
+ let made: Row = {};
118
+ if (action === 'accept') {
119
+ const lines = ((q.line_items as Row | undefined)?.data as Row[] | undefined) ?? [];
120
+ const recurring = lines.some((l) => l.price && typeof l.price === 'object' && (l.price as Row).recurring);
121
+ if (!recurring && typeof q.customer === 'string') {
122
+ const invoice = await draftInvoiceFor(ctx, q.customer, String(q.currency ?? 'usd'), { type: 'quote_details', quote_details: { quote: id }, subscription_details: null }, lines.map((l) => ({ price: l.price, quantity: Number(l.quantity) || 1, amount: Number(l.amount_subtotal ?? l.amount_total) || 0, description: l.description })));
123
+ made = { invoice };
124
+ }
125
+ }
126
+ return ctx.reply(
127
+ await ctx.write('quote', id, {
128
+ status: action === 'finalize' ? 'open' : action === 'accept' ? 'accepted' : 'canceled',
129
+ status_transitions: { ...((q.status_transitions as Row) ?? {}), ...stamp },
130
+ ...(action === 'finalize' ? { number: `QT-${id.toUpperCase()}` } : {}),
131
+ ...made,
132
+ }, `quote.${action}`),
133
+ );
134
+ };
135
+ }
136
+
137
+ export const paymentLinks: Record<string, Semantics> = {
138
+ PostPaymentLinks: createLink,
139
+ GetPaymentLinks: listLinks,
140
+ GetPaymentLinksPaymentLinkLineItems: linkLines,
141
+ PostQuotes: createQuote,
142
+ GetQuotesQuoteLineItems: quoteLines,
143
+ GetQuotesQuoteComputedUpfrontLineItems: quoteLines,
144
+ GetQuotesQuotePdf: pdf,
145
+ PostQuotesQuoteFinalize: move('finalize', 'PostQuotesQuoteFinalize'),
146
+ PostQuotesQuoteAccept: move('accept', 'PostQuotesQuoteAccept'),
147
+ PostQuotesQuoteCancel: move('cancel', 'PostQuotesQuoteCancel'),
148
+ };