@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,435 @@
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 mutation = (name: string) =>
10
+ makeFunctionReference<"mutation">(`usageAllowance/mutations:${name}`);
11
+ const status = makeFunctionReference<"query">("usageAllowance/queries:status");
12
+ const record = makeFunctionReference<"mutation">("usage/mutations:record");
13
+ const policy = {
14
+ reset: "billing_period",
15
+ rollover: "none",
16
+ entitled: true,
17
+ overage: "allow",
18
+ limit: { mode: "hard", quantity: "12" },
19
+ };
20
+ async function setup() {
21
+ vi.useFakeTimers();
22
+ vi.setSystemTime(700000);
23
+ const t = convexTest(schema, modules);
24
+ const meter = {
25
+ ...request.meters[0],
26
+ binding: {
27
+ ...request.meters[0].binding,
28
+ plan: {
29
+ key: "calls",
30
+ version: "v1",
31
+ model: "included_overage",
32
+ unit: { name: "call", precision: 0 },
33
+ rate: { currency: "usd", unitAmountDecimal: "2" },
34
+ includedQuantity: "10",
35
+ reset: "billing_period",
36
+ },
37
+ },
38
+ };
39
+ const intent = await t.mutation(
40
+ makeFunctionReference<"mutation">("usageSubscriptions/mutations:prepare"),
41
+ {
42
+ termsJson: JSON.stringify({ ...request, meters: [meter] }),
43
+ method: "direct",
44
+ },
45
+ );
46
+ await t.mutation(
47
+ makeFunctionReference<"mutation">("usageSubscriptions/mutations:save"),
48
+ {
49
+ key: intent.key,
50
+ nativeJson: JSON.stringify(nativeSubscription()),
51
+ startedAt: Date.now(),
52
+ },
53
+ );
54
+ const subscription = {
55
+ subscriptionId: "sub_calls",
56
+ subscriptionItemId: "si_calls",
57
+ stripePriceId: "price_calls",
58
+ period: { start: 600, end: 1200 },
59
+ interval: "month",
60
+ };
61
+ const bindingJson = JSON.stringify({ ...meter, subscription });
62
+ const event = {
63
+ ...meter,
64
+ sourceEventId: "work1",
65
+ quantity: "6",
66
+ occurredAt: 700,
67
+ };
68
+ const args = {
69
+ inputJson: JSON.stringify(event),
70
+ subscriptionJson: JSON.stringify(subscription),
71
+ };
72
+ const configure = (value = policy, expectedRevision = 0) =>
73
+ t.mutation(mutation("configure"), {
74
+ bindingJson,
75
+ policyJson: JSON.stringify(value),
76
+ expectedRevision,
77
+ });
78
+ return { t, meter, event, subscription, bindingJson, args, configure };
79
+ }
80
+ afterEach(() => vi.useRealTimers());
81
+ it("reserves a hard cap atomically and commits included usage and overage exactly once", async () => {
82
+ const { t, args, configure, bindingJson, event } = await setup();
83
+ expect(await configure()).toEqual({ revision: 1 });
84
+ const a = await t.mutation(mutation("reserve"), args);
85
+ expect(a.state).toBe("reserved");
86
+ expect(await t.mutation(mutation("reserve"), args)).toEqual(a);
87
+ const outcomes = await Promise.all(
88
+ ["work2", "work3"].map((sourceEventId) =>
89
+ t.mutation(mutation("reserve"), {
90
+ ...args,
91
+ inputJson: JSON.stringify({ ...event, sourceEventId }),
92
+ }),
93
+ ),
94
+ );
95
+ expect(outcomes.map((o) => o.state).sort()).toEqual(["denied", "reserved"]);
96
+ await expect(t.mutation(record, args)).rejects.toThrow(
97
+ /reservation required/i,
98
+ );
99
+ const receipt = await t.mutation(record, {
100
+ ...args,
101
+ reservationId: a.reservationId,
102
+ });
103
+ expect(
104
+ await t.mutation(record, { ...args, reservationId: a.reservationId }),
105
+ ).toEqual(receipt);
106
+ expect(JSON.parse(await t.query(status, { bindingJson }))).toMatchObject({
107
+ revision: 1,
108
+ consumedQuantity: "6",
109
+ reservedQuantity: "6",
110
+ remainingIncludedQuantity: "0",
111
+ billableOverageQuantity: "0",
112
+ committedEstimate: { amountDecimal: "0", currency: "usd" },
113
+ projectedEstimate: { amountDecimal: "4", currency: "usd" },
114
+ });
115
+ });
116
+ it("does not let retired native enrollment look accepting in a fresh status read", async () => {
117
+ const { t, bindingJson, configure } = await setup();
118
+ await configure();
119
+ await t.run(async (ctx) => {
120
+ const row = await ctx.db.query("usageSubscriptionIntents").first();
121
+ await ctx.db.patch("usageSubscriptionIntents", row!._id, {
122
+ retiredAt: 701,
123
+ });
124
+ });
125
+ expect(JSON.parse(await t.query(status, { bindingJson })).accepting).toBe(
126
+ false,
127
+ );
128
+ });
129
+ it("does not bypass a configured scope with a different native customer on an unmanaged subscription", async () => {
130
+ const { t, configure, event, subscription } = await setup();
131
+ await configure();
132
+ await expect(
133
+ t.mutation(record, {
134
+ inputJson: JSON.stringify({
135
+ ...event,
136
+ binding: { ...event.binding, stripeCustomerId: "cus_other" },
137
+ }),
138
+ subscriptionJson: JSON.stringify({
139
+ ...subscription,
140
+ subscriptionId: "sub_other",
141
+ }),
142
+ }),
143
+ ).rejects.toThrow(/allowance/i);
144
+ });
145
+ it("retains consumed and reserved units across cap changes and stale policy edits", async () => {
146
+ const { t, args, configure, bindingJson } = await setup();
147
+ await configure();
148
+ const a = await t.mutation(mutation("reserve"), args);
149
+ await t.mutation(record, { ...args, reservationId: a.reservationId });
150
+ expect(
151
+ await configure({ ...policy, limit: { mode: "hard", quantity: "4" } }, 1),
152
+ ).toEqual({ revision: 2 });
153
+ expect(JSON.parse(await t.query(status, { bindingJson }))).toMatchObject({
154
+ revision: 2,
155
+ consumedQuantity: "6",
156
+ hardLimitRemainingQuantity: "0",
157
+ accepting: false,
158
+ });
159
+ await expect(configure({ ...policy, entitled: false }, 1)).rejects.toThrow(
160
+ /stale/i,
161
+ );
162
+ expect(await configure({ ...policy, entitled: false }, 2)).toEqual({
163
+ revision: 3,
164
+ });
165
+ const denied = await t.mutation(mutation("reserve"), {
166
+ ...args,
167
+ inputJson: JSON.stringify({
168
+ ...JSON.parse(args.inputJson),
169
+ sourceEventId: "work2",
170
+ }),
171
+ });
172
+ expect(denied).toMatchObject({
173
+ state: "denied",
174
+ reason: "not_entitled",
175
+ revision: 3,
176
+ });
177
+ });
178
+ it("retains abandoned reservations across timeouts and releases explicit failed work exactly once", async () => {
179
+ const { t, args, configure, bindingJson, meter } = await setup();
180
+ await configure();
181
+ const a = await t.mutation(mutation("reserve"), args);
182
+ vi.setSystemTime(900000);
183
+ expect(
184
+ JSON.parse(await t.query(status, { bindingJson })).reservedQuantity,
185
+ ).toBe("6");
186
+ await expect(
187
+ t.mutation(mutation("release"), {
188
+ scope: { ...meter.scope, customerAccount: "acct_other" },
189
+ reservationId: a.reservationId,
190
+ reason: "work_failed",
191
+ }),
192
+ ).rejects.toThrow(/unavailable/i);
193
+ const releaseArgs = {
194
+ scope: meter.scope,
195
+ reservationId: a.reservationId,
196
+ reason: "abandoned_before_work",
197
+ };
198
+ await t.mutation(mutation("release"), releaseArgs);
199
+ await t.mutation(mutation("release"), releaseArgs);
200
+ expect(
201
+ JSON.parse(await t.query(status, { bindingJson })).reservedQuantity,
202
+ ).toBe("0");
203
+ expect(await t.mutation(mutation("reserve"), args)).toMatchObject({
204
+ state: "released",
205
+ reservationId: a.reservationId,
206
+ });
207
+ await expect(
208
+ t.mutation(record, { ...args, reservationId: a.reservationId }),
209
+ ).rejects.toThrow(/does not match/i);
210
+ await expect(
211
+ t.mutation(mutation("release"), { ...releaseArgs, reason: "work_failed" }),
212
+ ).rejects.toThrow(/replay conflict/i);
213
+ });
214
+ it("starts a fresh verified billing period without resetting old counters or replaying historical sources", async () => {
215
+ const { t, args, configure, bindingJson, meter, subscription, event } =
216
+ await setup();
217
+ await configure();
218
+ const a = await t.mutation(mutation("reserve"), args);
219
+ await t.mutation(record, { ...args, reservationId: a.reservationId });
220
+ vi.setSystemTime(1300000);
221
+ const native = nativeSubscription();
222
+ for (const item of native.items.data) {
223
+ item.current_period_start = 1200;
224
+ item.current_period_end = 1800;
225
+ }
226
+ const intent = await t.run((ctx) =>
227
+ ctx.db.query("usageSubscriptionIntents").first(),
228
+ );
229
+ await t.mutation(
230
+ makeFunctionReference<"mutation">("usageSubscriptions/mutations:save"),
231
+ {
232
+ key: intent!.key,
233
+ nativeJson: JSON.stringify(native),
234
+ startedAt: Date.now(),
235
+ },
236
+ );
237
+ const next = { ...subscription, period: { start: 1200, end: 1800 } },
238
+ nextJson = JSON.stringify({ ...meter, subscription: next });
239
+ await expect(
240
+ t.mutation(record, {
241
+ inputJson: JSON.stringify({
242
+ ...event,
243
+ sourceEventId: "bypassNewPeriod",
244
+ occurredAt: 1300,
245
+ }),
246
+ subscriptionJson: JSON.stringify(next),
247
+ }),
248
+ ).rejects.toThrow(/allowance/i);
249
+ await t.mutation(mutation("configure"), {
250
+ bindingJson: nextJson,
251
+ policyJson: JSON.stringify(policy),
252
+ expectedRevision: 0,
253
+ });
254
+ expect(
255
+ JSON.parse(await t.query(status, { bindingJson: nextJson })),
256
+ ).toMatchObject({
257
+ consumedQuantity: "0",
258
+ reservedQuantity: "0",
259
+ remainingIncludedQuantity: "10",
260
+ });
261
+ expect(JSON.parse(await t.query(status, { bindingJson }))).toMatchObject({
262
+ consumedQuantity: "6",
263
+ accepting: false,
264
+ });
265
+ await expect(
266
+ t.mutation(mutation("reserve"), {
267
+ inputJson: JSON.stringify({ ...event, occurredAt: 1300 }),
268
+ subscriptionJson: JSON.stringify(next),
269
+ }),
270
+ ).rejects.toThrow(/replay conflict/i);
271
+ await t.mutation(mutation("reserve"), {
272
+ inputJson: JSON.stringify({
273
+ ...event,
274
+ sourceEventId: "workNewPeriod",
275
+ occurredAt: 1300,
276
+ }),
277
+ subscriptionJson: JSON.stringify(next),
278
+ });
279
+ });
280
+ it("warns at a soft threshold but permits overage at the original exact rate", async () => {
281
+ const { t, args, configure, bindingJson } = await setup();
282
+ await configure({ ...policy, limit: { mode: "soft", quantity: "5" } });
283
+ for (const sourceEventId of ["work1", "work2", "work3"]) {
284
+ const input = {
285
+ ...args,
286
+ inputJson: JSON.stringify({
287
+ ...JSON.parse(args.inputJson),
288
+ sourceEventId,
289
+ }),
290
+ };
291
+ const a = await t.mutation(mutation("reserve"), input);
292
+ await t.mutation(record, { ...input, reservationId: a.reservationId });
293
+ }
294
+ expect(JSON.parse(await t.query(status, { bindingJson }))).toMatchObject({
295
+ consumedQuantity: "18",
296
+ softLimitReached: true,
297
+ accepting: true,
298
+ billableOverageQuantity: "8",
299
+ committedEstimate: { amountDecimal: "16", currency: "usd" },
300
+ cashCollection: "none",
301
+ });
302
+ });
303
+ it("rejects changed native price terms, overlapping periods and late setup over unaccounted usage", async () => {
304
+ const { t, args, bindingJson, configure, subscription } = await setup();
305
+ await t.mutation(record, args);
306
+ await expect(configure()).rejects.toThrow(/existing period usage/i);
307
+ const f = await setup();
308
+ await f.configure();
309
+ const b = JSON.parse(bindingJson);
310
+ b.binding.plan.includedQuantity = "20";
311
+ await expect(
312
+ f.t.mutation(mutation("configure"), {
313
+ bindingJson: JSON.stringify(b),
314
+ policyJson: JSON.stringify(policy),
315
+ expectedRevision: 1,
316
+ }),
317
+ ).rejects.toThrow();
318
+ const overlap = {
319
+ ...JSON.parse(bindingJson),
320
+ subscription: { ...subscription, period: { start: 601, end: 1200 } },
321
+ };
322
+ await expect(
323
+ f.t.mutation(mutation("configure"), {
324
+ bindingJson: JSON.stringify(overlap),
325
+ policyJson: JSON.stringify(policy),
326
+ expectedRevision: 0,
327
+ }),
328
+ ).rejects.toThrow();
329
+ });
330
+ it("holds accounting reconciliation on incomplete or mismatched local evidence without restoring units", async () => {
331
+ const { t, args, configure, bindingJson } = await setup();
332
+ await configure();
333
+ const a = await t.mutation(mutation("reserve"), args);
334
+ await t.mutation(record, { ...args, reservationId: a.reservationId });
335
+ const reconcile = makeFunctionReference<"query">(
336
+ "usageAllowance/queries:reconciliation",
337
+ );
338
+ expect(await t.query(reconcile, { bindingJson })).toMatchObject({
339
+ status: "matched",
340
+ consumedScaledQuantity: "6",
341
+ reservedScaledQuantity: "0",
342
+ acceptedScaledQuantity: "6",
343
+ repaired: false,
344
+ });
345
+ await t.run(async (ctx) => {
346
+ const row = await ctx.db.query("usageAllowancePolicies").first();
347
+ await ctx.db.patch("usageAllowancePolicies", row!._id, { consumed: "7" });
348
+ });
349
+ expect(await t.query(reconcile, { bindingJson })).toMatchObject({
350
+ status: "held",
351
+ reason: "accounting_mismatch",
352
+ repaired: false,
353
+ });
354
+ expect(
355
+ JSON.parse(await t.query(status, { bindingJson })).consumedQuantity,
356
+ ).toBe("7");
357
+ });
358
+ it("does not refund allowance on provider uncertainty, committed release or conflicting replay", async () => {
359
+ const { t, args, configure, bindingJson, meter, event } = await setup();
360
+ await configure();
361
+ const a = await t.mutation(mutation("reserve"), args);
362
+ await expect(
363
+ t.mutation(mutation("reserve"), {
364
+ ...args,
365
+ inputJson: JSON.stringify({ ...event, quantity: "7" }),
366
+ }),
367
+ ).rejects.toThrow(/replay conflict/i);
368
+ const receipt = await t.mutation(record, {
369
+ ...args,
370
+ reservationId: a.reservationId,
371
+ });
372
+ await t.run(async (ctx) => {
373
+ const outbox = await ctx.db.query("usageOutbox").first();
374
+ await ctx.db.patch("usageOutbox", outbox!._id, { state: "unknown" });
375
+ });
376
+ await expect(
377
+ t.mutation(mutation("release"), {
378
+ scope: meter.scope,
379
+ reservationId: a.reservationId,
380
+ reason: "work_failed",
381
+ }),
382
+ ).rejects.toThrow(/correction/i);
383
+ expect(
384
+ await t.mutation(record, { ...args, reservationId: a.reservationId }),
385
+ ).toEqual(receipt);
386
+ expect(
387
+ JSON.parse(await t.query(status, { bindingJson })).consumedQuantity,
388
+ ).toBe("6");
389
+ const history = makeFunctionReference<"query">(
390
+ "usageAllowance/queries:readHistory",
391
+ );
392
+ await expect(
393
+ t.query(history, {
394
+ bindingJson,
395
+ paginationOpts: { numItems: 101, cursor: null },
396
+ }),
397
+ ).rejects.toThrow(/page/i);
398
+ await expect(
399
+ t.query(history, {
400
+ bindingJson: JSON.stringify({
401
+ ...JSON.parse(bindingJson),
402
+ scope: { ...meter.scope, customerAccount: "acct_other" },
403
+ }),
404
+ paginationOpts: { numItems: 1, cursor: null },
405
+ }),
406
+ ).rejects.toThrow(/unavailable/i);
407
+ });
408
+ it("reports bounded reconciliation as held instead of equating a partial history with zero", async () => {
409
+ const { t, configure, bindingJson, args } = await setup();
410
+ await configure();
411
+ const a = await t.mutation(mutation("reserve"), args);
412
+ await t.mutation(record, { ...args, reservationId: a.reservationId });
413
+ await t.run(async (ctx) => {
414
+ const row = (await ctx.db.query("usageEvents").first())!;
415
+ for (let i = 0; i < 500; i++)
416
+ await ctx.db.insert("usageEvents", {
417
+ scopeKey: row.scopeKey,
418
+ identity: `synthetic_${i}`,
419
+ recordJson: row.recordJson,
420
+ subscriptionJson: row.subscriptionJson,
421
+ occurredAt: row.occurredAt,
422
+ acceptedAt: row.acceptedAt,
423
+ subscriptionId: row.subscriptionId,
424
+ });
425
+ });
426
+ const reconcile = makeFunctionReference<"query">(
427
+ "usageAllowance/queries:reconciliation",
428
+ );
429
+ expect(await t.query(reconcile, { bindingJson })).toMatchObject({
430
+ status: "held",
431
+ reason: "local_evidence_incomplete",
432
+ consumedScaledQuantity: "6",
433
+ repaired: false,
434
+ });
435
+ });
@@ -199,7 +199,7 @@ it("rolls back event, counter and reservation commit if scheduling fails", async
199
199
  await t.run((ctx) => ctx.db.get("usageReservations", reservationId)),
200
200
  ).toMatchObject({ state: "reserved" });
