@fantastic.dev/better-stripe 0.57.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 (88) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +3 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +122 -36
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +45 -2
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +122 -36
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +45 -2
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/usage/allowanceClient.d.ts +51 -0
  12. package/dist/client/usage/allowanceClient.d.ts.map +1 -0
  13. package/dist/client/usage/allowanceClient.js +64 -0
  14. package/dist/client/usage/allowanceClient.js.map +1 -0
  15. package/dist/client/usage/allowanceTerms.d.ts +64 -0
  16. package/dist/client/usage/allowanceTerms.d.ts.map +1 -0
  17. package/dist/client/usage/allowanceTerms.js +101 -0
  18. package/dist/client/usage/allowanceTerms.js.map +1 -0
  19. package/dist/client/usage/client.d.ts +2 -2
  20. package/dist/client/usage/client.d.ts.map +1 -1
  21. package/dist/client/usage/client.js +2 -2
  22. package/dist/client/usage/client.js.map +1 -1
  23. package/dist/client/usage/index.d.ts +2 -0
  24. package/dist/client/usage/index.d.ts.map +1 -1
  25. package/dist/client/usageExports.d.ts +2 -0
  26. package/dist/client/usageExports.d.ts.map +1 -1
  27. package/dist/component/_generated/api.d.ts +8 -0
  28. package/dist/component/_generated/api.d.ts.map +1 -1
  29. package/dist/component/_generated/api.js.map +1 -1
  30. package/dist/component/_generated/component.d.ts +70 -0
  31. package/dist/component/_generated/component.d.ts.map +1 -1
  32. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  33. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  34. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  35. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  36. package/dist/component/earnings/triggers.d.ts +110 -18
  37. package/dist/component/earnings/triggers.d.ts.map +1 -1
  38. package/dist/component/schema.d.ts +45 -2
  39. package/dist/component/schema.js +3 -0
  40. package/dist/component/schema.js.map +1 -1
  41. package/dist/component/usage/mutations.d.ts.map +1 -1
  42. package/dist/component/usage/mutations.js +4 -0
  43. package/dist/component/usage/mutations.js.map +1 -1
  44. package/dist/component/usage/schema.d.ts +3 -2
  45. package/dist/component/usage/schema.d.ts.map +1 -1
  46. package/dist/component/usage/schema.js +2 -1
  47. package/dist/component/usage/schema.js.map +1 -1
  48. package/dist/component/usageAllowance/helpers.d.ts +78 -0
  49. package/dist/component/usageAllowance/helpers.d.ts.map +1 -0
  50. package/dist/component/usageAllowance/helpers.js +99 -0
  51. package/dist/component/usageAllowance/helpers.js.map +1 -0
  52. package/dist/component/usageAllowance/mutations.d.ts +37 -0
  53. package/dist/component/usageAllowance/mutations.d.ts.map +1 -0
  54. package/dist/component/usageAllowance/mutations.js +99 -0
  55. package/dist/component/usageAllowance/mutations.js.map +1 -0
  56. package/dist/component/usageAllowance/queries.d.ts +36 -0
  57. package/dist/component/usageAllowance/queries.d.ts.map +1 -0
  58. package/dist/component/usageAllowance/queries.js +113 -0
  59. package/dist/component/usageAllowance/queries.js.map +1 -0
  60. package/dist/component/usageAllowance/reservations.d.ts +25 -0
  61. package/dist/component/usageAllowance/reservations.d.ts.map +1 -0
  62. package/dist/component/usageAllowance/reservations.js +150 -0
  63. package/dist/component/usageAllowance/reservations.js.map +1 -0
  64. package/dist/component/usageAllowance/schema.d.ts +77 -0
  65. package/dist/component/usageAllowance/schema.d.ts.map +1 -0
  66. package/dist/component/usageAllowance/schema.js +32 -0
  67. package/dist/component/usageAllowance/schema.js.map +1 -0
  68. package/docs/README.md +2 -0
  69. package/docs/usage-limits.md +217 -0
  70. package/package.json +2 -1
  71. package/src/client/usage/allowanceClient.test.ts +93 -0
  72. package/src/client/usage/allowanceClient.ts +134 -0
  73. package/src/client/usage/allowanceTerms.test.ts +131 -0
  74. package/src/client/usage/allowanceTerms.ts +172 -0
  75. package/src/client/usage/client.ts +2 -2
  76. package/src/client/usage/index.ts +8 -0
  77. package/src/client/usageExports.ts +8 -0
  78. package/src/component/_generated/api.ts +8 -0
  79. package/src/component/_generated/component.ts +94 -0
  80. package/src/component/schema.ts +6 -0
  81. package/src/component/usage/allowance.test.ts +435 -0
  82. package/src/component/usage/mutations.ts +13 -0
  83. package/src/component/usage/schema.ts +4 -1
  84. package/src/component/usageAllowance/helpers.ts +137 -0
  85. package/src/component/usageAllowance/mutations.ts +139 -0
  86. package/src/component/usageAllowance/queries.ts +133 -0
  87. package/src/component/usageAllowance/reservations.ts +220 -0
  88. package/src/component/usageAllowance/schema.ts +36 -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
+ });
@@ -1,3 +1,7 @@
1
+ import {
2
+ commit as commitAllowanceReservation,
3
+ requireReservation,
4
+ } from "../usageAllowance/reservations.js";
1
5
  import { commit as commitCreditReservation } from "../usageCredits/reservations.js";
2
6
  import { managedBillingCutoff } from "../usageSubscriptions/acceptance.js";
3
7
  import { v } from "convex/values";
@@ -100,6 +104,7 @@ export const record = mutation({
100
104
  reservation.state !== "reserved")
101
105
  )
102
106
  throw new Error("Usage reservation does not match event");
107
+ await requireReservation(ctx, event, subscription, reservation);
103
108
  const eventId = await ctx.db.insert("usageEvents", {
104
109
  subscriptionId: subscription.subscriptionId,
105
110
  reservationId: args.reservationId,
@@ -132,6 +137,14 @@ export const record = mutation({
132
137
  subscription,
133
138
  eventId,
134
139
  );
140
+ if (reservation?.accountingKind === "allowance")
141
+ await commitAllowanceReservation(
142
+ ctx,
143
+ reservation,
144
+ event,
145
+ subscription,
146
+ eventId,
147
+ );
135
148
  if (reservation)
136
149
  await ctx.db.patch("usageReservations", reservation._id, {
137
150
  state: "committed",
@@ -78,12 +78,15 @@ export const usageReservationsTable = defineTable({
78
78
  v.literal("released"),
79
79
  ),
80
80
  eventId: v.optional(v.id("usageEvents")),
81
- accountingKind: v.optional(v.literal("prepaid")),
81
+ accountingKind: v.optional(
82
+ v.union(v.literal("prepaid"), v.literal("allowance")),
83
+ ),
82
84
  accountKey: v.optional(v.string()),
83
85
  inputJson: v.optional(v.string()),
84
86
  subscriptionJson: v.optional(v.string()),
85
87
  allocationsJson: v.optional(v.string()),
86
88
  releaseReason: v.optional(v.string()),
87
89
  })
90
+ .index("by_account_state", ["accountKey", "state"])
88
91
  .index("by_scope_source", ["scopeKey", "sourceEventId"])
89
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
+ }