@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,389 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { afterEach, expect, it, vi } from "vitest";
4
+ import { schema, modules } from "../../test.js";
5
+ import {
6
+ request,
7
+ nativeSubscription,
8
+ } from "../../client/usage/subscription.fixtures.js";
9
+ const ref = (name: string) =>
10
+ makeFunctionReference<"mutation">(`usageCredits/mutations:${name}`);
11
+ const prepare = makeFunctionReference<"mutation">(
12
+ "usageSubscriptions/mutations:prepare",
13
+ );
14
+ const save = makeFunctionReference<"mutation">(
15
+ "usageSubscriptions/mutations:save",
16
+ );
17
+ const record = makeFunctionReference<"mutation">("usage/mutations:record");
18
+ const balance = makeFunctionReference<"query">("usageCredits/queries:balance");
19
+ export async function setupCredits() {
20
+ vi.useFakeTimers();
21
+ vi.setSystemTime(700000);
22
+ const t = convexTest(schema, modules);
23
+ const meter = {
24
+ scope: request.meters[0].scope,
25
+ binding: {
26
+ ...request.meters[0].binding,
27
+ plan: {
28
+ key: "calls",
29
+ version: "v1",
30
+ model: "prepaid",
31
+ unit: { name: "call", precision: 0 },
32
+ rate: { currency: "usd", unitAmountDecimal: "2" },
33
+ insufficientBalance: "reject",
34
+ } as const,
35
+ },
36
+ };
37
+ const terms = { ...request, meters: [meter] };
38
+ const intent = await t.mutation(prepare, {
39
+ termsJson: JSON.stringify(terms),
40
+ method: "direct",
41
+ });
42
+ await t.mutation(save, {
43
+ key: intent.key,
44
+ nativeJson: JSON.stringify(nativeSubscription()),
45
+ startedAt: Date.now(),
46
+ });
47
+ const purchase = {
48
+ ...meter,
49
+ purchaseId: "topup1",
50
+ quantity: "10",
51
+ ownership: "issuer",
52
+ rollover: "retain_original_terms",
53
+ };
54
+ const row = await t.mutation(ref("preparePurchase"), {
55
+ inputJson: JSON.stringify(purchase),
56
+ });
57
+ await t.mutation(ref("pinPayment"), {
58
+ key: row.key,
59
+ paymentIntentId: "pi_topup1",
60
+ });
61
+ const proof = {
62
+ paymentIntentId: "pi_topup1",
63
+ chargeId: "ch_topup1",
64
+ amount: 20,
65
+ currency: "usd",
66
+ customerAccount: "acct_buyer",
67
+ livemode: false,
68
+ };
69
+ await t.mutation(ref("verifyPayment"), {
70
+ key: row.key,
71
+ proofJson: JSON.stringify(proof),
72
+ });
73
+ await t.mutation(ref("pinGrant"), {
74
+ key: row.key,
75
+ proofJson: JSON.stringify({
76
+ ...proof,
77
+ creditGrantId: "credgr_topup1",
78
+ stripePriceId: "price_calls",
79
+ createdAt: 700,
80
+ effectiveAt: 700,
81
+ expiresAt: null,
82
+ }),
83
+ });
84
+ const subscription = {
85
+ subscriptionId: "sub_calls",
86
+ subscriptionItemId: "si_calls",
87
+ stripePriceId: "price_calls",
88
+ period: { start: 600, end: 1200 },
89
+ interval: "month",
90
+ };
91
+ const event = {
92
+ ...meter,
93
+ sourceEventId: "work1",
94
+ quantity: "6",
95
+ occurredAt: 700,
96
+ };
97
+ return { t, meter, purchase, row, proof, subscription, event };
98
+ }
99
+ afterEach(() => vi.useRealTimers());
100
+ it("atomically reserves payment-backed units, commits with ledger acceptance and rejects concurrent overspend", async () => {
101
+ const { t, meter, event, subscription } = await setupCredits();
102
+ const args = {
103
+ inputJson: JSON.stringify(event),
104
+ subscriptionJson: JSON.stringify(subscription),
105
+ };
106
+ const first = await t.mutation(ref("reserve"), args);
107
+ expect(await t.mutation(ref("reserve"), args)).toEqual(first);
108
+ await expect(
109
+ t.mutation(ref("reserve"), {
110
+ ...args,
111
+ inputJson: JSON.stringify({ ...event, sourceEventId: "work2" }),
112
+ }),
113
+ ).rejects.toThrow(/insufficient/i);
114
+ expect(
115
+ await t.query(balance, { bindingJson: JSON.stringify(meter) }),
116
+ ).toMatchObject({
117
+ availableQuantity: "4",
118
+ reservedQuantity: "6",
119
+ consumedQuantity: "0",
120
+ });
121
+ const receipt = await t.mutation(record, {
122
+ ...args,
123
+ reservationId: first.reservationId,
124
+ });
125
+ expect(
126
+ await t.mutation(record, { ...args, reservationId: first.reservationId }),
127
+ ).toEqual(receipt);
128
+ expect(
129
+ await t.query(balance, { bindingJson: JSON.stringify(meter) }),
130
+ ).toMatchObject({
131
+ availableQuantity: "4",
132
+ reservedQuantity: "0",
133
+ consumedQuantity: "6",
134
+ cashCollection: "none",
135
+ });
136
+ await expect(
137
+ t.mutation(ref("release"), {
138
+ scope: meter.scope,
139
+ reservationId: first.reservationId,
140
+ reason: "work_failed",
141
+ }),
142
+ ).rejects.toThrow(/committed/i);
143
+ });
144
+ it("releases only uncommitted work and rejects changed reservation provenance", async () => {
145
+ const { t, meter, event, subscription } = await setupCredits();
146
+ const args = {
147
+ inputJson: JSON.stringify(event),
148
+ subscriptionJson: JSON.stringify(subscription),
149
+ };
150
+ const first = await t.mutation(ref("reserve"), args);
151
+ await expect(
152
+ t.mutation(record, {
153
+ ...args,
154
+ inputJson: JSON.stringify({ ...event, occurredAt: 701 }),
155
+ reservationId: first.reservationId,
156
+ }),
157
+ ).rejects.toThrow(/reservation/i);
158
+ await expect(
159
+ t.mutation(ref("reserve"), {
160
+ ...args,
161
+ inputJson: JSON.stringify({ ...event, quantity: "5" }),
162
+ }),
163
+ ).rejects.toThrow(/conflict/i);
164
+ await t.mutation(ref("release"), {
165
+ scope: meter.scope,
166
+ reservationId: first.reservationId,
167
+ reason: "abandoned_before_work",
168
+ });
169
+ await t.mutation(ref("release"), {
170
+ scope: meter.scope,
171
+ reservationId: first.reservationId,
172
+ reason: "abandoned_before_work",
173
+ });
174
+ expect(
175
+ await t.query(balance, { bindingJson: JSON.stringify(meter) }),
176
+ ).toMatchObject({ availableQuantity: "10", reservedQuantity: "0" });
177
+ expect((await t.mutation(ref("reserve"), args)).state).toBe("released");
178
+ });
179
+ it("never accepts unpaid grants, reuses original purchase identities and prevents duplicate payment backing", async () => {
180
+ const { t, purchase, row, proof } = await setupCredits();
181
+ expect(
182
+ (
183
+ await t.mutation(ref("preparePurchase"), {
184
+ inputJson: JSON.stringify(purchase),
185
+ })
186
+ ).key,
187
+ ).toBe(row.key);
188
+ await expect(
189
+ t.mutation(ref("preparePurchase"), {
190
+ inputJson: JSON.stringify({ ...purchase, quantity: "11" }),
191
+ }),
192
+ ).rejects.toThrow(/conflict/i);
193
+ const other = await t.mutation(ref("preparePurchase"), {
194
+ inputJson: JSON.stringify({ ...purchase, purchaseId: "topup2" }),
195
+ });
196
+ await expect(
197
+ t.mutation(ref("pinGrant"), {
198
+ key: other.key,
199
+ proofJson: JSON.stringify({
200
+ ...proof,
201
+ creditGrantId: "credgr_other",
202
+ stripePriceId: "price_calls",
203
+ createdAt: 700,
204
+ effectiveAt: 700,
205
+ expiresAt: null,
206
+ }),
207
+ }),
208
+ ).rejects.toThrow(/payment/i);
209
+ await expect(
210
+ t.mutation(ref("pinPayment"), {
211
+ key: other.key,
212
+ paymentIntentId: "pi_topup1",
213
+ }),
214
+ ).rejects.toThrow(/payment/i);
215
+ });
216
+
217
+ it("holds consumption after refund/dispute evidence without releasing committed or reserved backing", async () => {
218
+ const { t, meter, event, subscription, row } = await setupCredits();
219
+ const args = {
220
+ inputJson: JSON.stringify(event),
221
+ subscriptionJson: JSON.stringify(subscription),
222
+ };
223
+ const reservation = await t.mutation(ref("reserve"), args);
224
+ await t.mutation(ref("freezePurchase"), {
225
+ key: row.key,
226
+ paymentIntentId: "pi_topup1",
227
+ reason: "payment_refunded",
228
+ });
229
+ await expect(
230
+ t.mutation(record, { ...args, reservationId: reservation.reservationId }),
231
+ ).rejects.toThrow(/reconciliation|backing/i);
232
+ expect(
233
+ await t.query(balance, { bindingJson: JSON.stringify(meter) }),
234
+ ).toMatchObject({
235
+ status: "held",
236
+ availableQuantity: "0",
237
+ reservedQuantity: "6",
238
+ consumedQuantity: "0",
239
+ });
240
+ expect(
241
+ await t.run((ctx) => ctx.db.query("usageEvents").collect()),
242
+ ).toHaveLength(0);
243
+ });
244
+ it("cannot spend the same last units from two concurrent work requests", async () => {
245
+ const { t, meter, event, subscription } = await setupCredits();
246
+ const results = await Promise.allSettled(
247
+ ["left", "right"].map((sourceEventId) =>
248
+ t.mutation(ref("reserve"), {
249
+ inputJson: JSON.stringify({ ...event, sourceEventId }),
250
+ subscriptionJson: JSON.stringify(subscription),
251
+ }),
252
+ ),
253
+ );
254
+ expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1);
255
+ expect(
256
+ await t.query(balance, { bindingJson: JSON.stringify(meter) }),
257
+ ).toMatchObject({ availableQuantity: "4", reservedQuantity: "6" });
258
+ });
259
+
260
+ it("retains expired units as provenance and closes only fully reconciled credit accounts", async () => {
261
+ const { t, meter, purchase } = await setupCredits();
262
+ await expect(
263
+ t.mutation(ref("closeAccount"), { bindingJson: JSON.stringify(meter) }),
264
+ ).rejects.toThrow(/reconcil|credit/i);
265
+ await t.mutation(ref("saveObservation"), {
266
+ inputJson: JSON.stringify(purchase),
267
+ startedAt: Date.now(),
268
+ proofJson: JSON.stringify({
269
+ creditGrantId: "credgr_topup1",
270
+ paymentIntentId: "pi_topup1",
271
+ currency: "usd",
272
+ ledgerAmount: 0,
273
+ availableAmount: 0,
274
+ granted: 20,
275
+ applied: 0,
276
+ expired: 20,
277
+ voided: 0,
278
+ reinstated: 0,
279
+ invoicesVerified: true,
280
+ complete: true,
281
+ transactions: [
282
+ {
283
+ id: "cbtxn_expire",
284
+ kind: "credits_expired",
285
+ amount: 20,
286
+ invoiceId: null,
287
+ invoiceLineId: null,
288
+ },
289
+ ],
290
+ }),
291
+ });
292
+ expect(
293
+ await t.query(balance, { bindingJson: JSON.stringify(meter) }),
294
+ ).toMatchObject({ availableQuantity: "0", expiredQuantity: "10" });
295
+ await expect(
296
+ t.mutation(ref("closeAccount"), { bindingJson: JSON.stringify(meter) }),
297
+ ).rejects.toThrow(/refund/i);
298
+ await t.mutation(ref("freezePurchase"), {
299
+ key: (
300
+ await t.mutation(ref("preparePurchase"), {
301
+ inputJson: JSON.stringify(purchase),
302
+ })
303
+ ).key,
304
+ paymentIntentId: "pi_topup1",
305
+ reason: "payment_refunded",
306
+ refundedAmount: 20,
307
+ });
308
+ await t.mutation(ref("closeAccount"), { bindingJson: JSON.stringify(meter) });
309
+ await expect(
310
+ t.mutation(ref("preparePurchase"), {
311
+ inputJson: JSON.stringify({ ...purchase, purchaseId: "afterclose" }),
312
+ }),
313
+ ).rejects.toThrow(/reconciliation|closed/i);
314
+ });
315
+
316
+ it("counts locally consumed but unfinalized native grants before accepting another purchase", async () => {
317
+ const { t, purchase } = await setupCredits();
318
+ await t.run(async (ctx) => {
319
+ const grant = (await ctx.db.query("usageCreditGrants").first())!;
320
+ const { _id, _creationTime, ...fields } = grant;
321
+ await ctx.db.patch("usageCreditGrants", _id, {
322
+ available: "0",
323
+ reserved: "0",
324
+ consumed: "10",
325
+ });
326
+ for (let index = 1; index < 100; index++)
327
+ await ctx.db.insert("usageCreditGrants", {
328
+ ...fields,
329
+ purchaseKey: "capacity" + index,
330
+ creditGrantId: "credgr_capacity" + index,
331
+ available: "0",
332
+ reserved: "0",
333
+ consumed: "10",
334
+ });
335
+ });
336
+ await expect(
337
+ t.mutation(ref("preparePurchase"), {
338
+ inputJson: JSON.stringify({ ...purchase, purchaseId: "over-native-cap" }),
339
+ }),
340
+ ).rejects.toThrow(/capacity|quota/i);
341
+ });
342
+
343
+ it("allocates by provider creation time when native grants are mirrored out of order", async () => {
344
+ const { t, purchase, event, subscription } = await setupCredits();
345
+ const row = await t.mutation(ref("preparePurchase"), {
346
+ inputJson: JSON.stringify({ ...purchase, purchaseId: "older-native" }),
347
+ });
348
+ const proof = {
349
+ paymentIntentId: "pi_older",
350
+ chargeId: "ch_older",
351
+ amount: 20,
352
+ currency: "usd",
353
+ customerAccount: "acct_buyer",
354
+ livemode: false,
355
+ };
356
+ await t.mutation(ref("pinPayment"), {
357
+ key: row.key,
358
+ paymentIntentId: proof.paymentIntentId,
359
+ });
360
+ await t.mutation(ref("verifyPayment"), {
361
+ key: row.key,
362
+ proofJson: JSON.stringify(proof),
363
+ });
364
+ await t.mutation(ref("pinGrant"), {
365
+ key: row.key,
366
+ proofJson: JSON.stringify({
367
+ ...proof,
368
+ creditGrantId: "credgr_older",
369
+ stripePriceId: "price_calls",
370
+ createdAt: 690,
371
+ effectiveAt: 700,
372
+ expiresAt: null,
373
+ }),
374
+ });
375
+ const reservation = await t.mutation(ref("reserve"), {
376
+ inputJson: JSON.stringify(event),
377
+ subscriptionJson: JSON.stringify(subscription),
378
+ });
379
+ const grants = await t.run((ctx) =>
380
+ ctx.db.query("usageCreditGrants").take(10),
381
+ );
382
+ expect(grants.find((g) => g.creditGrantId === "credgr_older")?.reserved).toBe(
383
+ "6",
384
+ );
385
+ expect(
386
+ grants.find((g) => g.creditGrantId === "credgr_topup1")?.reserved,
387
+ ).toBe("0");
388
+ expect(reservation.state).toBe("reserved");
389
+ });
@@ -0,0 +1,160 @@
1
+ import { convexToJson, type Value } from "convex/values";
2
+ import type { MutationCtx, QueryCtx } from "../_generated/server.js";
3
+ import type { Doc } from "../_generated/dataModel.js";
4
+ import { canonicalFingerprint } from "../operationEvidence/canonical.js";
5
+ import {
6
+ creditBinding,
7
+ creditPurchaseTerms,
8
+ type UsageCreditBinding,
9
+ } from "../../client/usage/creditTerms.js";
10
+ import { scopeKey } from "../usage/helpers.js";
11
+ import { jsonTerms } from "../usageSubscriptions/helpers.js";
12
+ import type { UsageSubscriptionView } from "../../client/usage/subscriptionTerms.js";
13
+ export function boundedJson(json: string, max = 8192) {
14
+ if (new TextEncoder().encode(json).length > max)
15
+ throw new Error("Credit payload exceeds size limit");
16
+ return JSON.parse(json) as unknown;
17
+ }
18
+ export async function accountTerms(input: UsageCreditBinding) {
19
+ const binding = creditBinding(input),
20
+ bindingJson = JSON.stringify(convexToJson(binding));
21
+ return {
22
+ binding,
23
+ bindingJson,
24
+ key: await canonicalFingerprint(binding),
25
+ scopeKey: scopeKey(binding.scope),
26
+ };
27
+ }
28
+ export async function purchaseTerms(json: string) {
29
+ const terms = creditPurchaseTerms(boundedJson(json));
30
+ const account = await accountTerms(terms);
31
+ const termsJson = JSON.stringify(
32
+ convexToJson({
33
+ scope: terms.scope,
34
+ binding: terms.binding,
35
+ purchaseId: terms.purchaseId,
36
+ quantity: terms.quantity,
37
+ ownership: terms.ownership,
38
+ rollover: terms.rollover,
39
+ ...(terms.expiresAt === undefined ? {} : { expiresAt: terms.expiresAt }),
40
+ }),
41
+ );
42
+ return {
43
+ terms,
44
+ termsJson,
45
+ account,
46
+ key: await canonicalFingerprint([account.key, terms.purchaseId]),
47
+ };
48
+ }
49
+ export async function purchase(ctx: QueryCtx, key: string) {
50
+ const row = await ctx.db
51
+ .query("usageCreditPurchases")
52
+ .withIndex("by_key", (q) => q.eq("key", key))
53
+ .unique();
54
+ if (!row) throw new Error("Credit purchase unavailable");
55
+ return row;
56
+ }
57
+ export async function account(ctx: QueryCtx, key: string) {
58
+ const row = await ctx.db
59
+ .query("usageCreditAccounts")
60
+ .withIndex("by_key", (q) => q.eq("key", key))
61
+ .unique();
62
+ if (!row) throw new Error("Credit account unavailable");
63
+ return row;
64
+ }
65
+ export async function grants(ctx: QueryCtx, key: string) {
66
+ const rows = await ctx.db
67
+ .query("usageCreditGrants")
68
+ .withIndex("by_account", (q) => q.eq("accountKey", key))
69
+ .take(1001);
70
+ if (rows.length > 1000)
71
+ throw new Error("Credit account retained grant quota exceeded");
72
+ return rows;
73
+ }
74
+ export async function activeEnrollment(
75
+ ctx: QueryCtx,
76
+ binding: ReturnType<typeof creditBinding>,
77
+ ) {
78
+ const { scope } = binding;
79
+ const lock = await ctx.db
80
+ .query("usageSubscriptionLocks")
81
+ .withIndex("by_key", (q) =>
82
+ q.eq(
83
+ "key",
84
+ JSON.stringify([
85
+ scope.stripeAccountId,
86
+ scope.livemode,
87
+ binding.binding.stripeCustomerId,
88
+ scope.meterId,
89
+ ]),
90
+ ),
91
+ )
92
+ .unique();
93
+ const intent =
94
+ lock &&
95
+ (await ctx.db
96
+ .query("usageSubscriptionIntents")
97
+ .withIndex("by_key", (q) => q.eq("key", lock.intentKey))
98
+ .unique());
99
+ if (!intent?.viewJson || intent.retiredAt !== undefined)
100
+ throw new Error("Active managed prepaid enrollment required");
101
+ const terms = jsonTerms(intent.termsJson).terms;
102
+ const match = terms.meters.find((m) => m.scope.meterId === scope.meterId);
103
+ if (
104
+ !match ||
105
+ JSON.stringify(convexToJson(match)) !==
106
+ JSON.stringify(convexToJson(binding))
107
+ )
108
+ throw new Error("Original prepaid enrollment terms mismatch");
109
+ const view = JSON.parse(intent.viewJson) as UsageSubscriptionView;
110
+ if (view.status !== "active" || view.collection.method !== "send_invoice")
111
+ throw new Error(
112
+ "Prepaid accounting requires active managed send-invoice collection",
113
+ );
114
+ const item = view.items.find(
115
+ (i) => i.stripePriceId === binding.binding.stripePriceId,
116
+ );
117
+ if (!item || Date.now() / 1000 >= item.period.end - 60)
118
+ throw new Error("Prepaid billing period is closing");
119
+ return { intent, view, item };
120
+ }
121
+ export async function history(
122
+ ctx: MutationCtx,
123
+ accountKey: string,
124
+ kind: Doc<"usageCreditHistory">["kind"],
125
+ sourceKey: string,
126
+ evidence: Value,
127
+ purchaseKey?: string,
128
+ ) {
129
+ const evidenceJson = JSON.stringify(convexToJson(evidence));
130
+ if (evidenceJson.length > 8192)
131
+ throw new Error("Credit history evidence exceeds size limit");
132
+ const fingerprint = await canonicalFingerprint([
133
+ accountKey,
134
+ kind,
135
+ sourceKey,
136
+ evidence,
137
+ ]);
138
+ if (
139
+ await ctx.db
140
+ .query("usageCreditHistory")
141
+ .withIndex("by_fingerprint", (q) => q.eq("fingerprint", fingerprint))
142
+ .unique()
143
+ )
144
+ return;
145
+ const row = await account(ctx, accountKey);
146
+ if (row.historyCount >= 100000)
147
+ throw new Error("Credit history retained quota exhausted");
148
+ await ctx.db.insert("usageCreditHistory", {
149
+ accountKey,
150
+ purchaseKey,
151
+ kind,
152
+ sourceKey,
153
+ fingerprint,
154
+ evidenceJson,
155
+ at: Math.floor(Date.now() / 1000),
156
+ });
157
+ await ctx.db.patch("usageCreditAccounts", row._id, {
158
+ historyCount: row.historyCount + 1,
159
+ });
160
+ }