201
201
  });
202
- it("requires and atomically commits the exact prepaid reservation", async () => {
202
+ it("rejects unbacked prepaid reservations even when unit claims match", async () => {
203
203
  const t = convexTest(schema, modules);
204
204
  const input = {
205
205
  ...event,
@@ -224,22 +224,15 @@ it("requires and atomically commits the exact prepaid reservation", async () =>
224
224
  state: "reserved",
225
225
  }),
226
226
  );
227
- await t.mutation(record, { ...args(input), reservationId });
227
+ await expect(
228
+ t.mutation(record, { ...args(input), reservationId }),
229
+ ).rejects.toThrow("Prepaid reservation provenance mismatch");
228
230
  expect(
229
231
  await t.run((ctx) => ctx.db.get("usageReservations", reservationId)),
230
- ).toMatchObject({ state: "committed" });
231
- const secondReservation = await t.run((ctx) =>
232
- ctx.db.insert("usageReservations", {
233
- scopeKey: JSON.stringify(scope),
234
- sourceEventId: input.sourceEventId,
235
- planJson: JSON.stringify(input.binding.plan),
236
- scaledQuantity: "120",
237
- state: "reserved",
238
- }),
239
- );
240
- await expect(
241
- t.mutation(record, { ...args(input), reservationId: secondReservation }),
242
- ).rejects.toThrow("Conflicting usage reservation replay");
232
+ ).toMatchObject({ state: "reserved" });
233
+ expect(
234
+ await t.run((ctx) => ctx.db.query("usageEvents").collect()),
235
+ ).toHaveLength(0);
243
236
  });
