@fantastic.dev/better-stripe 0.60.0 → 0.61.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 (193) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +5 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +26 -6
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +13 -3
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +26 -6
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +13 -3
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/usage/creditCapacity.d.ts.map +1 -1
  12. package/dist/client/usage/creditCapacity.js +7 -1
  13. package/dist/client/usage/creditCapacity.js.map +1 -1
  14. package/dist/client/usage/creditClient.d.ts +3 -0
  15. package/dist/client/usage/creditClient.d.ts.map +1 -1
  16. package/dist/client/usage/creditDelivery.d.ts.map +1 -1
  17. package/dist/client/usage/creditDelivery.js +4 -1
  18. package/dist/client/usage/creditDelivery.js.map +1 -1
  19. package/dist/client/usage/creditLifecycle.d.ts.map +1 -1
  20. package/dist/client/usage/creditLifecycle.js +2 -1
  21. package/dist/client/usage/creditLifecycle.js.map +1 -1
  22. package/dist/client/usage/creditNative.d.ts +3 -0
  23. package/dist/client/usage/creditNative.d.ts.map +1 -1
  24. package/dist/client/usage/creditNative.js +3 -0
  25. package/dist/client/usage/creditNative.js.map +1 -1
  26. package/dist/client/usage/creditProvider.d.ts.map +1 -1
  27. package/dist/client/usage/creditProvider.js +2 -1
  28. package/dist/client/usage/creditProvider.js.map +1 -1
  29. package/dist/client/usage/creditRead.d.ts +1 -0
  30. package/dist/client/usage/creditRead.d.ts.map +1 -1
  31. package/dist/client/usage/creditReconciliation.d.ts.map +1 -1
  32. package/dist/client/usage/creditReconciliation.js +11 -3
  33. package/dist/client/usage/creditReconciliation.js.map +1 -1
  34. package/dist/client/usage/creditSettlement.fixtures.d.ts +1 -0
  35. package/dist/client/usage/creditSettlement.fixtures.d.ts.map +1 -1
  36. package/dist/client/usage/creditTransport.fixtures.d.ts +1 -0
  37. package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -1
  38. package/dist/client/usage/creditTransport.fixtures.js +2 -1
  39. package/dist/client/usage/creditTransport.fixtures.js.map +1 -1
  40. package/dist/client/usage/index.d.ts +2 -0
  41. package/dist/client/usage/index.d.ts.map +1 -1
  42. package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -1
  43. package/dist/client/usage/subscriptionCancellation.js +3 -2
  44. package/dist/client/usage/subscriptionCancellation.js.map +1 -1
  45. package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -1
  46. package/dist/client/usage/subscriptionCheckout.js +3 -2
  47. package/dist/client/usage/subscriptionCheckout.js.map +1 -1
  48. package/dist/client/usage/subscriptionLifecycle.d.ts +1 -0
  49. package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -1
  50. package/dist/client/usage/subscriptionLifecycle.js +3 -2
  51. package/dist/client/usage/subscriptionLifecycle.js.map +1 -1
  52. package/dist/client/usage/subscriptionProvider.d.ts +2 -0
  53. package/dist/client/usage/subscriptionProvider.d.ts.map +1 -1
  54. package/dist/client/usage/subscriptionProvider.js +9 -2
  55. package/dist/client/usage/subscriptionProvider.js.map +1 -1
  56. package/dist/component/_generated/component.d.ts +21 -0
  57. package/dist/component/_generated/component.d.ts.map +1 -1
  58. package/dist/component/earnings/triggers.d.ts +16 -6
  59. package/dist/component/earnings/triggers.d.ts.map +1 -1
  60. package/dist/component/schema.d.ts +13 -3
  61. package/dist/component/usage/allowance.fixtures.d.ts +4212 -0
  62. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -0
  63. package/dist/component/usage/allowance.fixtures.js +67 -0
  64. package/dist/component/usage/allowance.fixtures.js.map +1 -0
  65. package/dist/component/usageCredits/accounting.fixtures.d.ts +4235 -0
  66. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -0
  67. package/dist/component/usageCredits/accounting.fixtures.js +89 -0
  68. package/dist/component/usageCredits/accounting.fixtures.js.map +1 -0
  69. package/dist/component/usageCredits/helpers.d.ts +7 -0
  70. package/dist/component/usageCredits/helpers.d.ts.map +1 -1
  71. package/dist/component/usageCredits/helpers.js +5 -0
  72. package/dist/component/usageCredits/helpers.js.map +1 -1
  73. package/dist/component/usageCredits/mutations.d.ts +6 -0
  74. package/dist/component/usageCredits/mutations.d.ts.map +1 -1
  75. package/dist/component/usageCredits/mutations.js +70 -7
  76. package/dist/component/usageCredits/mutations.js.map +1 -1
  77. package/dist/component/usageCredits/purchase.d.ts +1 -0
  78. package/dist/component/usageCredits/purchase.d.ts.map +1 -1
  79. package/dist/component/usageCredits/queries.d.ts +10 -0
  80. package/dist/component/usageCredits/queries.d.ts.map +1 -1
  81. package/dist/component/usageCredits/schema.d.ts +24 -4
  82. package/dist/component/usageCredits/schema.d.ts.map +1 -1
  83. package/dist/component/usageCredits/schema.js +4 -0
  84. package/dist/component/usageCredits/schema.js.map +1 -1
  85. package/dist/component/usageSubscriptions/history.d.ts.map +1 -1
  86. package/dist/component/usageSubscriptions/history.js +3 -1
  87. package/dist/component/usageSubscriptions/history.js.map +1 -1
  88. package/dist/component/usageSubscriptions/mutations.d.ts +5 -0
  89. package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -1
  90. package/dist/component/usageSubscriptions/mutations.js +19 -0
  91. package/dist/component/usageSubscriptions/mutations.js.map +1 -1
  92. package/dist/component/usageSubscriptions/queries.d.ts +2 -0
  93. package/dist/component/usageSubscriptions/queries.d.ts.map +1 -1
  94. package/dist/component/usageSubscriptions/schema.d.ts +7 -2
  95. package/dist/component/usageSubscriptions/schema.d.ts.map +1 -1
  96. package/dist/component/usageSubscriptions/schema.js +1 -0
  97. package/dist/component/usageSubscriptions/schema.js.map +1 -1
  98. package/dist/react/index.d.ts +12 -0
  99. package/dist/react/index.d.ts.map +1 -1
  100. package/dist/react/index.js +7 -0
  101. package/dist/react/index.js.map +1 -1
  102. package/dist/react/workflows/Pagination.d.ts +1 -0
  103. package/dist/react/workflows/Pagination.d.ts.map +1 -1
  104. package/dist/react/workflows/Pagination.js +1 -0
  105. package/dist/react/workflows/Pagination.js.map +1 -1
  106. package/dist/react/workflows/Usage.fixtures.d.ts +17 -0
  107. package/dist/react/workflows/Usage.fixtures.d.ts.map +1 -0
  108. package/dist/react/workflows/Usage.fixtures.js +79 -0
  109. package/dist/react/workflows/Usage.fixtures.js.map +1 -0
  110. package/dist/react/workflows/Usage.types.d.ts +25 -0
  111. package/dist/react/workflows/Usage.types.d.ts.map +1 -0
  112. package/dist/react/workflows/Usage.types.js +11 -0
  113. package/dist/react/workflows/Usage.types.js.map +1 -0
  114. package/dist/react/workflows/UsageAllowance.d.ts +14 -0
  115. package/dist/react/workflows/UsageAllowance.d.ts.map +1 -0
  116. package/dist/react/workflows/UsageAllowance.js +21 -0
  117. package/dist/react/workflows/UsageAllowance.js.map +1 -0
  118. package/dist/react/workflows/UsageBilling.d.ts +20 -0
  119. package/dist/react/workflows/UsageBilling.d.ts.map +1 -0
  120. package/dist/react/workflows/UsageBilling.js +40 -0
  121. package/dist/react/workflows/UsageBilling.js.map +1 -0
  122. package/dist/react/workflows/UsageCredits.d.ts +14 -0
  123. package/dist/react/workflows/UsageCredits.d.ts.map +1 -0
  124. package/dist/react/workflows/UsageCredits.js +25 -0
  125. package/dist/react/workflows/UsageCredits.js.map +1 -0
  126. package/dist/react/workflows/UsageHistory.d.ts +40 -0
  127. package/dist/react/workflows/UsageHistory.d.ts.map +1 -0
  128. package/dist/react/workflows/UsageHistory.js +74 -0
  129. package/dist/react/workflows/UsageHistory.js.map +1 -0
  130. package/dist/react/workflows/UsageSummary.d.ts +19 -0
  131. package/dist/react/workflows/UsageSummary.d.ts.map +1 -0
  132. package/dist/react/workflows/UsageSummary.js +54 -0
  133. package/dist/react/workflows/UsageSummary.js.map +1 -0
  134. package/dist/react/workflows/usage-format.d.ts +11 -0
  135. package/dist/react/workflows/usage-format.d.ts.map +1 -0
  136. package/dist/react/workflows/usage-format.js +43 -0
  137. package/dist/react/workflows/usage-format.js.map +1 -0
  138. package/dist/react/workflows/usage-scope.d.ts +5 -0
  139. package/dist/react/workflows/usage-scope.d.ts.map +1 -0
  140. package/dist/react/workflows/usage-scope.js +26 -0
  141. package/dist/react/workflows/usage-scope.js.map +1 -0
  142. package/docs/README.md +4 -0
  143. package/docs/react-api.md +4 -0
  144. package/docs/usage-credits.md +6 -1
  145. package/docs/usage-react.md +182 -0
  146. package/docs/usage-security.md +130 -0
  147. package/package.json +3 -1
  148. package/src/client/usage/creditBackingIsolation.test.ts +110 -0
  149. package/src/client/usage/creditCapacity.test.ts +80 -1
  150. package/src/client/usage/creditCapacity.ts +10 -1
  151. package/src/client/usage/creditDelivery.ts +4 -0
  152. package/src/client/usage/creditLifecycle.ts +2 -0
  153. package/src/client/usage/creditNative.ts +5 -0
  154. package/src/client/usage/creditProofBounds.test.ts +187 -0
  155. package/src/client/usage/creditProvider.test.ts +74 -0
  156. package/src/client/usage/creditProvider.ts +2 -0
  157. package/src/client/usage/creditReconciliation.ts +18 -3
  158. package/src/client/usage/creditTransport.fixtures.ts +2 -1
  159. package/src/client/usage/index.ts +3 -0
  160. package/src/client/usage/subscriptionCancellation.ts +3 -2
  161. package/src/client/usage/subscriptionCheckout.ts +7 -2
  162. package/src/client/usage/subscriptionClient.test.ts +60 -1
  163. package/src/client/usage/subscriptionLifecycle.ts +3 -2
  164. package/src/client/usage/subscriptionProvider.ts +27 -3
  165. package/src/component/_generated/component.ts +40 -1
  166. package/src/component/usage/allowance.fixtures.ts +77 -0
  167. package/src/component/usage/allowance.test.ts +3 -66
  168. package/src/component/usage/allowanceBounds.test.ts +79 -0
  169. package/src/component/usage/historyIsolation.test.ts +124 -0
  170. package/src/component/usageCredits/accounting.fixtures.ts +96 -0
  171. package/src/component/usageCredits/accounting.test.ts +176 -82
  172. package/src/component/usageCredits/freshness.test.ts +33 -0
  173. package/src/component/usageCredits/helpers.ts +8 -0
  174. package/src/component/usageCredits/mutations.ts +83 -5
  175. package/src/component/usageCredits/quotas.test.ts +63 -0
  176. package/src/component/usageCredits/schema.ts +10 -0
  177. package/src/component/usageSubscriptions/history.test.ts +57 -0
  178. package/src/component/usageSubscriptions/history.ts +3 -1
  179. package/src/component/usageSubscriptions/mutations.ts +23 -0
  180. package/src/component/usageSubscriptions/schema.ts +1 -0
  181. package/src/react/index.ts +20 -0
  182. package/src/react/workflows/Pagination.tsx +2 -0
  183. package/src/react/workflows/Usage.fixtures.ts +88 -0
  184. package/src/react/workflows/Usage.test.tsx +373 -0
  185. package/src/react/workflows/Usage.types.ts +39 -0
  186. package/src/react/workflows/UsageAllowance.tsx +114 -0
  187. package/src/react/workflows/UsageBilling.tsx +90 -0
  188. package/src/react/workflows/UsageCredits.tsx +112 -0
  189. package/src/react/workflows/UsageHistory.test.tsx +206 -0
  190. package/src/react/workflows/UsageHistory.tsx +154 -0
  191. package/src/react/workflows/UsageSummary.tsx +204 -0
  192. package/src/react/workflows/usage-format.ts +48 -0
  193. package/src/react/workflows/usage-scope.ts +42 -0
