@fantastic.dev/better-stripe 0.51.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 +20 -0
- package/README.md +1 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +210 -32
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +105 -16
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +178 -0
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +89 -0
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/index.d.ts +6 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +5 -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/usage/client.d.ts +37 -0
- package/dist/client/usage/client.d.ts.map +1 -0
- package/dist/client/usage/client.js +59 -0
- package/dist/client/usage/client.js.map +1 -0
- package/dist/client/usage/records.d.ts +1 -1
- package/dist/client/usage/records.d.ts.map +1 -1
- package/dist/client/usage/records.js +1 -1
- package/dist/client/usage/records.js.map +1 -1
- 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 +10 -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 +141 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
- package/dist/component/balanceFunding/mutations.d.ts +43 -43
- package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
- package/dist/component/earnings/triggers.d.ts +224 -16
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/schema.d.ts +89 -0
- package/dist/component/schema.js +7 -0
- package/dist/component/schema.js.map +1 -1
- package/dist/component/usage/helpers.d.ts +13 -0
- package/dist/component/usage/helpers.d.ts.map +1 -0
- package/dist/component/usage/helpers.js +34 -0
- package/dist/component/usage/helpers.js.map +1 -0
- package/dist/component/usage/mutations.d.ts +14 -0
- package/dist/component/usage/mutations.d.ts.map +1 -0
- package/dist/component/usage/mutations.js +124 -0
- package/dist/component/usage/mutations.js.map +1 -0
- package/dist/component/usage/queries.d.ts +62 -0
- package/dist/component/usage/queries.d.ts.map +1 -0
- package/dist/component/usage/queries.js +65 -0
- package/dist/component/usage/queries.js.map +1 -0
- package/dist/component/usage/schema.d.ts +110 -0
- package/dist/component/usage/schema.d.ts.map +1 -0
- package/dist/component/usage/schema.js +54 -0
- package/dist/component/usage/schema.js.map +1 -0
- 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 +5 -1
- package/docs/metered-usage.md +2 -2
- package/docs/metering-setup.md +4 -1
- package/docs/usage-catalog.md +106 -0
- package/docs/usage-ledger.md +62 -0
- package/package.json +4 -2
- package/src/client/index.ts +12 -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/usage/client.ts +97 -0
- package/src/client/usage/ledger-client.test.ts +74 -0
- package/src/client/usage/records.ts +1 -1
- package/src/client/webhooks/processors.ts +2 -0
- package/src/component/_generated/api.ts +10 -0
- package/src/component/_generated/component.ts +184 -0
- package/src/component/schema.ts +12 -0
- package/src/component/usage/helpers.ts +33 -0
- package/src/component/usage/ledger.test.ts +310 -0
- package/src/component/usage/mutations.ts +139 -0
- package/src/component/usage/queries.ts +69 -0
- package/src/component/usage/schema.ts +65 -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,464 @@
|
|
|
1
|
+
import Stripe from "stripe";
|
|
2
|
+
import { convexToJson } from "convex/values";
|
|
3
|
+
import { CatalogClient } from "../products/catalogClient.js";
|
|
4
|
+
import { getUsagePriceBinding } from "./catalogRead.js";
|
|
5
|
+
import { componentsGeneric, type FunctionReference } from "convex/server";
|
|
6
|
+
import { expect, it, vi } from "vitest";
|
|
7
|
+
import schema from "../../component/schema.js";
|
|
8
|
+
import { modules } from "../../test.js";
|
|
9
|
+
import { initConvexTest } from "../setup.test.js";
|
|
10
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
11
|
+
import { defineUsagePlan } from "./contracts.js";
|
|
12
|
+
import { ensureUsageMeter, ensureUsagePrice } from "./catalog.js";
|
|
13
|
+
import {
|
|
14
|
+
adoptUsageMeter,
|
|
15
|
+
getUsageMeterFromStripe,
|
|
16
|
+
listStripeUsageMeters,
|
|
17
|
+
setUsageMeterActive,
|
|
18
|
+
} from "./catalogLifecycle.js";
|
|
19
|
+
import { STRIPE_API_VERSION } from "../constants.js";
|
|
20
|
+
const scope = { stripeAccountId: "acct_platform", livemode: false };
|
|
21
|
+
const plan = defineUsagePlan({
|
|
22
|
+
key: "calls",
|
|
23
|
+
version: "v1",
|
|
24
|
+
model: "pay_as_you_go",
|
|
25
|
+
unit: { name: "call", precision: 2 },
|
|
26
|
+
rate: { currency: "usd", unitAmountDecimal: "2" },
|
|
27
|
+
});
|
|
28
|
+
function setup() {
|
|
29
|
+
const t = initConvexTest();
|
|
30
|
+
t.registerComponent("betterStripe", schema, modules);
|
|
31
|
+
const component = componentsGeneric().betterStripe as unknown as Component;
|
|
32
|
+
const meters = new Map<string, Record<string, unknown>>(),
|
|
33
|
+
prices = new Map<string, Record<string, unknown>>();
|
|
34
|
+
const requests: Array<{
|
|
35
|
+
method: string;
|
|
36
|
+
path: string;
|
|
37
|
+
body: URLSearchParams;
|
|
38
|
+
key: string | null;
|
|
39
|
+
}> = [];
|
|
40
|
+
const control = { failComplete: false, wrongRealm: false };
|
|
41
|
+
const stripe = new Stripe("sk_test_catalog", {
|
|
42
|
+
apiVersion: STRIPE_API_VERSION,
|
|
43
|
+
maxNetworkRetries: 0,
|
|
44
|
+
httpClient: Stripe.createFetchHttpClient(async (input, init) => {
|
|
45
|
+
const url = new URL(String(input));
|
|
46
|
+
const method = init?.method ?? "GET";
|
|
47
|
+
const body = new URLSearchParams(String(init?.body ?? ""));
|
|
48
|
+
requests.push({
|
|
49
|
+
method,
|
|
50
|
+
path: url.pathname,
|
|
51
|
+
body,
|
|
52
|
+
key: new Headers(init?.headers).get("idempotency-key"),
|
|
53
|
+
});
|
|
54
|
+
let result: unknown;
|
|
55
|
+
if (url.pathname === "/v1/account")
|
|
56
|
+
result = { id: control.wrongRealm ? "acct_other" : "acct_platform" };
|
|
57
|
+
else if (url.pathname === "/v1/balance")
|
|
58
|
+
result = {
|
|
59
|
+
livemode: false,
|
|
60
|
+
object: "balance",
|
|
61
|
+
available: [],
|
|
62
|
+
pending: [],
|
|
63
|
+
};
|
|
64
|
+
else if (url.pathname === "/v1/billing/meters" && method === "GET")
|
|
65
|
+
result = {
|
|
66
|
+
object: "list",
|
|
67
|
+
data: [...meters.values()],
|
|
68
|
+
has_more: false,
|
|
69
|
+
};
|
|
70
|
+
else if (url.pathname === "/v1/billing/meters" && method === "POST") {
|
|
71
|
+
const id = `mtr_${meters.size + 1}`;
|
|
72
|
+
result = {
|
|
73
|
+
id,
|
|
74
|
+
object: "billing.meter",
|
|
75
|
+
event_name: body.get("event_name"),
|
|
76
|
+
display_name: body.get("display_name"),
|
|
77
|
+
default_aggregation: {
|
|
78
|
+
formula: body.get("default_aggregation[formula]"),
|
|
79
|
+
},
|
|
80
|
+
customer_mapping: {
|
|
81
|
+
type: "by_id",
|
|
82
|
+
event_payload_key: "stripe_customer_id",
|
|
83
|
+
},
|
|
84
|
+
value_settings: { event_payload_key: "value" },
|
|
85
|
+
event_time_window: null,
|
|
86
|
+
livemode: false,
|
|
87
|
+
status: "active",
|
|
88
|
+
};
|
|
89
|
+
meters.set(id, result as Record<string, unknown>);
|
|
90
|
+
} else if (url.pathname.startsWith("/v1/billing/meters/")) {
|
|
91
|
+
const parts = url.pathname.split("/");
|
|
92
|
+
const meter = meters.get(parts[4]);
|
|
93
|
+
if (meter && method === "POST")
|
|
94
|
+
meter.status = parts[5] === "reactivate" ? "active" : "inactive";
|
|
95
|
+
result = meter;
|
|
96
|
+
} else if (url.pathname === "/v1/products/prod_calls")
|
|
97
|
+
result = {
|
|
98
|
+
id: "prod_calls",
|
|
99
|
+
object: "product",
|
|
100
|
+
active: true,
|
|
101
|
+
name: "Calls",
|
|
102
|
+
};
|
|
103
|
+
else if (url.pathname.startsWith("/v1/prices/"))
|
|
104
|
+
result = prices.get(url.pathname.split("/").slice(-1)[0]);
|
|
105
|
+
else if (url.pathname === "/v1/prices" && method === "GET")
|
|
106
|
+
result = {
|
|
107
|
+
object: "list",
|
|
108
|
+
data: [...prices.values()].filter(
|
|
109
|
+
(p) => p.lookup_key === url.searchParams.get("lookup_keys[0]"),
|
|
110
|
+
),
|
|
111
|
+
has_more: false,
|
|
112
|
+
};
|
|
113
|
+
else if (url.pathname === "/v1/prices" && method === "POST") {
|
|
114
|
+
const id = `price_${prices.size + 1}`;
|
|
115
|
+
const tiered = body.get("billing_scheme") === "tiered";
|
|
116
|
+
result = {
|
|
117
|
+
id,
|
|
118
|
+
object: "price",
|
|
119
|
+
product: "prod_calls",
|
|
120
|
+
lookup_key: body.get("lookup_key"),
|
|
121
|
+
active: true,
|
|
122
|
+
livemode: false,
|
|
123
|
+
type: "recurring",
|
|
124
|
+
currency: body.get("currency"),
|
|
125
|
+
billing_scheme: body.get("billing_scheme"),
|
|
126
|
+
transform_quantity: null,
|
|
127
|
+
unit_amount_decimal: body.get("unit_amount_decimal"),
|
|
128
|
+
recurring: {
|
|
129
|
+
interval: "month",
|
|
130
|
+
interval_count: 1,
|
|
131
|
+
usage_type: "metered",
|
|
132
|
+
meter: body.get("recurring[meter]"),
|
|
133
|
+
},
|
|
134
|
+
tiers_mode: tiered ? "graduated" : null,
|
|
135
|
+
tiers: tiered
|
|
136
|
+
? [
|
|
137
|
+
{
|
|
138
|
+
up_to: Number(body.get("tiers[0][up_to]")),
|
|
139
|
+
unit_amount_decimal: body.get(
|
|
140
|
+
"tiers[0][unit_amount_decimal]",
|
|
141
|
+
),
|
|
142
|
+
flat_amount: null,
|
|
143
|
+
flat_amount_decimal: null,
|
|
144
|
+
},
|
|
145
|
+
{
|
|
146
|
+
up_to: null,
|
|
147
|
+
unit_amount_decimal: body.get(
|
|
148
|
+
"tiers[1][unit_amount_decimal]",
|
|
149
|
+
),
|
|
150
|
+
flat_amount: null,
|
|
151
|
+
flat_amount_decimal: null,
|
|
152
|
+
},
|
|
153
|
+
]
|
|
154
|
+
: undefined,
|
|
155
|
+
};
|
|
156
|
+
prices.set(id, result as Record<string, unknown>);
|
|
157
|
+
} else result = { error: { message: "Unexpected fixture request" } };
|
|
158
|
+
return new Response(JSON.stringify(result), {
|
|
159
|
+
status: result ? 200 : 404,
|
|
160
|
+
headers: {
|
|
161
|
+
"content-type": "application/json",
|
|
162
|
+
"request-id": "req_fixture",
|
|
163
|
+
},
|
|
164
|
+
});
|
|
165
|
+
}),
|
|
166
|
+
});
|
|
167
|
+
const ctx = {
|
|
168
|
+
runQuery: (
|
|
169
|
+
ref: FunctionReference<"query">,
|
|
170
|
+
args: Record<string, unknown>,
|
|
171
|
+
) => t.query(ref, args),
|
|
172
|
+
runMutation: (
|
|
173
|
+
ref: FunctionReference<"mutation">,
|
|
174
|
+
args: Record<string, unknown>,
|
|
175
|
+
) => {
|
|
176
|
+
if (control.failComplete && args.providerId) {
|
|
177
|
+
control.failComplete = false;
|
|
178
|
+
throw new Error("Mirror unavailable");
|
|
179
|
+
}
|
|
180
|
+
return t.mutation(ref, args);
|
|
181
|
+
},
|
|
182
|
+
} as RunCtx;
|
|
183
|
+
return { t, component, ctx, stripe, requests, meters, prices, control };
|
|
184
|
+
}
|
|
185
|
+
it("repairs provider-success/mirror-failure without duplicate native resources", async () => {
|
|
186
|
+
const f = setup();
|
|
187
|
+
const opts = { scope, plan, eventName: "calls_v1", displayName: "Calls" };
|
|
188
|
+
f.control.failComplete = true;
|
|
189
|
+
await expect(
|
|
190
|
+
ensureUsageMeter(f.stripe, f.component, f.ctx, opts),
|
|
191
|
+
).rejects.toThrow("Mirror unavailable");
|
|
192
|
+
const meter = await ensureUsageMeter(f.stripe, f.component, f.ctx, opts);
|
|
193
|
+
expect(f.meters.size).toBe(1);
|
|
194
|
+
expect(meter.id).toBe("mtr_1");
|
|
195
|
+
const priceOpts = {
|
|
196
|
+
scope,
|
|
197
|
+
plan,
|
|
198
|
+
meterId: meter.id,
|
|
199
|
+
stripeProductId: "prod_calls",
|
|
200
|
+
lookupKey: "calls_v1",
|
|
201
|
+
};
|
|
202
|
+
f.control.failComplete = true;
|
|
203
|
+
await expect(
|
|
204
|
+
ensureUsagePrice(f.stripe, f.component, f.ctx, priceOpts),
|
|
205
|
+
).rejects.toThrow("Mirror unavailable");
|
|
206
|
+
const price = await ensureUsagePrice(f.stripe, f.component, f.ctx, priceOpts);
|
|
207
|
+
expect(f.prices.size).toBe(1);
|
|
208
|
+
expect(
|
|
209
|
+
await getUsagePriceBinding(f.component, f.ctx, {
|
|
210
|
+
scope,
|
|
211
|
+
lookupKey: "calls_v1",
|
|
212
|
+
}),
|
|
213
|
+
).toMatchObject({
|
|
214
|
+
status: "available",
|
|
215
|
+
value: {
|
|
216
|
+
pricingMode: "metered",
|
|
217
|
+
unitAmountDecimal: "0.02",
|
|
218
|
+
billingScheme: "per_unit",
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
expect(
|
|
222
|
+
await getUsagePriceBinding(f.component, f.ctx, {
|
|
223
|
+
scope: { ...scope, stripeAccountId: "acct_other" },
|
|
224
|
+
lookupKey: "calls_v1",
|
|
225
|
+
}),
|
|
226
|
+
).toMatchObject({ status: "unavailable" });
|
|
227
|
+
|
|
228
|
+
expect(price.unit_amount_decimal?.toString()).toBe("0.02");
|
|
229
|
+
for (const request of f.requests.filter((r) => r.method === "POST"))
|
|
230
|
+
expect(request.key).toMatch(/^bs_usage_/);
|
|
231
|
+
});
|
|
232
|
+
it.each(["included_overage", "prepaid"])(
|
|
233
|
+
"provisions exact native %s pricing",
|
|
234
|
+
async (model) => {
|
|
235
|
+
const f = setup();
|
|
236
|
+
const terms = defineUsagePlan({
|
|
237
|
+
...plan,
|
|
238
|
+
model,
|
|
239
|
+
...(model === "included_overage"
|
|
240
|
+
? { includedQuantity: "10", reset: "billing_period" }
|
|
241
|
+
: { insufficientBalance: "reject" }),
|
|
242
|
+
});
|
|
243
|
+
const meter = await ensureUsageMeter(f.stripe, f.component, f.ctx, {
|
|
244
|
+
scope,
|
|
245
|
+
plan: terms,
|
|
246
|
+
eventName: "calls_v1",
|
|
247
|
+
displayName: "Calls",
|
|
248
|
+
});
|
|
249
|
+
const price = await ensureUsagePrice(f.stripe, f.component, f.ctx, {
|
|
250
|
+
scope,
|
|
251
|
+
plan: terms,
|
|
252
|
+
meterId: meter.id,
|
|
253
|
+
stripeProductId: "prod_calls",
|
|
254
|
+
lookupKey: "calls_v1",
|
|
255
|
+
});
|
|
256
|
+
expect(price.recurring?.usage_type).toBe("metered");
|
|
257
|
+
if (model === "included_overage")
|
|
258
|
+
expect(
|
|
259
|
+
price.tiers?.map((tier) => ({
|
|
260
|
+
up_to: tier.up_to,
|
|
261
|
+
unit_amount_decimal: tier.unit_amount_decimal?.toString(),
|
|
262
|
+
})),
|
|
263
|
+
).toMatchObject([
|
|
264
|
+
{ up_to: 1000, unit_amount_decimal: "0" },
|
|
265
|
+
{ up_to: null, unit_amount_decimal: "0.02" },
|
|
266
|
+
]);
|
|
267
|
+
},
|
|
268
|
+
);
|
|
269
|
+
it("rejects scope and immutable term changes before duplicate provisioning", async () => {
|
|
270
|
+
const f = setup();
|
|
271
|
+
const opts = { scope, plan, eventName: "calls_v1", displayName: "Calls" };
|
|
272
|
+
await ensureUsageMeter(f.stripe, f.component, f.ctx, opts);
|
|
273
|
+
await expect(
|
|
274
|
+
ensureUsageMeter(f.stripe, f.component, f.ctx, {
|
|
275
|
+
...opts,
|
|
276
|
+
eventName: "changed",
|
|
277
|
+
}),
|
|
278
|
+
).rejects.toThrow();
|
|
279
|
+
f.control.wrongRealm = true;
|
|
280
|
+
await expect(
|
|
281
|
+
ensureUsageMeter(f.stripe, f.component, f.ctx, {
|
|
282
|
+
...opts,
|
|
283
|
+
plan: { ...plan, version: "v2" },
|
|
284
|
+
}),
|
|
285
|
+
).rejects.toThrow();
|
|
286
|
+
expect(f.meters.size).toBe(1);
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
it("never recreates a pinned meter when provider discovery stops returning it", async () => {
|
|
290
|
+
const f = setup();
|
|
291
|
+
const opts = { scope, plan, eventName: "calls_v1", displayName: "Calls" };
|
|
292
|
+
await ensureUsageMeter(f.stripe, f.component, f.ctx, opts);
|
|
293
|
+
f.meters.clear();
|
|
294
|
+
await expect(
|
|
295
|
+
ensureUsageMeter(f.stripe, f.component, f.ctx, opts),
|
|
296
|
+
).rejects.toThrow();
|
|
297
|
+
expect(
|
|
298
|
+
f.requests.filter(
|
|
299
|
+
(r) => r.method === "POST" && r.path === "/v1/billing/meters",
|
|
300
|
+
),
|
|
301
|
+
).toHaveLength(1);
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
it("rejects changed provider pricing and ambiguous discovery", async () => {
|
|
305
|
+
const f = setup();
|
|
306
|
+
const opts = { scope, plan, eventName: "calls_v1", displayName: "Calls" };
|
|
307
|
+
const meter = await ensureUsageMeter(f.stripe, f.component, f.ctx, opts);
|
|
308
|
+
const priceOpts = {
|
|
309
|
+
scope,
|
|
310
|
+
plan,
|
|
311
|
+
meterId: meter.id,
|
|
312
|
+
stripeProductId: "prod_calls",
|
|
313
|
+
lookupKey: "calls_v1",
|
|
314
|
+
};
|
|
315
|
+
await ensureUsagePrice(f.stripe, f.component, f.ctx, priceOpts);
|
|
316
|
+
const price = [...f.prices.values()][0];
|
|
317
|
+
price.unit_amount_decimal = "99";
|
|
318
|
+
await expect(
|
|
319
|
+
ensureUsagePrice(f.stripe, f.component, f.ctx, priceOpts),
|
|
320
|
+
).rejects.toThrow("incompatible immutable terms");
|
|
321
|
+
const second = setup();
|
|
322
|
+
second.meters.set("mtr_1", { ...f.meters.get(meter.id), id: "mtr_1" });
|
|
323
|
+
second.meters.set("mtr_2", { ...f.meters.get(meter.id), id: "mtr_2" });
|
|
324
|
+
await expect(
|
|
325
|
+
ensureUsageMeter(second.stripe, second.component, second.ctx, opts),
|
|
326
|
+
).rejects.toThrow("ambiguous");
|
|
327
|
+
expect(second.requests.filter((r) => r.method === "POST")).toEqual([]);
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
it("adopts, retrieves, pages and explicitly deactivates/reactivates native meters", async () => {
|
|
331
|
+
const f = setup();
|
|
332
|
+
const opts = { scope, plan, eventName: "calls_v1", displayName: "Calls" };
|
|
333
|
+
const meter = await ensureUsageMeter(f.stripe, f.component, f.ctx, opts);
|
|
334
|
+
expect(
|
|
335
|
+
(
|
|
336
|
+
await adoptUsageMeter(f.stripe, f.component, f.ctx, {
|
|
337
|
+
...opts,
|
|
338
|
+
meterId: meter.id,
|
|
339
|
+
})
|
|
340
|
+
).id,
|
|
341
|
+
).toBe(meter.id);
|
|
342
|
+
expect(
|
|
343
|
+
(await getUsageMeterFromStripe(f.stripe, { scope, meterId: meter.id })).id,
|
|
344
|
+
).toBe(meter.id);
|
|
345
|
+
expect(
|
|
346
|
+
await listStripeUsageMeters(f.stripe, { scope, limit: 10 }),
|
|
347
|
+
).toMatchObject({ data: [{ id: meter.id }], hasMore: false, cursor: null });
|
|
348
|
+
expect(
|
|
349
|
+
(
|
|
350
|
+
await setUsageMeterActive(f.stripe, f.component, f.ctx, {
|
|
351
|
+
scope,
|
|
352
|
+
meterId: meter.id,
|
|
353
|
+
active: false,
|
|
354
|
+
})
|
|
355
|
+
).status,
|
|
356
|
+
).toBe("inactive");
|
|
357
|
+
await expect(
|
|
358
|
+
ensureUsageMeter(f.stripe, f.component, f.ctx, opts),
|
|
359
|
+
).rejects.toThrow();
|
|
360
|
+
expect(
|
|
361
|
+
(
|
|
362
|
+
await setUsageMeterActive(f.stripe, f.component, f.ctx, {
|
|
363
|
+
scope,
|
|
364
|
+
meterId: meter.id,
|
|
365
|
+
active: true,
|
|
366
|
+
})
|
|
367
|
+
).status,
|
|
368
|
+
).toBe("active");
|
|
369
|
+
expect(
|
|
370
|
+
f.requests.filter(
|
|
371
|
+
(r) => r.method === "POST" && r.path === "/v1/billing/meters",
|
|
372
|
+
),
|
|
373
|
+
).toHaveLength(1);
|
|
374
|
+
await expect(
|
|
375
|
+
listStripeUsageMeters(f.stripe, { scope, limit: 101 }),
|
|
376
|
+
).rejects.toThrow();
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
it("holds unresolved creation after its safe provider retry window", async () => {
|
|
380
|
+
const f = setup();
|
|
381
|
+
const opts = { scope, plan, eventName: "calls_v1", displayName: "Calls" };
|
|
382
|
+
f.control.failComplete = true;
|
|
383
|
+
await expect(
|
|
384
|
+
ensureUsageMeter(f.stripe, f.component, f.ctx, opts),
|
|
385
|
+
).rejects.toThrow("Mirror unavailable");
|
|
386
|
+
f.meters.clear();
|
|
387
|
+
const now = Date.now();
|
|
388
|
+
const clock = vi.spyOn(Date, "now").mockReturnValue(now + 24 * 3600 * 1000);
|
|
389
|
+
try {
|
|
390
|
+
await expect(
|
|
391
|
+
ensureUsageMeter(f.stripe, f.component, f.ctx, opts),
|
|
392
|
+
).rejects.toThrow("safe retry window");
|
|
393
|
+
} finally {
|
|
394
|
+
clock.mockRestore();
|
|
395
|
+
}
|
|
396
|
+
expect(f.requests.filter((r) => r.method === "POST")).toHaveLength(1);
|
|
397
|
+
});
|
|
398
|
+
it("rejects adoption that reassigns an already bound native meter", async () => {
|
|
399
|
+
const f = setup();
|
|
400
|
+
const opts = { scope, plan, eventName: "calls_v1", displayName: "Calls" };
|
|
401
|
+
const meter = await ensureUsageMeter(f.stripe, f.component, f.ctx, opts);
|
|
402
|
+
await expect(
|
|
403
|
+
adoptUsageMeter(f.stripe, f.component, f.ctx, {
|
|
404
|
+
...opts,
|
|
405
|
+
plan: { ...plan, version: "v2" },
|
|
406
|
+
meterId: meter.id,
|
|
407
|
+
}),
|
|
408
|
+
).rejects.toThrow("ownership conflict");
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
it("returns a plain Convex-safe public price binding instead of SDK Decimal objects", async () => {
|
|
412
|
+
const f = setup();
|
|
413
|
+
class Client extends CatalogClient {
|
|
414
|
+
get statementDescriptorSuffix() {
|
|
415
|
+
return undefined;
|
|
416
|
+
}
|
|
417
|
+
protected stripe() {
|
|
418
|
+
return f.stripe;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
const sdk = new Client(f.component);
|
|
422
|
+
const meter = await sdk.ensureUsageMeter(f.ctx, {
|
|
423
|
+
scope,
|
|
424
|
+
plan,
|
|
425
|
+
eventName: "calls_v1",
|
|
426
|
+
displayName: "Calls",
|
|
427
|
+
});
|
|
428
|
+
const price = await sdk.ensureUsagePrice(f.ctx, {
|
|
429
|
+
scope,
|
|
430
|
+
plan,
|
|
431
|
+
meterId: meter.id,
|
|
432
|
+
stripeProductId: "prod_calls",
|
|
433
|
+
lookupKey: "calls_v1",
|
|
434
|
+
});
|
|
435
|
+
expect(price).toMatchObject({
|
|
436
|
+
pricingMode: "metered",
|
|
437
|
+
stripePriceId: "price_1",
|
|
438
|
+
unitAmountDecimal: "0.02",
|
|
439
|
+
});
|
|
440
|
+
expect(() => convexToJson(price)).not.toThrow();
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
it("rejects a mismatched meter returned for a pinned price binding", async () => {
|
|
444
|
+
const f = setup();
|
|
445
|
+
const meter = await ensureUsageMeter(f.stripe, f.component, f.ctx, {
|
|
446
|
+
scope,
|
|
447
|
+
plan,
|
|
448
|
+
eventName: "calls_v1",
|
|
449
|
+
displayName: "Calls",
|
|
450
|
+
});
|
|
451
|
+
f.meters.get(meter.id)!.id = "mtr_other";
|
|
452
|
+
await expect(
|
|
453
|
+
ensureUsagePrice(f.stripe, f.component, f.ctx, {
|
|
454
|
+
scope,
|
|
455
|
+
plan,
|
|
456
|
+
meterId: meter.id,
|
|
457
|
+
stripeProductId: "prod_calls",
|
|
458
|
+
lookupKey: "calls_v1",
|
|
459
|
+
}),
|
|
460
|
+
).rejects.toThrow("incompatible immutable terms");
|
|
461
|
+
expect(
|
|
462
|
+
f.requests.filter((r) => r.path === "/v1/prices" && r.method === "POST"),
|
|
463
|
+
).toHaveLength(0);
|
|
464
|
+
});
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
3
|
+
import {
|
|
4
|
+
UsageCatalogError,
|
|
5
|
+
verifyMeter,
|
|
6
|
+
meterObservation,
|
|
7
|
+
meterTerms,
|
|
8
|
+
meterKey,
|
|
9
|
+
verifyRealm,
|
|
10
|
+
prepareCatalog,
|
|
11
|
+
completeCatalog,
|
|
12
|
+
operationKey,
|
|
13
|
+
permitCreate,
|
|
14
|
+
nativeCall,
|
|
15
|
+
type UsageMeterOptions,
|
|
16
|
+
} from "./catalogTypes.js";
|
|
17
|
+
export type {
|
|
18
|
+
UsageCatalogScope,
|
|
19
|
+
UsageMeterOptions,
|
|
20
|
+
UsagePriceOptions,
|
|
21
|
+
} from "./catalogTypes.js";
|
|
22
|
+
export { ensureUsagePrice } from "./catalogPrices.js";
|
|
23
|
+
|
|
24
|
+
export async function ensureUsageMeter(
|
|
25
|
+
stripe: Stripe,
|
|
26
|
+
component: Component,
|
|
27
|
+
ctx: RunCtx,
|
|
28
|
+
opts: UsageMeterOptions,
|
|
29
|
+
): Promise<Stripe.Billing.Meter> {
|
|
30
|
+
const terms = meterTerms(opts);
|
|
31
|
+
await verifyRealm(stripe, terms.scope);
|
|
32
|
+
const row = await prepareCatalog(
|
|
33
|
+
component,
|
|
34
|
+
ctx,
|
|
35
|
+
"meter",
|
|
36
|
+
terms.scope,
|
|
37
|
+
meterKey(terms.plan),
|
|
38
|
+
terms,
|
|
39
|
+
);
|
|
40
|
+
if (row.providerId) {
|
|
41
|
+
const pinned = await nativeCall(() =>
|
|
42
|
+
stripe.billing.meters.retrieve(row.providerId!),
|
|
43
|
+
);
|
|
44
|
+
verifyMeter(pinned, terms);
|
|
45
|
+
if (pinned.id !== row.providerId)
|
|
46
|
+
throw new UsageCatalogError(
|
|
47
|
+
"incompatible_terms",
|
|
48
|
+
"Native meter identity changed",
|
|
49
|
+
);
|
|
50
|
+
await completeCatalog(
|
|
51
|
+
component,
|
|
52
|
+
ctx,
|
|
53
|
+
row,
|
|
54
|
+
pinned.id,
|
|
55
|
+
meterObservation(pinned),
|
|
56
|
+
);
|
|
57
|
+
return pinned;
|
|
58
|
+
}
|
|
59
|
+
let match: Stripe.Billing.Meter | undefined;
|
|
60
|
+
let cursor: string | undefined;
|
|
61
|
+
for (let page = 0; page < 10; page++) {
|
|
62
|
+
const result = await nativeCall(() =>
|
|
63
|
+
stripe.billing.meters.list({ limit: 100, starting_after: cursor }),
|
|
64
|
+
);
|
|
65
|
+
for (const meter of result.data)
|
|
66
|
+
if (meter.event_name === terms.eventName) {
|
|
67
|
+
if (match)
|
|
68
|
+
throw new UsageCatalogError(
|
|
69
|
+
"ambiguous_lookup",
|
|
70
|
+
"Native meter event name is ambiguous",
|
|
71
|
+
);
|
|
72
|
+
match = meter;
|
|
73
|
+
}
|
|
74
|
+
if (!result.has_more) {
|
|
75
|
+
cursor = undefined;
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
cursor = result.data[result.data.length - 1]?.id;
|
|
79
|
+
if (!cursor)
|
|
80
|
+
throw new UsageCatalogError(
|
|
81
|
+
"ambiguous_lookup",
|
|
82
|
+
"Native meter lookup is incomplete",
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
if (cursor)
|
|
86
|
+
throw new UsageCatalogError(
|
|
87
|
+
"ambiguous_lookup",
|
|
88
|
+
"Native meter lookup exceeds its bounded page budget",
|
|
89
|
+
);
|
|
90
|
+
if (!match) {
|
|
91
|
+
permitCreate(row);
|
|
92
|
+
const key = await operationKey(terms, "meter");
|
|
93
|
+
match = await nativeCall(() =>
|
|
94
|
+
stripe.billing.meters.create(
|
|
95
|
+
{
|
|
96
|
+
display_name: terms.displayName,
|
|
97
|
+
event_name: terms.eventName,
|
|
98
|
+
default_aggregation: { formula: "sum" },
|
|
99
|
+
customer_mapping: {
|
|
100
|
+
type: "by_id",
|
|
101
|
+
event_payload_key: "stripe_customer_id",
|
|
102
|
+
},
|
|
103
|
+
value_settings: { event_payload_key: "value" },
|
|
104
|
+
},
|
|
105
|
+
{ idempotencyKey: key },
|
|
106
|
+
),
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
verifyMeter(match, terms);
|
|
110
|
+
if (row.providerId && row.providerId !== match.id)
|
|
111
|
+
throw new UsageCatalogError(
|
|
112
|
+
"incompatible_terms",
|
|
113
|
+
"Native meter identity changed",
|
|
114
|
+
);
|
|
115
|
+
await completeCatalog(component, ctx, row, match.id, meterObservation(match));
|
|
116
|
+
return match;
|
|
117
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type 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 {
|
|
6
|
+
UsageCatalogError,
|
|
7
|
+
meterTerms,
|
|
8
|
+
meterKey,
|
|
9
|
+
verifyRealm,
|
|
10
|
+
verifyMeter,
|
|
11
|
+
meterObservation,
|
|
12
|
+
prepareCatalog,
|
|
13
|
+
completeCatalog,
|
|
14
|
+
catalogScope,
|
|
15
|
+
nativeCall,
|
|
16
|
+
type UsageCatalogScope,
|
|
17
|
+
type UsageMeterOptions,
|
|
18
|
+
} from "./catalogTypes.js";
|
|
19
|
+
import type { Doc } from "../../component/_generated/dataModel.js";
|
|
20
|
+
const meterId = z
|
|
21
|
+
.string()
|
|
22
|
+
.regex(/^mtr_[a-zA-Z0-9_]+$/)
|
|
23
|
+
.max(100);
|
|
24
|
+
export async function adoptUsageMeter(
|
|
25
|
+
stripe: Stripe,
|
|
26
|
+
component: Component,
|
|
27
|
+
ctx: RunCtx,
|
|
28
|
+
opts: UsageMeterOptions & { meterId: string },
|
|
29
|
+
): Promise<Stripe.Billing.Meter> {
|
|
30
|
+
const terms = meterTerms(opts);
|
|
31
|
+
const meter = await getUsageMeterFromStripe(stripe, {
|
|
32
|
+
scope: terms.scope,
|
|
33
|
+
meterId: opts.meterId,
|
|
34
|
+
});
|
|
35
|
+
verifyMeter(meter, terms, false);
|
|
36
|
+
const row = await prepareCatalog(
|
|
37
|
+
component,
|
|
38
|
+
ctx,
|
|
39
|
+
"meter",
|
|
40
|
+
terms.scope,
|
|
41
|
+
meterKey(terms.plan),
|
|
42
|
+
terms,
|
|
43
|
+
);
|
|
44
|
+
await completeCatalog(component, ctx, row, meter.id, meterObservation(meter));
|
|
45
|
+
return meter;
|
|
46
|
+
}
|
|
47
|
+
export async function getUsageMeterFromStripe(
|
|
48
|
+
stripe: Stripe,
|
|
49
|
+
opts: { scope: UsageCatalogScope; meterId: string },
|
|
50
|
+
): Promise<Stripe.Billing.Meter> {
|
|
51
|
+
const id = meterId.parse(opts.meterId);
|
|
52
|
+
await verifyRealm(stripe, opts.scope);
|
|
53
|
+
const meter = await nativeCall(() => stripe.billing.meters.retrieve(id));
|
|
54
|
+
if (meter.id !== id || meter.livemode !== opts.scope.livemode)
|
|
55
|
+
throw new UsageCatalogError(
|
|
56
|
+
"incompatible_terms",
|
|
57
|
+
"Native meter identity or mode mismatch",
|
|
58
|
+
);
|
|
59
|
+
return meter;
|
|
60
|
+
}
|
|
61
|
+
export async function listStripeUsageMeters(
|
|
62
|
+
stripe: Stripe,
|
|
63
|
+
opts: { scope: UsageCatalogScope; limit: number; cursor?: string },
|
|
64
|
+
): Promise<{
|
|
65
|
+
data: Stripe.Billing.Meter[];
|
|
66
|
+
hasMore: boolean;
|
|
67
|
+
cursor: string | null;
|
|
68
|
+
}> {
|
|
69
|
+
const limit = z.number().int().min(1).max(100).parse(opts.limit);
|
|
70
|
+
const cursor = meterId.optional().parse(opts.cursor);
|
|
71
|
+
await verifyRealm(stripe, opts.scope);
|
|
72
|
+
const page = await nativeCall(() =>
|
|
73
|
+
stripe.billing.meters.list({ limit, starting_after: cursor }),
|
|
74
|
+
);
|
|
75
|
+
if (
|
|
76
|
+
page.data.some((meter) => meter.livemode !== opts.scope.livemode) ||
|
|
77
|
+
(page.has_more && !page.data.length)
|
|
78
|
+
)
|
|
79
|
+
throw new UsageCatalogError(
|
|
80
|
+
"ambiguous_lookup",
|
|
81
|
+
"Native meter page is inconsistent",
|
|
82
|
+
);
|
|
83
|
+
return {
|
|
84
|
+
data: page.data,
|
|
85
|
+
hasMore: page.has_more,
|
|
86
|
+
cursor: page.has_more ? page.data[page.data.length - 1].id : null,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
export async function setUsageMeterActive(
|
|
90
|
+
stripe: Stripe,
|
|
91
|
+
component: Component,
|
|
92
|
+
ctx: RunCtx,
|
|
93
|
+
opts: { scope: UsageCatalogScope; meterId: string; active: boolean },
|
|
94
|
+
): Promise<Stripe.Billing.Meter> {
|
|
95
|
+
const current = await getUsageMeterFromStripe(stripe, opts);
|
|
96
|
+
const row = (await ctx.runQuery(
|
|
97
|
+
componentRef(component, "usageCatalog/queries/getByProvider"),
|
|
98
|
+
{
|
|
99
|
+
scopeKey: JSON.stringify(catalogScope(opts.scope)),
|
|
100
|
+
kind: "meter",
|
|
101
|
+
providerId: opts.meterId,
|
|
102
|
+
},
|
|
103
|
+
)) as Doc<"usageCatalog"> | null;
|
|
104
|
+
if (!row)
|
|
105
|
+
throw new UsageCatalogError(
|
|
106
|
+
"incompatible_terms",
|
|
107
|
+
"Adopt a native meter before changing its lifecycle",
|
|
108
|
+
);
|
|
109
|
+
const terms = meterTerms(JSON.parse(row.termsJson) as UsageMeterOptions);
|
|
110
|
+
verifyMeter(current, terms, false);
|
|
111
|
+
const target = opts.active ? "active" : "inactive";
|
|
112
|
+
const meter =
|
|
113
|
+
current.status === target
|
|
114
|
+
? current
|
|
115
|
+
: await nativeCall(() =>
|
|
116
|
+
opts.active
|
|
117
|
+
? stripe.billing.meters.reactivate(opts.meterId)
|
|
118
|
+
: stripe.billing.meters.deactivate(opts.meterId),
|
|
119
|
+
);
|
|
120
|
+
verifyMeter(meter, terms, false);
|
|
121
|
+
if (meter.id !== opts.meterId || meter.status !== target)
|
|
122
|
+
throw new UsageCatalogError(
|
|
123
|
+
"provider_unavailable",
|
|
124
|
+
"Native meter lifecycle outcome is uncertain",
|
|
125
|
+
);
|
|
126
|
+
await completeCatalog(component, ctx, row, meter.id, meterObservation(meter));
|
|
127
|
+
return meter;
|
|
128
|
+
}
|