244
237
 
245
238
  it("pages an explicit period without exposing guessed or cross-scope events", async () => {
@@ -1,3 +1,8 @@
1
+ import {
2
+ commit as commitAllowanceReservation,
3
+ requireReservation,
4
+ } from "../usageAllowance/reservations.js";
5
+ import { commit as commitCreditReservation } from "../usageCredits/reservations.js";
1
6
  import { managedBillingCutoff } from "../usageSubscriptions/acceptance.js";
2
7
  import { v } from "convex/values";
3
8
  import type { FunctionHandle } from "convex/server";
@@ -99,6 +104,7 @@ export const record = mutation({
99
104
  reservation.state !== "reserved")
100
105
  )
101
106
  throw new Error("Usage reservation does not match event");
107
+ await requireReservation(ctx, event, subscription, reservation);
102
108
  const eventId = await ctx.db.insert("usageEvents", {
103
109
  subscriptionId: subscription.subscriptionId,
104
110
  reservationId: args.reservationId,
@@ -123,6 +129,22 @@ export const record = mutation({
123
129
  count: counter.count + 1,
124
130
  });
125
131
  else await ctx.db.insert("usageScopeCounters", { scopeKey: key, count: 1 });
132
+ if (reservation && event.binding.plan.model === "prepaid")
133
+ await commitCreditReservation(
134
+ ctx,
135
+ reservation,
136
+ event,
137
+ subscription,
138
+ eventId,
139
+ );
140
+ if (reservation?.accountingKind === "allowance")
141
+ await commitAllowanceReservation(
142
+ ctx,
143
+ reservation,
144
+ event,
145
+ subscription,
146
+ eventId,
147
+ );
126
148
  if (reservation)
127
149
  await ctx.db.patch("usageReservations", reservation._id, {
128
150
  state: "committed",
@@ -34,6 +34,11 @@ export const eventDoc = v.object({
34
34
  export const usageEventsTable = defineTable(eventFields)
35
35
  .index("by_identity", ["identity"])
36
36
  .index("by_scope_subscription", ["scopeKey", "subscriptionId"])
37
+ .index("by_scope_subscription_time", [
38
+ "scopeKey",
39
+ "subscriptionId",
40
+ "occurredAt",
41
+ ])
37
42
  .index("by_scope_time", ["scopeKey", "occurredAt"]);
38
43
  export const outboxFields = {
39
44
  ...deliveryFields,
@@ -73,6 +78,15 @@ export const usageReservationsTable = defineTable({
73
78
  v.literal("released"),
74
79
  ),
75
80
  eventId: v.optional(v.id("usageEvents")),
81
+ accountingKind: v.optional(
82
+ v.union(v.literal("prepaid"), v.literal("allowance")),
83
+ ),
84
+ accountKey: v.optional(v.string()),
85
+ inputJson: v.optional(v.string()),
86
+ subscriptionJson: v.optional(v.string()),
87
+ allocationsJson: v.optional(v.string()),
88
+ releaseReason: v.optional(v.string()),
76
89
  })
90
+ .index("by_account_state", ["accountKey", "state"])
77
91
  .index("by_scope_source", ["scopeKey", "sourceEventId"])
78
92
  .index("by_scope_state", ["scopeKey", "state"]);
@@ -0,0 +1,137 @@
1
+ import { convexToJson, type Value } from "convex/values";
2
+ import type { QueryCtx, MutationCtx } from "../_generated/server.js";
3
+ import type { Doc } from "../_generated/dataModel.js";
4
+ import {
5
+ allowanceBinding,
6
+ type UsageAllowanceBinding,
7
+ } from "../../client/usage/allowanceTerms.js";
8
+ import type { PreparedUsageRecord } from "../../client/usage/records.js";
9
+ import type { UsageSubscriptionBinding } from "../../client/usage/boundaries.js";
10
+ import { managedBillingCutoff } from "../usageSubscriptions/acceptance.js";
11
+ import { scopeKey } from "../usage/helpers.js";
12
+ export const canonical = (value: Value) => JSON.stringify(convexToJson(value));
13
+ export function json(json: string) {
14
+ if (new TextEncoder().encode(json).length > 8192)
15
+ throw new Error("Allowance payload exceeds size limit");
16
+ return JSON.parse(json) as unknown;
17
+ }
18
+ export function terms(input: unknown) {
19
+ const binding = allowanceBinding(input);
20
+ const nativeKey = canonical([
21
+ binding.scope.stripeAccountId,
22
+ binding.scope.livemode,
23
+ binding.binding.stripeCustomerId,
24
+ binding.scope.meterId,
25
+ ]);
26
+ return {
27
+ binding,
28
+ nativeKey,
29
+ key: canonical([
30
+ nativeKey,
31
+ binding.subscription.period.start,
32
+ binding.subscription.period.end,
33
+ ]),
34
+ scopeKey: scopeKey(binding.scope),
35
+ bindingJson: canonical(binding),
36
+ };
37
+ }
38
+ export async function policyRow(ctx: QueryCtx, key: string) {
39
+ return ctx.db
40
+ .query("usageAllowancePolicies")
41
+ .withIndex("by_key", (q) => q.eq("key", key))
42
+ .unique();
43
+ }
44
+ export async function overlapping(
45
+ ctx: QueryCtx,
46
+ nativeKey: string,
47
+ period: UsageSubscriptionBinding["period"],
48
+ ) {
49
+ const row = await ctx.db
50
+ .query("usageAllowancePolicies")
51
+ .withIndex("by_native_start", (q) =>
52
+ q.eq("nativeKey", nativeKey).lt("start", period.end),
53
+ )
54
+ .order("desc")
55
+ .first();
56
+ return row && row.end > period.start ? row : null;
57
+ }
58
+ export async function active(
59
+ ctx: QueryCtx,
60
+ binding: UsageAllowanceBinding,
61
+ event?: PreparedUsageRecord,
62
+ ) {
63
+ const now = Math.floor(Date.now() / 1000);
64
+ const record = event ?? {
65
+ ...binding,
66
+ sourceEventId: "validation",
67
+ occurredAt: now,
68
+ quantity: "0",
69
+ scaledQuantity: "0",
70
+ schemaVersion: 1,
71
+ identity: "validation",
72
+ };
73
+ const cutoff = await managedBillingCutoff(ctx, record, binding.subscription);
74
+ if (
75
+ cutoff === null ||
76
+ now < binding.subscription.period.start ||
77
+ now >= cutoff ||
78
+ (event &&
79
+ (event.occurredAt < binding.subscription.period.start ||
80
+ event.occurredAt >= binding.subscription.period.end ||
81
+ event.occurredAt < now - 35 * 86400 ||
82
+ event.occurredAt > now + 300))
83
+ )
84
+ throw new Error("Active managed allowance period required");
85
+ }
86
+ export async function history(
87
+ ctx: MutationCtx,
88
+ row: Doc<"usageAllowancePolicies">,
89
+ kind: Doc<"usageAllowanceHistory">["kind"],
90
+ evidence: Value,
91
+ ) {
92
+ const current = await ctx.db.get("usageAllowancePolicies", row._id);
93
+ if (!current || current.historyCount >= 100000)
94
+ throw new Error("Allowance history quota exhausted");
95
+ await ctx.db.insert("usageAllowanceHistory", {
96
+ key: row.key,
97
+ kind,
98
+ evidenceJson: canonical(evidence),
99
+ at: Math.floor(Date.now() / 1000),
100
+ });
101
+ await ctx.db.patch("usageAllowancePolicies", row._id, {
102
+ historyCount: current.historyCount + 1,
103
+ });
104
+ }
105
+
106
+ export async function scopeOverlap(
107
+ ctx: QueryCtx,
108
+ key: string,
109
+ period: UsageSubscriptionBinding["period"],
110
+ ) {
111
+ const row = await ctx.db
112
+ .query("usageAllowancePolicies")
113
+ .withIndex("by_scope_start", (q) =>
114
+ q.eq("scopeKey", key).lt("start", period.end),
115
+ )
116
+ .order("desc")
117
+ .first();
118
+ return row && row.end > period.start ? row : null;
119
+ }
120
+
121
+ export async function configuredScope(
122
+ ctx: QueryCtx,
123
+ original: ReturnType<typeof terms>,
124
+ ) {
125
+ return (
126
+ (await ctx.db
127
+ .query("usageAllowancePolicies")
128
+ .withIndex("by_native_start", (q) =>
129
+ q.eq("nativeKey", original.nativeKey),
130
+ )
131
+ .first()) ??
132
+ (await ctx.db
133
+ .query("usageAllowancePolicies")
134
+ .withIndex("by_scope_start", (q) => q.eq("scopeKey", original.scopeKey))
135
+ .first())
136
+ );
137
+ }