@@ -1,7 +1,6 @@
1
- import { convexTest } from "convex-test";
1
+ import { setupCredits } from "./accounting.fixtures.js";
2
2
  import { makeFunctionReference } from "convex/server";
3
3
  import { afterEach, expect, it, vi } from "vitest";
4
- import { schema, modules } from "../../test.js";
5
4
  import {
6
5
  request,
7
6
  nativeSubscription,
@@ -16,86 +15,7 @@ const save = makeFunctionReference<"mutation">(
16
15
  );
17
16
  const record = makeFunctionReference<"mutation">("usage/mutations:record");
18
17
  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
- }
18
+
99
19
  afterEach(() => vi.useRealTimers());
100
20
  it("atomically reserves payment-backed units, commits with ledger acceptance and rejects concurrent overspend", async () => {
101
21
  const { t, meter, event, subscription } = await setupCredits();
@@ -387,3 +307,177 @@ it("allocates by provider creation time when native grants are mirrored out of o
387
307
  ).toBe("0");
388
308
  expect(reservation.state).toBe("reserved");
389
309
  });
310
+
311
+ it("does not replace credit backing with conflicting same-time evidence or resume through that ambiguity", async () => {
312
+ const { t, purchase, meter } = await setupCredits();
313
+ const proof = {
314
+ creditGrantId: "credgr_topup1",
315
+ paymentIntentId: "pi_topup1",
316
+ currency: "usd",
317
+ ledgerAmount: 8,
318
+ availableAmount: 8,
319
+ granted: 20,
320
+ applied: 12,
321
+ expired: 0,
322
+ voided: 0,
323
+ reinstated: 0,
324
+ invoicesVerified: true,
325
+ complete: true,
326
+ transactions: [],
327
+ };
328
+ const saveProof = (value: typeof proof, startedAt = Date.now()) =>
329
+ t.mutation(ref("saveObservation"), {
330
+ inputJson: JSON.stringify(purchase),
331
+ proofJson: JSON.stringify(value),
332
+ startedAt,
333
+ });
334
+ await saveProof(proof);
335
+ const result = JSON.parse(
336
+ await saveProof({
337
+ ...proof,
338
+ ledgerAmount: 20,
339
+ availableAmount: 20,
340
+ applied: 0,
341
+ }),
342
+ );
343
+ expect(result.backing).toBe("held");
344
+ const grant = await t.run((ctx) => ctx.db.query("usageCreditGrants").first());
345
+ expect(JSON.parse(grant!.nativeObservationJson!).ledgerAmount).toBe(8);
346
+ await expect(
347
+ t.mutation(ref("resumeAccount"), { bindingJson: JSON.stringify(meter) }),
348
+ ).rejects.toThrow(/reconciliation|ambigu|funding/i);
349
+ });
350
+
351
+ it("keeps later credit history and grant cursors inside the requested original tenant binding", async () => {
352
+ const { t, meter } = await setupCredits();
353
+ const seed = async (binding: typeof meter, suffix: string) => {
354
+ const row = await t.mutation(ref("preparePurchase"), {
355
+ inputJson: JSON.stringify({
356
+ ...binding,
357
+ purchaseId: suffix,
358
+ quantity: "10",
359
+ ownership: "issuer",
360
+ rollover: "retain_original_terms",
361
+ }),
362
+ });
363
+ await t.mutation(ref("pinPayment"), {
364
+ key: row.key,
365
+ paymentIntentId: `pi_${suffix}`,
366
+ });
367
+ const proof = {
368
+ paymentIntentId: `pi_${suffix}`,
369
+ chargeId: `ch_${suffix}`,
370
+ amount: 20,
371
+ currency: "usd",
372
+ customerAccount: binding.scope.customerAccount,
373
+ livemode: false,
374
+ };
375
+ await t.mutation(ref("verifyPayment"), {
376
+ key: row.key,
377
+ proofJson: JSON.stringify(proof),
378
+ });
379
+ await t.mutation(ref("pinGrant"), {
380
+ key: row.key,
381
+ proofJson: JSON.stringify({
382
+ ...proof,
383
+ creditGrantId: `credgr_${suffix}`,
384
+ stripePriceId: binding.binding.stripePriceId,
385
+ createdAt: 700,
386
+ effectiveAt: 700,
387
+ expiresAt: null,
388
+ }),
389
+ });
390
+ return row;
391
+ };
392
+ const original = await seed(meter, "topup2");
393
+ const foreign = {
394
+ ...meter,
395
+ scope: { ...meter.scope, customerAccount: "acct_other" },
396
+ binding: { ...meter.binding, stripeCustomerId: "cus_other" },
397
+ };
398
+ const intent = await t.mutation(prepare, {
399
+ termsJson: JSON.stringify({ ...request, meters: [foreign] }),
400
+ method: "direct",
401
+ });
402
+ const native = nativeSubscription();
403
+ native.id = "sub_other";
404
+ native.customer = "cus_other";
405
+ native.customer_account = "acct_other";
406
+ await t.mutation(save, {
407
+ key: intent.key,
408
+ nativeJson: JSON.stringify(native),
409
+ startedAt: Date.now(),
410
+ });
411
+ const other = await seed(foreign, "other1");
412
+ for (const name of ["readHistory", "readGrants"]) {
413
+ const query = makeFunctionReference<"query">(
414
+ `usageCredits/queries:${name}`,
415
+ );
416
+ const args = {
417
+ bindingJson: JSON.stringify(meter),
418
+ paginationOpts: { numItems: 1, cursor: null },
419
+ };
420
+ const first = await t.query(query, args);
421
+ expect(first.isDone).toBe(false);
422
+ const next = {
423
+ ...args,
424
+ paginationOpts: { numItems: 1, cursor: first.continueCursor },
425
+ };
426
+ expect(await t.query(query, next)).toEqual(await t.query(query, next));
427
+ try {
428
+ const page = await t.query(query, {
429
+ ...next,
430
+ bindingJson: JSON.stringify(foreign),
431
+ });
432
+ expect(
433
+ page.page.every(
434
+ (row: { accountKey: string }) =>
435
+ row.accountKey === other.accountKey &&
436
+ row.accountKey !== original.accountKey,
437
+ ),
438
+ ).toBe(true);
439
+ } catch (error) {
440
+ expect(String(error)).toMatch(/cursor|range|index|position|pagination/i);
441
+ }
442
+ }
443
+ });
444
+
445
+ it("retains open credit liabilities when a dispute freezes a fully consumed grant after a zero-balance observation", async () => {
446
+ const { t, meter, purchase, row, event, subscription } = await setupCredits();
447
+ const args = {
448
+ inputJson: JSON.stringify({ ...event, quantity: "10" }),
449
+ subscriptionJson: JSON.stringify(subscription),
450
+ };
451
+ const reserved = await t.mutation(ref("reserve"), args);
452
+ await t.mutation(record, { ...args, reservationId: reserved.reservationId });
453
+ await t.mutation(ref("saveObservation"), {
454
+ inputJson: JSON.stringify(purchase),
455
+ startedAt: Date.now(),
456
+ proofJson: JSON.stringify({
457
+ creditGrantId: "credgr_topup1",
458
+ paymentIntentId: "pi_topup1",
459
+ currency: "usd",
460
+ ledgerAmount: 0,
461
+ availableAmount: 0,
462
+ granted: 20,
463
+ applied: 20,
464
+ expired: 0,
465
+ voided: 0,
466
+ reinstated: 0,
467
+ invoicesVerified: true,
468
+ complete: true,
469
+ transactions: [],
470
+ }),
471
+ });
472
+ await t.mutation(ref("freezePurchase"), {
473
+ key: row.key,
474
+ paymentIntentId: "pi_topup1",
475
+ reason: "payment_disputed",
476
+ });
477
+ await expect(
478
+ t.mutation(ref("closeAccount"), { bindingJson: JSON.stringify(meter) }),
479
+ ).rejects.toThrow(/dispute|recovery|reconcil/i);
480
+ expect(
481
+ await t.run((ctx) => ctx.db.query("usageCreditAccounts").first()),
482
+ ).toMatchObject({ closed: false, frozenReason: "payment_disputed" });
483
+ });
@@ -0,0 +1,33 @@
1
+ import { makeFunctionReference } from "convex/server";
2
+ import { afterEach, expect, it, vi } from "vitest";
3
+ import { setupCredits } from "./accounting.fixtures.js";
4
+ const ref = (name: string) =>
5
+ makeFunctionReference<"mutation">(`usageCredits/mutations:${name}`);
6
+ afterEach(() => vi.useRealTimers());
7
+ for (const age of [60000, 60001])
8
+ it(`uses native proof wall time rather than a future logical order at age ${age}ms`, async () => {
9
+ const { t, purchase, row } = await setupCredits();
10
+ await t.mutation(ref("saveObservation"), {
11
+ inputJson: JSON.stringify(purchase),
12
+ startedAt: Date.now() + 100000,
13
+ proofJson: JSON.stringify({
14
+ creditGrantId: "credgr_topup1",
15
+ paymentIntentId: "pi_topup1",
16
+ currency: "usd",
17
+ ledgerAmount: 20,
18
+ availableAmount: 20,
19
+ granted: 20,
20
+ applied: 0,
21
+ expired: 0,
22
+ voided: 0,
23
+ reinstated: 0,
24
+ invoicesVerified: true,
25
+ complete: true,
26
+ transactions: [],
27
+ }),
28
+ });
29
+ vi.setSystemTime(Date.now() + age);
30
+ const prepare = t.mutation(ref("prepareRefund"), { key: row.key });
31
+ if (age === 60000) await expect(prepare).resolves.toBeNull();
32
+ else await expect(prepare).rejects.toThrow(/current.*reconciliation/i);
33
+ });
@@ -158,3 +158,11 @@ export async function history(
158
158
  historyCount: row.historyCount + 1,
159
159
  });
