@fantastic.dev/better-stripe 0.56.0 → 0.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +5 -1
- package/dist/client/billing/setup-intent-read.d.ts +12 -1
- package/dist/client/billing/setup-intent-read.d.ts.map +1 -1
- package/dist/client/billing/setup-intent-read.js +13 -8
- package/dist/client/billing/setup-intent-read.js.map +1 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +366 -2
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +183 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +366 -2
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +183 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/index.d.ts +2 -12
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +3 -20
- package/dist/client/index.js.map +1 -1
- package/dist/client/types/triggers.d.ts +3 -1
- package/dist/client/types/triggers.d.ts.map +1 -1
- package/dist/client/usage/allowanceClient.d.ts +51 -0
- package/dist/client/usage/allowanceClient.d.ts.map +1 -0
- package/dist/client/usage/allowanceClient.js +64 -0
- package/dist/client/usage/allowanceClient.js.map +1 -0
- package/dist/client/usage/allowanceTerms.d.ts +64 -0
- package/dist/client/usage/allowanceTerms.d.ts.map +1 -0
- package/dist/client/usage/allowanceTerms.js +101 -0
- package/dist/client/usage/allowanceTerms.js.map +1 -0
- package/dist/client/usage/client.d.ts +2 -2
- package/dist/client/usage/client.d.ts.map +1 -1
- package/dist/client/usage/client.js +4 -4
- package/dist/client/usage/client.js.map +1 -1
- package/dist/client/usage/creditCapacity.d.ts +5 -0
- package/dist/client/usage/creditCapacity.d.ts.map +1 -0
- package/dist/client/usage/creditCapacity.js +47 -0
- package/dist/client/usage/creditCapacity.js.map +1 -0
- package/dist/client/usage/creditClient.d.ts +104 -0
- package/dist/client/usage/creditClient.d.ts.map +1 -0
- package/dist/client/usage/creditClient.js +111 -0
- package/dist/client/usage/creditClient.js.map +1 -0
- package/dist/client/usage/creditDelivery.d.ts +6 -0
- package/dist/client/usage/creditDelivery.d.ts.map +1 -0
- package/dist/client/usage/creditDelivery.js +71 -0
- package/dist/client/usage/creditDelivery.js.map +1 -0
- package/dist/client/usage/creditInvoice.d.ts +6 -0
- package/dist/client/usage/creditInvoice.d.ts.map +1 -0
- package/dist/client/usage/creditInvoice.js +63 -0
- package/dist/client/usage/creditInvoice.js.map +1 -0
- package/dist/client/usage/creditLifecycle.d.ts +14 -0
- package/dist/client/usage/creditLifecycle.d.ts.map +1 -0
- package/dist/client/usage/creditLifecycle.js +90 -0
- package/dist/client/usage/creditLifecycle.js.map +1 -0
- package/dist/client/usage/creditNative.d.ts +20 -0
- package/dist/client/usage/creditNative.d.ts.map +1 -0
- package/dist/client/usage/creditNative.js +100 -0
- package/dist/client/usage/creditNative.js.map +1 -0
- package/dist/client/usage/creditObservation.d.ts +23 -0
- package/dist/client/usage/creditObservation.d.ts.map +1 -0
- package/dist/client/usage/creditObservation.js +54 -0
- package/dist/client/usage/creditObservation.js.map +1 -0
- package/dist/client/usage/creditProofs.d.ts +50 -0
- package/dist/client/usage/creditProofs.d.ts.map +1 -0
- package/dist/client/usage/creditProofs.js +58 -0
- package/dist/client/usage/creditProofs.js.map +1 -0
- package/dist/client/usage/creditProvider.d.ts +11 -0
- package/dist/client/usage/creditProvider.d.ts.map +1 -0
- package/dist/client/usage/creditProvider.js +195 -0
- package/dist/client/usage/creditProvider.js.map +1 -0
- package/dist/client/usage/creditRead.d.ts +47 -0
- package/dist/client/usage/creditRead.d.ts.map +1 -0
- package/dist/client/usage/creditRead.js +18 -0
- package/dist/client/usage/creditRead.js.map +1 -0
- package/dist/client/usage/creditReconciliation.d.ts +20 -0
- package/dist/client/usage/creditReconciliation.d.ts.map +1 -0
- package/dist/client/usage/creditReconciliation.js +157 -0
- package/dist/client/usage/creditReconciliation.js.map +1 -0
- package/dist/client/usage/creditTerms.d.ts +89 -0
- package/dist/client/usage/creditTerms.d.ts.map +1 -0
- package/dist/client/usage/creditTerms.js +76 -0
- package/dist/client/usage/creditTerms.js.map +1 -0
- package/dist/client/usage/creditTransport.fixtures.d.ts +101 -0
- package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -0
- package/dist/client/usage/creditTransport.fixtures.js +271 -0
- package/dist/client/usage/creditTransport.fixtures.js.map +1 -0
- package/dist/client/usage/deliveryProvider.d.ts.map +1 -1
- package/dist/client/usage/deliveryProvider.js +2 -0
- package/dist/client/usage/deliveryProvider.js.map +1 -1
- package/dist/client/usage/index.d.ts +4 -0
- package/dist/client/usage/index.d.ts.map +1 -1
- package/dist/client/usage/index.js +1 -0
- package/dist/client/usage/index.js.map +1 -1
- package/dist/client/usage/records.d.ts +2 -0
- package/dist/client/usage/records.d.ts.map +1 -1
- package/dist/client/usage/records.js +22 -0
- package/dist/client/usage/records.js.map +1 -1
- package/dist/client/usage/subscriptionTransport.fixtures.d.ts +1 -1
- package/dist/client/usage/subscriptionTransport.fixtures.d.ts.map +1 -1
- package/dist/client/usage/subscriptionTransport.fixtures.js +4 -1
- package/dist/client/usage/subscriptionTransport.fixtures.js.map +1 -1
- package/dist/client/usage/summary.js +2 -2
- package/dist/client/usage/summary.js.map +1 -1
- package/dist/client/usageExports.d.ts +16 -0
- package/dist/client/usageExports.d.ts.map +1 -0
- package/dist/client/usageExports.js +3 -0
- package/dist/client/usageExports.js.map +1 -0
- package/dist/client/webhooks/subscriptionDeleted.d.ts +5 -0
- package/dist/client/webhooks/subscriptionDeleted.d.ts.map +1 -0
- package/dist/client/webhooks/subscriptionDeleted.js +34 -0
- package/dist/client/webhooks/subscriptionDeleted.js.map +1 -0
- package/dist/component/_generated/api.d.ts +18 -0
- package/dist/component/_generated/api.d.ts.map +1 -1
- package/dist/component/_generated/api.js.map +1 -1
- package/dist/component/_generated/component.d.ts +360 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/accountClosure/mutations.d.ts.map +1 -1
- package/dist/component/accountClosure/mutations.js +10 -0
- package/dist/component/accountClosure/mutations.js.map +1 -1
- package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
- package/dist/component/balanceFunding/mutations.d.ts +16 -16
- package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
- package/dist/component/balanceFunding/queries.d.ts +1 -1
- package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
- package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
- package/dist/component/earnings/triggers.d.ts +352 -18
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/payoutRelease/queries.d.ts +2 -2
- package/dist/component/payoutRelease/queries.d.ts.map +1 -1
- package/dist/component/schema.d.ts +183 -1
- package/dist/component/schema.js +8 -0
- package/dist/component/schema.js.map +1 -1
- package/dist/component/usage/mutations.d.ts.map +1 -1
- package/dist/component/usage/mutations.js +7 -0
- package/dist/component/usage/mutations.js.map +1 -1
- package/dist/component/usage/schema.d.ts +15 -1
- package/dist/component/usage/schema.d.ts.map +1 -1
- package/dist/component/usage/schema.js +12 -0
- package/dist/component/usage/schema.js.map +1 -1
- package/dist/component/usageAllowance/helpers.d.ts +78 -0
- package/dist/component/usageAllowance/helpers.d.ts.map +1 -0
- package/dist/component/usageAllowance/helpers.js +99 -0
- package/dist/component/usageAllowance/helpers.js.map +1 -0
- package/dist/component/usageAllowance/mutations.d.ts +37 -0
- package/dist/component/usageAllowance/mutations.d.ts.map +1 -0
- package/dist/component/usageAllowance/mutations.js +99 -0
- package/dist/component/usageAllowance/mutations.js.map +1 -0
- package/dist/component/usageAllowance/queries.d.ts +36 -0
- package/dist/component/usageAllowance/queries.d.ts.map +1 -0
- package/dist/component/usageAllowance/queries.js +113 -0
- package/dist/component/usageAllowance/queries.js.map +1 -0
- package/dist/component/usageAllowance/reservations.d.ts +25 -0
- package/dist/component/usageAllowance/reservations.d.ts.map +1 -0
- package/dist/component/usageAllowance/reservations.js +150 -0
- package/dist/component/usageAllowance/reservations.js.map +1 -0
- package/dist/component/usageAllowance/schema.d.ts +77 -0
- package/dist/component/usageAllowance/schema.d.ts.map +1 -0
- package/dist/component/usageAllowance/schema.js +32 -0
- package/dist/component/usageAllowance/schema.js.map +1 -0
- package/dist/component/usageCredits/helpers.d.ts +205 -0
- package/dist/component/usageCredits/helpers.d.ts.map +1 -0
- package/dist/component/usageCredits/helpers.js +129 -0
- package/dist/component/usageCredits/helpers.js.map +1 -0
- package/dist/component/usageCredits/mutations.d.ts +80 -0
- package/dist/component/usageCredits/mutations.d.ts.map +1 -0
- package/dist/component/usageCredits/mutations.js +344 -0
- package/dist/component/usageCredits/mutations.js.map +1 -0
- package/dist/component/usageCredits/purchase.d.ts +23 -0
- package/dist/component/usageCredits/purchase.d.ts.map +1 -0
- package/dist/component/usageCredits/purchase.js +166 -0
- package/dist/component/usageCredits/purchase.js.map +1 -0
- package/dist/component/usageCredits/queries.d.ts +184 -0
- package/dist/component/usageCredits/queries.d.ts.map +1 -0
- package/dist/component/usageCredits/queries.js +243 -0
- package/dist/component/usageCredits/queries.js.map +1 -0
- package/dist/component/usageCredits/reservations.d.ts +16 -0
- package/dist/component/usageCredits/reservations.d.ts.map +1 -0
- package/dist/component/usageCredits/reservations.js +161 -0
- package/dist/component/usageCredits/reservations.js.map +1 -0
- package/dist/component/usageCredits/schema.d.ts +282 -0
- package/dist/component/usageCredits/schema.d.ts.map +1 -0
- package/dist/component/usageCredits/schema.js +92 -0
- package/dist/component/usageCredits/schema.js.map +1 -0
- package/docs/README.md +4 -0
- package/docs/setup-intent-recovery.md +7 -0
- package/docs/usage-credits.md +255 -0
- package/docs/usage-ledger.md +7 -0
- package/docs/usage-limits.md +217 -0
- package/docs/webhooks.md +15 -1
- package/package.json +3 -1
- package/src/client/billing/setup-intent-read.test.ts +40 -0
- package/src/client/billing/setup-intent-read.ts +23 -9
- package/src/client/index.ts +9 -67
- package/src/client/types/triggers.ts +2 -0
- package/src/client/usage/allowanceClient.test.ts +93 -0
- package/src/client/usage/allowanceClient.ts +134 -0
- package/src/client/usage/allowanceTerms.test.ts +131 -0
- package/src/client/usage/allowanceTerms.ts +172 -0
- package/src/client/usage/client.ts +4 -4
- package/src/client/usage/creditCapacity.test.ts +83 -0
- package/src/client/usage/creditCapacity.ts +76 -0
- package/src/client/usage/creditClient.test.ts +221 -0
- package/src/client/usage/creditClient.ts +246 -0
- package/src/client/usage/creditDelivery.ts +105 -0
- package/src/client/usage/creditInvoice.test.ts +149 -0
- package/src/client/usage/creditInvoice.ts +87 -0
- package/src/client/usage/creditLifecycle.ts +175 -0
- package/src/client/usage/creditNative.ts +148 -0
- package/src/client/usage/creditObservation.test.ts +150 -0
- package/src/client/usage/creditObservation.ts +82 -0
- package/src/client/usage/creditProofs.ts +61 -0
- package/src/client/usage/creditProvider.test.ts +202 -0
- package/src/client/usage/creditProvider.ts +304 -0
- package/src/client/usage/creditRead.ts +32 -0
- package/src/client/usage/creditReconciliation.ts +213 -0
- package/src/client/usage/creditTerms.test.ts +48 -0
- package/src/client/usage/creditTerms.ts +140 -0
- package/src/client/usage/creditTransport.fixtures.ts +282 -0
- package/src/client/usage/deliveryProvider.ts +2 -0
- package/src/client/usage/index.ts +16 -0
- package/src/client/usage/record-composition.test.ts +195 -0
- package/src/client/usage/records.ts +26 -0
- package/src/client/usage/subscriptionTransport.fixtures.ts +6 -0
- package/src/client/usage/summary.test.ts +1 -1
- package/src/client/usage/summary.ts +2 -2
- package/src/client/usageExports.ts +56 -0
- package/src/client/webhook-handlers.test.ts +0 -34
- package/src/client/webhooks/subscription-deleted-dispatch.test.ts +61 -0
- package/src/client/webhooks/subscription-deleted.integration.test.ts +313 -0
- package/src/client/webhooks/subscriptionDeleted.ts +56 -0
- package/src/component/_generated/api.ts +18 -0
- package/src/component/_generated/component.ts +486 -0
- package/src/component/accountClosure/mutations.ts +14 -0
- package/src/component/schema.ts +16 -0
- package/src/component/usage/allowance.test.ts +435 -0
- package/src/component/usage/ledger.test.ts +8 -15
- package/src/component/usage/mutations.ts +22 -0
- package/src/component/usage/schema.ts +14 -0
- package/src/component/usageAllowance/helpers.ts +137 -0
- package/src/component/usageAllowance/mutations.ts +139 -0
- package/src/component/usageAllowance/queries.ts +133 -0
- package/src/component/usageAllowance/reservations.ts +220 -0
- package/src/component/usageAllowance/schema.ts +36 -0
- package/src/component/usageCredits/accounting.test.ts +389 -0
- package/src/component/usageCredits/helpers.ts +160 -0
- package/src/component/usageCredits/mutations.ts +451 -0
- package/src/component/usageCredits/purchase.ts +219 -0
- package/src/component/usageCredits/queries.ts +300 -0
- package/src/component/usageCredits/reservations.ts +214 -0
- package/src/component/usageCredits/schema.ts +106 -0
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
import { canonicalFingerprint } from "../operationEvidence/canonical.js";
|
|
2
|
+
import { accountTerms, grants } from "./helpers.js";
|
|
3
|
+
import {
|
|
4
|
+
creditCost,
|
|
5
|
+
type UsageCreditBinding,
|
|
6
|
+
} from "../../client/usage/creditTerms.js";
|
|
7
|
+
import { creditNativeObservation } from "../../client/usage/creditProofs.js";
|
|
8
|
+
import { normalizeCreditState } from "../../client/usage/creditObservation.js";
|
|
9
|
+
import { purchaseTerms } from "./helpers.js";
|
|
10
|
+
import { v } from "convex/values";
|
|
11
|
+
import { mutation } from "../_generated/server.js";
|
|
12
|
+
import { scopeValidator } from "../usage/schema.js";
|
|
13
|
+
import { purchaseDoc } from "./schema.js";
|
|
14
|
+
import * as purchases from "./purchase.js";
|
|
15
|
+
import * as reservations from "./reservations.js";
|
|
16
|
+
import { boundedJson, purchase, account, history } from "./helpers.js";
|
|
17
|
+
export const preparePurchase = mutation({
|
|
18
|
+
args: { inputJson: v.string() },
|
|
19
|
+
returns: purchaseDoc,
|
|
20
|
+
handler: (ctx, args) => purchases.preparePurchase(ctx, args.inputJson),
|
|
21
|
+
});
|
|
22
|
+
export const pinPayment = mutation({
|
|
23
|
+
args: { key: v.string(), paymentIntentId: v.string() },
|
|
24
|
+
returns: v.null(),
|
|
25
|
+
handler: async (ctx, args) => {
|
|
26
|
+
await purchases.pinPayment(ctx, args.key, args.paymentIntentId);
|
|
27
|
+
return null;
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
export const verifyPayment = mutation({
|
|
31
|
+
args: { key: v.string(), proofJson: v.string() },
|
|
32
|
+
returns: v.null(),
|
|
33
|
+
handler: async (ctx, args) => {
|
|
34
|
+
boundedJson(args.proofJson);
|
|
35
|
+
await purchases.verifyPayment(ctx, args.key, args.proofJson);
|
|
36
|
+
return null;
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
export const pinGrant = mutation({
|
|
40
|
+
args: { key: v.string(), proofJson: v.string() },
|
|
41
|
+
returns: v.null(),
|
|
42
|
+
handler: async (ctx, args) => {
|
|
43
|
+
boundedJson(args.proofJson);
|
|
44
|
+
await purchases.pinGrant(ctx, args.key, args.proofJson);
|
|
45
|
+
return null;
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
export const reserve = mutation({
|
|
49
|
+
args: { inputJson: v.string(), subscriptionJson: v.string() },
|
|
50
|
+
returns: v.object({
|
|
51
|
+
reservationId: v.id("usageReservations"),
|
|
52
|
+
state: v.union(
|
|
53
|
+
v.literal("reserved"),
|
|
54
|
+
v.literal("committed"),
|
|
55
|
+
v.literal("released"),
|
|
56
|
+
),
|
|
57
|
+
}),
|
|
58
|
+
handler: (ctx, args) =>
|
|
59
|
+
reservations.reserve(ctx, args.inputJson, args.subscriptionJson),
|
|
60
|
+
});
|
|
61
|
+
export const release = mutation({
|
|
62
|
+
args: {
|
|
63
|
+
scope: scopeValidator,
|
|
64
|
+
reservationId: v.id("usageReservations"),
|
|
65
|
+
reason: v.union(
|
|
66
|
+
v.literal("work_failed"),
|
|
67
|
+
v.literal("abandoned_before_work"),
|
|
68
|
+
),
|
|
69
|
+
},
|
|
70
|
+
returns: v.null(),
|
|
71
|
+
handler: async (ctx, args) => {
|
|
72
|
+
await reservations.release(
|
|
73
|
+
ctx,
|
|
74
|
+
args.scope,
|
|
75
|
+
args.reservationId,
|
|
76
|
+
args.reason,
|
|
77
|
+
);
|
|
78
|
+
return null;
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
export const freezePurchase = mutation({
|
|
83
|
+
args: {
|
|
84
|
+
key: v.string(),
|
|
85
|
+
paymentIntentId: v.string(),
|
|
86
|
+
refundedAmount: v.optional(v.number()),
|
|
87
|
+
reason: v.union(
|
|
88
|
+
v.literal("payment_refunded"),
|
|
89
|
+
v.literal("payment_disputed"),
|
|
90
|
+
v.literal("native_state_changed"),
|
|
91
|
+
),
|
|
92
|
+
},
|
|
93
|
+
returns: v.null(),
|
|
94
|
+
handler: async (ctx, args) => {
|
|
95
|
+
const row = await purchase(ctx, args.key);
|
|
96
|
+
if (row.paymentIntentId !== args.paymentIntentId)
|
|
97
|
+
throw new Error("Credit recovery payment identity mismatch");
|
|
98
|
+
const grant = await ctx.db
|
|
99
|
+
.query("usageCreditGrants")
|
|
100
|
+
.withIndex("by_purchase", (q) => q.eq("purchaseKey", row.key))
|
|
101
|
+
.unique();
|
|
102
|
+
const terms = (await purchaseTerms(row.termsJson)).terms;
|
|
103
|
+
if (
|
|
104
|
+
args.refundedAmount !== undefined &&
|
|
105
|
+
(!Number.isSafeInteger(args.refundedAmount) ||
|
|
106
|
+
args.refundedAmount < 0 ||
|
|
107
|
+
args.refundedAmount > terms.amount)
|
|
108
|
+
)
|
|
109
|
+
throw new Error("Invalid original credit refund amount");
|
|
110
|
+
await ctx.db.patch("usageCreditPurchases", row._id, {
|
|
111
|
+
state: "frozen",
|
|
112
|
+
refundedAmount: Math.max(
|
|
113
|
+
row.refundedAmount ?? 0,
|
|
114
|
+
args.refundedAmount ?? 0,
|
|
115
|
+
),
|
|
116
|
+
});
|
|
117
|
+
if (grant)
|
|
118
|
+
await ctx.db.patch("usageCreditGrants", grant._id, { frozen: true });
|
|
119
|
+
if (grant && (BigInt(grant.reserved) > 0n || BigInt(grant.consumed) > 0n)) {
|
|
120
|
+
const ledger = await account(ctx, row.accountKey);
|
|
121
|
+
await ctx.db.patch("usageCreditAccounts", ledger._id, {
|
|
122
|
+
frozenReason: args.reason,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
await history(
|
|
126
|
+
ctx,
|
|
127
|
+
row.accountKey,
|
|
128
|
+
"recovery",
|
|
129
|
+
args.paymentIntentId,
|
|
130
|
+
{
|
|
131
|
+
reason: args.reason,
|
|
132
|
+
creditGrantId: row.creditGrantId ?? null,
|
|
133
|
+
cashCollection: "none",
|
|
134
|
+
refundedAmount: args.refundedAmount ?? null,
|
|
135
|
+
},
|
|
136
|
+
row.key,
|
|
137
|
+
);
|
|
138
|
+
return null;
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
export const saveObservation = mutation({
|
|
143
|
+
args: { inputJson: v.string(), proofJson: v.string(), startedAt: v.number() },
|
|
144
|
+
returns: v.string(),
|
|
145
|
+
handler: async (ctx, args) => {
|
|
146
|
+
if (
|
|
147
|
+
!Number.isSafeInteger(args.startedAt) ||
|
|
148
|
+
args.startedAt < 0 ||
|
|
149
|
+
args.startedAt > Date.now() + 300000
|
|
150
|
+
)
|
|
151
|
+
throw new Error("Invalid credit observation time");
|
|
152
|
+
const parsed = await purchaseTerms(args.inputJson),
|
|
153
|
+
row = await purchase(ctx, parsed.key);
|
|
154
|
+
const proof = creditNativeObservation.parse(
|
|
155
|
+
boundedJson(args.proofJson, 65536),
|
|
156
|
+
);
|
|
157
|
+
if (
|
|
158
|
+
row.creditGrantId !== proof.creditGrantId ||
|
|
159
|
+
row.paymentIntentId !== proof.paymentIntentId ||
|
|
160
|
+
proof.currency !== parsed.terms.binding.plan.rate.currency
|
|
161
|
+
)
|
|
162
|
+
throw new Error("Credit observation provenance mismatch");
|
|
163
|
+
const grant = await ctx.db
|
|
164
|
+
.query("usageCreditGrants")
|
|
165
|
+
.withIndex("by_purchase", (q) => q.eq("purchaseKey", row.key))
|
|
166
|
+
.unique();
|
|
167
|
+
if (!grant) throw new Error("Credit grant unavailable");
|
|
168
|
+
const result = normalizeCreditState(
|
|
169
|
+
parsed.terms,
|
|
170
|
+
grant,
|
|
171
|
+
proof,
|
|
172
|
+
proof.invoicesVerified && proof.complete,
|
|
173
|
+
);
|
|
174
|
+
if (
|
|
175
|
+
row.state === "frozen" &&
|
|
176
|
+
(BigInt(grant.reserved) > 0n ||
|
|
177
|
+
BigInt(grant.consumed) > 0n ||
|
|
178
|
+
proof.ledgerAmount > 0)
|
|
179
|
+
) {
|
|
180
|
+
result.backing = "held";
|
|
181
|
+
result.reason = "credit_purchase_frozen";
|
|
182
|
+
}
|
|
183
|
+
for (const tx of proof.transactions)
|
|
184
|
+
await history(ctx, row.accountKey, "observation", tx.id, tx, row.key);
|
|
185
|
+
const ledger = await account(ctx, row.accountKey);
|
|
186
|
+
if ((grant.observedAt ?? -1) <= args.startedAt) {
|
|
187
|
+
await ctx.db.patch("usageCreditGrants", grant._id, {
|
|
188
|
+
nativeUnused: proof.ledgerAmount > 0,
|
|
189
|
+
nativeObservationJson: JSON.stringify(proof),
|
|
190
|
+
observedAt: args.startedAt,
|
|
191
|
+
...(proof.expired > 0 || proof.voided > 0
|
|
192
|
+
? { frozen: true, nativeExpired: true }
|
|
193
|
+
: {}),
|
|
194
|
+
});
|
|
195
|
+
if (result.backing === "held")
|
|
196
|
+
await ctx.db.patch("usageCreditAccounts", ledger._id, {
|
|
197
|
+
frozenReason: result.reason!,
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
await history(
|
|
201
|
+
ctx,
|
|
202
|
+
row.accountKey,
|
|
203
|
+
"observation",
|
|
204
|
+
proof.creditGrantId,
|
|
205
|
+
{
|
|
206
|
+
native: {
|
|
207
|
+
ledgerAmount: proof.ledgerAmount,
|
|
208
|
+
availableAmount: proof.availableAmount,
|
|
209
|
+
granted: proof.granted,
|
|
210
|
+
applied: proof.applied,
|
|
211
|
+
expired: proof.expired,
|
|
212
|
+
voided: proof.voided,
|
|
213
|
+
reinstated: proof.reinstated,
|
|
214
|
+
complete: proof.complete,
|
|
215
|
+
},
|
|
216
|
+
backing: result.backing,
|
|
217
|
+
reason: result.reason,
|
|
218
|
+
transactionCount: proof.transactions.length,
|
|
219
|
+
},
|
|
220
|
+
row.key,
|
|
221
|
+
);
|
|
222
|
+
return JSON.stringify(result);
|
|
223
|
+
},
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
export const closeAccount = mutation({
|
|
227
|
+
args: { bindingJson: v.string() },
|
|
228
|
+
returns: v.null(),
|
|
229
|
+
handler: async (ctx, args) => {
|
|
230
|
+
const original = await accountTerms(
|
|
231
|
+
boundedJson(args.bindingJson) as UsageCreditBinding,
|
|
232
|
+
);
|
|
233
|
+
const ledger = await account(ctx, original.key);
|
|
234
|
+
if (ledger.closed) return null;
|
|
235
|
+
const purchases = await ctx.db
|
|
236
|
+
.query("usageCreditPurchases")
|
|
237
|
+
.withIndex("by_account", (q) => q.eq("accountKey", original.key))
|
|
238
|
+
.take(1001);
|
|
239
|
+
if (
|
|
240
|
+
purchases.length > 1000 ||
|
|
241
|
+
purchases.some((p) => !p.creditGrantId && p.state !== "canceled")
|
|
242
|
+
)
|
|
243
|
+
throw new Error("Credit purchases require reconciliation before closure");
|
|
244
|
+
for (const grant of await grants(ctx, original.key)) {
|
|
245
|
+
const proof = grant.nativeObservationJson
|
|
246
|
+
? creditNativeObservation.parse(JSON.parse(grant.nativeObservationJson))
|
|
247
|
+
: null;
|
|
248
|
+
const purchaseRow = await purchase(ctx, grant.purchaseKey),
|
|
249
|
+
terms = (await purchaseTerms(purchaseRow.termsJson)).terms;
|
|
250
|
+
if (
|
|
251
|
+
BigInt(grant.available) > 0n &&
|
|
252
|
+
!(
|
|
253
|
+
terms.expiresAt !== undefined && terms.expiresAt <= Date.now() / 1000
|
|
254
|
+
) &&
|
|
255
|
+
purchaseRow.refundedAmount !== terms.amount
|
|
256
|
+
)
|
|
257
|
+
throw new Error(
|
|
258
|
+
"Unspent paid credits require verified refund before closure",
|
|
259
|
+
);
|
|
260
|
+
const consumed =
|
|
261
|
+
BigInt(grant.consumed) === 0n
|
|
262
|
+
? 0
|
|
263
|
+
: creditCost(terms.binding.plan, grant.consumed);
|
|
264
|
+
if (
|
|
265
|
+
BigInt(grant.reserved) !== 0n ||
|
|
266
|
+
!proof?.complete ||
|
|
267
|
+
!proof.invoicesVerified ||
|
|
268
|
+
proof.ledgerAmount !== 0 ||
|
|
269
|
+
proof.availableAmount !== 0 ||
|
|
270
|
+
proof.reinstated !== 0 ||
|
|
271
|
+
proof.applied !== consumed
|
|
272
|
+
)
|
|
273
|
+
throw new Error(
|
|
274
|
+
"Credit backing and consumption require reconciliation before closure",
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
await ctx.db.patch("usageCreditAccounts", ledger._id, { closed: true });
|
|
278
|
+
await history(ctx, ledger.key, "closure", ledger.key, {
|
|
279
|
+
cashCollection: "none",
|
|
280
|
+
originalTermsRetained: true,
|
|
281
|
+
});
|
|
282
|
+
return null;
|
|
283
|
+
},
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
export const cancelPurchase = mutation({
|
|
287
|
+
args: { key: v.string(), paymentIntentId: v.string() },
|
|
288
|
+
returns: v.null(),
|
|
289
|
+
handler: async (ctx, args) => {
|
|
290
|
+
const row = await purchase(ctx, args.key);
|
|
291
|
+
if (
|
|
292
|
+
row.paymentIntentId !== args.paymentIntentId ||
|
|
293
|
+
row.creditGrantId ||
|
|
294
|
+
row.paymentProofJson
|
|
295
|
+
)
|
|
296
|
+
throw new Error(
|
|
297
|
+
"Only an original unpaid credit purchase can be canceled",
|
|
298
|
+
);
|
|
299
|
+
await ctx.db.patch("usageCreditPurchases", row._id, {
|
|
300
|
+
state: "canceled",
|
|
301
|
+
capacityReserved: false,
|
|
302
|
+
});
|
|
303
|
+
await history(
|
|
304
|
+
ctx,
|
|
305
|
+
row.accountKey,
|
|
306
|
+
"recovery",
|
|
307
|
+
args.paymentIntentId,
|
|
308
|
+
{ nativeStatus: "canceled", cashCollection: "none" },
|
|
309
|
+
row.key,
|
|
310
|
+
);
|
|
311
|
+
return null;
|
|
312
|
+
},
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
export const prepareRefund = mutation({
|
|
316
|
+
args: { key: v.string() },
|
|
317
|
+
returns: v.null(),
|
|
318
|
+
handler: async (ctx, args) => {
|
|
319
|
+
const row = await purchase(ctx, args.key),
|
|
320
|
+
grant = await ctx.db
|
|
321
|
+
.query("usageCreditGrants")
|
|
322
|
+
.withIndex("by_purchase", (q) => q.eq("purchaseKey", row.key))
|
|
323
|
+
.unique();
|
|
324
|
+
if (
|
|
325
|
+
!grant ||
|
|
326
|
+
!row.creditGrantId ||
|
|
327
|
+
!row.paymentProofJson ||
|
|
328
|
+
row.state === "canceled"
|
|
329
|
+
)
|
|
330
|
+
throw new Error("Verified credit purchase required");
|
|
331
|
+
if (BigInt(grant.reserved) !== 0n || BigInt(grant.consumed) !== 0n)
|
|
332
|
+
throw new Error(
|
|
333
|
+
"Consumed or reserved credits require recovery reconciliation",
|
|
334
|
+
);
|
|
335
|
+
if (row.state === "frozen") return null;
|
|
336
|
+
const proof = grant.nativeObservationJson
|
|
337
|
+
? creditNativeObservation.parse(JSON.parse(grant.nativeObservationJson))
|
|
338
|
+
: null;
|
|
339
|
+
const terms = (await purchaseTerms(row.termsJson)).terms;
|
|
340
|
+
if (
|
|
341
|
+
!proof?.complete ||
|
|
342
|
+
!proof.invoicesVerified ||
|
|
343
|
+
Date.now() - (grant.observedAt ?? 0) > 60000 ||
|
|
344
|
+
proof.ledgerAmount !== terms.amount ||
|
|
345
|
+
proof.applied !== 0 ||
|
|
346
|
+
proof.reinstated !== 0 ||
|
|
347
|
+
proof.expired !== 0 ||
|
|
348
|
+
proof.voided !== 0
|
|
349
|
+
)
|
|
350
|
+
throw new Error("Current unspent native credit reconciliation required");
|
|
351
|
+
await ctx.db.patch("usageCreditGrants", grant._id, { frozen: true });
|
|
352
|
+
await ctx.db.patch("usageCreditPurchases", row._id, { state: "frozen" });
|
|
353
|
+
await history(
|
|
354
|
+
ctx,
|
|
355
|
+
row.accountKey,
|
|
356
|
+
"recovery",
|
|
357
|
+
row.creditGrantId,
|
|
358
|
+
{
|
|
359
|
+
reason: "refund_requested",
|
|
360
|
+
originalPaymentIntentId: row.paymentIntentId!,
|
|
361
|
+
},
|
|
362
|
+
row.key,
|
|
363
|
+
);
|
|
364
|
+
return null;
|
|
365
|
+
},
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
export const resumeAccount = mutation({
|
|
369
|
+
args: { bindingJson: v.string() },
|
|
370
|
+
returns: v.null(),
|
|
371
|
+
handler: async (ctx, args) => {
|
|
372
|
+
const original = await accountTerms(
|
|
373
|
+
boundedJson(args.bindingJson) as UsageCreditBinding,
|
|
374
|
+
),
|
|
375
|
+
ledger = await account(ctx, original.key);
|
|
376
|
+
if (ledger.closed) throw new Error("Closed credit account cannot resume");
|
|
377
|
+
const evidence = [];
|
|
378
|
+
for (const grant of await grants(ctx, original.key)) {
|
|
379
|
+
const row = await purchase(ctx, grant.purchaseKey),
|
|
380
|
+
terms = (await purchaseTerms(row.termsJson)).terms;
|
|
381
|
+
const proof = grant.nativeObservationJson
|
|
382
|
+
? creditNativeObservation.parse(JSON.parse(grant.nativeObservationJson))
|
|
383
|
+
: null;
|
|
384
|
+
if (
|
|
385
|
+
!proof ||
|
|
386
|
+
!proof.complete ||
|
|
387
|
+
!proof.invoicesVerified ||
|
|
388
|
+
Date.now() - (grant.observedAt ?? 0) > 60000 ||
|
|
389
|
+
normalizeCreditState(terms, grant, proof, true).backing !==
|
|
390
|
+
"sufficient" ||
|
|
391
|
+
(row.state === "frozen" &&
|
|
392
|
+
(BigInt(grant.reserved) > 0n ||
|
|
393
|
+
BigInt(grant.consumed) > 0n ||
|
|
394
|
+
proof.ledgerAmount > 0))
|
|
395
|
+
)
|
|
396
|
+
throw new Error(
|
|
397
|
+
"Fresh complete funding and invoice reconciliation required before resume",
|
|
398
|
+
);
|
|
399
|
+
evidence.push({
|
|
400
|
+
creditGrantId: grant.creditGrantId,
|
|
401
|
+
observedAt: grant.observedAt!,
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
await ctx.db.patch("usageCreditAccounts", ledger._id, {
|
|
405
|
+
frozenReason: undefined,
|
|
406
|
+
});
|
|
407
|
+
await history(ctx, ledger.key, "recovery", ledger.key, {
|
|
408
|
+
reason: "verified_observation_resume",
|
|
409
|
+
grantCount: evidence.length,
|
|
410
|
+
observationFingerprint: await canonicalFingerprint(evidence),
|
|
411
|
+
});
|
|
412
|
+
return null;
|
|
413
|
+
},
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
export const markPaymentAttempt = mutation({
|
|
417
|
+
args: { key: v.string() },
|
|
418
|
+
returns: v.null(),
|
|
419
|
+
handler: async (ctx, args) => {
|
|
420
|
+
const row = await purchase(ctx, args.key);
|
|
421
|
+
if (row.state !== "pending" || !row.capacityReserved)
|
|
422
|
+
throw new Error("Original purchase no longer permits payment creation");
|
|
423
|
+
await ctx.db.patch("usageCreditPurchases", row._id, {
|
|
424
|
+
paymentAttemptedAt:
|
|
425
|
+
row.paymentAttemptedAt ?? Math.floor(Date.now() / 1000),
|
|
426
|
+
});
|
|
427
|
+
return null;
|
|
428
|
+
},
|
|
429
|
+
});
|
|
430
|
+
export const cancelUnstarted = mutation({
|
|
431
|
+
args: { key: v.string() },
|
|
432
|
+
returns: v.null(),
|
|
433
|
+
handler: async (ctx, args) => {
|
|
434
|
+
const row = await purchase(ctx, args.key);
|
|
435
|
+
if (
|
|
436
|
+
row.paymentAttemptedAt !== undefined ||
|
|
437
|
+
row.paymentIntentId ||
|
|
438
|
+
row.paymentProofJson ||
|
|
439
|
+
row.creditGrantId
|
|
440
|
+
)
|
|
441
|
+
throw new Error("Unknown native payment requires reconciliation");
|
|
442
|
+
await ctx.db.patch("usageCreditPurchases", row._id, {
|
|
443
|
+
state: "canceled",
|
|
444
|
+
capacityReserved: false,
|
|
445
|
+
});
|
|
446
|
+
await history(ctx, row.accountKey, "recovery", row.key, {
|
|
447
|
+
reason: "canceled_before_native_payment_attempt",
|
|
448
|
+
});
|
|
449
|
+
return null;
|
|
450
|
+
},
|
|
451
|
+
});
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { convexToJson } from "convex/values";
|
|
2
|
+
import type { MutationCtx } from "../_generated/server.js";
|
|
3
|
+
import {
|
|
4
|
+
purchaseTerms,
|
|
5
|
+
account,
|
|
6
|
+
activeEnrollment,
|
|
7
|
+
history,
|
|
8
|
+
purchase,
|
|
9
|
+
} from "./helpers.js";
|
|
10
|
+
import {
|
|
11
|
+
paymentCreditProof,
|
|
12
|
+
grantCreditProof,
|
|
13
|
+
} from "../../client/usage/creditProofs.js";
|
|
14
|
+
import { closureByStripeId } from "../accountClosure/helpers.js";
|
|
15
|
+
export async function preparePurchase(ctx: MutationCtx, inputJson: string) {
|
|
16
|
+
const parsed = await purchaseTerms(inputJson),
|
|
17
|
+
{ terms } = parsed;
|
|
18
|
+
const prior = await ctx.db
|
|
19
|
+
.query("usageCreditPurchases")
|
|
20
|
+
.withIndex("by_key", (q) => q.eq("key", parsed.key))
|
|
21
|
+
.unique();
|
|
22
|
+
if (prior) {
|
|
23
|
+
if (prior.termsJson !== parsed.termsJson)
|
|
24
|
+
throw new Error("Credit purchase replay conflict");
|
|
25
|
+
return prior;
|
|
26
|
+
}
|
|
27
|
+
for (const id of [terms.scope.stripeAccountId, terms.scope.customerAccount])
|
|
28
|
+
if (await closureByStripeId(ctx, id))
|
|
29
|
+
throw new Error("Account closure prevents credit purchase");
|
|
30
|
+
const { item } = await activeEnrollment(ctx, parsed.account.binding);
|
|
31
|
+
if (
|
|
32
|
+
terms.expiresAt !== undefined &&
|
|
33
|
+
terms.expiresAt <= item.period.end + 72 * 3600
|
|
34
|
+
)
|
|
35
|
+
throw new Error(
|
|
36
|
+
"Credit expiry must cover original billing closeout and finalization",
|
|
37
|
+
);
|
|
38
|
+
let ledger = await ctx.db
|
|
39
|
+
.query("usageCreditAccounts")
|
|
40
|
+
.withIndex("by_key", (q) => q.eq("key", parsed.account.key))
|
|
41
|
+
.unique();
|
|
42
|
+
if (!ledger) {
|
|
43
|
+
const id = await ctx.db.insert("usageCreditAccounts", {
|
|
44
|
+
key: parsed.account.key,
|
|
45
|
+
scopeKey: parsed.account.scopeKey,
|
|
46
|
+
bindingJson: parsed.account.bindingJson,
|
|
47
|
+
stripeAccountId: terms.scope.stripeAccountId,
|
|
48
|
+
customerAccount: terms.scope.customerAccount,
|
|
49
|
+
closed: false,
|
|
50
|
+
purchaseCount: 0,
|
|
51
|
+
historyCount: 0,
|
|
52
|
+
});
|
|
53
|
+
ledger = (await ctx.db.get("usageCreditAccounts", id))!;
|
|
54
|
+
}
|
|
55
|
+
if (ledger.closed || ledger.frozenReason)
|
|
56
|
+
throw new Error("Credit account requires reconciliation");
|
|
57
|
+
if (ledger.purchaseCount >= 1000)
|
|
58
|
+
throw new Error("Credit account retained purchase quota exhausted");
|
|
59
|
+
const nativeCustomerKey = JSON.stringify([
|
|
60
|
+
terms.scope.stripeAccountId,
|
|
61
|
+
terms.scope.livemode,
|
|
62
|
+
terms.binding.stripeCustomerId,
|
|
63
|
+
]);
|
|
64
|
+
const unused = await ctx.db
|
|
65
|
+
.query("usageCreditGrants")
|
|
66
|
+
.withIndex("by_customer_unused", (q) =>
|
|
67
|
+
q.eq("nativeCustomerKey", nativeCustomerKey).eq("nativeUnused", true),
|
|
68
|
+
)
|
|
69
|
+
.take(101);
|
|
70
|
+
const pending = await ctx.db
|
|
71
|
+
.query("usageCreditPurchases")
|
|
72
|
+
.withIndex("by_customer_capacity", (q) =>
|
|
73
|
+
q.eq("nativeCustomerKey", nativeCustomerKey).eq("capacityReserved", true),
|
|
74
|
+
)
|
|
75
|
+
.take(101);
|
|
76
|
+
if (unused.length + pending.length >= 100)
|
|
77
|
+
throw new Error(
|
|
78
|
+
"Native credit customer capacity exhausted; reconcile or cancel outstanding purchases",
|
|
79
|
+
);
|
|
80
|
+
const id = await ctx.db.insert("usageCreditPurchases", {
|
|
81
|
+
key: parsed.key,
|
|
82
|
+
accountKey: ledger.key,
|
|
83
|
+
nativeCustomerKey,
|
|
84
|
+
capacityReserved: true,
|
|
85
|
+
termsJson: parsed.termsJson,
|
|
86
|
+
firstAttemptAt: Math.floor(Date.now() / 1000),
|
|
87
|
+
state: "pending",
|
|
88
|
+
});
|
|
89
|
+
await ctx.db.patch("usageCreditAccounts", ledger._id, {
|
|
90
|
+
purchaseCount: ledger.purchaseCount + 1,
|
|
91
|
+
});
|
|
92
|
+
await history(ctx, ledger.key, "purchase", parsed.key, { terms }, parsed.key);
|
|
93
|
+
return (await ctx.db.get("usageCreditPurchases", id))!;
|
|
94
|
+
}
|
|
95
|
+
export async function pinPayment(
|
|
96
|
+
ctx: MutationCtx,
|
|
97
|
+
key: string,
|
|
98
|
+
paymentIntentId: string,
|
|
99
|
+
) {
|
|
100
|
+
if (!/^pi_[a-zA-Z0-9_]{1,190}$/.test(paymentIntentId))
|
|
101
|
+
throw new Error("Invalid credit payment identity");
|
|
102
|
+
const row = await purchase(ctx, key),
|
|
103
|
+
{ terms } = await purchaseTerms(row.termsJson);
|
|
104
|
+
if (row.paymentIntentId && row.paymentIntentId !== paymentIntentId)
|
|
105
|
+
throw new Error("Credit payment identity conflict");
|
|
106
|
+
const paymentKey = JSON.stringify([
|
|
107
|
+
terms.scope.stripeAccountId,
|
|
108
|
+
terms.scope.livemode,
|
|
109
|
+
paymentIntentId,
|
|
110
|
+
]);
|
|
111
|
+
const other = await ctx.db
|
|
112
|
+
.query("usageCreditPurchases")
|
|
113
|
+
.withIndex("by_payment", (q) => q.eq("paymentKey", paymentKey))
|
|
114
|
+
.unique();
|
|
115
|
+
if (other && other.key !== key)
|
|
116
|
+
throw new Error("Credit payment already backs another purchase");
|
|
117
|
+
await ctx.db.patch("usageCreditPurchases", row._id, {
|
|
118
|
+
paymentIntentId,
|
|
119
|
+
paymentKey,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
export async function verifyPayment(
|
|
123
|
+
ctx: MutationCtx,
|
|
124
|
+
key: string,
|
|
125
|
+
proofJson: string,
|
|
126
|
+
) {
|
|
127
|
+
const proof = paymentCreditProof.parse(JSON.parse(proofJson)),
|
|
128
|
+
row = await purchase(ctx, key);
|
|
129
|
+
const { terms } = await purchaseTerms(row.termsJson);
|
|
130
|
+
if (
|
|
131
|
+
row.paymentIntentId !== proof.paymentIntentId ||
|
|
132
|
+
proof.amount !== terms.amount ||
|
|
133
|
+
proof.currency !== terms.binding.plan.rate.currency ||
|
|
134
|
+
proof.customerAccount !== terms.scope.customerAccount ||
|
|
135
|
+
proof.livemode !== terms.scope.livemode
|
|
136
|
+
)
|
|
137
|
+
throw new Error("Credit payment provenance mismatch");
|
|
138
|
+
const normalized = JSON.stringify(convexToJson(proof));
|
|
139
|
+
if (row.paymentProofJson && row.paymentProofJson !== normalized)
|
|
140
|
+
throw new Error("Credit payment proof conflict");
|
|
141
|
+
if (row.state === "frozen" || row.state === "canceled")
|
|
142
|
+
throw new Error("Credit payment requires recovery");
|
|
143
|
+
await ctx.db.patch("usageCreditPurchases", row._id, {
|
|
144
|
+
paymentProofJson: normalized,
|
|
145
|
+
grantFirstAttemptAt:
|
|
146
|
+
row.grantFirstAttemptAt ?? Math.floor(Date.now() / 1000),
|
|
147
|
+
});
|
|
148
|
+
await history(
|
|
149
|
+
ctx,
|
|
150
|
+
row.accountKey,
|
|
151
|
+
"payment",
|
|
152
|
+
proof.paymentIntentId,
|
|
153
|
+
proof,
|
|
154
|
+
key,
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
export async function pinGrant(
|
|
158
|
+
ctx: MutationCtx,
|
|
159
|
+
key: string,
|
|
160
|
+
proofJson: string,
|
|
161
|
+
) {
|
|
162
|
+
const proof = grantCreditProof.parse(JSON.parse(proofJson)),
|
|
163
|
+
row = await purchase(ctx, key);
|
|
164
|
+
const { terms } = await purchaseTerms(row.termsJson);
|
|
165
|
+
if (!row.paymentProofJson || row.state === "frozen")
|
|
166
|
+
throw new Error("Verified credit payment required");
|
|
167
|
+
const original = JSON.parse(row.paymentProofJson) as ReturnType<
|
|
168
|
+
typeof paymentCreditProof.parse
|
|
169
|
+
>;
|
|
170
|
+
if (
|
|
171
|
+
Object.entries(original).some(
|
|
172
|
+
([field, value]) => proof[field as keyof typeof proof] !== value,
|
|
173
|
+
) ||
|
|
174
|
+
proof.stripePriceId !== terms.binding.stripePriceId ||
|
|
175
|
+
proof.expiresAt !== (terms.expiresAt ?? null) ||
|
|
176
|
+
proof.effectiveAt > Date.now() / 1000 + 300
|
|
177
|
+
)
|
|
178
|
+
throw new Error("Credit grant provenance mismatch");
|
|
179
|
+
if (row.creditGrantId && row.creditGrantId !== proof.creditGrantId)
|
|
180
|
+
throw new Error("Credit grant identity conflict");
|
|
181
|
+
const other = await ctx.db
|
|
182
|
+
.query("usageCreditGrants")
|
|
183
|
+
.withIndex("by_native", (q) => q.eq("creditGrantId", proof.creditGrantId))
|
|
184
|
+
.unique();
|
|
185
|
+
if (other) {
|
|
186
|
+
if (
|
|
187
|
+
other.purchaseKey !== key ||
|
|
188
|
+
other.proofJson !== JSON.stringify(convexToJson(proof))
|
|
189
|
+
)
|
|
190
|
+
throw new Error("Credit grant replay conflict");
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const ledger = await account(ctx, row.accountKey);
|
|
194
|
+
if (ledger.closed || ledger.frozenReason)
|
|
195
|
+
throw new Error("Credit account requires reconciliation");
|
|
196
|
+
await ctx.db.insert("usageCreditGrants", {
|
|
197
|
+
purchaseKey: key,
|
|
198
|
+
accountKey: row.accountKey,
|
|
199
|
+
creditGrantId: proof.creditGrantId,
|
|
200
|
+
nativeCustomerKey: row.nativeCustomerKey,
|
|
201
|
+
nativeUnused: true,
|
|
202
|
+
nativeCreated: proof.createdAt,
|
|
203
|
+
paymentIntentId: proof.paymentIntentId,
|
|
204
|
+
chargeId: proof.chargeId,
|
|
205
|
+
proofJson: JSON.stringify(convexToJson(proof)),
|
|
206
|
+
available: terms.scaledQuantity,
|
|
207
|
+
reserved: "0",
|
|
208
|
+
consumed: "0",
|
|
209
|
+
effectiveAt: proof.effectiveAt,
|
|
210
|
+
expiresAt: proof.expiresAt,
|
|
211
|
+
frozen: false,
|
|
212
|
+
});
|
|
213
|
+
await ctx.db.patch("usageCreditPurchases", row._id, {
|
|
214
|
+
state: "ready",
|
|
215
|
+
capacityReserved: false,
|
|
216
|
+
creditGrantId: proof.creditGrantId,
|
|
217
|
+
});
|
|
218
|
+
await history(ctx, row.accountKey, "grant", proof.creditGrantId, proof, key);
|
|
219
|
+
}
|