@fantastic.dev/better-stripe 0.52.0 → 0.53.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 +6 -0
- package/README.md +1 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +44 -0
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +22 -0
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +44 -0
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +22 -0
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/index.d.ts +3 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +1 -0
- package/dist/client/index.js.map +1 -1
- package/dist/client/products/catalogClient.d.ts +23 -0
- package/dist/client/products/catalogClient.d.ts.map +1 -1
- package/dist/client/products/catalogClient.js +32 -0
- package/dist/client/products/catalogClient.js.map +1 -1
- package/dist/client/products/fixedPrice.d.ts +4 -0
- package/dist/client/products/fixedPrice.d.ts.map +1 -0
- package/dist/client/products/fixedPrice.js +10 -0
- package/dist/client/products/fixedPrice.js.map +1 -0
- package/dist/client/products/products.d.ts.map +1 -1
- package/dist/client/products/products.js +3 -0
- package/dist/client/products/products.js.map +1 -1
- package/dist/client/usage/catalog.d.ts +7 -0
- package/dist/client/usage/catalog.d.ts.map +1 -0
- package/dist/client/usage/catalog.js +55 -0
- package/dist/client/usage/catalog.js.map +1 -0
- package/dist/client/usage/catalogLifecycle.d.ts +25 -0
- package/dist/client/usage/catalogLifecycle.d.ts.map +1 -0
- package/dist/client/usage/catalogLifecycle.js +64 -0
- package/dist/client/usage/catalogLifecycle.js.map +1 -0
- package/dist/client/usage/catalogMath.d.ts +3 -0
- package/dist/client/usage/catalogMath.d.ts.map +1 -0
- package/dist/client/usage/catalogMath.js +21 -0
- package/dist/client/usage/catalogMath.js.map +1 -0
- package/dist/client/usage/catalogPrices.d.ts +5 -0
- package/dist/client/usage/catalogPrices.d.ts.map +1 -0
- package/dist/client/usage/catalogPrices.js +178 -0
- package/dist/client/usage/catalogPrices.js.map +1 -0
- package/dist/client/usage/catalogRead.d.ts +25 -0
- package/dist/client/usage/catalogRead.d.ts.map +1 -0
- package/dist/client/usage/catalogRead.js +71 -0
- package/dist/client/usage/catalogRead.js.map +1 -0
- package/dist/client/usage/catalogTypes.d.ts +97 -0
- package/dist/client/usage/catalogTypes.d.ts.map +1 -0
- package/dist/client/usage/catalogTypes.js +106 -0
- package/dist/client/usage/catalogTypes.js.map +1 -0
- package/dist/client/webhooks/processors.d.ts.map +1 -1
- package/dist/client/webhooks/processors.js +3 -0
- package/dist/client/webhooks/processors.js.map +1 -1
- package/dist/component/_generated/api.d.ts +4 -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 +62 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/balanceFunding/mutations.d.ts +43 -43
- package/dist/component/earnings/triggers.d.ts +46 -0
- 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 +22 -0
- package/dist/component/schema.js +2 -0
- package/dist/component/schema.js.map +1 -1
- package/dist/component/usageCatalog/mutations.d.ts +25 -0
- package/dist/component/usageCatalog/mutations.d.ts.map +1 -0
- package/dist/component/usageCatalog/mutations.js +75 -0
- package/dist/component/usageCatalog/mutations.js.map +1 -0
- package/dist/component/usageCatalog/queries.d.ts +33 -0
- package/dist/component/usageCatalog/queries.d.ts.map +1 -0
- package/dist/component/usageCatalog/queries.js +26 -0
- package/dist/component/usageCatalog/queries.js.map +1 -0
- package/dist/component/usageCatalog/schema.d.ts +57 -0
- package/dist/component/usageCatalog/schema.d.ts.map +1 -0
- package/dist/component/usageCatalog/schema.js +22 -0
- package/dist/component/usageCatalog/schema.js.map +1 -0
- package/docs/README.md +3 -1
- package/docs/metering-setup.md +2 -0
- package/docs/usage-catalog.md +106 -0
- package/package.json +3 -2
- package/src/client/index.ts +7 -0
- package/src/client/products/catalogClient.ts +77 -0
- package/src/client/products/fixedPrice.test.ts +57 -0
- package/src/client/products/fixedPrice.ts +13 -0
- package/src/client/products/products.ts +2 -0
- package/src/client/usage/catalog.test.ts +464 -0
- package/src/client/usage/catalog.ts +117 -0
- package/src/client/usage/catalogLifecycle.ts +128 -0
- package/src/client/usage/catalogMath.test.ts +13 -0
- package/src/client/usage/catalogMath.ts +22 -0
- package/src/client/usage/catalogPrices.ts +251 -0
- package/src/client/usage/catalogRead.ts +98 -0
- package/src/client/usage/catalogTypes.ts +170 -0
- package/src/client/webhooks/processors.ts +2 -0
- package/src/component/_generated/api.ts +4 -0
- package/src/component/_generated/component.ts +78 -0
- package/src/component/schema.ts +2 -0
- package/src/component/usageCatalog/mutations.ts +79 -0
- package/src/component/usageCatalog/queries.ts +32 -0
- package/src/component/usageCatalog/schema.ts +21 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { expect, it } from "vitest";
|
|
2
|
+
import { scaledUsageRate } from "./catalogMath.js";
|
|
3
|
+
it("scales native per-unit rates exactly without money floats", () => {
|
|
4
|
+
expect(scaledUsageRate("2", 2)).toBe("0.02");
|
|
5
|
+
expect(scaledUsageRate("123.4500", 3)).toBe("0.12345");
|
|
6
|
+
expect(scaledUsageRate("0", 6)).toBe("0");
|
|
7
|
+
expect(scaledUsageRate("999999999999.123456", 6)).toBe("999999.999999123456");
|
|
8
|
+
});
|
|
9
|
+
it("rejects native decimal precision loss rather than rounding", () => {
|
|
10
|
+
expect(() => scaledUsageRate("0.000000000001", 1)).toThrow();
|
|
11
|
+
expect(() => scaledUsageRate("2", 7)).toThrow();
|
|
12
|
+
expect(() => scaledUsageRate("-2", 0)).toThrow();
|
|
13
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Convert minor currency units per whole unit to a native scaled-unit rate. */
|
|
2
|
+
export function scaledUsageRate(rate: string, precision: number): string {
|
|
3
|
+
if (
|
|
4
|
+
!Number.isInteger(precision) ||
|
|
5
|
+
precision < 0 ||
|
|
6
|
+
precision > 6 ||
|
|
7
|
+
!/^(0|[1-9]\d{0,11})(\.\d{1,12})?$/.test(rate)
|
|
8
|
+
)
|
|
9
|
+
throw new Error("Unsupported native usage rate");
|
|
10
|
+
const [whole, fraction = ""] = rate.split(".");
|
|
11
|
+
const places = fraction.length + precision;
|
|
12
|
+
const digits = (whole + fraction).padStart(places + 1, "0");
|
|
13
|
+
const raw = places
|
|
14
|
+
? `${digits.slice(0, -places)}.${digits.slice(-places)}`
|
|
15
|
+
: digits;
|
|
16
|
+
const [integer, decimal = ""] = raw.split(".");
|
|
17
|
+
const normalized = decimal.replace(/0+$/, "");
|
|
18
|
+
if (normalized.length > 12)
|
|
19
|
+
throw new Error("Unsupported native usage rate precision");
|
|
20
|
+
const base = BigInt(integer).toString();
|
|
21
|
+
return normalized ? `${base}.${normalized}` : base;
|
|
22
|
+
}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import Stripe from "stripe";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
4
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
5
|
+
import { getChargeCurrencyMetadata } from "../charge-currency.js";
|
|
6
|
+
import { defineUsagePlan, parseUsageQuantity } from "./contracts.js";
|
|
7
|
+
import { scaledUsageRate } from "./catalogMath.js";
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
UsageCatalogError,
|
|
11
|
+
verifyMeter,
|
|
12
|
+
catalogScope,
|
|
13
|
+
meterKey,
|
|
14
|
+
meterTerms,
|
|
15
|
+
verifyRealm,
|
|
16
|
+
prepareCatalog,
|
|
17
|
+
completeCatalog,
|
|
18
|
+
operationKey,
|
|
19
|
+
permitCreate,
|
|
20
|
+
nativeCall,
|
|
21
|
+
type UsageMeterOptions,
|
|
22
|
+
type UsagePriceOptions,
|
|
23
|
+
} from "./catalogTypes.js";
|
|
24
|
+
import type { Doc } from "../../component/_generated/dataModel.js";
|
|
25
|
+
function incompatible(): never {
|
|
26
|
+
throw new UsageCatalogError(
|
|
27
|
+
"incompatible_terms",
|
|
28
|
+
"Native price has incompatible immutable terms",
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
function decimal(
|
|
32
|
+
value: Stripe.Decimal | string | null | undefined,
|
|
33
|
+
integer: number | null | undefined,
|
|
34
|
+
) {
|
|
35
|
+
const text =
|
|
36
|
+
value?.toString() ??
|
|
37
|
+
(Number.isSafeInteger(integer) && integer !== null && integer !== undefined
|
|
38
|
+
? String(integer)
|
|
39
|
+
: undefined);
|
|
40
|
+
if (text === undefined || !/^\d+(\.\d{1,12})?$/.test(text))
|
|
41
|
+
return incompatible();
|
|
42
|
+
const [whole, fraction = ""] = text.split(".");
|
|
43
|
+
const trimmed = fraction.replace(/0+$/, "");
|
|
44
|
+
const normalized = BigInt(whole).toString();
|
|
45
|
+
return trimmed ? `${normalized}.${trimmed}` : normalized;
|
|
46
|
+
}
|
|
47
|
+
function termsFor(opts: UsagePriceOptions) {
|
|
48
|
+
const plan = defineUsagePlan(opts.plan);
|
|
49
|
+
if (!getChargeCurrencyMetadata(plan.rate.currency)) return incompatible();
|
|
50
|
+
const terms = {
|
|
51
|
+
scope: catalogScope(opts.scope),
|
|
52
|
+
plan,
|
|
53
|
+
meterId: z
|
|
54
|
+
.string()
|
|
55
|
+
.regex(/^mtr_[a-zA-Z0-9_]+$/)
|
|
56
|
+
.max(100)
|
|
57
|
+
.parse(opts.meterId),
|
|
58
|
+
stripeProductId: z
|
|
59
|
+
.string()
|
|
60
|
+
.regex(/^prod_[a-zA-Z0-9]+$/)
|
|
61
|
+
.max(100)
|
|
62
|
+
.parse(opts.stripeProductId),
|
|
63
|
+
lookupKey: z.string().min(1).max(200).parse(opts.lookupKey),
|
|
64
|
+
};
|
|
65
|
+
const rate = scaledUsageRate(
|
|
66
|
+
plan.rate.unitAmountDecimal,
|
|
67
|
+
plan.unit.precision,
|
|
68
|
+
);
|
|
69
|
+
let included: number | undefined;
|
|
70
|
+
if (plan.model === "included_overage") {
|
|
71
|
+
const scaled = BigInt(
|
|
72
|
+
parseUsageQuantity(plan.includedQuantity, plan.unit.precision)
|
|
73
|
+
.scaledQuantity,
|
|
74
|
+
);
|
|
75
|
+
if (scaled < 1n || scaled > BigInt(Number.MAX_SAFE_INTEGER))
|
|
76
|
+
return incompatible();
|
|
77
|
+
included = Number(scaled);
|
|
78
|
+
}
|
|
79
|
+
return { terms, rate, included };
|
|
80
|
+
}
|
|
81
|
+
function verifyPrice(
|
|
82
|
+
price: Stripe.Price,
|
|
83
|
+
opts: UsagePriceOptions,
|
|
84
|
+
rate: string,
|
|
85
|
+
included: number | undefined,
|
|
86
|
+
) {
|
|
87
|
+
const product =
|
|
88
|
+
typeof price.product === "string" ? price.product : price.product.id;
|
|
89
|
+
if (
|
|
90
|
+
!price.active ||
|
|
91
|
+
price.livemode !== opts.scope.livemode ||
|
|
92
|
+
price.lookup_key !== opts.lookupKey ||
|
|
93
|
+
product !== opts.stripeProductId ||
|
|
94
|
+
price.currency !== opts.plan.rate.currency ||
|
|
95
|
+
price.type !== "recurring" ||
|
|
96
|
+
price.recurring?.interval !== "month" ||
|
|
97
|
+
price.recurring.interval_count !== 1 ||
|
|
98
|
+
price.recurring.usage_type !== "metered" ||
|
|
99
|
+
price.recurring.meter !== opts.meterId ||
|
|
100
|
+
price.transform_quantity != null
|
|
101
|
+
)
|
|
102
|
+
return incompatible();
|
|
103
|
+
if (included === undefined) {
|
|
104
|
+
if (
|
|
105
|
+
price.billing_scheme !== "per_unit" ||
|
|
106
|
+
decimal(price.unit_amount_decimal, price.unit_amount) !== rate
|
|
107
|
+
)
|
|
108
|
+
return incompatible();
|
|
109
|
+
} else {
|
|
110
|
+
if (
|
|
111
|
+
price.billing_scheme !== "tiered" ||
|
|
112
|
+
price.tiers_mode !== "graduated" ||
|
|
113
|
+
price.tiers?.length !== 2
|
|
114
|
+
)
|
|
115
|
+
return incompatible();
|
|
116
|
+
const [free, overage] = price.tiers;
|
|
117
|
+
if (
|
|
118
|
+
free.up_to !== included ||
|
|
119
|
+
overage.up_to !== null ||
|
|
120
|
+
decimal(free.unit_amount_decimal, free.unit_amount) !== "0" ||
|
|
121
|
+
decimal(overage.unit_amount_decimal, overage.unit_amount) !== rate
|
|
122
|
+
)
|
|
123
|
+
return incompatible();
|
|
124
|
+
for (const tier of price.tiers)
|
|
125
|
+
if (
|
|
126
|
+
(tier.flat_amount != null && tier.flat_amount !== 0) ||
|
|
127
|
+
(tier.flat_amount_decimal != null &&
|
|
128
|
+
decimal(tier.flat_amount_decimal, 0) !== "0")
|
|
129
|
+
)
|
|
130
|
+
return incompatible();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
export async function ensureUsagePrice(
|
|
134
|
+
stripe: Stripe,
|
|
135
|
+
component: Component,
|
|
136
|
+
ctx: RunCtx,
|
|
137
|
+
opts: UsagePriceOptions,
|
|
138
|
+
): Promise<Stripe.Price> {
|
|
139
|
+
const { terms, rate, included } = termsFor(opts);
|
|
140
|
+
await verifyRealm(stripe, terms.scope);
|
|
141
|
+
const meterRow = (await ctx.runQuery(
|
|
142
|
+
componentRef(component, "usageCatalog/queries/get"),
|
|
143
|
+
{
|
|
144
|
+
scopeKey: JSON.stringify(terms.scope),
|
|
145
|
+
kind: "meter",
|
|
146
|
+
key: meterKey(terms.plan),
|
|
147
|
+
},
|
|
148
|
+
)) as Doc<"usageCatalog"> | null;
|
|
149
|
+
if (!meterRow || meterRow.providerId !== terms.meterId) return incompatible();
|
|
150
|
+
const meterOpts = meterTerms(
|
|
151
|
+
JSON.parse(meterRow.termsJson) as UsageMeterOptions,
|
|
152
|
+
);
|
|
153
|
+
if (JSON.stringify(meterOpts.plan) !== JSON.stringify(terms.plan))
|
|
154
|
+
return incompatible();
|
|
155
|
+
const meter = await nativeCall(() =>
|
|
156
|
+
stripe.billing.meters.retrieve(terms.meterId),
|
|
157
|
+
);
|
|
158
|
+
if (meter.id !== terms.meterId) return incompatible();
|
|
159
|
+
verifyMeter(meter, meterOpts);
|
|
160
|
+
const product = await nativeCall(() =>
|
|
161
|
+
stripe.products.retrieve(terms.stripeProductId),
|
|
162
|
+
);
|
|
163
|
+
if (
|
|
164
|
+
"deleted" in product ||
|
|
165
|
+
!product.active ||
|
|
166
|
+
product.id !== terms.stripeProductId
|
|
167
|
+
)
|
|
168
|
+
return incompatible();
|
|
169
|
+
const row = await prepareCatalog(
|
|
170
|
+
component,
|
|
171
|
+
ctx,
|
|
172
|
+
"price",
|
|
173
|
+
terms.scope,
|
|
174
|
+
terms.lookupKey,
|
|
175
|
+
terms,
|
|
176
|
+
);
|
|
177
|
+
let price: Stripe.Price | undefined;
|
|
178
|
+
if (row.providerId)
|
|
179
|
+
price = await nativeCall(() =>
|
|
180
|
+
stripe.prices.retrieve(row.providerId!, { expand: ["tiers"] }),
|
|
181
|
+
);
|
|
182
|
+
else {
|
|
183
|
+
const result = await nativeCall(() =>
|
|
184
|
+
stripe.prices.list({
|
|
185
|
+
lookup_keys: [terms.lookupKey],
|
|
186
|
+
limit: 2,
|
|
187
|
+
expand: ["data.tiers"],
|
|
188
|
+
}),
|
|
189
|
+
);
|
|
190
|
+
if (result.has_more || result.data.length > 1)
|
|
191
|
+
throw new UsageCatalogError(
|
|
192
|
+
"ambiguous_lookup",
|
|
193
|
+
"Native price lookup key is ambiguous",
|
|
194
|
+
);
|
|
195
|
+
price = result.data[0];
|
|
196
|
+
}
|
|
197
|
+
if (!price) {
|
|
198
|
+
permitCreate(row);
|
|
199
|
+
const key = await operationKey(terms, "price");
|
|
200
|
+
const params: Stripe.PriceCreateParams = {
|
|
201
|
+
product: terms.stripeProductId,
|
|
202
|
+
currency: terms.plan.rate.currency,
|
|
203
|
+
lookup_key: terms.lookupKey,
|
|
204
|
+
recurring: {
|
|
205
|
+
interval: "month",
|
|
206
|
+
usage_type: "metered",
|
|
207
|
+
meter: terms.meterId,
|
|
208
|
+
},
|
|
209
|
+
expand: ["tiers"],
|
|
210
|
+
...(included === undefined
|
|
211
|
+
? {
|
|
212
|
+
billing_scheme: "per_unit",
|
|
213
|
+
unit_amount_decimal: Stripe.Decimal.from(rate),
|
|
214
|
+
}
|
|
215
|
+
: {
|
|
216
|
+
billing_scheme: "tiered",
|
|
217
|
+
tiers_mode: "graduated",
|
|
218
|
+
tiers: [
|
|
219
|
+
{ up_to: included, unit_amount_decimal: Stripe.Decimal.zero },
|
|
220
|
+
{ up_to: "inf", unit_amount_decimal: Stripe.Decimal.from(rate) },
|
|
221
|
+
],
|
|
222
|
+
}),
|
|
223
|
+
};
|
|
224
|
+
price = await nativeCall(() =>
|
|
225
|
+
stripe.prices.create(params, { idempotencyKey: key }),
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
verifyPrice(price, terms, rate, included);
|
|
229
|
+
if (row.providerId && row.providerId !== price.id) return incompatible();
|
|
230
|
+
await completeCatalog(component, ctx, row, price.id, {
|
|
231
|
+
type: "metered_price",
|
|
232
|
+
id: price.id,
|
|
233
|
+
productId: terms.stripeProductId,
|
|
234
|
+
meterId: terms.meterId,
|
|
235
|
+
livemode: price.livemode,
|
|
236
|
+
active: price.active,
|
|
237
|
+
currency: price.currency,
|
|
238
|
+
billingScheme: price.billing_scheme,
|
|
239
|
+
unitAmountDecimal:
|
|
240
|
+
price.billing_scheme === "per_unit"
|
|
241
|
+
? decimal(price.unit_amount_decimal, price.unit_amount)
|
|
242
|
+
: null,
|
|
243
|
+
tiers:
|
|
244
|
+
price.tiers?.map((tier) => ({
|
|
245
|
+
upTo: tier.up_to === null ? null : String(tier.up_to),
|
|
246
|
+
unitAmountDecimal: decimal(tier.unit_amount_decimal, tier.unit_amount),
|
|
247
|
+
})) ?? [],
|
|
248
|
+
interval: "month",
|
|
249
|
+
});
|
|
250
|
+
return price;
|
|
251
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
3
|
+
import { catalogScope } from "./catalogTypes.js";
|
|
4
|
+
import { defineUsagePlan } from "./contracts.js";
|
|
5
|
+
import type { Doc } from "../../component/_generated/dataModel.js";
|
|
6
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
7
|
+
import type { UsageCatalogScope } from "./catalogTypes.js";
|
|
8
|
+
import type { UsageAvailability } from "./boundaries.js";
|
|
9
|
+
import type { UsagePlan } from "./contracts.js";
|
|
10
|
+
export type UsagePriceBinding = {
|
|
11
|
+
pricingMode: "metered";
|
|
12
|
+
stripePriceId: string;
|
|
13
|
+
stripeProductId: string;
|
|
14
|
+
meterId: string;
|
|
15
|
+
active: boolean;
|
|
16
|
+
currency: string;
|
|
17
|
+
billingScheme: "per_unit" | "tiered";
|
|
18
|
+
unitAmountDecimal: string | null;
|
|
19
|
+
tiers: Array<{ upTo: string | null; unitAmountDecimal: string }>;
|
|
20
|
+
interval: "month";
|
|
21
|
+
plan: UsagePlan;
|
|
22
|
+
};
|
|
23
|
+
const observation = z.strictObject({
|
|
24
|
+
type: z.literal("metered_price"),
|
|
25
|
+
id: z.string(),
|
|
26
|
+
productId: z.string(),
|
|
27
|
+
meterId: z.string(),
|
|
28
|
+
livemode: z.boolean(),
|
|
29
|
+
active: z.boolean(),
|
|
30
|
+
currency: z.string(),
|
|
31
|
+
billingScheme: z.enum(["per_unit", "tiered"]),
|
|
32
|
+
unitAmountDecimal: z.string().nullable(),
|
|
33
|
+
tiers: z.array(
|
|
34
|
+
z.strictObject({
|
|
35
|
+
upTo: z.string().nullable(),
|
|
36
|
+
unitAmountDecimal: z.string(),
|
|
37
|
+
}),
|
|
38
|
+
),
|
|
39
|
+
interval: z.literal("month"),
|
|
40
|
+
});
|
|
41
|
+
export async function getUsagePriceBinding(
|
|
42
|
+
component: Component,
|
|
43
|
+
ctx: RunCtx,
|
|
44
|
+
opts: { scope: UsageCatalogScope; lookupKey: string },
|
|
45
|
+
): Promise<UsageAvailability<UsagePriceBinding>> {
|
|
46
|
+
const scope = catalogScope(opts.scope);
|
|
47
|
+
const key = z.string().min(1).max(200).parse(opts.lookupKey);
|
|
48
|
+
const row = (await ctx.runQuery(
|
|
49
|
+
componentRef(component, "usageCatalog/queries/get"),
|
|
50
|
+
{ scopeKey: JSON.stringify(scope), kind: "price", key },
|
|
51
|
+
)) as Doc<"usageCatalog"> | null;
|
|
52
|
+
if (!row)
|
|
53
|
+
return {
|
|
54
|
+
status: "unavailable",
|
|
55
|
+
reason: "catalog_not_found",
|
|
56
|
+
retryable: false,
|
|
57
|
+
};
|
|
58
|
+
if (!row.observationJson || row.observedAt === undefined)
|
|
59
|
+
return {
|
|
60
|
+
status: "unavailable",
|
|
61
|
+
reason: "catalog_pending",
|
|
62
|
+
retryable: true,
|
|
63
|
+
};
|
|
64
|
+
try {
|
|
65
|
+
const price = observation.parse(JSON.parse(row.observationJson));
|
|
66
|
+
const plan = defineUsagePlan(JSON.parse(row.termsJson).plan);
|
|
67
|
+
if (
|
|
68
|
+
price.id !== row.providerId ||
|
|
69
|
+
price.livemode !== scope.livemode ||
|
|
70
|
+
price.currency !== plan.rate.currency ||
|
|
71
|
+
(price.billingScheme === "per_unit" && price.unitAmountDecimal === null)
|
|
72
|
+
)
|
|
73
|
+
throw new Error("Invalid catalog observation");
|
|
74
|
+
return {
|
|
75
|
+
status: "available",
|
|
76
|
+
observedAt: row.observedAt,
|
|
77
|
+
value: {
|
|
78
|
+
pricingMode: "metered",
|
|
79
|
+
stripePriceId: price.id,
|
|
80
|
+
stripeProductId: price.productId,
|
|
81
|
+
meterId: price.meterId,
|
|
82
|
+
active: price.active,
|
|
83
|
+
currency: price.currency,
|
|
84
|
+
billingScheme: price.billingScheme,
|
|
85
|
+
unitAmountDecimal: price.unitAmountDecimal,
|
|
86
|
+
tiers: price.tiers,
|
|
87
|
+
interval: price.interval,
|
|
88
|
+
plan,
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
} catch {
|
|
92
|
+
return {
|
|
93
|
+
status: "unavailable",
|
|
94
|
+
reason: "invalid_catalog_observation",
|
|
95
|
+
retryable: false,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
4
|
+
import { runMutationOrThrow } from "../helpers.js";
|
|
5
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
6
|
+
import { defineUsagePlan, type UsagePlan } from "./contracts.js";
|
|
7
|
+
import type { Doc } from "../../component/_generated/dataModel.js";
|
|
8
|
+
export type UsageCatalogScope = { stripeAccountId: string; livemode: boolean };
|
|
9
|
+
export type UsageMeterOptions = {
|
|
10
|
+
scope: UsageCatalogScope;
|
|
11
|
+
plan: UsagePlan;
|
|
12
|
+
eventName: string;
|
|
13
|
+
displayName: string;
|
|
14
|
+
};
|
|
15
|
+
export type UsagePriceOptions = {
|
|
16
|
+
scope: UsageCatalogScope;
|
|
17
|
+
plan: UsagePlan;
|
|
18
|
+
meterId: string;
|
|
19
|
+
stripeProductId: string;
|
|
20
|
+
lookupKey: string;
|
|
21
|
+
};
|
|
22
|
+
export class UsageCatalogError extends Error {
|
|
23
|
+
constructor(
|
|
24
|
+
public readonly code:
|
|
25
|
+
| "unsupported_scope"
|
|
26
|
+
| "incompatible_terms"
|
|
27
|
+
| "ambiguous_lookup"
|
|
28
|
+
| "unknown_create_outcome"
|
|
29
|
+
| "provider_unavailable",
|
|
30
|
+
message: string,
|
|
31
|
+
) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "UsageCatalogError";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const scopeSchema = z.strictObject({
|
|
37
|
+
stripeAccountId: z
|
|
38
|
+
.string()
|
|
39
|
+
.regex(/^acct_[a-zA-Z0-9]+$/)
|
|
40
|
+
.max(100),
|
|
41
|
+
livemode: z.boolean(),
|
|
42
|
+
});
|
|
43
|
+
export function catalogScope(scope: UsageCatalogScope) {
|
|
44
|
+
return scopeSchema.parse(scope);
|
|
45
|
+
}
|
|
46
|
+
export function meterTerms(opts: UsageMeterOptions) {
|
|
47
|
+
return {
|
|
48
|
+
scope: catalogScope(opts.scope),
|
|
49
|
+
plan: defineUsagePlan(opts.plan),
|
|
50
|
+
eventName: z
|
|
51
|
+
.string()
|
|
52
|
+
.regex(/^[\w.-]{1,100}$/)
|
|
53
|
+
.parse(opts.eventName),
|
|
54
|
+
displayName: z.string().min(1).max(100).parse(opts.displayName),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
export function meterKey(plan: UsagePlan) {
|
|
58
|
+
return JSON.stringify([plan.key, plan.version]);
|
|
59
|
+
}
|
|
60
|
+
export async function nativeCall<T>(call: () => Promise<T>): Promise<T> {
|
|
61
|
+
try {
|
|
62
|
+
return await call();
|
|
63
|
+
} catch {
|
|
64
|
+
throw new UsageCatalogError(
|
|
65
|
+
"provider_unavailable",
|
|
66
|
+
"Native Stripe catalog is unavailable",
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
export async function verifyRealm(stripe: Stripe, scope: UsageCatalogScope) {
|
|
71
|
+
const parsed = catalogScope(scope);
|
|
72
|
+
const [account, balance] = await Promise.all([
|
|
73
|
+
nativeCall(() => stripe.accounts.retrieve(null)),
|
|
74
|
+
nativeCall(() => stripe.balance.retrieve()),
|
|
75
|
+
]);
|
|
76
|
+
if (
|
|
77
|
+
account.id !== parsed.stripeAccountId ||
|
|
78
|
+
balance.livemode !== parsed.livemode
|
|
79
|
+
)
|
|
80
|
+
throw new UsageCatalogError(
|
|
81
|
+
"unsupported_scope",
|
|
82
|
+
"Native catalog scope must match the configured Stripe realm and mode",
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
export async function operationKey(terms: unknown, kind: string) {
|
|
86
|
+
const bytes = new TextEncoder().encode(JSON.stringify(terms));
|
|
87
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
88
|
+
return `bs_usage_${kind}_${Array.from(new Uint8Array(digest), (n) => n.toString(16).padStart(2, "0")).join("")}`;
|
|
89
|
+
}
|
|
90
|
+
export async function prepareCatalog(
|
|
91
|
+
component: Component,
|
|
92
|
+
ctx: RunCtx,
|
|
93
|
+
kind: "meter" | "price",
|
|
94
|
+
scope: UsageCatalogScope,
|
|
95
|
+
key: string,
|
|
96
|
+
terms: unknown,
|
|
97
|
+
): Promise<Doc<"usageCatalog">> {
|
|
98
|
+
return runMutationOrThrow(
|
|
99
|
+
ctx,
|
|
100
|
+
componentRef(component, "usageCatalog/mutations/prepare"),
|
|
101
|
+
{
|
|
102
|
+
scopeKey: JSON.stringify(catalogScope(scope)),
|
|
103
|
+
kind,
|
|
104
|
+
key,
|
|
105
|
+
termsJson: JSON.stringify(terms),
|
|
106
|
+
},
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
export async function completeCatalog(
|
|
110
|
+
component: Component,
|
|
111
|
+
ctx: RunCtx,
|
|
112
|
+
row: Doc<"usageCatalog">,
|
|
113
|
+
providerId: string,
|
|
114
|
+
observation: unknown,
|
|
115
|
+
) {
|
|
116
|
+
return runMutationOrThrow(
|
|
117
|
+
ctx,
|
|
118
|
+
componentRef(component, "usageCatalog/mutations/complete"),
|
|
119
|
+
{
|
|
120
|
+
scopeKey: row.scopeKey,
|
|
121
|
+
kind: row.kind,
|
|
122
|
+
key: row.key,
|
|
123
|
+
providerId,
|
|
124
|
+
observationJson: JSON.stringify(observation),
|
|
125
|
+
},
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
export function permitCreate(row: Doc<"usageCatalog">) {
|
|
129
|
+
if (Date.now() / 1000 - row.firstAttemptAt >= 23 * 3600)
|
|
130
|
+
throw new UsageCatalogError(
|
|
131
|
+
"unknown_create_outcome",
|
|
132
|
+
"Native catalog create requires reconciliation after its safe retry window",
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function verifyMeter(
|
|
137
|
+
meter: Stripe.Billing.Meter,
|
|
138
|
+
opts: UsageMeterOptions,
|
|
139
|
+
active = true,
|
|
140
|
+
) {
|
|
141
|
+
if (
|
|
142
|
+
meter.livemode !== opts.scope.livemode ||
|
|
143
|
+
meter.event_name !== opts.eventName ||
|
|
144
|
+
meter.default_aggregation.formula !== "sum" ||
|
|
145
|
+
meter.customer_mapping.type !== "by_id" ||
|
|
146
|
+
meter.customer_mapping.event_payload_key !== "stripe_customer_id" ||
|
|
147
|
+
meter.value_settings.event_payload_key !== "value" ||
|
|
148
|
+
meter.event_time_window !== null ||
|
|
149
|
+
!["active", "inactive"].includes(meter.status) ||
|
|
150
|
+
(active && meter.status !== "active")
|
|
151
|
+
)
|
|
152
|
+
throw new UsageCatalogError(
|
|
153
|
+
"incompatible_terms",
|
|
154
|
+
"Native meter has incompatible immutable terms or status",
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function meterObservation(meter: Stripe.Billing.Meter) {
|
|
159
|
+
return {
|
|
160
|
+
type: "meter",
|
|
161
|
+
id: meter.id,
|
|
162
|
+
eventName: meter.event_name,
|
|
163
|
+
displayName: meter.display_name,
|
|
164
|
+
active: meter.status === "active",
|
|
165
|
+
livemode: meter.livemode,
|
|
166
|
+
aggregation: meter.default_aggregation.formula,
|
|
167
|
+
customerPayloadKey: meter.customer_mapping.event_payload_key,
|
|
168
|
+
valuePayloadKey: meter.value_settings.event_payload_key,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isFixedPrice } from "../products/fixedPrice.js";
|
|
1
2
|
import { handleRefundEvent } from "./refundDelivery.js";
|
|
2
3
|
import { handlePayoutEvent } from "./payoutReconciliation.js";
|
|
3
4
|
import { reconcileDisputeMoney } from "./disputeRecovery.js";
|
|
@@ -157,6 +158,7 @@ async function handlePriceEvent(
|
|
|
157
158
|
whCtx: WebhookContext,
|
|
158
159
|
price: Stripe.Price,
|
|
159
160
|
): Promise<void> {
|
|
161
|
+
if (!isFixedPrice(price)) return;
|
|
160
162
|
const { ctx, component, stripe } = whCtx;
|
|
161
163
|
const stripeProductId: string =
|
|
162
164
|
typeof price.product === "string"
|
|
@@ -165,6 +165,8 @@ import type * as settlement_queries from "../settlement/queries.js";
|
|
|
165
165
|
import type * as usage_helpers from "../usage/helpers.js";
|
|
166
166
|
import type * as usage_mutations from "../usage/mutations.js";
|
|
167
167
|
import type * as usage_queries from "../usage/queries.js";
|
|
168
|
+
import type * as usageCatalog_mutations from "../usageCatalog/mutations.js";
|
|
169
|
+
import type * as usageCatalog_queries from "../usageCatalog/queries.js";
|
|
168
170
|
import type * as webhooks_mutations from "../webhooks/mutations.js";
|
|
169
171
|
import type * as webhooks_queries from "../webhooks/queries.js";
|
|
170
172
|
import type * as webhooks_validators from "../webhooks/validators.js";
|
|
@@ -334,6 +336,8 @@ const fullApi: ApiFromModules<{
|
|
|
334
336
|
"usage/helpers": typeof usage_helpers;
|
|
335
337
|
"usage/mutations": typeof usage_mutations;
|
|
336
338
|
"usage/queries": typeof usage_queries;
|
|
339
|
+
"usageCatalog/mutations": typeof usageCatalog_mutations;
|
|
340
|
+
"usageCatalog/queries": typeof usageCatalog_queries;
|
|
337
341
|
"webhooks/mutations": typeof webhooks_mutations;
|
|
338
342
|
"webhooks/queries": typeof webhooks_queries;
|
|
339
343
|
"webhooks/validators": typeof webhooks_validators;
|
|
@@ -8376,6 +8376,84 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
|
|
|
8376
8376
|
>;
|
|
8377
8377
|
};
|
|
8378
8378
|
};
|
|
8379
|
+
usageCatalog: {
|
|
8380
|
+
mutations: {
|
|
8381
|
+
complete: FunctionReference<
|
|
8382
|
+
"mutation",
|
|
8383
|
+
"internal",
|
|
8384
|
+
{
|
|
8385
|
+
key: string;
|
|
8386
|
+
kind: "meter" | "price";
|
|
8387
|
+
observationJson: string;
|
|
8388
|
+
providerId: string;
|
|
8389
|
+
scopeKey: string;
|
|
8390
|
+
},
|
|
8391
|
+
null,
|
|
8392
|
+
Name
|
|
8393
|
+
>;
|
|
8394
|
+
prepare: FunctionReference<
|
|
8395
|
+
"mutation",
|
|
8396
|
+
"internal",
|
|
8397
|
+
{
|
|
8398
|
+
key: string;
|
|
8399
|
+
kind: "meter" | "price";
|
|
8400
|
+
scopeKey: string;
|
|
8401
|
+
termsJson: string;
|
|
8402
|
+
},
|
|
8403
|
+
{
|
|
8404
|
+
_creationTime: number;
|
|
8405
|
+
_id: string;
|
|
8406
|
+
firstAttemptAt: number;
|
|
8407
|
+
key: string;
|
|
8408
|
+
kind: "meter" | "price";
|
|
8409
|
+
observationJson?: string;
|
|
8410
|
+
observedAt?: number;
|
|
8411
|
+
providerId?: string;
|
|
8412
|
+
scopeKey: string;
|
|
8413
|
+
termsJson: string;
|
|
8414
|
+
},
|
|
8415
|
+
Name
|
|
8416
|
+
>;
|
|
8417
|
+
};
|
|
8418
|
+
queries: {
|
|
8419
|
+
get: FunctionReference<
|
|
8420
|
+
"query",
|
|
8421
|
+
"internal",
|
|
8422
|
+
{ key: string; kind: "meter" | "price"; scopeKey: string },
|
|
8423
|
+
{
|
|
8424
|
+
_creationTime: number;
|
|
8425
|
+
_id: string;
|
|
8426
|
+
firstAttemptAt: number;
|
|
8427
|
+
key: string;
|
|
8428
|
+
kind: "meter" | "price";
|
|
8429
|
+
observationJson?: string;
|
|
8430
|
+
observedAt?: number;
|
|
8431
|
+
providerId?: string;
|
|
8432
|
+
scopeKey: string;
|
|
8433
|
+
termsJson: string;
|
|
8434
|
+
} | null,
|
|
8435
|
+
Name
|
|
8436
|
+
>;
|
|
8437
|
+
getByProvider: FunctionReference<
|
|
8438
|
+
"query",
|
|
8439
|
+
"internal",
|
|
8440
|
+
{ kind: "meter" | "price"; providerId: string; scopeKey: string },
|
|
8441
|
+
{
|
|
8442
|
+
_creationTime: number;
|
|
8443
|
+
_id: string;
|
|
8444
|
+
firstAttemptAt: number;
|
|
8445
|
+
key: string;
|
|
8446
|
+
kind: "meter" | "price";
|
|
8447
|
+
observationJson?: string;
|
|
8448
|
+
observedAt?: number;
|
|
8449
|
+
providerId?: string;
|
|
8450
|
+
scopeKey: string;
|
|
8451
|
+
termsJson: string;
|
|
8452
|
+
} | null,
|
|
8453
|
+
Name
|
|
8454
|
+
>;
|
|
8455
|
+
};
|
|
8456
|
+
};
|
|
8379
8457
|
webhooks: {
|
|
8380
8458
|
mutations: {
|
|
8381
8459
|
insertWebhookEvent: FunctionReference<
|
package/src/component/schema.ts
CHANGED
|
@@ -68,6 +68,7 @@ import {
|
|
|
68
68
|
commissionTermsTable,
|
|
69
69
|
commissionDecisionsTable,
|
|
70
70
|
} from "./settlement/schema";
|
|
71
|
+
import { usageCatalogTable } from "./usageCatalog/schema.js";
|
|
71
72
|
import { defineSchema } from "convex/server";
|
|
72
73
|
import {
|
|
73
74
|
usageEventsTable,
|
|
@@ -95,6 +96,7 @@ import { pricesTable, productsTable } from "./products/schema";
|
|
|
95
96
|
import { webhookEventsTable } from "./webhooks/schema";
|
|
96
97
|
|
|
97
98
|
export default defineSchema({
|
|
99
|
+
usageCatalog: usageCatalogTable,
|
|
98
100
|
usageEvents: usageEventsTable,
|
|
99
101
|
usageOutbox: usageOutboxTable,
|
|
100
102
|
usageScopeCounters: usageScopeCountersTable,
|