@fantastic.dev/better-stripe 0.60.0 → 0.60.1
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.
- package/CHANGELOG.md +6 -0
- package/README.md +3 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +26 -6
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +13 -3
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +26 -6
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +13 -3
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/usage/creditCapacity.d.ts.map +1 -1
- package/dist/client/usage/creditCapacity.js +7 -1
- package/dist/client/usage/creditCapacity.js.map +1 -1
- package/dist/client/usage/creditClient.d.ts +3 -0
- package/dist/client/usage/creditClient.d.ts.map +1 -1
- package/dist/client/usage/creditDelivery.d.ts.map +1 -1
- package/dist/client/usage/creditDelivery.js +4 -1
- package/dist/client/usage/creditDelivery.js.map +1 -1
- package/dist/client/usage/creditLifecycle.d.ts.map +1 -1
- package/dist/client/usage/creditLifecycle.js +2 -1
- package/dist/client/usage/creditLifecycle.js.map +1 -1
- package/dist/client/usage/creditNative.d.ts +3 -0
- package/dist/client/usage/creditNative.d.ts.map +1 -1
- package/dist/client/usage/creditNative.js +3 -0
- package/dist/client/usage/creditNative.js.map +1 -1
- package/dist/client/usage/creditProvider.d.ts.map +1 -1
- package/dist/client/usage/creditProvider.js +2 -1
- package/dist/client/usage/creditProvider.js.map +1 -1
- package/dist/client/usage/creditRead.d.ts +1 -0
- package/dist/client/usage/creditRead.d.ts.map +1 -1
- package/dist/client/usage/creditReconciliation.d.ts.map +1 -1
- package/dist/client/usage/creditReconciliation.js +11 -3
- package/dist/client/usage/creditReconciliation.js.map +1 -1
- package/dist/client/usage/creditSettlement.fixtures.d.ts +1 -0
- package/dist/client/usage/creditSettlement.fixtures.d.ts.map +1 -1
- package/dist/client/usage/creditTransport.fixtures.d.ts +1 -0
- package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -1
- package/dist/client/usage/creditTransport.fixtures.js +2 -1
- package/dist/client/usage/creditTransport.fixtures.js.map +1 -1
- package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -1
- package/dist/client/usage/subscriptionCancellation.js +3 -2
- package/dist/client/usage/subscriptionCancellation.js.map +1 -1
- package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -1
- package/dist/client/usage/subscriptionCheckout.js +3 -2
- package/dist/client/usage/subscriptionCheckout.js.map +1 -1
- package/dist/client/usage/subscriptionLifecycle.d.ts +1 -0
- package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -1
- package/dist/client/usage/subscriptionLifecycle.js +3 -2
- package/dist/client/usage/subscriptionLifecycle.js.map +1 -1
- package/dist/client/usage/subscriptionProvider.d.ts +2 -0
- package/dist/client/usage/subscriptionProvider.d.ts.map +1 -1
- package/dist/client/usage/subscriptionProvider.js +9 -2
- package/dist/client/usage/subscriptionProvider.js.map +1 -1
- package/dist/component/_generated/component.d.ts +21 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/earnings/triggers.d.ts +16 -6
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/schema.d.ts +13 -3
- package/dist/component/usage/allowance.fixtures.d.ts +4212 -0
- package/dist/component/usage/allowance.fixtures.d.ts.map +1 -0
- package/dist/component/usage/allowance.fixtures.js +67 -0
- package/dist/component/usage/allowance.fixtures.js.map +1 -0
- package/dist/component/usageCredits/accounting.fixtures.d.ts +4235 -0
- package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -0
- package/dist/component/usageCredits/accounting.fixtures.js +89 -0
- package/dist/component/usageCredits/accounting.fixtures.js.map +1 -0
- package/dist/component/usageCredits/helpers.d.ts +7 -0
- package/dist/component/usageCredits/helpers.d.ts.map +1 -1
- package/dist/component/usageCredits/helpers.js +5 -0
- package/dist/component/usageCredits/helpers.js.map +1 -1
- package/dist/component/usageCredits/mutations.d.ts +6 -0
- package/dist/component/usageCredits/mutations.d.ts.map +1 -1
- package/dist/component/usageCredits/mutations.js +70 -7
- package/dist/component/usageCredits/mutations.js.map +1 -1
- package/dist/component/usageCredits/purchase.d.ts +1 -0
- package/dist/component/usageCredits/purchase.d.ts.map +1 -1
- package/dist/component/usageCredits/queries.d.ts +10 -0
- package/dist/component/usageCredits/queries.d.ts.map +1 -1
- package/dist/component/usageCredits/schema.d.ts +24 -4
- package/dist/component/usageCredits/schema.d.ts.map +1 -1
- package/dist/component/usageCredits/schema.js +4 -0
- package/dist/component/usageCredits/schema.js.map +1 -1
- package/dist/component/usageSubscriptions/history.d.ts.map +1 -1
- package/dist/component/usageSubscriptions/history.js +3 -1
- package/dist/component/usageSubscriptions/history.js.map +1 -1
- package/dist/component/usageSubscriptions/mutations.d.ts +5 -0
- package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -1
- package/dist/component/usageSubscriptions/mutations.js +19 -0
- package/dist/component/usageSubscriptions/mutations.js.map +1 -1
- package/dist/component/usageSubscriptions/queries.d.ts +2 -0
- package/dist/component/usageSubscriptions/queries.d.ts.map +1 -1
- package/dist/component/usageSubscriptions/schema.d.ts +7 -2
- package/dist/component/usageSubscriptions/schema.d.ts.map +1 -1
- package/dist/component/usageSubscriptions/schema.js +1 -0
- package/dist/component/usageSubscriptions/schema.js.map +1 -1
- package/docs/README.md +2 -0
- package/docs/usage-credits.md +6 -1
- package/docs/usage-security.md +130 -0
- package/package.json +2 -1
- package/src/client/usage/creditBackingIsolation.test.ts +110 -0
- package/src/client/usage/creditCapacity.test.ts +80 -1
- package/src/client/usage/creditCapacity.ts +10 -1
- package/src/client/usage/creditDelivery.ts +4 -0
- package/src/client/usage/creditLifecycle.ts +2 -0
- package/src/client/usage/creditNative.ts +5 -0
- package/src/client/usage/creditProofBounds.test.ts +187 -0
- package/src/client/usage/creditProvider.test.ts +74 -0
- package/src/client/usage/creditProvider.ts +2 -0
- package/src/client/usage/creditReconciliation.ts +18 -3
- package/src/client/usage/creditTransport.fixtures.ts +2 -1
- package/src/client/usage/subscriptionCancellation.ts +3 -2
- package/src/client/usage/subscriptionCheckout.ts +7 -2
- package/src/client/usage/subscriptionClient.test.ts +60 -1
- package/src/client/usage/subscriptionLifecycle.ts +3 -2
- package/src/client/usage/subscriptionProvider.ts +27 -3
- package/src/component/_generated/component.ts +40 -1
- package/src/component/usage/allowance.fixtures.ts +77 -0
- package/src/component/usage/allowance.test.ts +3 -66
- package/src/component/usage/allowanceBounds.test.ts +79 -0
- package/src/component/usage/historyIsolation.test.ts +124 -0
- package/src/component/usageCredits/accounting.fixtures.ts +96 -0
- package/src/component/usageCredits/accounting.test.ts +176 -82
- package/src/component/usageCredits/freshness.test.ts +33 -0
- package/src/component/usageCredits/helpers.ts +8 -0
- package/src/component/usageCredits/mutations.ts +83 -5
- package/src/component/usageCredits/quotas.test.ts +63 -0
- package/src/component/usageCredits/schema.ts +10 -0
- package/src/component/usageSubscriptions/history.test.ts +57 -0
- package/src/component/usageSubscriptions/history.ts +3 -1
- package/src/component/usageSubscriptions/mutations.ts +23 -0
- package/src/component/usageSubscriptions/schema.ts +1 -0
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { convexTest } from "convex-test";
|
|
2
|
+
import { makeFunctionReference } from "convex/server";
|
|
3
|
+
import { vi } from "vitest";
|
|
4
|
+
import { schema, modules } from "../../test.js";
|
|
5
|
+
import {
|
|
6
|
+
request,
|
|
7
|
+
nativeSubscription,
|
|
8
|
+
} from "../../client/usage/subscription.fixtures.js";
|
|
9
|
+
const ref = (name: string) =>
|
|
10
|
+
makeFunctionReference<"mutation">(`usageCredits/mutations:${name}`);
|
|
11
|
+
const prepare = makeFunctionReference<"mutation">(
|
|
12
|
+
"usageSubscriptions/mutations:prepare",
|
|
13
|
+
);
|
|
14
|
+
const save = makeFunctionReference<"mutation">(
|
|
15
|
+
"usageSubscriptions/mutations:save",
|
|
16
|
+
);
|
|
17
|
+
export async function setupCredits() {
|
|
18
|
+
vi.useFakeTimers();
|
|
19
|
+
vi.setSystemTime(700000);
|
|
20
|
+
const t = convexTest(schema, modules);
|
|
21
|
+
const meter = {
|
|
22
|
+
scope: request.meters[0].scope,
|
|
23
|
+
binding: {
|
|
24
|
+
...request.meters[0].binding,
|
|
25
|
+
plan: {
|
|
26
|
+
key: "calls",
|
|
27
|
+
version: "v1",
|
|
28
|
+
model: "prepaid",
|
|
29
|
+
unit: { name: "call", precision: 0 },
|
|
30
|
+
rate: { currency: "usd", unitAmountDecimal: "2" },
|
|
31
|
+
insufficientBalance: "reject",
|
|
32
|
+
} as const,
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
const terms = { ...request, meters: [meter] };
|
|
36
|
+
const intent = await t.mutation(prepare, {
|
|
37
|
+
termsJson: JSON.stringify(terms),
|
|
38
|
+
method: "direct",
|
|
39
|
+
});
|
|
40
|
+
await t.mutation(save, {
|
|
41
|
+
key: intent.key,
|
|
42
|
+
nativeJson: JSON.stringify(nativeSubscription()),
|
|
43
|
+
startedAt: Date.now(),
|
|
44
|
+
});
|
|
45
|
+
const purchase = {
|
|
46
|
+
...meter,
|
|
47
|
+
purchaseId: "topup1",
|
|
48
|
+
quantity: "10",
|
|
49
|
+
ownership: "issuer",
|
|
50
|
+
rollover: "retain_original_terms",
|
|
51
|
+
};
|
|
52
|
+
const row = await t.mutation(ref("preparePurchase"), {
|
|
53
|
+
inputJson: JSON.stringify(purchase),
|
|
54
|
+
});
|
|
55
|
+
await t.mutation(ref("pinPayment"), {
|
|
56
|
+
key: row.key,
|
|
57
|
+
paymentIntentId: "pi_topup1",
|
|
58
|
+
});
|
|
59
|
+
const proof = {
|
|
60
|
+
paymentIntentId: "pi_topup1",
|
|
61
|
+
chargeId: "ch_topup1",
|
|
62
|
+
amount: 20,
|
|
63
|
+
currency: "usd",
|
|
64
|
+
customerAccount: "acct_buyer",
|
|
65
|
+
livemode: false,
|
|
66
|
+
};
|
|
67
|
+
await t.mutation(ref("verifyPayment"), {
|
|
68
|
+
key: row.key,
|
|
69
|
+
proofJson: JSON.stringify(proof),
|
|
70
|
+
});
|
|
71
|
+
await t.mutation(ref("pinGrant"), {
|
|
72
|
+
key: row.key,
|
|
73
|
+
proofJson: JSON.stringify({
|
|
74
|
+
...proof,
|
|
75
|
+
creditGrantId: "credgr_topup1",
|
|
76
|
+
stripePriceId: "price_calls",
|
|
77
|
+
createdAt: 700,
|
|
78
|
+
effectiveAt: 700,
|
|
79
|
+
expiresAt: null,
|
|
80
|
+
}),
|
|
81
|
+
});
|
|
82
|
+
const subscription = {
|
|
83
|
+
subscriptionId: "sub_calls",
|
|
84
|
+
subscriptionItemId: "si_calls",
|
|
85
|
+
stripePriceId: "price_calls",
|
|
86
|
+
period: { start: 600, end: 1200 },
|
|
87
|
+
interval: "month",
|
|
88
|
+
};
|
|
89
|
+
const event = {
|
|
90
|
+
...meter,
|
|
91
|
+
sourceEventId: "work1",
|
|
92
|
+
quantity: "6",
|
|
93
|
+
occurredAt: 700,
|
|
94
|
+
};
|
|
95
|
+
return { t, meter, purchase, row, proof, subscription, event };
|
|
96
|
+
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import {
|
|
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
|
-
|
|
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: {
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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"),
|