@volter/twin-stripe 0.1.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/README.md +64 -27
  2. package/client/dashboard-api.ts +286 -0
  3. package/client/stripe-mirror.css +272 -159
  4. package/client/stripe-mirror.tsx +1384 -541
  5. package/dist/client/dashboard-api.d.ts +107 -0
  6. package/dist/client/dashboard-api.js +238 -0
  7. package/dist/client/dashboard-api.ts +286 -0
  8. package/dist/client/stripe-mirror.bundle.js +236 -0
  9. package/dist/client/stripe-mirror.css +275 -0
  10. package/dist/client/stripe-mirror.d.ts +134 -0
  11. package/dist/client/stripe-mirror.js +823 -0
  12. package/dist/client/stripe-mirror.tsx +1534 -0
  13. package/dist/src/cli.d.ts +2 -0
  14. package/dist/src/cli.js +39 -0
  15. package/dist/src/generated/events.gen.json +1 -0
  16. package/dist/src/generated/surface.gen.json +1 -0
  17. package/dist/src/generated/ui.gen.json +1 -0
  18. package/dist/src/index.d.ts +14 -0
  19. package/dist/src/index.js +73 -0
  20. package/dist/src/manifest.d.ts +2 -0
  21. package/dist/src/manifest.js +1065 -0
  22. package/dist/src/screens/checkout.d.ts +31 -0
  23. package/dist/src/screens/checkout.js +241 -0
  24. package/dist/src/screens/consent-skin.d.ts +4 -0
  25. package/dist/src/screens/consent-skin.js +18 -0
  26. package/dist/src/screens/financial-connections.d.ts +5 -0
  27. package/dist/src/screens/financial-connections.js +90 -0
  28. package/dist/src/screens/identity.d.ts +5 -0
  29. package/dist/src/screens/identity.js +86 -0
  30. package/dist/src/screens/industries.d.ts +1 -0
  31. package/dist/src/screens/industries.js +267 -0
  32. package/dist/src/screens/onboarding.d.ts +13 -0
  33. package/dist/src/screens/onboarding.js +225 -0
  34. package/dist/src/screens/portal.d.ts +5 -0
  35. package/dist/src/screens/portal.js +214 -0
  36. package/dist/src/screens/public-details.d.ts +5 -0
  37. package/dist/src/screens/public-details.js +90 -0
  38. package/dist/src/semantics/after-payment.d.ts +22 -0
  39. package/dist/src/semantics/after-payment.js +93 -0
  40. package/dist/src/semantics/apps-secrets.d.ts +2 -0
  41. package/dist/src/semantics/apps-secrets.js +54 -0
  42. package/dist/src/semantics/balance.d.ts +11 -0
  43. package/dist/src/semantics/balance.js +195 -0
  44. package/dist/src/semantics/billing.d.ts +2 -0
  45. package/dist/src/semantics/billing.js +220 -0
  46. package/dist/src/semantics/charges.d.ts +28 -0
  47. package/dist/src/semantics/charges.js +201 -0
  48. package/dist/src/semantics/checkout.d.ts +15 -0
  49. package/dist/src/semantics/checkout.js +303 -0
  50. package/dist/src/semantics/connect.d.ts +5 -0
  51. package/dist/src/semantics/connect.js +476 -0
  52. package/dist/src/semantics/coupons.d.ts +6 -0
  53. package/dist/src/semantics/coupons.js +92 -0
  54. package/dist/src/semantics/credit-notes.d.ts +2 -0
  55. package/dist/src/semantics/credit-notes.js +172 -0
  56. package/dist/src/semantics/customers.d.ts +6 -0
  57. package/dist/src/semantics/customers.js +429 -0
  58. package/dist/src/semantics/disputes.d.ts +2 -0
  59. package/dist/src/semantics/disputes.js +51 -0
  60. package/dist/src/semantics/entitlements.d.ts +2 -0
  61. package/dist/src/semantics/entitlements.js +95 -0
  62. package/dist/src/semantics/ephemeral-keys.d.ts +2 -0
  63. package/dist/src/semantics/ephemeral-keys.js +34 -0
  64. package/dist/src/semantics/files.d.ts +2 -0
  65. package/dist/src/semantics/files.js +125 -0
  66. package/dist/src/semantics/invoices.d.ts +18 -0
  67. package/dist/src/semantics/invoices.js +541 -0
  68. package/dist/src/semantics/issuing.d.ts +13 -0
  69. package/dist/src/semantics/issuing.js +570 -0
  70. package/dist/src/semantics/ledger.d.ts +54 -0
  71. package/dist/src/semantics/ledger.js +181 -0
  72. package/dist/src/semantics/payment-intents.d.ts +18 -0
  73. package/dist/src/semantics/payment-intents.js +404 -0
  74. package/dist/src/semantics/payment-links.d.ts +2 -0
  75. package/dist/src/semantics/payment-links.js +133 -0
  76. package/dist/src/semantics/payment-methods.d.ts +20 -0
  77. package/dist/src/semantics/payment-methods.js +138 -0
  78. package/dist/src/semantics/plans.d.ts +5 -0
  79. package/dist/src/semantics/plans.js +121 -0
  80. package/dist/src/semantics/platform.d.ts +9 -0
  81. package/dist/src/semantics/platform.js +206 -0
  82. package/dist/src/semantics/products.d.ts +2 -0
  83. package/dist/src/semantics/products.js +140 -0
  84. package/dist/src/semantics/radar.d.ts +2 -0
  85. package/dist/src/semantics/radar.js +83 -0
  86. package/dist/src/semantics/refunds.d.ts +9 -0
  87. package/dist/src/semantics/refunds.js +195 -0
  88. package/dist/src/semantics/renewals.d.ts +47 -0
  89. package/dist/src/semantics/renewals.js +251 -0
  90. package/dist/src/semantics/setup-intents.d.ts +2 -0
  91. package/dist/src/semantics/setup-intents.js +84 -0
  92. package/dist/src/semantics/shared.d.ts +78 -0
  93. package/dist/src/semantics/shared.js +192 -0
  94. package/dist/src/semantics/subscription-schedules.d.ts +2 -0
  95. package/dist/src/semantics/subscription-schedules.js +119 -0
  96. package/dist/src/semantics/subscriptions.d.ts +11 -0
  97. package/dist/src/semantics/subscriptions.js +605 -0
  98. package/dist/src/semantics/tax.d.ts +2 -0
  99. package/dist/src/semantics/tax.js +197 -0
  100. package/dist/src/semantics/terminal.d.ts +5 -0
  101. package/dist/src/semantics/terminal.js +182 -0
  102. package/dist/src/semantics/test-clocks.d.ts +6 -0
  103. package/dist/src/semantics/test-clocks.js +73 -0
  104. package/dist/src/semantics/tokens.d.ts +4 -0
  105. package/dist/src/semantics/tokens.js +44 -0
  106. package/dist/src/semantics/transfers.d.ts +2 -0
  107. package/dist/src/semantics/transfers.js +154 -0
  108. package/dist/src/semantics/treasury.d.ts +2 -0
  109. package/dist/src/semantics/treasury.js +377 -0
  110. package/dist/src/semantics/webhook-endpoints.d.ts +3 -0
  111. package/dist/src/semantics/webhook-endpoints.js +85 -0
  112. package/dist/src/stripe-budget.d.ts +55 -0
  113. package/dist/src/stripe-budget.js +155 -0
  114. package/dist/src/stripe-capabilities.d.ts +3 -0
  115. package/dist/src/stripe-capabilities.js +5052 -0
  116. package/dist/src/stripe-conformance.d.ts +41 -0
  117. package/dist/src/stripe-conformance.js +96 -0
  118. package/dist/src/stripe-connector.d.ts +161 -0
  119. package/dist/src/stripe-connector.js +414 -0
  120. package/dist/src/stripe-emit.d.ts +2 -0
  121. package/dist/src/stripe-emit.js +145 -0
  122. package/dist/src/stripe-events.d.ts +93 -0
  123. package/dist/src/stripe-events.js +388 -0
  124. package/dist/src/stripe-js.d.ts +4 -0
  125. package/dist/src/stripe-js.js +70 -0
  126. package/dist/src/stripe-mirror-ui.d.ts +15 -0
  127. package/dist/src/stripe-mirror-ui.js +87 -0
  128. package/dist/src/stripe-params.d.ts +3 -0
  129. package/dist/src/stripe-params.js +43 -0
  130. package/dist/src/stripe-perform-harness.d.ts +9 -0
  131. package/dist/src/stripe-perform-harness.js +26 -0
  132. package/dist/src/stripe-server.d.ts +33 -0
  133. package/dist/src/stripe-server.js +326 -0
  134. package/dist/src/stripe-shared.d.ts +106 -0
  135. package/dist/src/stripe-shared.js +273 -0
  136. package/dist/src/stripe-twin.d.ts +155 -0
  137. package/dist/src/stripe-twin.js +1226 -0
  138. package/dist/src/stripe-ui-conformance.d.ts +5 -0
  139. package/dist/src/stripe-ui-conformance.js +79 -0
  140. package/dist/src/stripe-ui-structure.d.ts +3 -0
  141. package/dist/src/stripe-ui-structure.js +168 -0
  142. package/dist/src/stripe-version.d.ts +10 -0
  143. package/dist/src/stripe-version.js +285 -0
  144. package/dist/test-fixtures/stripe-known-deviations.json +105 -0
  145. package/dist/test-fixtures/stripe-openapi-operations.SOURCE.md +14 -0
  146. package/dist/test-fixtures/stripe-openapi-operations.json +4717 -0
  147. package/dist/test-fixtures/stripe-schemas.SOURCE.md +35 -0
  148. package/dist/test-fixtures/stripe-schemas.json +3740 -0
  149. package/package.json +18 -10
  150. package/src/cli.ts +7 -7
  151. package/src/generated/events.gen.json +1 -0
  152. package/src/generated/surface.gen.json +1 -0
  153. package/src/generated/ui.gen.json +1 -0
  154. package/src/index.ts +31 -9
  155. package/src/manifest.ts +1097 -0
  156. package/src/screens/checkout.tsx +252 -0
  157. package/src/screens/consent-skin.ts +20 -0
  158. package/src/screens/financial-connections.tsx +101 -0
  159. package/src/screens/identity.tsx +96 -0
  160. package/src/screens/industries.ts +267 -0
  161. package/src/screens/onboarding.tsx +243 -0
  162. package/src/screens/portal.tsx +218 -0
  163. package/src/screens/public-details.tsx +105 -0
  164. package/src/semantics/after-payment.ts +113 -0
  165. package/src/semantics/apps-secrets.ts +58 -0
  166. package/src/semantics/balance.ts +209 -0
  167. package/src/semantics/billing.ts +216 -0
  168. package/src/semantics/charges.ts +211 -0
  169. package/src/semantics/checkout.ts +297 -0
  170. package/src/semantics/connect.ts +471 -0
  171. package/src/semantics/coupons.ts +97 -0
  172. package/src/semantics/credit-notes.ts +168 -0
  173. package/src/semantics/customers.ts +432 -0
  174. package/src/semantics/disputes.ts +62 -0
  175. package/src/semantics/entitlements.ts +94 -0
  176. package/src/semantics/ephemeral-keys.ts +34 -0
  177. package/src/semantics/files.ts +143 -0
  178. package/src/semantics/invoices.ts +541 -0
  179. package/src/semantics/issuing.ts +585 -0
  180. package/src/semantics/ledger.ts +216 -0
  181. package/src/semantics/payment-intents.ts +420 -0
  182. package/src/semantics/payment-links.ts +148 -0
  183. package/src/semantics/payment-methods.ts +143 -0
  184. package/src/semantics/plans.ts +131 -0
  185. package/src/semantics/platform.ts +220 -0
  186. package/src/semantics/products.ts +154 -0
  187. package/src/semantics/radar.ts +85 -0
  188. package/src/semantics/refunds.ts +218 -0
  189. package/src/semantics/renewals.ts +274 -0
  190. package/src/semantics/setup-intents.ts +87 -0
  191. package/src/semantics/shared.ts +215 -0
  192. package/src/semantics/subscription-schedules.ts +129 -0
  193. package/src/semantics/subscriptions.ts +610 -0
  194. package/src/semantics/tax.ts +220 -0
  195. package/src/semantics/terminal.ts +195 -0
  196. package/src/semantics/test-clocks.ts +77 -0
  197. package/src/semantics/tokens.ts +52 -0
  198. package/src/semantics/transfers.ts +174 -0
  199. package/src/semantics/treasury.ts +383 -0
  200. package/src/semantics/webhook-endpoints.ts +87 -0
  201. package/src/stripe-budget.ts +4 -4
  202. package/src/stripe-capabilities.ts +1456 -222
  203. package/src/stripe-conformance.ts +6 -5
  204. package/src/stripe-connector.ts +68 -40
  205. package/src/stripe-emit.ts +14 -7
  206. package/src/stripe-events.ts +94 -36
  207. package/src/stripe-js.ts +70 -0
  208. package/src/stripe-mirror-ui.ts +28 -298
  209. package/src/stripe-params.ts +44 -0
  210. package/src/stripe-perform-harness.ts +29 -0
  211. package/src/stripe-server.ts +263 -38
  212. package/src/stripe-shared.ts +294 -0
  213. package/src/stripe-twin.ts +429 -5325
  214. package/src/stripe-ui-conformance.ts +70 -107
  215. package/src/stripe-ui-structure.ts +124 -348
  216. package/src/stripe-version.ts +278 -0
  217. package/test-fixtures/stripe-known-deviations.json +2 -7
  218. package/test-fixtures/stripe-openapi-operations.json +1188 -2855
  219. package/src/stripe-form.ts +0 -35
