@fantastic.dev/better-stripe 0.56.0 → 0.58.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 (248) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +5 -1
  3. package/dist/client/billing/setup-intent-read.d.ts +12 -1
  4. package/dist/client/billing/setup-intent-read.d.ts.map +1 -1
  5. package/dist/client/billing/setup-intent-read.js +13 -8
  6. package/dist/client/billing/setup-intent-read.js.map +1 -1
  7. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +366 -2
  8. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +183 -1
  10. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  11. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +366 -2
  12. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutSyncTestHelpers.d.ts +183 -1
  14. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  15. package/dist/client/index.d.ts +2 -12
  16. package/dist/client/index.d.ts.map +1 -1
  17. package/dist/client/index.js +3 -20
  18. package/dist/client/index.js.map +1 -1
  19. package/dist/client/types/triggers.d.ts +3 -1
  20. package/dist/client/types/triggers.d.ts.map +1 -1
  21. package/dist/client/usage/allowanceClient.d.ts +51 -0
  22. package/dist/client/usage/allowanceClient.d.ts.map +1 -0
  23. package/dist/client/usage/allowanceClient.js +64 -0
  24. package/dist/client/usage/allowanceClient.js.map +1 -0
  25. package/dist/client/usage/allowanceTerms.d.ts +64 -0
  26. package/dist/client/usage/allowanceTerms.d.ts.map +1 -0
  27. package/dist/client/usage/allowanceTerms.js +101 -0
  28. package/dist/client/usage/allowanceTerms.js.map +1 -0
  29. package/dist/client/usage/client.d.ts +2 -2
  30. package/dist/client/usage/client.d.ts.map +1 -1
  31. package/dist/client/usage/client.js +4 -4
  32. package/dist/client/usage/client.js.map +1 -1
  33. package/dist/client/usage/creditCapacity.d.ts +5 -0
  34. package/dist/client/usage/creditCapacity.d.ts.map +1 -0
  35. package/dist/client/usage/creditCapacity.js +47 -0
  36. package/dist/client/usage/creditCapacity.js.map +1 -0
  37. package/dist/client/usage/creditClient.d.ts +104 -0
  38. package/dist/client/usage/creditClient.d.ts.map +1 -0
  39. package/dist/client/usage/creditClient.js +111 -0
  40. package/dist/client/usage/creditClient.js.map +1 -0
  41. package/dist/client/usage/creditDelivery.d.ts +6 -0
  42. package/dist/client/usage/creditDelivery.d.ts.map +1 -0
  43. package/dist/client/usage/creditDelivery.js +71 -0
  44. package/dist/client/usage/creditDelivery.js.map +1 -0
  45. package/dist/client/usage/creditInvoice.d.ts +6 -0
  46. package/dist/client/usage/creditInvoice.d.ts.map +1 -0
  47. package/dist/client/usage/creditInvoice.js +63 -0
  48. package/dist/client/usage/creditInvoice.js.map +1 -0
  49. package/dist/client/usage/creditLifecycle.d.ts +14 -0
  50. package/dist/client/usage/creditLifecycle.d.ts.map +1 -0
  51. package/dist/client/usage/creditLifecycle.js +90 -0
  52. package/dist/client/usage/creditLifecycle.js.map +1 -0
  53. package/dist/client/usage/creditNative.d.ts +20 -0
  54. package/dist/client/usage/creditNative.d.ts.map +1 -0
  55. package/dist/client/usage/creditNative.js +100 -0
  56. package/dist/client/usage/creditNative.js.map +1 -0
  57. package/dist/client/usage/creditObservation.d.ts +23 -0
  58. package/dist/client/usage/creditObservation.d.ts.map +1 -0
  59. package/dist/client/usage/creditObservation.js +54 -0
  60. package/dist/client/usage/creditObservation.js.map +1 -0
  61. package/dist/client/usage/creditProofs.d.ts +50 -0
  62. package/dist/client/usage/creditProofs.d.ts.map +1 -0
  63. package/dist/client/usage/creditProofs.js +58 -0
  64. package/dist/client/usage/creditProofs.js.map +1 -0
  65. package/dist/client/usage/creditProvider.d.ts +11 -0
  66. package/dist/client/usage/creditProvider.d.ts.map +1 -0
  67. package/dist/client/usage/creditProvider.js +195 -0
  68. package/dist/client/usage/creditProvider.js.map +1 -0
  69. package/dist/client/usage/creditRead.d.ts +47 -0
  70. package/dist/client/usage/creditRead.d.ts.map +1 -0
  71. package/dist/client/usage/creditRead.js +18 -0
  72. package/dist/client/usage/creditRead.js.map +1 -0
  73. package/dist/client/usage/creditReconciliation.d.ts +20 -0
  74. package/dist/client/usage/creditReconciliation.d.ts.map +1 -0
  75. package/dist/client/usage/creditReconciliation.js +157 -0
  76. package/dist/client/usage/creditReconciliation.js.map +1 -0
  77. package/dist/client/usage/creditTerms.d.ts +89 -0
  78. package/dist/client/usage/creditTerms.d.ts.map +1 -0
  79. package/dist/client/usage/creditTerms.js +76 -0
  80. package/dist/client/usage/creditTerms.js.map +1 -0
  81. package/dist/client/usage/creditTransport.fixtures.d.ts +101 -0
  82. package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -0
  83. package/dist/client/usage/creditTransport.fixtures.js +271 -0
  84. package/dist/client/usage/creditTransport.fixtures.js.map +1 -0
  85. package/dist/client/usage/deliveryProvider.d.ts.map +1 -1
  86. package/dist/client/usage/deliveryProvider.js +2 -0
  87. package/dist/client/usage/deliveryProvider.js.map +1 -1
  88. package/dist/client/usage/index.d.ts +4 -0
  89. package/dist/client/usage/index.d.ts.map +1 -1
  90. package/dist/client/usage/index.js +1 -0
  91. package/dist/client/usage/index.js.map +1 -1
  92. package/dist/client/usage/records.d.ts +2 -0
  93. package/dist/client/usage/records.d.ts.map +1 -1
  94. package/dist/client/usage/records.js +22 -0
  95. package/dist/client/usage/records.js.map +1 -1
  96. package/dist/client/usage/subscriptionTransport.fixtures.d.ts +1 -1
  97. package/dist/client/usage/subscriptionTransport.fixtures.d.ts.map +1 -1
  98. package/dist/client/usage/subscriptionTransport.fixtures.js +4 -1
  99. package/dist/client/usage/subscriptionTransport.fixtures.js.map +1 -1
  100. package/dist/client/usage/summary.js +2 -2
  101. package/dist/client/usage/summary.js.map +1 -1
  102. package/dist/client/usageExports.d.ts +16 -0
  103. package/dist/client/usageExports.d.ts.map +1 -0
  104. package/dist/client/usageExports.js +3 -0
  105. package/dist/client/usageExports.js.map +1 -0
  106. package/dist/client/webhooks/subscriptionDeleted.d.ts +5 -0
  107. package/dist/client/webhooks/subscriptionDeleted.d.ts.map +1 -0
  108. package/dist/client/webhooks/subscriptionDeleted.js +34 -0
  109. package/dist/client/webhooks/subscriptionDeleted.js.map +1 -0
  110. package/dist/component/_generated/api.d.ts +18 -0
  111. package/dist/component/_generated/api.d.ts.map +1 -1
  112. package/dist/component/_generated/api.js.map +1 -1
  113. package/dist/component/_generated/component.d.ts +360 -0
  114. package/dist/component/_generated/component.d.ts.map +1 -1
  115. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  116. package/dist/component/accountClosure/mutations.js +10 -0
  117. package/dist/component/accountClosure/mutations.js.map +1 -1
  118. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  119. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  120. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  121. package/dist/component/balanceFunding/queries.d.ts +1 -1
  122. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  123. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  124. package/dist/component/earnings/triggers.d.ts +352 -18
  125. package/dist/component/earnings/triggers.d.ts.map +1 -1
  126. package/dist/component/payoutRelease/queries.d.ts +2 -2
  127. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  128. package/dist/component/schema.d.ts +183 -1
  129. package/dist/component/schema.js +8 -0
  130. package/dist/component/schema.js.map +1 -1
  131. package/dist/component/usage/mutations.d.ts.map +1 -1
  132. package/dist/component/usage/mutations.js +7 -0
  133. package/dist/component/usage/mutations.js.map +1 -1
  134. package/dist/component/usage/schema.d.ts +15 -1
  135. package/dist/component/usage/schema.d.ts.map +1 -1
  136. package/dist/component/usage/schema.js +12 -0
  137. package/dist/component/usage/schema.js.map +1 -1
  138. package/dist/component/usageAllowance/helpers.d.ts +78 -0
  139. package/dist/component/usageAllowance/helpers.d.ts.map +1 -0
  140. package/dist/component/usageAllowance/helpers.js +99 -0
  141. package/dist/component/usageAllowance/helpers.js.map +1 -0
  142. package/dist/component/usageAllowance/mutations.d.ts +37 -0
  143. package/dist/component/usageAllowance/mutations.d.ts.map +1 -0
  144. package/dist/component/usageAllowance/mutations.js +99 -0
  145. package/dist/component/usageAllowance/mutations.js.map +1 -0
  146. package/dist/component/usageAllowance/queries.d.ts +36 -0
  147. package/dist/component/usageAllowance/queries.d.ts.map +1 -0
  148. package/dist/component/usageAllowance/queries.js +113 -0
  149. package/dist/component/usageAllowance/queries.js.map +1 -0
  150. package/dist/component/usageAllowance/reservations.d.ts +25 -0
  151. package/dist/component/usageAllowance/reservations.d.ts.map +1 -0
  152. package/dist/component/usageAllowance/reservations.js +150 -0
  153. package/dist/component/usageAllowance/reservations.js.map +1 -0
  154. package/dist/component/usageAllowance/schema.d.ts +77 -0
  155. package/dist/component/usageAllowance/schema.d.ts.map +1 -0
  156. package/dist/component/usageAllowance/schema.js +32 -0
  157. package/dist/component/usageAllowance/schema.js.map +1 -0
  158. package/dist/component/usageCredits/helpers.d.ts +205 -0
  159. package/dist/component/usageCredits/helpers.d.ts.map +1 -0
  160. package/dist/component/usageCredits/helpers.js +129 -0
  161. package/dist/component/usageCredits/helpers.js.map +1 -0
  162. package/dist/component/usageCredits/mutations.d.ts +80 -0
  163. package/dist/component/usageCredits/mutations.d.ts.map +1 -0
  164. package/dist/component/usageCredits/mutations.js +344 -0
  165. package/dist/component/usageCredits/mutations.js.map +1 -0
  166. package/dist/component/usageCredits/purchase.d.ts +23 -0
  167. package/dist/component/usageCredits/purchase.d.ts.map +1 -0
  168. package/dist/component/usageCredits/purchase.js +166 -0
  169. package/dist/component/usageCredits/purchase.js.map +1 -0
  170. package/dist/component/usageCredits/queries.d.ts +184 -0
  171. package/dist/component/usageCredits/queries.d.ts.map +1 -0
  172. package/dist/component/usageCredits/queries.js +243 -0
  173. package/dist/component/usageCredits/queries.js.map +1 -0
  174. package/dist/component/usageCredits/reservations.d.ts +16 -0
  175. package/dist/component/usageCredits/reservations.d.ts.map +1 -0
  176. package/dist/component/usageCredits/reservations.js +161 -0
  177. package/dist/component/usageCredits/reservations.js.map +1 -0
  178. package/dist/component/usageCredits/schema.d.ts +282 -0
  179. package/dist/component/usageCredits/schema.d.ts.map +1 -0
  180. package/dist/component/usageCredits/schema.js +92 -0
  181. package/dist/component/usageCredits/schema.js.map +1 -0
  182. package/docs/README.md +4 -0
  183. package/docs/setup-intent-recovery.md +7 -0
  184. package/docs/usage-credits.md +255 -0
  185. package/docs/usage-ledger.md +7 -0
  186. package/docs/usage-limits.md +217 -0
  187. package/docs/webhooks.md +15 -1
  188. package/package.json +3 -1
  189. package/src/client/billing/setup-intent-read.test.ts +40 -0
  190. package/src/client/billing/setup-intent-read.ts +23 -9
  191. package/src/client/index.ts +9 -67
  192. package/src/client/types/triggers.ts +2 -0
  193. package/src/client/usage/allowanceClient.test.ts +93 -0
  194. package/src/client/usage/allowanceClient.ts +134 -0
  195. package/src/client/usage/allowanceTerms.test.ts +131 -0
  196. package/src/client/usage/allowanceTerms.ts +172 -0
  197. package/src/client/usage/client.ts +4 -4
  198. package/src/client/usage/creditCapacity.test.ts +83 -0
  199. package/src/client/usage/creditCapacity.ts +76 -0
  200. package/src/client/usage/creditClient.test.ts +221 -0
  201. package/src/client/usage/creditClient.ts +246 -0
  202. package/src/client/usage/creditDelivery.ts +105 -0
  203. package/src/client/usage/creditInvoice.test.ts +149 -0
  204. package/src/client/usage/creditInvoice.ts +87 -0
  205. package/src/client/usage/creditLifecycle.ts +175 -0
  206. package/src/client/usage/creditNative.ts +148 -0
  207. package/src/client/usage/creditObservation.test.ts +150 -0
  208. package/src/client/usage/creditObservation.ts +82 -0
  209. package/src/client/usage/creditProofs.ts +61 -0
  210. package/src/client/usage/creditProvider.test.ts +202 -0
  211. package/src/client/usage/creditProvider.ts +304 -0
  212. package/src/client/usage/creditRead.ts +32 -0
  213. package/src/client/usage/creditReconciliation.ts +213 -0
  214. package/src/client/usage/creditTerms.test.ts +48 -0
  215. package/src/client/usage/creditTerms.ts +140 -0
  216. package/src/client/usage/creditTransport.fixtures.ts +282 -0
  217. package/src/client/usage/deliveryProvider.ts +2 -0
  218. package/src/client/usage/index.ts +16 -0
  219. package/src/client/usage/record-composition.test.ts +195 -0
  220. package/src/client/usage/records.ts +26 -0
  221. package/src/client/usage/subscriptionTransport.fixtures.ts +6 -0
  222. package/src/client/usage/summary.test.ts +1 -1
  223. package/src/client/usage/summary.ts +2 -2
  224. package/src/client/usageExports.ts +56 -0
  225. package/src/client/webhook-handlers.test.ts +0 -34
  226. package/src/client/webhooks/subscription-deleted-dispatch.test.ts +61 -0
  227. package/src/client/webhooks/subscription-deleted.integration.test.ts +313 -0
  228. package/src/client/webhooks/subscriptionDeleted.ts +56 -0
  229. package/src/component/_generated/api.ts +18 -0
  230. package/src/component/_generated/component.ts +486 -0
  231. package/src/component/accountClosure/mutations.ts +14 -0
  232. package/src/component/schema.ts +16 -0
  233. package/src/component/usage/allowance.test.ts +435 -0
  234. package/src/component/usage/ledger.test.ts +8 -15
  235. package/src/component/usage/mutations.ts +22 -0
  236. package/src/component/usage/schema.ts +14 -0
  237. package/src/component/usageAllowance/helpers.ts +137 -0
  238. package/src/component/usageAllowance/mutations.ts +139 -0
  239. package/src/component/usageAllowance/queries.ts +133 -0
  240. package/src/component/usageAllowance/reservations.ts +220 -0
  241. package/src/component/usageAllowance/schema.ts +36 -0
  242. package/src/component/usageCredits/accounting.test.ts +389 -0
  243. package/src/component/usageCredits/helpers.ts +160 -0
  244. package/src/component/usageCredits/mutations.ts +451 -0
  245. package/src/component/usageCredits/purchase.ts +219 -0
  246. package/src/component/usageCredits/queries.ts +300 -0
  247. package/src/component/usageCredits/reservations.ts +214 -0
  248. package/src/component/usageCredits/schema.ts +106 -0