160
160
  }
161
+
162
+ /** Observation order never extends the wall-clock lifetime of native financial evidence. */
163
+ export function freshCreditProof(grant: Doc<"usageCreditGrants">) {
164
+ const start = grant.proofStartedAt ?? grant.observedAt;
165
+ return (
166
+ start !== undefined && start <= Date.now() && Date.now() - start <= 60000
167
+ );
168
+ }
@@ -1,3 +1,4 @@
1
+ import { freshCreditProof } from "./helpers.js";
1
2
  import { canonicalFingerprint } from "../operationEvidence/canonical.js";
2
3
  import { accountTerms, grants } from "./helpers.js";
3
4
  import {
@@ -109,6 +110,7 @@ export const freezePurchase = mutation({
109
110
  throw new Error("Invalid original credit refund amount");
110
111
  await ctx.db.patch("usageCreditPurchases", row._id, {
111
112
  state: "frozen",
113
+ recoveryReason: args.reason,
112
114
  refundedAmount: Math.max(
113
115
  row.refundedAmount ?? 0,
114
116
  args.refundedAmount ?? 0,
@@ -140,7 +142,12 @@ export const freezePurchase = mutation({
140
142
  });
141
143
 
142
144
  export const saveObservation = mutation({
143
- args: { inputJson: v.string(), proofJson: v.string(), startedAt: v.number() },
145
+ args: {
146
+ inputJson: v.string(),
147
+ proofJson: v.string(),
148
+ startedAt: v.number(),
149
+ proofStartedAt: v.optional(v.number()),
150
+ },
144
151
  returns: v.string(),
145
152
  handler: async (ctx, args) => {
146
153
  if (
@@ -149,6 +156,15 @@ export const saveObservation = mutation({
149
156
  args.startedAt > Date.now() + 300000
150
157
  )
151
158
  throw new Error("Invalid credit observation time");
159
+ const proofStartedAt =
160
+ args.proofStartedAt ?? Math.min(args.startedAt, Date.now());
161
+ if (
162
+ !Number.isSafeInteger(proofStartedAt) ||
163
+ proofStartedAt < 0 ||
164
+ proofStartedAt > Date.now() ||
165
+ proofStartedAt > args.startedAt
166
+ )
167
+ throw new Error("Invalid credit proof wall time");
152
168
  const parsed = await purchaseTerms(args.inputJson),
153
169
  row = await purchase(ctx, parsed.key);
154
170
  const proof = creditNativeObservation.parse(
@@ -183,11 +199,33 @@ export const saveObservation = mutation({
183
199
  for (const tx of proof.transactions)
184
200
  await history(ctx, row.accountKey, "observation", tx.id, tx, row.key);
185
201
  const ledger = await account(ctx, row.accountKey);
186
- if ((grant.observedAt ?? -1) <= args.startedAt) {
202
+ const tiedConflict =
203
+ grant.observedAt === args.startedAt &&
204
+ (await canonicalFingerprint(proof)) !==
205
+ (await canonicalFingerprint(
206
+ grant.nativeObservationJson
207
+ ? JSON.parse(grant.nativeObservationJson)
208
+ : null,
209
+ ));
210
+ if ((grant.observedAt ?? -1) >= args.startedAt) {
211
+ result.backing = "held";
212
+ result.reason = "stale_native_observation";
213
+ if (tiedConflict) {
214
+ await ctx.db.patch("usageCreditGrants", grant._id, {
215
+ observationConflictAt: args.startedAt,
216
+ });
217
+ await ctx.db.patch("usageCreditAccounts", ledger._id, {
218
+ frozenReason: "observation_order_conflict",
219
+ });
220
+ }
221
+ }
222
+ if ((grant.observedAt ?? -1) < args.startedAt) {
187
223
  await ctx.db.patch("usageCreditGrants", grant._id, {
188
224
  nativeUnused: proof.ledgerAmount > 0,
189
225
  nativeObservationJson: JSON.stringify(proof),
190
226
  observedAt: args.startedAt,
227
+ proofStartedAt,
228
+ observationConflictAt: undefined,
191
229
  ...(proof.expired > 0 || proof.voided > 0
192
230
  ? { frozen: true, nativeExpired: true }
193
231
  : {}),
@@ -232,6 +270,8 @@ export const closeAccount = mutation({
232
270
  );
233
271
  const ledger = await account(ctx, original.key);
234
272
  if (ledger.closed) return null;
273
+ if (ledger.frozenReason)
274
+ throw new Error("Credit recovery reconciliation required before closure");
235
275
  const purchases = await ctx.db
236
276
  .query("usageCreditPurchases")
237
277
  .withIndex("by_account", (q) => q.eq("accountKey", original.key))
@@ -247,6 +287,14 @@ export const closeAccount = mutation({
247
287
  : null;
248
288
  const purchaseRow = await purchase(ctx, grant.purchaseKey),
249
289
  terms = (await purchaseTerms(purchaseRow.termsJson)).terms;
290
+ if (
291
+ purchaseRow.state === "frozen" &&
292
+ (purchaseRow.recoveryReason !== "payment_refunded" ||
293
+ purchaseRow.refundedAmount !== terms.amount)
294
+ )
295
+ throw new Error(
296
+ "Original payment recovery requires reconciliation before closure",
297
+ );
250
298
  if (
251
299
  BigInt(grant.available) > 0n &&
252
300
  !(
@@ -263,6 +311,8 @@ export const closeAccount = mutation({
263
311
  : creditCost(terms.binding.plan, grant.consumed);
264
312
  if (
265
313
  BigInt(grant.reserved) !== 0n ||
314
+ grant.observationConflictAt !== undefined ||
315
+ !freshCreditProof(grant) ||
266
316
  !proof?.complete ||
267
317
  !proof.invoicesVerified ||
268
318
  proof.ledgerAmount !== 0 ||
@@ -338,9 +388,10 @@ export const prepareRefund = mutation({
338
388
  : null;
339
389
  const terms = (await purchaseTerms(row.termsJson)).terms;
340
390
  if (
391
+ grant.observationConflictAt !== undefined ||
341
392
  !proof?.complete ||
342
393
  !proof.invoicesVerified ||
343
- Date.now() - (grant.observedAt ?? 0) > 60000 ||
394
+ !freshCreditProof(grant) ||
344
395
  proof.ledgerAmount !== terms.amount ||
345
396
  proof.applied !== 0 ||
346
397
  proof.reinstated !== 0 ||
@@ -382,10 +433,11 @@ export const resumeAccount = mutation({
382
433
  ? creditNativeObservation.parse(JSON.parse(grant.nativeObservationJson))
383
434
  : null;
384
435
  if (
436
+ grant.observationConflictAt !== undefined ||
385
437
  !proof ||
386
438
  !proof.complete ||
387
439
  !proof.invoicesVerified ||
388
- Date.now() - (grant.observedAt ?? 0) > 60000 ||
440
+ !freshCreditProof(grant) ||
389
441
  normalizeCreditState(terms, grant, proof, true).backing !==
390
442
  "sufficient" ||
391
443
  (row.state === "frozen" &&
@@ -398,7 +450,7 @@ export const resumeAccount = mutation({
398
450
  );
399
451
  evidence.push({
400
452
  creditGrantId: grant.creditGrantId,
401
- observedAt: grant.observedAt!,
453
+ observedAt: grant.proofStartedAt ?? grant.observedAt!,
402
454
  });
403
455
  }
404
456
  await ctx.db.patch("usageCreditAccounts", ledger._id, {
@@ -449,3 +501,29 @@ export const cancelUnstarted = mutation({
449
501
  return null;
450
502
  },
451
503
  });
504
+
505
+ /** Trusted host reserves a unique observation order before reading original native backing. */
506
+ export const beginObservation = mutation({
507
+ args: { inputJson: v.string() },
508
+ returns: v.number(),
509
+ handler: async (ctx, args) => {
510
+ const parsed = await purchaseTerms(args.inputJson),
511
+ row = await purchase(ctx, parsed.key);
512
+ const grant = await ctx.db
513
+ .query("usageCreditGrants")
514
+ .withIndex("by_purchase", (q) => q.eq("purchaseKey", row.key))
515
+ .unique();
516
+ if (!grant) throw new Error("Credit grant unavailable");
517
+ const startedAt = Math.max(
518
+ Date.now(),
519
+ (grant.observedAt ?? -1) + 1,
520
+ (grant.observationStartedAt ?? -1) + 1,
521
+ );
522
+ if (!Number.isSafeInteger(startedAt) || startedAt > Date.now() + 300000)
523
+ throw new Error("Credit observation order capacity exhausted");
524
+ await ctx.db.patch("usageCreditGrants", grant._id, {
525
+ observationStartedAt: startedAt,
526
+ });
527
+ return startedAt;
528
+ },
529
+ });
@@ -0,0 +1,63 @@
1
+ import { makeFunctionReference } from "convex/server";
2
+ import { afterEach, expect, it, vi } from "vitest";
3
+ import { setupCredits } from "./accounting.fixtures.js";
4
+ const ref = (name: string) =>
5
+ makeFunctionReference<"mutation">(`usageCredits/mutations:${name}`);
6
+ afterEach(() => vi.useRealTimers());
7
+ it("accepts the 1000th retained purchase, preserves replay and rejects 1001 without writing", async () => {
8
+ const { t, purchase } = await setupCredits();
9
+ await t.run(async (ctx) => {
10
+ const row = (await ctx.db.query("usageCreditAccounts").first())!;
11
+ await ctx.db.patch(row._id, { purchaseCount: 999 });
12
+ });
13
+ const inputJson = JSON.stringify({
14
+ ...purchase,
15
+ purchaseId: "last_retained",
16
+ });
17
+ const last = await t.mutation(ref("preparePurchase"), { inputJson });
18
+ expect(await t.mutation(ref("preparePurchase"), { inputJson })).toEqual(last);
19
+ await expect(
20
+ t.mutation(ref("preparePurchase"), {
21
+ inputJson: JSON.stringify({ ...purchase, purchaseId: "over_retained" }),
22
+ }),
23
+ ).rejects.toThrow(/purchase quota/i);
24
+ await t.run(async (ctx) => {
25
+ expect(await ctx.db.query("usageCreditAccounts").first()).toMatchObject({
26
+ purchaseCount: 1000,
27
+ });
28
+ expect(await ctx.db.query("usageCreditPurchases").take(3)).toHaveLength(2);
29
+ });
30
+ });
31
+ it("commits the 100000th credit audit entry and rolls back the next reservation", async () => {
32
+ const { t, event, subscription } = await setupCredits();
33
+ await t.run(async (ctx) => {
34
+ const row = (await ctx.db.query("usageCreditAccounts").first())!;
35
+ await ctx.db.patch(row._id, { historyCount: 99999 });
36
+ });
37
+ const args = {
38
+ inputJson: JSON.stringify({ ...event, quantity: "1" }),
39
+ subscriptionJson: JSON.stringify(subscription),
40
+ };
41
+ const last = await t.mutation(ref("reserve"), args);
42
+ expect(await t.mutation(ref("reserve"), args)).toEqual(last);
43
+ await expect(
44
+ t.mutation(ref("reserve"), {
45
+ ...args,
46
+ inputJson: JSON.stringify({
47
+ ...event,
48
+ quantity: "1",
49
+ sourceEventId: "over_retained",
50
+ }),
51
+ }),
52
+ ).rejects.toThrow(/history.*quota/i);
53
+ await t.run(async (ctx) => {
54
+ expect(await ctx.db.query("usageCreditAccounts").first()).toMatchObject({
55
+ historyCount: 100000,
56
+ });
57
+ expect(await ctx.db.query("usageReservations").take(2)).toHaveLength(1);
58
+ expect(await ctx.db.query("usageCreditGrants").first()).toMatchObject({
59
+ available: "9",
60
+ reserved: "1",
61
+ });
62
+ });
63
+ });
@@ -33,6 +33,13 @@ export const purchaseFields = {
33
33
  paymentKey: v.optional(v.string()),
34
34
  paymentProofJson: v.optional(v.string()),
35
35
  refundedAmount: v.optional(v.number()),
36
+ recoveryReason: v.optional(
37
+ v.union(
38
+ v.literal("payment_refunded"),
39
+ v.literal("payment_disputed"),
40
+ v.literal("native_state_changed"),
41
+ ),
42
+ ),
36
43
  grantFirstAttemptAt: v.optional(v.number()),
37
44
  creditGrantId: v.optional(v.string()),
38
45
  };
@@ -65,6 +72,9 @@ export const grantFields = {
65
72
  nativeExpired: v.optional(v.boolean()),
66
73
  nativeObservationJson: v.optional(v.string()),
67
74
  observedAt: v.optional(v.number()),
75
+ proofStartedAt: v.optional(v.number()),
76
+ observationStartedAt: v.optional(v.number()),
77
+ observationConflictAt: v.optional(v.number()),
68
78
  };
69
79
  export const grantDoc = v.object({
70
80
  _id: v.id("usageCreditGrants"),
@@ -67,3 +67,60 @@ it("retains original and renewed snapshots, deduplicates replay and keeps newer
67
67
  }),
68
68
  ).rejects.toThrow();
69
69
  });
70
+
71
+ it("retains the newer projection when conflicting native observations have the same timestamp", async () => {
72
+ const t = convexTest(schema, modules),
73
+ now = Date.now();
74
+ const intent = await t.mutation(prepare, {
75
+ termsJson: JSON.stringify(request),
76
+ method: "direct",
77
+ });
78
+ const renewed = nativeSubscription();
79
+ renewed.items.data.forEach((item) => {
80
+ item.current_period_start = 1200;
81
+ item.current_period_end = 1800;
82
+ });
83
+ await t.mutation(save, {
84
+ key: intent.key,
85
+ nativeJson: JSON.stringify(renewed),
86
+ startedAt: now,
87
+ });
88
+ await t.mutation(save, {
89
+ key: intent.key,
90
+ nativeJson: JSON.stringify(nativeSubscription()),
91
+ startedAt: now,
92
+ });
93
+ const scope = {
94
+ stripeAccountId: "acct_platform",
95
+ customerAccount: "acct_buyer",
96
+ livemode: false,
97
+ };
98
+ const projection = await t.query(get, { scope, requestId: "signup1" });
99
+ expect(
100
+ JSON.parse(projection.viewJson).bindings[0].subscription.period.start,
101
+ ).toBe(1200);
102
+ const page = await t.query(history, {
103
+ scope,
104
+ requestId: "signup1",
105
+ kind: "subscription",
106
+ paginationOpts: { numItems: 10, cursor: null },
107
+ });
108
+ expect(page.page).toHaveLength(2);
109
+ });
110
+
111
+ it("reserves distinct ordered observations before native I/O in a concurrent clock tick", async () => {
112
+ const t = convexTest(schema, modules);
113
+ const intent = await t.mutation(prepare, {
114
+ termsJson: JSON.stringify(request),
115
+ method: "direct",
116
+ });
117
+ const begin = makeFunctionReference<"mutation">(
118
+ "usageSubscriptions/mutations:beginObservation",
119
+ );
120
+ const stamps = await Promise.all([
121
+ t.mutation(begin, { key: intent.key }),
122
+ t.mutation(begin, { key: intent.key }),
123
+ ]);
124
+ expect(new Set(stamps).size).toBe(2);
125
+ expect(stamps.every(Number.isSafeInteger)).toBe(true);
126
+ });
@@ -58,7 +58,9 @@ export async function saveView(
58
58
  view,
59
59
  startedAt,
60
60
  );
61
- if ((intent.startedAt ?? -1) <= startedAt)
61
+ if ((intent.startedAt ?? -1) >= startedAt && intent.viewJson)
62
+ return JSON.parse(intent.viewJson) as ReturnType<typeof subscriptionView>;
63
+ if ((intent.startedAt ?? -1) < startedAt)
62
64
  await ctx.db.patch("usageSubscriptionIntents", intent._id, {
63
65
  providerId: view.subscriptionId,
64
66
  viewJson: JSON.stringify(view),
@@ -273,3 +273,26 @@ export const abandon = mutation({
273
273
  return null;
274
274
  },
275
275
  });
276
+
277
+ /** Reserve a unique order before native I/O, including concurrent same-clock observations. */
278
+ export const beginObservation = mutation({
279
+ args: { key: v.string() },
280
+ returns: v.number(),
281
+ handler: async (ctx, args) => {
282
+ const intent = await ctx.db
283
+ .query("usageSubscriptionIntents")
284
+ .withIndex("by_key", (q) => q.eq("key", args.key))
285
+ .unique();
286
+ if (!intent) throw new Error("Subscription intent not found");
287
+ const startedAt = Math.max(
288
+ Date.now(),
289
+ (intent.startedAt ?? -1) + 1,
290
+ (intent.observationStartedAt ?? -1) + 1,
291
+ );
292
+ observationStart(startedAt);
293
+ await ctx.db.patch("usageSubscriptionIntents", intent._id, {
294
+ observationStartedAt: startedAt,
295
+ });
296
+ return startedAt;
297
+ },
298
+ });
@@ -11,6 +11,7 @@ export const intentFields = {
11
11
  checkoutId: v.optional(v.string()),
12
12
  viewJson: v.optional(v.string()),
13
13
  startedAt: v.optional(v.number()),
14
+ observationStartedAt: v.optional(v.number()),
14
15
  controlKey: v.optional(v.string()),
15
16
  historyCount: v.optional(v.number()),
16
17
  retiredAt: v.optional(v.number()),