@@ -0,0 +1,541 @@
1
+ // Invoice and InvoiceItem semantics. The machine in ../manifest.ts says which moves of an invoice's
2
+ // `status` are legal (finalize, send, pay, mark_uncollectible, void) and what Stripe answers
3
+ // otherwise; these handlers compute each move, keep a draft's lines and totals in step with its
4
+ // items, and mint the PaymentIntent a finalized invoice collects through. The invoice list and the
5
+ // item list are the derived core's.
6
+ import type { Semantics, SemanticsContext } from '@volter/world-core';
7
+ import { addBillingInterval, applyCouponDiscount, asBool, cardError, declineFor, mintClientSecret, paginate, priceAmount, subscriptionItemPairs } from '../stripe-twin.ts';
8
+ import { mintCharge } from './payment-intents.ts';
9
+ import { spendOnceCoupon } from './renewals.ts';
10
+ import { at, created, expanded, fail, finder, list, newest, path, search, send, type Row } from './shared.ts';
11
+
12
+ const INV = 'invoice';
13
+ const invoiceMissing = (ctx: SemanticsContext, id: string): Response => fail(ctx, `No such invoice: '${id}'`, 404, 'resource_missing');
14
+ const linesOf = (inv: Row): Row[] => (inv.lines as { data?: Row[] } | undefined)?.data ?? [];
15
+ const sumLines = (lines: Row[]): number => lines.reduce((s, l) => s + (Number(l.amount) || 0), 0);
16
+
17
+ /** Write a draft's line list and the totals derived from it. */
18
+ async function writeLines(ctx: SemanticsContext, invoiceId: string, next: Row[]): Promise<Row> {
19
+ const subtotal = sumLines(next);
20
+ const lines = { object: 'list', data: next, has_more: false, total_count: next.length, url: `/v1/invoices/${invoiceId}/lines` };
21
+ return ctx.write(INV, invoiceId, { lines, subtotal, total: subtotal, amount_due: subtotal, amount_remaining: subtotal }, 'invoice.update');
22
+ }
23
+
24
+ /** Paying an invoice with nothing to pay it: "If not set, defaults to the subscription's default payment method, if any,
25
+ * or to the default payment method in the customer's invoice settings" (docs.stripe.com/api/invoices/object,
26
+ * default_payment_method), and none of them is set. */
27
+ function nothingToPayWith(ctx: SemanticsContext): Response {
28
+ return fail(ctx, 'This customer has no attached payment source or default payment method. Please consider adding a default payment method.', 400, 'missing');
29
+ }
30
+
31
+ /** A subscription waiting on the invoice paid through the invoice's own pay (incomplete on its first, past_due on a
32
+ * failed renewal) is active again. */
33
+ async function activatedByPayment(ctx: SemanticsContext, subId: string): Promise<void> {
34
+ await ctx.write('subscription', subId, { status: 'active' }, 'subscription.update');
35
+ }
36
+
37
+ /** A draft's line no invoice item made (a subscription's) stays as it is when an item changes. */
38
+ function unlinkedLine(line: Row): Row {
39
+ return line;
40
+ }
41
+
42
+ /** A preview's proration for a change at proration_date. Where the documentation stops and the twin decides: half the
43
+ * period's charge credited as unused time and half charged as remaining time. */
44
+ function prorationLines(out: Row[], subtotal: number, currency: string, now: number, period: number): void {
45
+ const half = Math.round(subtotal / 2);
46
+ out.unshift({ id: 'il_twin_proration_unused', object: 'line_item', type: 'invoiceitem', amount: -half, currency, proration: true, period: { start: now, end: period }, description: 'Unused time (proration credit)' });
47
+ out.push({ id: 'il_twin_proration_remaining', object: 'line_item', type: 'invoiceitem', amount: half, currency, proration: true, period: { start: now, end: period }, description: 'Remaining time (proration charge)' });
48
+ }
49
+
50
+ /** Re-derive a draft's lines from the items still on it: an item that changed or was deleted moves the invoice with it. */
51
+ async function resyncDraftLines(ctx: SemanticsContext, invoiceId: string): Promise<void> {
52
+ const inv = ctx.get(INV, invoiceId);
53
+ if (!inv || inv.status !== 'draft') return;
54
+ const next: Row[] = [];
55
+ for (const line of linesOf(inv)) {
56
+ const itemId = typeof line.invoice_item === 'string' ? line.invoice_item : '';
57
+ if (!itemId) next.push(unlinkedLine(line));
58
+ const item = itemId ? ctx.get('invoiceitem', itemId) : undefined;
59
+ if (item) next.push({ ...line, amount: Number(item.amount) || 0, description: (item.description as string) ?? null });
60
+ }
61
+ await writeLines(ctx, invoiceId, next);
62
+ }
63
+
64
+ // ── invoice items: a price-based item takes its amount from the price; one naming a draft invoice
65
+ // lands on its lines at once ──
66
+
67
+ /** An item priced by a Price: its unit amount times the quantity, in its currency (docs.stripe.com/api/invoiceitems/create#create_invoiceitem-pricing). */
68
+ function pricedItem(ctx: SemanticsContext, priceRef: string, qty: number): { amount: number; currency: string | undefined } | Response {
69
+ const price = ctx.get('price', priceRef);
70
+ if (!price) return fail(ctx, `No such price: '${priceRef}'`, 400, 'resource_missing');
71
+ return { amount: priceAmount(price, qty), currency: typeof price.currency === 'string' ? price.currency : undefined };
72
+ }
73
+
74
+ const createItem: Semantics = async (ctx) => {
75
+ const params = ctx.params;
76
+ const now = Number(ctx.now());
77
+ const qty = Number(params.quantity) || 1;
78
+ // the served version names the price in `pricing[price]` ("The pricing information for the invoice item", the served
79
+ // spec); an older version sends `price`. It is kept as the item's price, which the answer renders as `pricing`
80
+ // (stripe-version.ts)
81
+ const { pricing: pricingParam, ...stored } = params;
82
+ const given = (pricingParam as Row | undefined)?.price;
83
+ const priceRef = typeof given === 'string' && given ? given : typeof params.price === 'string' ? params.price : '';
84
+ const priced = priceRef ? pricedItem(ctx, priceRef, qty) : undefined;
85
+ if (priced instanceof Response) return priced;
86
+ const resolvedAmount = priced?.amount;
87
+ let resolvedCurrency = priced?.currency;
88
+ // only a draft invoice takes new items
89
+ const invoiceRef = typeof params.invoice === 'string' ? params.invoice : '';
90
+ let target: Row | undefined;
91
+ if (invoiceRef) {
92
+ target = ctx.get(INV, invoiceRef);
93
+ if (!target) return invoiceMissing(ctx, invoiceRef);
94
+ if (target.status !== 'draft') return fail(ctx, `This invoice cannot have invoice items added because it has status ${String(target.status)}.`, 400, 'invoice_not_editable');
95
+ if (resolvedCurrency === undefined && typeof target.currency === 'string') resolvedCurrency = target.currency;
96
+ }
97
+ // an invoice item is dated by `date`, not `created`; its currency is the price's, else the invoice's
98
+ const item = await created(ctx, 'invoiceitem', { ...stored, ...(priceRef ? { price: priceRef } : {}) }, {
99
+ livemode: false, discountable: true, proration: false, quantity: qty, quantity_decimal: String(qty),
100
+ period: { start: now, end: now }, currency: resolvedCurrency ?? 'usd',
101
+ ...(resolvedAmount !== undefined ? { amount: resolvedAmount } : {}),
102
+ }, { timeField: 'date' });
103
+ if (target) {
104
+ await writeLines(ctx, invoiceRef, [...linesOf(target), {
105
+ id: `il_${String(item.id)}`, object: 'line_item', type: 'invoiceitem', amount: Number(item.amount) || 0, currency: String(target.currency ?? item.currency ?? 'usd'),
106
+ quantity: qty, proration: false, invoice_item: item.id, price: item.price ?? null,
107
+ period: item.period ?? { start: now, end: now }, description: (item.description as string) ?? null,
108
+ }]);
109
+ }
110
+ return ctx.reply(item);
111
+ };
112
+
113
+ const itemMissing = (ctx: SemanticsContext, id: string): Response => fail(ctx, `No such invoiceitem: '${id}'`, 404, 'resource_missing');
114
+
115
+ const retrieveItem: Semantics = async (ctx) => {
116
+ const it = ctx.get('invoiceitem', at(ctx, 'invoiceitem'));
117
+ return it ? ctx.reply(it) : itemMissing(ctx, at(ctx, 'invoiceitem'));
118
+ };
119
+
120
+ const updateItem: Semantics = async (ctx) => {
121
+ const id = at(ctx, 'invoiceitem');
122
+ const it = ctx.get('invoiceitem', id);
123
+ if (!it) return itemMissing(ctx, id);
124
+ const updated = await ctx.write('invoiceitem', id, ctx.params, 'invoiceitem.update');
125
+ if (typeof it.invoice === 'string') await resyncDraftLines(ctx, it.invoice);
126
+ return ctx.reply(updated);
127
+ };
128
+
129
+ // an item is deleted only while its invoice is still editable
130
+ const deleteItem: Semantics = async (ctx) => {
131
+ const id = at(ctx, 'invoiceitem');
132
+ const it = ctx.get('invoiceitem', id);
133
+ if (!it) return itemMissing(ctx, id);
134
+ const onInvoice = typeof it.invoice === 'string' ? ctx.get(INV, it.invoice) : undefined;
135
+ if (onInvoice && onInvoice.status !== 'draft') return fail(ctx, 'You cannot delete an invoice item that is attached to an invoice that is no longer editable.', 400, 'invoice_not_editable');
136
+ await ctx.write('invoiceitem', id, { deleted: true }, 'invoiceitem.delete');
137
+ if (typeof it.invoice === 'string') await resyncDraftLines(ctx, it.invoice);
138
+ return ctx.reply({ id, object: 'invoiceitem', deleted: true });
139
+ };
140
+
141
+ // ── invoices ──
142
+
143
+ /** A draft invoice's fields before anything is on it: what a new invoice and a preview start from. */
144
+ const draft = (now: number): Row => ({
145
+ status: 'draft', livemode: false, currency: 'usd', collection_method: 'charge_automatically',
146
+ auto_advance: false, attempt_count: 0, attempted: false,
147
+ amount_due: 0, amount_paid: 0, amount_remaining: 0, amount_overpaid: 0, amount_paid_off_stripe: 0, amount_shipping: 0,
148
+ subtotal: 0, total: 0, starting_balance: 0, post_payment_credit_notes_amount: 0, pre_payment_credit_notes_amount: 0,
149
+ period_start: now, period_end: now, default_tax_rates: [], discounts: [],
150
+ lines: { object: 'list', data: [], has_more: false, total_count: 0 },
151
+ automatic_tax: { enabled: false, liability: null, status: null },
152
+ status_transitions: { finalized_at: null, marked_uncollectible_at: null, paid_at: null, voided_at: null },
153
+ issuer: { type: 'self' },
154
+ payment_settings: { default_mandate: null, payment_method_options: null, payment_method_types: null },
155
+ // a draft has no PaymentIntent: finalize mints it
156
+ payment_intent: null,
157
+ });
158
+
159
+ // a new invoice pulls in the customer's pending items only when asked: pending_invoice_items_behavior "Defaults to
160
+ // `exclude` if the parameter is omitted" (docs.stripe.com/api/invoices/create)
161
+ const create: Semantics = async (ctx) => {
162
+ const params = ctx.params;
163
+ const now = Number(ctx.now());
164
+ // the lines list names where it can be read, "The URL where this list can be accessed" (served spec, invoice.lines.url)
165
+ const newId = ctx.mint(INV);
166
+ // a send_invoice invoice is due `days_until_due` days "from when the invoice is created" (the same page); the customer's
167
+ // email and name are its own "Until the invoice is finalized, this field will equal customer.email" (served spec,
168
+ // invoice.customer_email; .customer_name likewise)
169
+ const days = Number(params.days_until_due);
170
+ const due = params.collection_method === 'send_invoice' && params.due_date === undefined && Number.isFinite(days) && days > 0 ? { due_date: now + days * 86_400 } : {};
171
+ const holder = typeof params.customer === 'string' ? ctx.get('customer', params.customer) : undefined;
172
+ const snapshot = holder ? { customer_email: holder.email ?? null, customer_name: holder.name ?? null } : {};
173
+ const inv = await created(ctx, INV, { ...params, id: newId }, { ...draft(now), ...due, ...snapshot, lines: { object: 'list', data: [], has_more: false, total_count: 0, url: `/v1/invoices/${newId}/lines` } });
174
+ if (params.pending_invoice_items_behavior !== 'include') return ctx.reply(inv);
175
+ const invoiceId = String(inv.id);
176
+ const customerId = typeof inv.customer === 'string' ? inv.customer : '';
177
+ const pending = customerId ? newest(ctx, 'invoiceitem', 'date').filter((it) => it.customer === customerId && !it.invoice).reverse() : [];
178
+ for (const item of pending) await pullPendingItem(ctx, invoiceId, inv, item, now);
179
+ return ctx.reply(pending.length > 0 ? (ctx.get(INV, invoiceId) ?? inv) : inv);
180
+ };
181
+
182
+ /** A draft invoice another object makes (an accepted quote): its customer's, with an invoice item per line the
183
+ * object gives, and the object named as its parent. Answers the invoice's id. */
184
+ export async function draftInvoiceFor(ctx: SemanticsContext, customer: string, currency: string, parent: Row, lines: Array<{ price: unknown; quantity: number; amount: number; description: unknown }>): Promise<string> {
185
+ const now = Number(ctx.now());
186
+ const id = ctx.mint(INV);
187
+ const holder = ctx.get('customer', customer);
188
+ const inv = await created(ctx, INV, { id, customer, currency, parent }, { ...draft(now), currency, customer_email: holder?.email ?? null, customer_name: holder?.name ?? null, lines: { object: 'list', data: [], has_more: false, total_count: 0, url: `/v1/invoices/${id}/lines` } });
189
+ for (const l of lines) {
190
+ const price = typeof l.price === 'string' ? l.price : l.price && typeof l.price === 'object' ? String((l.price as Row).id) : null;
191
+ const item = await created(ctx, 'invoiceitem', { customer, currency, amount: l.amount, quantity: l.quantity, ...(price ? { price } : {}), description: l.description ?? null }, { date: now, livemode: false, metadata: {}, discountable: true, proration: false, period: { start: now, end: now } });
192
+ await pullPendingItem(ctx, id, inv, item, now);
193
+ }
194
+ return id;
195
+ }
196
+
197
+ /** 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). */
198
+ async function pullPendingItem(ctx: SemanticsContext, invoiceId: string, inv: Row, item: Row, now: number): Promise<void> {
199
+ const current = ctx.get(INV, invoiceId) ?? inv;
200
+ await writeLines(ctx, invoiceId, [...linesOf(current), {
201
+ id: `il_${String(item.id)}`, object: 'line_item', type: 'invoiceitem', amount: Number(item.amount) || 0, currency: String(current.currency ?? item.currency ?? 'usd'),
202
+ quantity: Number(item.quantity) || 1, proration: false, invoice_item: item.id, price: item.price ?? null,
203
+ period: item.period ?? { start: now, end: now }, description: (item.description as string) ?? null,
204
+ discountable: item.discountable ?? true, discounts: [], livemode: false, metadata: item.metadata ?? {}, tax_amounts: [], tax_rates: [],
205
+ }]);
206
+ await ctx.write('invoiceitem', String(item.id), { invoice: invoiceId }, 'invoiceitem.update');
207
+ }
208
+
209
+ /** The invoice the path names, and the machine's refusal when this operation may not move it. */
210
+ function load(ctx: SemanticsContext, operationId: string): { inv: Row } | { answer: Response } {
211
+ const id = at(ctx, 'invoice');
212
+ const inv = ctx.get(INV, id);
213
+ if (!inv) return { answer: invoiceMissing(ctx, id) };
214
+ const refused = ctx.legal(INV, 'status', operationId, inv.status, undefined, id);
215
+ return refused ? { answer: ctx.refuse(refused) } : { inv };
216
+ }
217
+
218
+ /** The PaymentIntent a charge_automatically invoice with a balance gets when it is finalized; it
219
+ * waits for confirmation when the invoice already names a default payment method. */
220
+ async function openPaymentIntent(ctx: SemanticsContext, piId: string, inv: Row, invoiceId: string): Promise<void> {
221
+ const defaultPaymentMethod = typeof inv.default_payment_method === 'string' ? inv.default_payment_method : undefined;
222
+ await created(ctx, 'payment_intent', {
223
+ id: piId, amount: Number(inv.amount_due) || 0, currency: String(inv.currency ?? 'usd'), customer: inv.customer, invoice: invoiceId,
224
+ ...(defaultPaymentMethod ? { payment_method: defaultPaymentMethod } : {}),
225
+ }, {
226
+ status: defaultPaymentMethod ? 'requires_confirmation' : 'requires_payment_method',
227
+ client_secret: mintClientSecret(piId), livemode: false,
228
+ capture_method: 'automatic', amount_capturable: 0, amount_received: 0, next_action: null,
229
+ automatic_payment_methods: null, payment_method_types: ['card', 'link'], payment_method_options: {},
230
+ });
231
+ }
232
+
233
+ /** Whether leaving draft mints a PaymentIntent: only a charge_automatically invoice with a balance. */
234
+ // "Finalizing an invoice does the following: ... It creates an incomplete payment intent for the invoice"
235
+ // (docs.stripe.com/invoicing/integration/workflow-transitions), whichever its collection method
236
+ const collectsThroughIntent = (inv: Row): boolean => inv.status === 'draft' && (Number(inv.amount_due) || 0) > 0;
237
+
238
+ const transitions = (inv: Row): object => (inv.status_transitions as object) ?? {};
239
+
240
+ /** What finalizing assigns: the invoice's `number`, the customer's invoice_prefix and a sequence
241
+ * (https://docs.stripe.com/api/invoices/object#invoice_object-number), and for send_invoice a
242
+ * `due_date` days_until_due after finalization (#invoice_object-due_date). */
243
+ /** A customer's invoice_prefix, "The prefix for the customer used to generate unique invoice numbers"
244
+ * (docs.stripe.com/api/customers/object): the twin's, from the customer's id. */
245
+ export const invoicePrefix = (customerId: string): string => customerId.replace(/[^a-z0-9]/gi, '').slice(-8).toUpperCase() || 'TWIN';
246
+
247
+ export function finalizedFields(ctx: SemanticsContext, inv: Row, now: number): Row {
248
+ const customerId = typeof inv.customer === 'string' ? inv.customer : '';
249
+ const customer = customerId ? ctx.get('customer', customerId) : undefined;
250
+ const prefix = typeof customer?.invoice_prefix === 'string' && customer.invoice_prefix
251
+ ? customer.invoice_prefix
252
+ : invoicePrefix(customerId);
253
+ const numbered = ctx.rows(INV).filter((i) => i.customer === customerId && typeof i.number === 'string' && i.id !== inv.id).length;
254
+ const fields: Row = { number: typeof inv.number === 'string' && inv.number ? inv.number : `${prefix}-${String(numbered + 1).padStart(4, '0')}` };
255
+ const days = Number(inv.days_until_due);
256
+ if (inv.collection_method === 'send_invoice' && inv.due_date == null && Number.isFinite(days) && days > 0) fields.due_date = now + days * 86400;
257
+ return fields;
258
+ }
259
+
260
+ const finalize: Semantics = async (ctx) => {
261
+ const loaded = load(ctx, 'PostInvoicesInvoiceFinalize');
262
+ if ('answer' in loaded) return loaded.answer;
263
+ const inv = loaded.inv;
264
+ const id = String(inv.id);
265
+ const piId = collectsThroughIntent(inv) ? ctx.mint('payment_intent') : null;
266
+ const body = await ctx.write(INV, id, { ...finalizedFields(ctx, inv, Number(ctx.now())), status: 'open', status_transitions: { ...transitions(inv), finalized_at: ctx.now() }, payment_intent: piId }, 'invoice.finalize');
267
+ // the customer's next_invoice_sequence, "The suffix of the customer's next invoice number" (docs.stripe.com/api/customers/object)
268
+ const customerId = typeof inv.customer === 'string' ? inv.customer : '';
269
+ if (customerId && ctx.get('customer', customerId)) await ctx.write('customer', customerId, { next_invoice_sequence: ctx.rows(INV).filter((i) => i.customer === customerId && typeof i.number === 'string').length + 1 }, 'customer.invoice_sequence');
270
+ if (piId) await openPaymentIntent(ctx, piId, inv, id);
271
+ // a subscription's invoice finalized spends the once coupon it took (renewals.ts spendOnceCoupon)
272
+ await spendOnceCoupon(ctx, inv);
273
+ return ctx.reply(expanded(ctx, INV, body));
274
+ };
275
+
276
+ // sending a draft finalizes it; any other invoice keeps its status and records the send
277
+ const sendInvoice: Semantics = async (ctx) => {
278
+ const loaded = load(ctx, 'PostInvoicesInvoiceSend');
279
+ if ('answer' in loaded) return loaded.answer;
280
+ const inv = loaded.inv;
281
+ const id = String(inv.id);
282
+ const becameOpen = inv.status === 'draft';
283
+ const piId = collectsThroughIntent(inv) ? ctx.mint('payment_intent') : null;
284
+ const now = ctx.now();
285
+ const body = await ctx.write(INV, id, {
286
+ status: becameOpen ? 'open' : (inv.status as string), _sent: true, _sent_at: now,
287
+ status_transitions: { ...transitions(inv), ...(becameOpen ? { finalized_at: now } : {}) },
288
+ ...(becameOpen ? { payment_intent: piId } : {}),
289
+ }, 'invoice.sent');
290
+ if (piId) await openPaymentIntent(ctx, piId, inv, id);
291
+ if (becameOpen) await spendOnceCoupon(ctx, inv);
292
+ return ctx.reply(expanded(ctx, INV, body));
293
+ };
294
+
295
+ // paying charges a payment method (the one passed, the invoice's default, or the customer's) unless
296
+ // the payment is recorded out of band; a declining card answers 402 and leaves the invoice open. A
297
+ // paid invoice settles the PaymentIntent finalize opened, and names the charge that took the money.
298
+ const pay: Semantics = async (ctx) => {
299
+ const id = at(ctx, 'invoice');
300
+ const inv = ctx.get(INV, id);
301
+ if (!inv) return invoiceMissing(ctx, id);
302
+ const refused = ctx.legal(INV, 'status', 'PostInvoicesInvoicePay', inv.status, undefined, id);
303
+ if (refused) return ctx.refuse(refused);
304
+ const params = ctx.params;
305
+ const paidOutOfBand = params.paid_out_of_band !== undefined && asBool(params.paid_out_of_band);
306
+ const payer = ctx.get('customer', String(inv.customer ?? ''));
307
+ const customerDefault = (payer?.invoice_settings as Row | undefined)?.default_payment_method || payer?.default_source;
308
+ if (!paidOutOfBand && !params.payment_method && !params.source && !inv.default_payment_method && !inv.default_source && !customerDefault) return nothingToPayWith(ctx);
309
+ // what it charges: the method passed, else the invoice's default, its subscription's, then its customer's
310
+ // (docs.stripe.com/api/invoices/pay#pay_invoice-payment_method)
311
+ const subscription = typeof inv.subscription === 'string' ? ctx.get('subscription', inv.subscription) : undefined;
312
+ const decline = declineFor(finder(ctx), params, { payment_method: inv.default_payment_method ?? subscription?.default_payment_method ?? customerDefault });
313
+ const intent = typeof inv.payment_intent === 'string' ? ctx.get('payment_intent', inv.payment_intent) : undefined;
314
+ if (decline) return send(ctx, cardError(decline, intent ? { payment_intent: intent } : {}));
315
+ const amountPaid = Number(inv.total ?? inv.amount_due) || 0;
316
+ let body = await ctx.write(INV, id, {
317
+ status: 'paid', paid: true, paid_out_of_band: paidOutOfBand, amount_paid: amountPaid, amount_remaining: 0,
318
+ status_transitions: { ...transitions(inv), paid_at: ctx.now() },
319
+ }, 'invoice.pay');
320
+ if (!paidOutOfBand && typeof inv.payment_intent === 'string' && inv.payment_intent) {
321
+ const pi = ctx.get('payment_intent', inv.payment_intent);
322
+ if (pi && pi.status !== 'succeeded' && !ctx.legal('payment_intent', 'status', 'PostInvoicesInvoicePay', pi.status)) {
323
+ const chargeId = await mintCharge(ctx, inv.payment_intent, { ...pi, invoice: id, ...(typeof params.payment_method === 'string' ? { payment_method: params.payment_method } : {}) }, amountPaid);
324
+ await ctx.write('payment_intent', inv.payment_intent, { status: 'succeeded', amount_received: amountPaid, amount_capturable: 0, next_action: null, latest_charge: chargeId }, 'payment_intent.succeeded');
325
+ body = await ctx.write(INV, id, { charge: chargeId }, 'invoice.update');
326
+ }
327
+ }
328
+ // a subscription waiting on this invoice (incomplete on its first, past_due on a failed renewal) is active once it is paid
329
+ const subId = typeof inv.subscription === 'string' ? inv.subscription : undefined;
330
+ const sub = subId ? ctx.get('subscription', subId) : undefined;
331
+ if (subId && sub && (sub.status === 'incomplete' || sub.status === 'past_due') && !ctx.legal('subscription', 'status', 'PostInvoicesInvoicePay', sub.status, 'active', subId)) await activatedByPayment(ctx, subId);
332
+ return ctx.reply(expanded(ctx, INV, body));
333
+ };
334
+
335
+ // only a draft is deleted; a finalized invoice is voided instead
336
+ const deleteDraft: Semantics = async (ctx) => {
337
+ const id = at(ctx, 'invoice');
338
+ const inv = ctx.get(INV, id);
339
+ if (!inv) return invoiceMissing(ctx, id);
340
+ if (inv.status !== 'draft') return fail(ctx, 'You can only delete draft invoices.', 400, 'invoice_not_editable');
341
+ await ctx.write(INV, id, { deleted: true }, 'invoice.deleted');
342
+ return ctx.reply({ id, object: 'invoice', deleted: true });
343
+ };
344
+
345
+ const markUncollectible: Semantics = async (ctx) => {
346
+ const loaded = load(ctx, 'PostInvoicesInvoiceMarkUncollectible');
347
+ if ('answer' in loaded) return loaded.answer;
348
+ const inv = loaded.inv;
349
+ const body = await ctx.write(INV, String(inv.id), { status: 'uncollectible', status_transitions: { ...transitions(inv), marked_uncollectible_at: ctx.now() } }, 'invoice.marked_uncollectible');
350
+ return ctx.reply(expanded(ctx, INV, body));
351
+ };
352
+
353
+ const voidInvoice: Semantics = async (ctx) => {
354
+ const loaded = load(ctx, 'PostInvoicesInvoiceVoid');
355
+ if ('answer' in loaded) return loaded.answer;
356
+ const inv = loaded.inv;
357
+ const body = await ctx.write(INV, String(inv.id), { status: 'void', status_transitions: { ...transitions(inv), voided_at: ctx.now() } }, 'invoice.void');
358
+ return ctx.reply(expanded(ctx, INV, body));
359
+ };
360
+
361
+ // the invoice's lines, a page at a time
362
+ const lines: Semantics = async (ctx) => {
363
+ const id = at(ctx, 'invoice');
364
+ const inv = ctx.get(INV, id);
365
+ if (!inv) return invoiceMissing(ctx, id);
366
+ const { page, hasMore } = paginate(linesOf(inv), ctx.params);
367
+ return ctx.reply({ object: 'list', url: path(ctx), has_more: hasMore, data: page.map((l) => ({ invoice: id, ...l })) });
368
+ };
369
+
370
+ // add_lines, update_lines and remove_lines edit a draft's lines in bulk and re-derive its totals
371
+ function editLines(kind: 'add' | 'update' | 'remove'): Semantics {
372
+ return async (ctx) => {
373
+ const id = at(ctx, 'invoice');
374
+ const inv = ctx.get(INV, id);
375
+ if (!inv) return invoiceMissing(ctx, id);
376
+ if (inv.status !== 'draft') return fail(ctx, `You can only add/update/remove lines on a draft invoice (this one is ${String(inv.status)}).`, 400, 'invoice_not_editable');
377
+ const cur = linesOf(inv);
378
+ let next = [...cur];
379
+ const raw = ctx.params.lines;
380
+ const entries = Array.isArray(raw) ? (raw as Row[]) : raw && typeof raw === 'object' ? [raw as Row] : [];
381
+ if (entries.length === 0) return fail(ctx, 'Missing required param: lines.', 400, 'parameter_missing');
382
+ const currency = String(inv.currency ?? 'usd');
383
+ if (kind === 'add') {
384
+ for (let i = 0; i < entries.length; i++) {
385
+ const e = entries[i]!;
386
+ const priceRef = typeof e.price === 'string' ? e.price : '';
387
+ const price = priceRef ? ctx.get('price', priceRef) : undefined;
388
+ if (priceRef && !price) return fail(ctx, `No such price: '${priceRef}'`, 400, 'resource_missing');
389
+ const quantity = e.quantity !== undefined ? Math.max(1, Math.trunc(Number(e.quantity) || 1)) : 1;
390
+ const unit = Math.trunc(Number(e.amount) || 0);
391
+ next.push({ id: `il_twin_${id}_${cur.length + i + 1}`, object: 'line_item', amount: price ? priceAmount(price, quantity) : unit, currency, quantity, price: price ?? (priceRef || null), description: typeof e.description === 'string' ? e.description : null, proration: false });
392
+ }
393
+ } else if (kind === 'update') {
394
+ for (const e of entries) {
395
+ const lid = typeof e.id === 'string' ? e.id : '';
396
+ next = next.map((l) => (l.id === lid ? { ...l, ...(e.amount !== undefined ? { amount: Math.trunc(Number(e.amount) || 0) } : {}), ...(e.quantity !== undefined ? { quantity: Math.max(1, Math.trunc(Number(e.quantity) || 1)) } : {}), ...(e.description !== undefined ? { description: e.description } : {}) } : l));
397
+ }
398
+ } else {
399
+ const remove = new Set(entries.map((e) => (typeof e.id === 'string' ? e.id : '')).filter(Boolean));
400
+ next = next.filter((l) => !remove.has(String(l.id)));
401
+ }
402
+ return ctx.reply(await writeLines(ctx, id, next));
403
+ };
404
+ }
405
+
406
+ const searchInvoices: Semantics = async (ctx) => search(ctx, INV);
407
+
408
+ const retrieve: Semantics = async (ctx) => {
409
+ const id = at(ctx, 'invoice');
410
+ const inv = ctx.get(INV, id);
411
+ return inv ? ctx.reply(expanded(ctx, INV, inv)) : invoiceMissing(ctx, id);
412
+ };
413
+
414
+ /**
415
+ * A preview of the next invoice for a customer or subscription (create_preview), computed and never
416
+ * stored: the subscription's items at their prices, the customer's pending items, the subscription's
417
+ * discount, and with `subscription_details.proration_date` a credit for the unused period against a
418
+ * charge for the new one (split evenly: there is no clock here to measure the remaining fraction).
419
+ */
420
+ const createPreview: Semantics = async (ctx) => {
421
+ const params = ctx.params;
422
+ const prorationDate = (params.subscription_details as Row | undefined)?.proration_date;
423
+ const now = Number(ctx.now());
424
+ let subId = typeof params.subscription === 'string' ? params.subscription : '';
425
+ let customer = typeof params.customer === 'string' ? params.customer : '';
426
+ let sub: Row | undefined;
427
+ if (subId) {
428
+ sub = ctx.get('subscription', subId);
429
+ if (!sub) return fail(ctx, `No such subscription: '${subId}'`, 404, 'resource_missing');
430
+ customer = customer || String(sub.customer ?? '');
431
+ } else if (customer) {
432
+ // no subscription named: the customer's first live one
433
+ sub = newest(ctx, 'subscription').find((s) => s.customer === customer && s.status !== 'canceled');
434
+ subId = sub ? String(sub.id) : '';
435
+ }
436
+ if (!customer) return fail(ctx, 'Missing required param: customer (or subscription).', 400, 'parameter_missing');
437
+ if (!ctx.get('customer', customer)) return fail(ctx, `No such customer: '${customer}'`, 404, 'resource_missing');
438
+ const currency = String((sub?.currency as string) ?? 'usd');
439
+ // the upcoming invoice bills the subscription's next period, its "subscription renewal charges"
440
+ // (docs.stripe.com/api/invoices/create_preview): from the current period's end, one billing interval long
441
+ const renewsAt = sub && Number(sub.current_period_end) > 0 ? Number(sub.current_period_end) : now;
442
+ const itemRows = sub ? ctx.rows('subscription_item').filter((r) => r.subscription === subId) : [];
443
+ const out: Row[] = [];
444
+ let subtotal = 0;
445
+ let period = now + 30 * 24 * 3600;
446
+ if (sub) {
447
+ for (const { price: priceId, quantity } of subscriptionItemPairs(sub)) {
448
+ const price = ctx.get('price', priceId);
449
+ const amount = priceAmount(price, quantity);
450
+ const recurring = (price?.recurring as Row | undefined) ?? {};
451
+ period = recurring.interval ? addBillingInterval(renewsAt, recurring.interval as Parameters<typeof addBillingInterval>[1], Number(recurring.interval_count) || 1) : period;
452
+ const item = itemRows.find((r) => (typeof r.price === 'string' ? r.price : (r.price as Row | undefined)?.id) === priceId);
453
+ subtotal += amount;
454
+ out.push({
455
+ id: `il_twin_${priceId}`, object: 'line_item', type: 'subscription', amount, currency,
456
+ quantity, proration: false, price: price ?? priceId, subscription: subId || null, subscription_item: item?.id ?? null,
457
+ period: { start: renewsAt, end: period }, description: `${quantity} × ${(price?.nickname as string) ?? priceId}`,
458
+ });
459
+ }
460
+ if (prorationDate !== undefined && subtotal > 0) prorationLines(out, subtotal, currency, now, period);
461
+ }
462
+ for (const ii of newest(ctx, 'invoiceitem', 'date')) {
463
+ if (ii.customer !== customer || ii.invoice) continue;
464
+ out.push({ id: `il_${String(ii.id)}`, object: 'line_item', type: 'invoiceitem', amount: Number(ii.amount) || 0, currency, quantity: Number(ii.quantity) || 1, proration: false, invoice_item: ii.id, period: ii.period ?? { start: now, end: now }, description: (ii.description as string) ?? null });
465
+ }
466
+ subtotal = sumLines(out);
467
+ const subDiscount = Array.isArray(sub?.discounts) && sub!.discounts.length ? (sub!.discounts as Row[])[0] : undefined;
468
+ const coupon = subDiscount && typeof subDiscount.coupon === 'object' ? (subDiscount.coupon as Row) : undefined;
469
+ const discountAmount = applyCouponDiscount(Math.max(0, subtotal), coupon);
470
+ const total = Math.max(0, subtotal - discountAmount);
471
+ return ctx.reply({
472
+ ...draft(now),
473
+ // "For preview invoices created using the create preview endpoint, this id will be prefixed with `upcoming_in`"
474
+ // (served spec, invoice.id; the create preview page's example answers "upcoming_in_1MtHbELkdIwHu7ixl4OzzPMv"). Where
475
+ // the documentation stops and the twin decides: the rest of the id is a fresh invoice id's, minted for the preview.
476
+ object: 'invoice', id: `upcoming_${ctx.mint(INV)}`, customer, subscription: subId || null, currency,
477
+ billing_reason: subId ? 'upcoming' : 'manual',
478
+ created: now, period_start: now, period_end: period,
479
+ subtotal, total, amount_due: total, amount_paid: 0, amount_remaining: total,
480
+ starting_balance: 0, ending_balance: null,
481
+ discounts: discountAmount > 0 && subDiscount ? [subDiscount] : [],
482
+ total_discount_amounts: discountAmount > 0 ? [{ amount: discountAmount, discount: subDiscount?.id ?? null }] : [],
483
+ lines: { object: 'list', url: '/v1/invoices/create_preview/lines', has_more: false, total_count: out.length, data: out },
484
+ });
485
+ };
486
+
487
+ /** An invoice's payment as Stripe answers it (docs.stripe.com/api/invoice-payment/object): the PaymentIntent that
488
+ * collects the invoice, open until the invoice is paid. Where the documentation stops and the twin decides: an
489
+ * invoice has one payment, its default, and the payment's id is the invoice's with `inpay_`. */
490
+ function invoicePayment(inv: Row): Row | undefined {
491
+ if (typeof inv.payment_intent !== 'string') return undefined;
492
+ const paid = inv.status === 'paid';
493
+ const transitions = (inv.status_transitions as Row | undefined) ?? {};
494
+ return {
495
+ id: `inpay_${String(inv.id).replace(/^in_/, '')}`, object: 'invoice_payment', invoice: inv.id, is_default: true, livemode: false,
496
+ amount_requested: Number(inv.amount_due ?? 0), amount_paid: paid ? Number(inv.amount_paid ?? inv.amount_due ?? 0) : null, currency: inv.currency,
497
+ created: inv.created, payment: { type: 'payment_intent', payment_intent: inv.payment_intent },
498
+ status: paid ? 'paid' : inv.status === 'void' ? 'canceled' : 'open',
499
+ status_transitions: { paid_at: paid ? (transitions.paid_at ?? null) : null, canceled_at: inv.status === 'void' ? (transitions.voided_at ?? null) : null },
500
+ };
501
+ }
502
+
503
+ const invoicePayments: Semantics = async (ctx) => {
504
+ const p = ctx.params;
505
+ const wanted = (p.payment as Row | undefined)?.payment_intent;
506
+ const items = newest(ctx, INV)
507
+ .filter((inv) => typeof p.invoice !== 'string' || inv.id === p.invoice)
508
+ .map(invoicePayment).filter((x): x is Row => !!x)
509
+ .filter((x) => typeof wanted !== 'string' || (x.payment as Row).payment_intent === wanted)
510
+ .filter((x) => typeof p.status !== 'string' || x.status === p.status);
511
+ return list(ctx, 'invoice_payment', items);
512
+ };
513
+
514
+ const invoicePaymentOne: Semantics = async (ctx) => {
515
+ const id = at(ctx, 'invoice_payment');
516
+ const found = newest(ctx, INV).map(invoicePayment).find((x) => x?.id === id);
517
+ return found ? ctx.reply(found) : fail(ctx, `No such invoice payment: '${id}'`, 404, 'resource_missing');
518
+ };
519
+
520
+ export const invoices: Record<string, Semantics> = {
521
+ GetInvoicePayments: invoicePayments,
522
+ GetInvoicePaymentsInvoicePayment: invoicePaymentOne,
523
+ PostInvoiceitems: createItem,
524
+ GetInvoiceitemsInvoiceitem: retrieveItem,
525
+ PostInvoiceitemsInvoiceitem: updateItem,
526
+ DeleteInvoiceitemsInvoiceitem: deleteItem,
527
+ PostInvoices: create,
528
+ PostInvoicesCreatePreview: createPreview,
529
+ PostInvoicesInvoiceFinalize: finalize,
530
+ PostInvoicesInvoiceSend: sendInvoice,
531
+ PostInvoicesInvoicePay: pay,
532
+ PostInvoicesInvoiceMarkUncollectible: markUncollectible,
533
+ PostInvoicesInvoiceVoid: voidInvoice,
534
+ DeleteInvoicesInvoice: deleteDraft,
535
+ GetInvoicesInvoiceLines: lines,
536
+ PostInvoicesInvoiceAddLines: editLines('add'),
537
+ PostInvoicesInvoiceUpdateLines: editLines('update'),
538
+ PostInvoicesInvoiceRemoveLines: editLines('remove'),
539
+ GetInvoicesSearch: searchInvoices,
540
+ GetInvoicesInvoice: retrieve,
541
+ };