@@ -0,0 +1,304 @@
1
+ import { verifyNativeCreditCapacity } from "./creditCapacity.js";
2
+ import type Stripe from "stripe";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import { runMutationOrThrow } from "../helpers.js";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+ import type { Doc } from "../../component/_generated/dataModel.js";
7
+ import {
8
+ creditPurchaseTerms,
9
+ UsageCreditRecoveryError,
10
+ type UsageCreditPurchaseOptions,
11
+ type UsageCreditPurchase,
12
+ type UsageCreditPurchaseTerms,
13
+ } from "./creditTerms.js";
14
+ import { grantCreditProof } from "./creditProofs.js";
15
+ import {
16
+ creditCall,
17
+ creditCreateWindow,
18
+ creditRequire,
19
+ discoverCredit,
20
+ paymentIdentity,
21
+ verifiedCreditPayment,
22
+ verifyCreditRealm,
23
+ } from "./creditNative.js";
24
+ import {
25
+ subscriptionTerms,
26
+ subscriptionView,
27
+ subscriptionEvidence,
28
+ } from "./subscriptionTerms.js";
29
+ export function creditPurchaseView(
30
+ row: Doc<"usageCreditPurchases">,
31
+ ): UsageCreditPurchase {
32
+ const terms = creditPurchaseTerms(JSON.parse(row.termsJson));
33
+ return {
34
+ purchaseId: terms.purchaseId,
35
+ state: row.state,
36
+ paymentIntentId: row.paymentIntentId ?? null,
37
+ creditGrantId: row.creditGrantId ?? null,
38
+ quantity: terms.quantity,
39
+ amount: terms.amount,
40
+ currency: terms.binding.plan.rate.currency,
41
+ };
42
+ }
43
+ const mutation = <T>(
44
+ component: Component,
45
+ ctx: RunCtx,
46
+ name: string,
47
+ args: Record<string, unknown>,
48
+ ) =>
49
+ runMutationOrThrow(
50
+ ctx,
51
+ componentRef(component, "usageCredits/mutations/" + name),
52
+ args,
53
+ ) as Promise<T>;
54
+ async function prepared(
55
+ component: Component,
56
+ ctx: RunCtx,
57
+ input: UsageCreditPurchaseOptions,
58
+ ) {
59
+ const terms = creditPurchaseTerms(input);
60
+ const row = await mutation<Doc<"usageCreditPurchases">>(
61
+ component,
62
+ ctx,
63
+ "preparePurchase",
64
+ { inputJson: JSON.stringify(input) },
65
+ );
66
+ return { row, terms };
67
+ }
68
+ async function latest(component: Component, ctx: RunCtx, key: string) {
69
+ const row = (await ctx.runQuery(
70
+ componentRef(component, "usageCredits/queries/getByKey"),
71
+ { key },
72
+ )) as Doc<"usageCreditPurchases"> | null;
73
+ creditRequire(row, "Credit purchase unavailable");
74
+ return row;
75
+ }
76
+ async function originalPayment(
77
+ stripe: Stripe,
78
+ component: Component,
79
+ ctx: RunCtx,
80
+ row: Doc<"usageCreditPurchases">,
81
+ terms: UsageCreditPurchaseTerms,
82
+ allowCreate: boolean,
83
+ ) {
84
+ let payment: Stripe.PaymentIntent | null = row.paymentIntentId
85
+ ? await stripe.paymentIntents.retrieve(row.paymentIntentId, {
86
+ expand: ["latest_charge"],
87
+ })
88
+ : await discoverCredit(row.key, (cursor) =>
89
+ stripe.paymentIntents.list({
90
+ customer_account: terms.scope.customerAccount,
91
+ limit: 100,
92
+ ...(cursor ? { starting_after: cursor } : {}),
93
+ }),
94
+ );
95
+ if (!payment && allowCreate) {
96
+ creditCreateWindow(row.firstAttemptAt);
97
+ const intent = (await ctx.runQuery(
98
+ componentRef(component, "usageCredits/queries/context"),
99
+ {
100
+ bindingJson: JSON.stringify({
101
+ scope: terms.scope,
102
+ binding: terms.binding,
103
+ }),
104
+ },
105
+ )) as Doc<"usageSubscriptionIntents">;
106
+ const native = await stripe.subscriptions.retrieve(intent.providerId!);
107
+ creditRequire(
108
+ native.id === intent.providerId,
109
+ "Native prepaid enrollment identity mismatch",
110
+ );
111
+ const view = subscriptionView(
112
+ subscriptionEvidence(native),
113
+ subscriptionTerms(JSON.parse(intent.termsJson)),
114
+ );
115
+ creditRequire(
116
+ view.status === "active" && view.collection.method === "send_invoice",
117
+ "Unsupported prepaid collection policy",
118
+ );
119
+ const pending = (await ctx.runQuery(
120
+ componentRef(component, "usageCredits/queries/capacity"),
121
+ {
122
+ bindingJson: JSON.stringify({
123
+ scope: terms.scope,
124
+ binding: terms.binding,
125
+ }),
126
+ },
127
+ )) as number;
128
+ await verifyNativeCreditCapacity(stripe, terms, pending);
129
+ await mutation(component, ctx, "markPaymentAttempt", { key: row.key });
130
+ payment = await stripe.paymentIntents.create(
131
+ {
132
+ customer_account: terms.scope.customerAccount,
133
+ amount: terms.amount,
134
+ currency: terms.binding.plan.rate.currency,
135
+ allowed_payment_method_types: ["card"],
136
+ metadata: { bsUsageCredit: row.key },
137
+ },
138
+ { idempotencyKey: "bs_usage_credit_payment_" + row.key },
139
+ );
140
+ }
141
+ if (!payment) return null;
142
+ paymentIdentity(payment, terms, row.key, row.paymentIntentId);
143
+ await mutation(component, ctx, "pinPayment", {
144
+ key: row.key,
145
+ paymentIntentId: payment.id,
146
+ });
147
+ // Discovery/list returns unexpanded charges. The original pinned ID is always re-read.
148
+ const observed = await stripe.paymentIntents.retrieve(payment.id, {
149
+ expand: ["latest_charge"],
150
+ });
151
+ paymentIdentity(observed, terms, row.key, payment.id);
152
+ return observed;
153
+ }
154
+ export async function ensureCreditPurchase(
155
+ stripe: Stripe,
156
+ component: Component,
157
+ ctx: RunCtx,
158
+ input: UsageCreditPurchaseOptions,
159
+ ) {
160
+ return creditCall(async () => {
161
+ const { row, terms } = await prepared(component, ctx, input);
162
+ await verifyCreditRealm(stripe, terms);
163
+ const payment = await originalPayment(
164
+ stripe,
165
+ component,
166
+ ctx,
167
+ row,
168
+ terms,
169
+ true,
170
+ );
171
+ creditRequire(payment, "Credit payment identity unavailable");
172
+ return {
173
+ purchase: creditPurchaseView(await latest(component, ctx, row.key)),
174
+ clientSecret: [
175
+ "requires_payment_method",
176
+ "requires_confirmation",
177
+ "requires_action",
178
+ ].includes(payment.status)
179
+ ? payment.client_secret
180
+ : null,
181
+ };
182
+ });
183
+ }
184
+ function grantProof(
185
+ grant: Stripe.Billing.CreditGrant,
186
+ terms: UsageCreditPurchaseTerms,
187
+ key: string,
188
+ payment: NonNullable<ReturnType<typeof verifiedCreditPayment>>,
189
+ ) {
190
+ const prices = grant.applicability_config.scope.prices;
191
+ creditRequire(
192
+ grant.object === "billing.credit_grant" &&
193
+ grant.customer_account === terms.scope.customerAccount &&
194
+ grant.livemode === terms.scope.livemode &&
195
+ grant.metadata?.bsUsageCredit === key &&
196
+ grant.category === "paid" &&
197
+ grant.amount.type === "monetary" &&
198
+ grant.amount.monetary?.value === terms.amount &&
199
+ grant.amount.monetary.currency === terms.binding.plan.rate.currency &&
200
+ !grant.voided_at &&
201
+ !grant.applicability_config.scope.price_type &&
202
+ prices?.length === 1 &&
203
+ prices[0].id === terms.binding.stripePriceId &&
204
+ grant.expires_at === (terms.expiresAt ?? null) &&
205
+ grant.priority === 50,
206
+ "Native credit grant provenance mismatch",
207
+ );
208
+ return grantCreditProof.parse({
209
+ ...payment,
210
+ creditGrantId: grant.id,
211
+ stripePriceId: terms.binding.stripePriceId,
212
+ createdAt: grant.created,
213
+ effectiveAt: grant.effective_at,
214
+ expiresAt: grant.expires_at,
215
+ });
216
+ }
217
+ export async function observeCreditPurchase(
218
+ stripe: Stripe,
219
+ component: Component,
220
+ ctx: RunCtx,
221
+ input: UsageCreditPurchaseOptions,
222
+ ) {
223
+ return creditCall(async () => {
224
+ const { row, terms } = await prepared(component, ctx, input);
225
+ await verifyCreditRealm(stripe, terms, false);
226
+ const payment = await originalPayment(
227
+ stripe,
228
+ component,
229
+ ctx,
230
+ row,
231
+ terms,
232
+ false,
233
+ );
234
+ if (!payment) return creditPurchaseView(row);
235
+ let proof;
236
+ try {
237
+ proof = verifiedCreditPayment(payment, terms);
238
+ } catch (error) {
239
+ if (error instanceof UsageCreditRecoveryError) {
240
+ await mutation(component, ctx, "freezePurchase", {
241
+ key: row.key,
242
+ paymentIntentId: payment.id,
243
+ reason: error.reason,
244
+ refundedAmount:
245
+ typeof payment.latest_charge === "object"
246
+ ? payment.latest_charge?.amount_refunded
247
+ : undefined,
248
+ });
249
+ }
250
+ throw error;
251
+ }
252
+ if (!proof)
253
+ return creditPurchaseView(await latest(component, ctx, row.key));
254
+ await mutation(component, ctx, "verifyPayment", {
255
+ key: row.key,
256
+ proofJson: JSON.stringify(proof),
257
+ });
258
+ let grant = row.creditGrantId
259
+ ? await stripe.billing.creditGrants.retrieve(row.creditGrantId)
260
+ : await discoverCredit(row.key, (cursor) =>
261
+ stripe.billing.creditGrants.list({
262
+ customer_account: terms.scope.customerAccount,
263
+ limit: 100,
264
+ ...(cursor ? { starting_after: cursor } : {}),
265
+ }),
266
+ );
267
+ if (!grant) {
268
+ const grantIntent = await latest(component, ctx, row.key);
269
+ creditCreateWindow(grantIntent.grantFirstAttemptAt!);
270
+ grant = await stripe.billing.creditGrants.create(
271
+ {
272
+ customer_account: terms.scope.customerAccount,
273
+ category: "paid",
274
+ priority: 50,
275
+ amount: {
276
+ type: "monetary",
277
+ monetary: {
278
+ currency: terms.binding.plan.rate.currency,
279
+ value: terms.amount,
280
+ },
281
+ },
282
+ applicability_config: {
283
+ scope: { prices: [{ id: terms.binding.stripePriceId }] },
284
+ },
285
+ metadata: { bsUsageCredit: row.key },
286
+ ...(terms.expiresAt === undefined
287
+ ? {}
288
+ : { expires_at: terms.expiresAt }),
289
+ },
290
+ { idempotencyKey: "bs_usage_credit_grant_" + row.key },
291
+ );
292
+ }
293
+ creditRequire(
294
+ !row.creditGrantId || grant.id === row.creditGrantId,
295
+ "Native credit grant identity mismatch",
296
+ );
297
+ const nativeProof = grantProof(grant, terms, row.key, proof);
298
+ await mutation(component, ctx, "pinGrant", {
299
+ key: row.key,
300
+ proofJson: JSON.stringify(nativeProof),
301
+ });
302
+ return creditPurchaseView(await latest(component, ctx, row.key));
303
+ });
304
+ }
@@ -0,0 +1,32 @@
1
+ import type { Component, RunCtx } from "../helpers.js";
2
+ import type { Doc } from "../../component/_generated/dataModel.js";
3
+ import { componentRef } from "../webhooks/helpers.js";
4
+ import {
5
+ creditPurchaseTerms,
6
+ type UsageCreditPurchaseOptions,
7
+ } from "./creditTerms.js";
8
+ import { creditRequire } from "./creditNative.js";
9
+ export async function findCreditPurchase(
10
+ component: Component,
11
+ ctx: RunCtx,
12
+ input: UsageCreditPurchaseOptions,
13
+ ) {
14
+ const terms = creditPurchaseTerms(input);
15
+ const row = (await ctx.runQuery(
16
+ componentRef(component, "usageCredits/queries/getPurchase"),
17
+ {
18
+ bindingJson: JSON.stringify({
19
+ scope: terms.scope,
20
+ binding: terms.binding,
21
+ }),
22
+ purchaseId: terms.purchaseId,
23
+ },
24
+ )) as Doc<"usageCreditPurchases"> | null;
25
+ creditRequire(row, "Credit purchase unavailable");
26
+ const retained = creditPurchaseTerms(JSON.parse(row.termsJson));
27
+ creditRequire(
28
+ JSON.stringify(retained) === JSON.stringify(terms),
29
+ "Original credit purchase terms conflict",
30
+ );
31
+ return { row, terms };
32
+ }
@@ -0,0 +1,213 @@
1
+ import { findCreditPurchase } from "./creditRead.js";
2
+ import type Stripe from "stripe";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import { runMutationOrThrow } from "../helpers.js";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+ import type { Doc } from "../../component/_generated/dataModel.js";
7
+ import {
8
+ creditPurchaseTerms,
9
+ UsageCreditRecoveryError,
10
+ type UsageCreditPurchaseOptions,
11
+ } from "./creditTerms.js";
12
+ import {
13
+ creditCall,
14
+ creditRequire,
15
+ verifyCreditRealm,
16
+ paymentIdentity,
17
+ verifiedCreditPayment,
18
+ } from "./creditNative.js";
19
+ import { observeCreditPurchase } from "./creditProvider.js";
20
+ import { verifyCreditInvoice } from "./creditInvoice.js";
21
+ import { creditNativeObservation } from "./creditProofs.js";
22
+ import type { UsageCreditReconciliation } from "./creditObservation.js";
23
+ const id = (v: string | { id: string } | null | undefined) =>
24
+ typeof v === "string" ? v : v?.id;
25
+ export async function reconcileCreditPurchase(
26
+ stripe: Stripe,
27
+ component: Component,
28
+ ctx: RunCtx,
29
+ input: UsageCreditPurchaseOptions,
30
+ ) {
31
+ return creditCall(async () => {
32
+ const terms = creditPurchaseTerms(input),
33
+ startedAt = Date.now();
34
+ let source = await findCreditPurchase(component, ctx, input);
35
+ if (!source.row.creditGrantId) {
36
+ await observeCreditPurchase(stripe, component, ctx, input);
37
+ source = await findCreditPurchase(component, ctx, input);
38
+ }
39
+ const purchase = source.row;
40
+ if (!purchase.creditGrantId || !purchase.paymentIntentId)
41
+ return {
42
+ status: "unavailable" as const,
43
+ reason: "credit_purchase_not_ready",
44
+ retryable: true,
45
+ };
46
+ await verifyCreditRealm(stripe, terms, false);
47
+ const payment = await stripe.paymentIntents.retrieve(
48
+ purchase.paymentIntentId,
49
+ { expand: ["latest_charge"] },
50
+ );
51
+ paymentIdentity(payment, terms, purchase.key, purchase.paymentIntentId);
52
+ try {
53
+ creditRequire(
54
+ verifiedCreditPayment(payment, terms),
55
+ "Original credit payment not successful",
56
+ );
57
+ } catch (error) {
58
+ if (!(error instanceof UsageCreditRecoveryError)) throw error;
59
+ await runMutationOrThrow(
60
+ ctx,
61
+ componentRef(component, "usageCredits/mutations/freezePurchase"),
62
+ {
63
+ key: purchase.key,
64
+ paymentIntentId: purchase.paymentIntentId,
65
+ reason: error.reason,
66
+ refundedAmount:
67
+ typeof payment.latest_charge === "object"
68
+ ? payment.latest_charge?.amount_refunded
69
+ : undefined,
70
+ },
71
+ );
72
+ }
73
+ const nativeGrant = await stripe.billing.creditGrants.retrieve(
74
+ purchase.creditGrantId,
75
+ );
76
+ creditRequire(
77
+ nativeGrant.id === purchase.creditGrantId &&
78
+ nativeGrant.customer_account === terms.scope.customerAccount &&
79
+ nativeGrant.livemode === terms.scope.livemode &&
80
+ nativeGrant.metadata?.bsUsageCredit === purchase.key &&
81
+ nativeGrant.amount.monetary?.value === terms.amount &&
82
+ nativeGrant.amount.monetary.currency ===
83
+ terms.binding.plan.rate.currency &&
84
+ nativeGrant.applicability_config.scope.prices?.length === 1 &&
85
+ nativeGrant.applicability_config.scope.prices[0].id ===
86
+ terms.binding.stripePriceId,
87
+ "Original native credit grant identity mismatch",
88
+ );
89
+ const [summary, transactions] = await Promise.all([
90
+ stripe.billing.creditBalanceSummaries.retrieve({
91
+ customer_account: terms.scope.customerAccount,
92
+ filter: { type: "credit_grant", credit_grant: purchase.creditGrantId },
93
+ }),
94
+ stripe.billing.creditBalanceTransactions.list({
95
+ customer_account: terms.scope.customerAccount,
96
+ credit_grant: purchase.creditGrantId,
97
+ limit: 100,
98
+ }),
99
+ ]);
100
+ creditRequire(
101
+ summary.livemode === terms.scope.livemode &&
102
+ summary.customer_account === terms.scope.customerAccount &&
103
+ id(summary.customer) === terms.binding.stripeCustomerId &&
104
+ summary.balances.length === 1,
105
+ "Native credit summary scope mismatch",
106
+ );
107
+ const row = summary.balances[0],
108
+ ledger = row.ledger_balance.monetary,
109
+ available = row.available_balance.monetary;
110
+ creditRequire(
111
+ ledger &&
112
+ available &&
113
+ ledger.currency === terms.binding.plan.rate.currency &&
114
+ available.currency === ledger.currency,
115
+ "Native credit summary currency mismatch",
116
+ );
117
+ let granted = 0,
118
+ applied = 0,
119
+ expired = 0,
120
+ voided = 0,
121
+ reinstated = 0;
122
+ let invoicesVerified = true;
123
+ const normalized = [];
124
+ const invoiceProofBudget =
125
+ transactions.data.filter((t) => t.debit?.type === "credits_applied")
126
+ .length <= 10;
127
+ for (const tx of transactions.data) {
128
+ creditRequire(
129
+ id(tx.credit_grant) === purchase.creditGrantId &&
130
+ tx.livemode === terms.scope.livemode &&
131
+ tx.object === "billing.credit_balance_transaction",
132
+ "Native credit transaction identity mismatch",
133
+ );
134
+ const entry =
135
+ tx.type === "credit"
136
+ ? tx.credit
137
+ : tx.type === "debit"
138
+ ? tx.debit
139
+ : null;
140
+ const amount = entry?.amount.monetary;
141
+ creditRequire(
142
+ entry &&
143
+ amount &&
144
+ amount.currency === ledger.currency &&
145
+ Number.isSafeInteger(amount.value) &&
146
+ amount.value >= 0,
147
+ "Native credit transaction amount unsupported",
148
+ );
149
+ const kind = entry.type;
150
+ let invoiceId: string | null = null,
151
+ invoiceLineId: string | null = null;
152
+ if (kind === "credits_granted") granted += amount.value;
153
+ else if (kind === "credits_applied") {
154
+ applied += amount.value;
155
+ invoiceId = id(tx.debit?.credits_applied?.invoice) ?? null;
156
+ invoiceLineId = tx.debit?.credits_applied?.invoice_line_item ?? null;
157
+ if (
158
+ !invoiceProofBudget ||
159
+ !(await verifyCreditInvoice(stripe, component, ctx, terms, tx))
160
+ )
161
+ invoicesVerified = false;
162
+ } else if (kind === "credits_expired") expired += amount.value;
163
+ else if (kind === "credits_voided") voided += amount.value;
164
+ else if (kind === "credits_application_invoice_voided") {
165
+ reinstated += amount.value;
166
+ invoicesVerified = false;
167
+ invoiceId =
168
+ id(tx.credit?.credits_application_invoice_voided?.invoice) ?? null;
169
+ invoiceLineId =
170
+ tx.credit?.credits_application_invoice_voided?.invoice_line_item ??
171
+ null;
172
+ } else creditRequire(false, "Unsupported native credit transaction type");
173
+ normalized.push({
174
+ id: tx.id,
175
+ kind,
176
+ amount: amount.value,
177
+ invoiceId,
178
+ invoiceLineId,
179
+ });
180
+ }
181
+ const proof = creditNativeObservation.parse({
182
+ creditGrantId: purchase.creditGrantId,
183
+ paymentIntentId: purchase.paymentIntentId,
184
+ currency: ledger.currency,
185
+ ledgerAmount: ledger.value,
186
+ availableAmount: available.value,
187
+ granted,
188
+ applied,
189
+ expired,
190
+ voided,
191
+ reinstated,
192
+ invoicesVerified,
193
+ complete: !transactions.has_more,
194
+ transactions: normalized,
195
+ });
196
+ const resultJson = (await runMutationOrThrow(
197
+ ctx,
198
+ componentRef(component, "usageCredits/mutations/saveObservation"),
199
+ {
200
+ inputJson: JSON.stringify(input),
201
+ proofJson: JSON.stringify(proof),
202
+ startedAt,
203
+ },
204
+ )) as string;
205
+ const result = JSON.parse(resultJson) as UsageCreditReconciliation;
206
+ return {
207
+ status: "available" as const,
208
+ observedAt: Math.floor(startedAt / 1000),
209
+ value: result,
210
+ };
211
+ });
212
+ }
213
+ export type CreditPurchaseDocument = Doc<"usageCreditPurchases">;
@@ -0,0 +1,48 @@
1
+ import { expect, it } from "vitest";
2
+ import { creditPurchaseTerms, creditCost } from "./creditTerms.js";
3
+ import { meter } from "./subscription.fixtures.js";
4
+ const input = {
5
+ ...meter,
6
+ binding: {
7
+ ...meter.binding,
8
+ plan: {
9
+ key: "calls",
10
+ version: "v1",
11
+ model: "prepaid",
12
+ unit: { name: "call", precision: 0 },
13
+ rate: { currency: "usd", unitAmountDecimal: "2" },
14
+ insufficientBalance: "reject",
15
+ },
16
+ },
17
+ purchaseId: "topup1",
18
+ quantity: "50",
19
+ ownership: "issuer",
20
+ rollover: "retain_original_terms",
21
+ };
22
+ it("pins original prepaid unit/payment terms and computes exact integer backing", () => {
23
+ const terms = creditPurchaseTerms(input);
24
+ expect(terms.amount).toBe(100);
25
+ expect(creditCost(terms.binding.plan, "15")).toBe(30);
26
+ });
27
+ it("rejects third-party wallets, fractional monetary backing and invalid quantities", () => {
28
+ expect(() =>
29
+ creditPurchaseTerms({ ...input, ownership: "seller" }),
30
+ ).toThrow();
31
+ expect(() => creditPurchaseTerms({ ...input, quantity: "0" })).toThrow();
32
+ expect(() =>
33
+ creditPurchaseTerms({
34
+ ...input,
35
+ binding: {
36
+ ...input.binding,
37
+ plan: {
38
+ ...input.binding.plan,
39
+ rate: { currency: "usd", unitAmountDecimal: "0.1" },
40
+ },
41
+ },
42
+ quantity: "1",
43
+ }),
44
+ ).toThrow(/whole minor/i);
45
+ expect(() =>
46
+ creditPurchaseTerms({ ...input, quantity: "50000000" }),
47
+ ).toThrow();
48
+ });