@fantastic.dev/better-stripe 0.53.0 → 0.55.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 +12 -0
- package/README.md +1 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +226 -34
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +97 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +226 -34
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +97 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/index.d.ts +8 -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/usage/client.d.ts +2 -2
- package/dist/client/usage/client.d.ts.map +1 -1
- package/dist/client/usage/client.js +3 -3
- package/dist/client/usage/client.js.map +1 -1
- package/dist/client/usage/deliveryClient.d.ts +64 -0
- package/dist/client/usage/deliveryClient.d.ts.map +1 -0
- package/dist/client/usage/deliveryClient.js +60 -0
- package/dist/client/usage/deliveryClient.js.map +1 -0
- package/dist/client/usage/deliveryProtocol.d.ts +130 -0
- package/dist/client/usage/deliveryProtocol.d.ts.map +1 -0
- package/dist/client/usage/deliveryProtocol.js +21 -0
- package/dist/client/usage/deliveryProtocol.js.map +1 -0
- package/dist/client/usage/deliveryProvider.d.ts +32 -0
- package/dist/client/usage/deliveryProvider.d.ts.map +1 -0
- package/dist/client/usage/deliveryProvider.js +127 -0
- package/dist/client/usage/deliveryProvider.js.map +1 -0
- package/dist/client/usage/index.d.ts +8 -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/invoiceObservation.d.ts +38 -0
- package/dist/client/usage/invoiceObservation.d.ts.map +1 -0
- package/dist/client/usage/invoiceObservation.js +157 -0
- package/dist/client/usage/invoiceObservation.js.map +1 -0
- package/dist/client/usage/observationClient.d.ts +83 -0
- package/dist/client/usage/observationClient.d.ts.map +1 -0
- package/dist/client/usage/observationClient.js +157 -0
- package/dist/client/usage/observationClient.js.map +1 -0
- package/dist/client/usage/observationTypes.d.ts +63 -0
- package/dist/client/usage/observationTypes.d.ts.map +1 -0
- package/dist/client/usage/observationTypes.js +59 -0
- package/dist/client/usage/observationTypes.js.map +1 -0
- package/dist/client/usage/providerObservation.d.ts +4 -0
- package/dist/client/usage/providerObservation.d.ts.map +1 -0
- package/dist/client/usage/providerObservation.js +96 -0
- package/dist/client/usage/providerObservation.js.map +1 -0
- package/dist/client/usage/reconciliation.d.ts +12 -0
- package/dist/client/usage/reconciliation.d.ts.map +1 -0
- package/dist/client/usage/reconciliation.js +48 -0
- package/dist/client/usage/reconciliation.js.map +1 -0
- package/dist/client/usage/summary.d.ts +50 -0
- package/dist/client/usage/summary.d.ts.map +1 -0
- package/dist/client/usage/summary.js +110 -0
- package/dist/client/usage/summary.js.map +1 -0
- package/dist/client/webhooks/handler.d.ts.map +1 -1
- package/dist/client/webhooks/handler.js +2 -1
- package/dist/client/webhooks/handler.js.map +1 -1
- package/dist/client/webhooks/meterErrors.d.ts +5 -0
- package/dist/client/webhooks/meterErrors.d.ts.map +1 -0
- package/dist/client/webhooks/meterErrors.js +98 -0
- package/dist/client/webhooks/meterErrors.js.map +1 -0
- package/dist/client/webhooks/v2.d.ts.map +1 -1
- package/dist/client/webhooks/v2.js +5 -0
- package/dist/client/webhooks/v2.js.map +1 -1
- package/dist/component/_generated/api.d.ts +22 -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 +265 -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 +27 -27
- package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
- package/dist/component/earnings/triggers.d.ts +206 -18
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/schema.d.ts +97 -1
- package/dist/component/schema.js +6 -0
- package/dist/component/schema.js.map +1 -1
- package/dist/component/usage/schema.d.ts +101 -1
- package/dist/component/usage/schema.d.ts.map +1 -1
- package/dist/component/usage/schema.js +11 -2
- package/dist/component/usage/schema.js.map +1 -1
- package/dist/component/usageDelivery/bridge.d.ts +25 -0
- package/dist/component/usageDelivery/bridge.d.ts.map +1 -0
- package/dist/component/usageDelivery/bridge.js +45 -0
- package/dist/component/usageDelivery/bridge.js.map +1 -0
- package/dist/component/usageDelivery/fields.d.ts +79 -0
- package/dist/component/usageDelivery/fields.d.ts.map +1 -0
- package/dist/component/usageDelivery/fields.js +39 -0
- package/dist/component/usageDelivery/fields.js.map +1 -0
- package/dist/component/usageDelivery/helpers.d.ts +84 -0
- package/dist/component/usageDelivery/helpers.d.ts.map +1 -0
- package/dist/component/usageDelivery/helpers.js +63 -0
- package/dist/component/usageDelivery/helpers.js.map +1 -0
- package/dist/component/usageDelivery/mutations.d.ts +97 -0
- package/dist/component/usageDelivery/mutations.d.ts.map +1 -0
- package/dist/component/usageDelivery/mutations.js +160 -0
- package/dist/component/usageDelivery/mutations.js.map +1 -0
- package/dist/component/usageDelivery/queries.d.ts +115 -0
- package/dist/component/usageDelivery/queries.d.ts.map +1 -0
- package/dist/component/usageDelivery/queries.js +22 -0
- package/dist/component/usageDelivery/queries.js.map +1 -0
- package/dist/component/usageDelivery/schema.d.ts +79 -0
- package/dist/component/usageDelivery/schema.d.ts.map +1 -0
- package/dist/component/usageDelivery/schema.js +30 -0
- package/dist/component/usageDelivery/schema.js.map +1 -0
- package/dist/component/usageDelivery/steps.d.ts +85 -0
- package/dist/component/usageDelivery/steps.d.ts.map +1 -0
- package/dist/component/usageDelivery/steps.js +161 -0
- package/dist/component/usageDelivery/steps.js.map +1 -0
- package/dist/component/usageDelivery/workflow.d.ts +15 -0
- package/dist/component/usageDelivery/workflow.d.ts.map +1 -0
- package/dist/component/usageDelivery/workflow.js +28 -0
- package/dist/component/usageDelivery/workflow.js.map +1 -0
- package/dist/component/usageObservations/helpers.d.ts +38 -0
- package/dist/component/usageObservations/helpers.d.ts.map +1 -0
- package/dist/component/usageObservations/helpers.js +80 -0
- package/dist/component/usageObservations/helpers.js.map +1 -0
- package/dist/component/usageObservations/history.d.ts +6 -0
- package/dist/component/usageObservations/history.d.ts.map +1 -0
- package/dist/component/usageObservations/history.js +29 -0
- package/dist/component/usageObservations/history.js.map +1 -0
- package/dist/component/usageObservations/mutations.d.ts +6 -0
- package/dist/component/usageObservations/mutations.d.ts.map +1 -0
- package/dist/component/usageObservations/mutations.js +39 -0
- package/dist/component/usageObservations/mutations.js.map +1 -0
- package/dist/component/usageObservations/queries.d.ts +78 -0
- package/dist/component/usageObservations/queries.d.ts.map +1 -0
- package/dist/component/usageObservations/queries.js +131 -0
- package/dist/component/usageObservations/queries.js.map +1 -0
- package/dist/component/usageObservations/schema.d.ts +72 -0
- package/dist/component/usageObservations/schema.d.ts.map +1 -0
- package/dist/component/usageObservations/schema.js +29 -0
- package/dist/component/usageObservations/schema.js.map +1 -0
- package/docs/README.md +5 -1
- package/docs/metering-setup.md +3 -1
- package/docs/usage-delivery.md +143 -0
- package/docs/usage-observations.md +152 -0
- package/package.json +4 -2
- package/src/client/index.ts +34 -0
- package/src/client/usage/client.ts +5 -2
- package/src/client/usage/deliveryClient.ts +130 -0
- package/src/client/usage/deliveryProtocol.ts +26 -0
- package/src/client/usage/deliveryProvider.test.ts +207 -0
- package/src/client/usage/deliveryProvider.ts +155 -0
- package/src/client/usage/index.ts +31 -0
- package/src/client/usage/invoiceObservation.test.ts +195 -0
- package/src/client/usage/invoiceObservation.ts +203 -0
- package/src/client/usage/observationClient.ts +233 -0
- package/src/client/usage/observationTypes.ts +101 -0
- package/src/client/usage/providerObservation.test.ts +207 -0
- package/src/client/usage/providerObservation.ts +124 -0
- package/src/client/usage/reconciliation.test.ts +117 -0
- package/src/client/usage/reconciliation.ts +86 -0
- package/src/client/usage/summary.test.ts +222 -0
- package/src/client/usage/summary.ts +188 -0
- package/src/client/webhooks/handler.ts +2 -1
- package/src/client/webhooks/meterErrors.test.ts +164 -0
- package/src/client/webhooks/meterErrors.ts +118 -0
- package/src/client/webhooks/v2.ts +5 -0
- package/src/component/_generated/api.ts +22 -0
- package/src/component/_generated/component.ts +437 -0
- package/src/component/schema.ts +12 -0
- package/src/component/usage/schema.ts +11 -2
- package/src/component/usageDelivery/bridge.ts +56 -0
- package/src/component/usageDelivery/concurrency.test.ts +62 -0
- package/src/component/usageDelivery/fields.ts +60 -0
- package/src/component/usageDelivery/helpers.ts +77 -0
- package/src/component/usageDelivery/mutations.ts +210 -0
- package/src/component/usageDelivery/queries.ts +25 -0
- package/src/component/usageDelivery/schema.ts +33 -0
- package/src/component/usageDelivery/steps.ts +209 -0
- package/src/component/usageDelivery/workflow.test.ts +402 -0
- package/src/component/usageDelivery/workflow.ts +36 -0
- package/src/component/usageObservations/helpers.ts +95 -0
- package/src/component/usageObservations/history.test.ts +87 -0
- package/src/component/usageObservations/history.ts +39 -0
- package/src/component/usageObservations/mutations.ts +39 -0
- package/src/component/usageObservations/queries.test.ts +162 -0
- package/src/component/usageObservations/queries.ts +145 -0
- package/src/component/usageObservations/schema.ts +40 -0
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { expect, it } from "vitest";
|
|
2
|
+
import { summarizeUsageRecords } from "./summary.js";
|
|
3
|
+
import { prepareUsageRecord } from "./records.js";
|
|
4
|
+
const scope = {
|
|
5
|
+
stripeAccountId: "acct_platform",
|
|
6
|
+
customerAccount: "acct_buyer",
|
|
7
|
+
meterId: "mtr_calls",
|
|
8
|
+
livemode: false,
|
|
9
|
+
};
|
|
10
|
+
const period = { start: 600, end: 1200 };
|
|
11
|
+
const subscription = {
|
|
12
|
+
subscriptionId: "sub_calls",
|
|
13
|
+
subscriptionItemId: "si_calls",
|
|
14
|
+
stripePriceId: "price_calls",
|
|
15
|
+
period,
|
|
16
|
+
interval: "month" as const,
|
|
17
|
+
};
|
|
18
|
+
function view(model = "pay_as_you_go", quantity = "1.25", currency = "usd") {
|
|
19
|
+
const record = prepareUsageRecord({
|
|
20
|
+
scope,
|
|
21
|
+
binding: {
|
|
22
|
+
stripeCustomerId: "cus_buyer",
|
|
23
|
+
stripePriceId: "price_calls",
|
|
24
|
+
eventName: "calls",
|
|
25
|
+
plan: {
|
|
26
|
+
key: "calls",
|
|
27
|
+
version: "v1",
|
|
28
|
+
model,
|
|
29
|
+
unit: { name: "call", precision: 2 },
|
|
30
|
+
rate: { currency, unitAmountDecimal: "2" },
|
|
31
|
+
...(model === "included_overage"
|
|
32
|
+
? { includedQuantity: "1", reset: "billing_period" }
|
|
33
|
+
: model === "prepaid"
|
|
34
|
+
? { insufficientBalance: "reject" }
|
|
35
|
+
: {}),
|
|
36
|
+
},
|
|
37
|
+
},
|
|
38
|
+
sourceEventId: "one",
|
|
39
|
+
quantity,
|
|
40
|
+
occurredAt: 700,
|
|
41
|
+
});
|
|
42
|
+
return {
|
|
43
|
+
record,
|
|
44
|
+
subscription,
|
|
45
|
+
delivery: "provider_accepted" as const,
|
|
46
|
+
hasValidationError: false,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
it("keeps exact accepted and transport-accepted quantities and separate currencies", () => {
|
|
50
|
+
const local = summarizeUsageRecords(
|
|
51
|
+
[
|
|
52
|
+
view(),
|
|
53
|
+
{
|
|
54
|
+
...view("pay_as_you_go", "2.5", "eur"),
|
|
55
|
+
record: {
|
|
56
|
+
...view("pay_as_you_go", "2.5", "eur").record,
|
|
57
|
+
binding: {
|
|
58
|
+
...view("pay_as_you_go", "2.5", "eur").record.binding,
|
|
59
|
+
stripeCustomerId: "cus_eur",
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
delivery: "queued",
|
|
63
|
+
},
|
|
64
|
+
],
|
|
65
|
+
{ period, complete: true, observedAt: 1201 },
|
|
66
|
+
);
|
|
67
|
+
expect(local).toMatchObject({
|
|
68
|
+
complete: true,
|
|
69
|
+
eventCount: 2,
|
|
70
|
+
groups: [
|
|
71
|
+
{
|
|
72
|
+
acceptedQuantity: "1.25",
|
|
73
|
+
providerAcceptedQuantity: "1.25",
|
|
74
|
+
estimate: {
|
|
75
|
+
status: "available",
|
|
76
|
+
value: { amountDecimal: "2.5", currency: "usd" },
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
acceptedQuantity: "2.5",
|
|
81
|
+
providerAcceptedQuantity: "0",
|
|
82
|
+
estimate: {
|
|
83
|
+
status: "available",
|
|
84
|
+
value: { amountDecimal: "5", currency: "eur" },
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
],
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
it("applies included units only to a complete original billing period", () => {
|
|
91
|
+
expect(
|
|
92
|
+
summarizeUsageRecords([view("included_overage")], {
|
|
93
|
+
period,
|
|
94
|
+
complete: true,
|
|
95
|
+
observedAt: 1201,
|
|
96
|
+
}),
|
|
97
|
+
).toMatchObject({
|
|
98
|
+
groups: [
|
|
99
|
+
{
|
|
100
|
+
included: {
|
|
101
|
+
status: "available",
|
|
102
|
+
value: { consumed: "1.25", remaining: "0", overage: "0.25" },
|
|
103
|
+
},
|
|
104
|
+
estimate: { status: "available", value: { amountDecimal: "0.5" } },
|
|
105
|
+
},
|
|
106
|
+
],
|
|
107
|
+
});
|
|
108
|
+
expect(
|
|
109
|
+
summarizeUsageRecords([view("included_overage")], {
|
|
110
|
+
period: { start: 700, end: 900 },
|
|
111
|
+
complete: true,
|
|
112
|
+
observedAt: 1201,
|
|
113
|
+
}),
|
|
114
|
+
).toMatchObject({
|
|
115
|
+
groups: [
|
|
116
|
+
{
|
|
117
|
+
included: { status: "unavailable", reason: "partial_billing_period" },
|
|
118
|
+
estimate: { status: "unavailable" },
|
|
119
|
+
},
|
|
120
|
+
],
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
it("does not fabricate prepaid balances or complete estimates from incomplete history", () => {
|
|
124
|
+
expect(
|
|
125
|
+
summarizeUsageRecords([view("prepaid")], {
|
|
126
|
+
period,
|
|
127
|
+
complete: true,
|
|
128
|
+
observedAt: 1201,
|
|
129
|
+
}),
|
|
130
|
+
).toMatchObject({
|
|
131
|
+
groups: [
|
|
132
|
+
{
|
|
133
|
+
credits: {
|
|
134
|
+
status: "unavailable",
|
|
135
|
+
reason: "credit_accounting_not_configured",
|
|
136
|
+
},
|
|
137
|
+
estimate: { status: "unavailable" },
|
|
138
|
+
},
|
|
139
|
+
],
|
|
140
|
+
});
|
|
141
|
+
expect(
|
|
142
|
+
summarizeUsageRecords([view()], {
|
|
143
|
+
period,
|
|
144
|
+
complete: false,
|
|
145
|
+
observedAt: 1201,
|
|
146
|
+
}),
|
|
147
|
+
).toMatchObject({
|
|
148
|
+
complete: false,
|
|
149
|
+
groups: [
|
|
150
|
+
{
|
|
151
|
+
estimate: { status: "unavailable", reason: "local_history_incomplete" },
|
|
152
|
+
},
|
|
153
|
+
],
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it("does not estimate invoice usage across overlapping native subscription items", () => {
|
|
158
|
+
const first = view(),
|
|
159
|
+
second = {
|
|
160
|
+
...view(),
|
|
161
|
+
subscription: { ...subscription, subscriptionItemId: "si_other" },
|
|
162
|
+
};
|
|
163
|
+
const result = summarizeUsageRecords([first, second], {
|
|
164
|
+
period,
|
|
165
|
+
complete: true,
|
|
166
|
+
observedAt: 1201,
|
|
167
|
+
});
|
|
168
|
+
expect(
|
|
169
|
+
result.groups.every(
|
|
170
|
+
(group) =>
|
|
171
|
+
group.estimate.status === "unavailable" &&
|
|
172
|
+
group.estimate.reason === "ambiguous_subscription_binding",
|
|
173
|
+
),
|
|
174
|
+
).toBe(true);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it("withholds allowance estimates across same-item price transitions", () => {
|
|
178
|
+
const first = view("included_overage", "0.75");
|
|
179
|
+
const second = structuredClone(first);
|
|
180
|
+
second.record.binding.plan.version = "v2";
|
|
181
|
+
second.record.binding.stripePriceId = "price_v2";
|
|
182
|
+
second.subscription = { ...subscription, stripePriceId: "price_v2" };
|
|
183
|
+
const result = summarizeUsageRecords([first, second], {
|
|
184
|
+
period,
|
|
185
|
+
complete: true,
|
|
186
|
+
observedAt: 1201,
|
|
187
|
+
});
|
|
188
|
+
expect(result.groups).toHaveLength(2);
|
|
189
|
+
for (const group of result.groups) {
|
|
190
|
+
expect(group.acceptedQuantity).toBe("0.75");
|
|
191
|
+
expect(group.included).toMatchObject({
|
|
192
|
+
status: "unavailable",
|
|
193
|
+
reason: "ambiguous_subscription_binding",
|
|
194
|
+
});
|
|
195
|
+
expect(group.estimate).toMatchObject({
|
|
196
|
+
status: "unavailable",
|
|
197
|
+
reason: "ambiguous_subscription_binding",
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
it("combines semantically identical snapshots regardless of property order", () => {
|
|
203
|
+
const first = view("included_overage", "0.75");
|
|
204
|
+
const second = structuredClone(first);
|
|
205
|
+
second.subscription = {
|
|
206
|
+
interval: subscription.interval,
|
|
207
|
+
period: { end: period.end, start: period.start },
|
|
208
|
+
stripePriceId: subscription.stripePriceId,
|
|
209
|
+
subscriptionItemId: subscription.subscriptionItemId,
|
|
210
|
+
subscriptionId: subscription.subscriptionId,
|
|
211
|
+
};
|
|
212
|
+
const result = summarizeUsageRecords([first, second], {
|
|
213
|
+
period,
|
|
214
|
+
complete: true,
|
|
215
|
+
observedAt: 1201,
|
|
216
|
+
});
|
|
217
|
+
expect(result.groups).toHaveLength(1);
|
|
218
|
+
expect(result.groups[0].included).toMatchObject({
|
|
219
|
+
status: "available",
|
|
220
|
+
value: { consumed: "1.5", overage: "0.5" },
|
|
221
|
+
});
|
|
222
|
+
});
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { convexToJson } from "convex/values";
|
|
2
|
+
import type { PreparedUsageRecord, UsageDeliveryState } from "./records.js";
|
|
3
|
+
import { parseUsageQuantity } from "./contracts.js";
|
|
4
|
+
import type {
|
|
5
|
+
UsageAvailability,
|
|
6
|
+
UsagePeriod,
|
|
7
|
+
UsageSubscriptionBinding,
|
|
8
|
+
} from "./boundaries.js";
|
|
9
|
+
export type UsageSummaryEvent = {
|
|
10
|
+
record: PreparedUsageRecord;
|
|
11
|
+
subscription: UsageSubscriptionBinding;
|
|
12
|
+
delivery: UsageDeliveryState;
|
|
13
|
+
hasValidationError: boolean;
|
|
14
|
+
};
|
|
15
|
+
export type UsageCreditSummary = {
|
|
16
|
+
availableQuantity: string;
|
|
17
|
+
reservedQuantity: string;
|
|
18
|
+
consumedQuantity: string;
|
|
19
|
+
expiredQuantity: string;
|
|
20
|
+
};
|
|
21
|
+
export type UsageLocalGroup = {
|
|
22
|
+
binding: PreparedUsageRecord["binding"];
|
|
23
|
+
subscription: UsageSubscriptionBinding;
|
|
24
|
+
acceptedScaledQuantity: string;
|
|
25
|
+
providerAcceptedScaledQuantity: string;
|
|
26
|
+
acceptedQuantity: string;
|
|
27
|
+
providerAcceptedQuantity: string;
|
|
28
|
+
eventCount: number;
|
|
29
|
+
validationErrorEventCount: number;
|
|
30
|
+
deliveryQuantities: Record<UsageDeliveryState, string>;
|
|
31
|
+
estimate: UsageAvailability<{ amountDecimal: string; currency: string }>;
|
|
32
|
+
included: UsageAvailability<{
|
|
33
|
+
included: string;
|
|
34
|
+
consumed: string;
|
|
35
|
+
remaining: string;
|
|
36
|
+
overage: string;
|
|
37
|
+
}>;
|
|
38
|
+
credits: UsageAvailability<UsageCreditSummary>;
|
|
39
|
+
};
|
|
40
|
+
export type UsageLocalSummary = {
|
|
41
|
+
period: UsagePeriod;
|
|
42
|
+
observedAt: number;
|
|
43
|
+
complete: boolean;
|
|
44
|
+
eventCount: number;
|
|
45
|
+
groups: UsageLocalGroup[];
|
|
46
|
+
};
|
|
47
|
+
export function decimalFromScaled(value: bigint, precision: number): string {
|
|
48
|
+
if (precision === 0) return value.toString();
|
|
49
|
+
const digits = value.toString().padStart(precision + 1, "0"),
|
|
50
|
+
whole = digits.slice(0, -precision),
|
|
51
|
+
fraction = digits.slice(-precision).replace(/0+$/, "");
|
|
52
|
+
return fraction ? `${whole}.${fraction}` : whole;
|
|
53
|
+
}
|
|
54
|
+
function rateAmount(quantity: bigint, record: PreparedUsageRecord) {
|
|
55
|
+
const [whole, fraction = ""] =
|
|
56
|
+
record.binding.plan.rate.unitAmountDecimal.split(".");
|
|
57
|
+
return decimalFromScaled(
|
|
58
|
+
quantity * BigInt(whole + fraction),
|
|
59
|
+
record.binding.plan.unit.precision + fraction.length,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
const unavailable = (reason: string) => ({
|
|
63
|
+
status: "unavailable" as const,
|
|
64
|
+
reason,
|
|
65
|
+
retryable: false,
|
|
66
|
+
});
|
|
67
|
+
const states: UsageDeliveryState[] = [
|
|
68
|
+
"queued",
|
|
69
|
+
"sending",
|
|
70
|
+
"provider_accepted",
|
|
71
|
+
"rejected",
|
|
72
|
+
"unknown",
|
|
73
|
+
"held",
|
|
74
|
+
];
|
|
75
|
+
export function summarizeUsageRecords(
|
|
76
|
+
events: UsageSummaryEvent[],
|
|
77
|
+
options: { period: UsagePeriod; complete: boolean; observedAt: number },
|
|
78
|
+
): UsageLocalSummary {
|
|
79
|
+
const grouped = new Map<string, UsageSummaryEvent[]>();
|
|
80
|
+
for (const event of events) {
|
|
81
|
+
const key = JSON.stringify(
|
|
82
|
+
convexToJson([event.record.binding, event.subscription]),
|
|
83
|
+
);
|
|
84
|
+
const group = grouped.get(key) ?? [];
|
|
85
|
+
group.push(event);
|
|
86
|
+
grouped.set(key, group);
|
|
87
|
+
}
|
|
88
|
+
const groups: UsageLocalGroup[] = [];
|
|
89
|
+
for (const values of grouped.values()) {
|
|
90
|
+
const { record, subscription } = values[0],
|
|
91
|
+
plan = record.binding.plan,
|
|
92
|
+
precision = plan.unit.precision;
|
|
93
|
+
const sums = Object.fromEntries(
|
|
94
|
+
states.map((state) => [state, 0n]),
|
|
95
|
+
) as Record<UsageDeliveryState, bigint>;
|
|
96
|
+
for (const value of values)
|
|
97
|
+
sums[value.delivery] += BigInt(value.record.scaledQuantity);
|
|
98
|
+
const accepted = states.reduce((sum, state) => sum + sums[state], 0n);
|
|
99
|
+
const fullPeriod =
|
|
100
|
+
options.period.start === subscription.period.start &&
|
|
101
|
+
options.period.end === subscription.period.end;
|
|
102
|
+
const eligible =
|
|
103
|
+
options.complete && (plan.model !== "included_overage" || fullPeriod);
|
|
104
|
+
let chargeable = accepted;
|
|
105
|
+
let included: UsageLocalGroup["included"] = unavailable(
|
|
106
|
+
plan.model === "included_overage"
|
|
107
|
+
? options.complete
|
|
108
|
+
? "partial_billing_period"
|
|
109
|
+
: "local_history_incomplete"
|
|
110
|
+
: "not_included_model",
|
|
111
|
+
);
|
|
112
|
+
if (plan.model === "included_overage" && eligible) {
|
|
113
|
+
const allowance = BigInt(
|
|
114
|
+
parseUsageQuantity(plan.includedQuantity, precision).scaledQuantity,
|
|
115
|
+
);
|
|
116
|
+
chargeable = accepted > allowance ? accepted - allowance : 0n;
|
|
117
|
+
included = {
|
|
118
|
+
status: "available",
|
|
119
|
+
observedAt: options.observedAt,
|
|
120
|
+
value: {
|
|
121
|
+
included: decimalFromScaled(allowance, precision),
|
|
122
|
+
consumed: decimalFromScaled(accepted, precision),
|
|
123
|
+
remaining: decimalFromScaled(
|
|
124
|
+
allowance > accepted ? allowance - accepted : 0n,
|
|
125
|
+
precision,
|
|
126
|
+
),
|
|
127
|
+
overage: decimalFromScaled(chargeable, precision),
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
groups.push({
|
|
132
|
+
binding: record.binding,
|
|
133
|
+
subscription,
|
|
134
|
+
acceptedScaledQuantity: accepted.toString(),
|
|
135
|
+
providerAcceptedScaledQuantity: sums.provider_accepted.toString(),
|
|
136
|
+
acceptedQuantity: decimalFromScaled(accepted, precision),
|
|
137
|
+
providerAcceptedQuantity: decimalFromScaled(
|
|
138
|
+
sums.provider_accepted,
|
|
139
|
+
precision,
|
|
140
|
+
),
|
|
141
|
+
eventCount: values.length,
|
|
142
|
+
validationErrorEventCount: values.filter((v) => v.hasValidationError)
|
|
143
|
+
.length,
|
|
144
|
+
deliveryQuantities: Object.fromEntries(
|
|
145
|
+
states.map((state) => [
|
|
146
|
+
state,
|
|
147
|
+
decimalFromScaled(sums[state], precision),
|
|
148
|
+
]),
|
|
149
|
+
) as Record<UsageDeliveryState, string>,
|
|
150
|
+
included,
|
|
151
|
+
estimate: !options.complete
|
|
152
|
+
? unavailable("local_history_incomplete")
|
|
153
|
+
: plan.model === "prepaid"
|
|
154
|
+
? unavailable("credit_accounting_not_configured")
|
|
155
|
+
: !eligible
|
|
156
|
+
? unavailable("partial_billing_period")
|
|
157
|
+
: {
|
|
158
|
+
status: "available",
|
|
159
|
+
observedAt: options.observedAt,
|
|
160
|
+
value: {
|
|
161
|
+
amountDecimal: rateAmount(chargeable, record),
|
|
162
|
+
currency: plan.rate.currency,
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
credits: unavailable(
|
|
166
|
+
plan.model === "prepaid"
|
|
167
|
+
? "credit_accounting_not_configured"
|
|
168
|
+
: "not_prepaid_model",
|
|
169
|
+
),
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
for (const group of groups) {
|
|
173
|
+
if (
|
|
174
|
+
groups.some(
|
|
175
|
+
(other) =>
|
|
176
|
+
other !== group &&
|
|
177
|
+
other.binding.stripeCustomerId === group.binding.stripeCustomerId &&
|
|
178
|
+
other.subscription.period.start < group.subscription.period.end &&
|
|
179
|
+
other.subscription.period.end > group.subscription.period.start,
|
|
180
|
+
)
|
|
181
|
+
) {
|
|
182
|
+
group.estimate = unavailable("ambiguous_subscription_binding");
|
|
183
|
+
if (group.binding.plan.model === "included_overage")
|
|
184
|
+
group.included = unavailable("ambiguous_subscription_binding");
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return { ...options, eventCount: events.length, groups };
|
|
188
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isMeterErrorEvent } from "./meterErrors.js";
|
|
1
2
|
import type Stripe from "stripe";
|
|
2
3
|
|
|
3
4
|
import type { Component } from "../helpers.js";
|
|
@@ -41,7 +42,7 @@ export async function handleWebhookRequest(
|
|
|
41
42
|
}
|
|
42
43
|
|
|
43
44
|
const eventType = (parsedBody.type as string) ?? "";
|
|
44
|
-
const isV2Event = eventType.startsWith("v2.");
|
|
45
|
+
const isV2Event = eventType.startsWith("v2.") || isMeterErrorEvent(eventType);
|
|
45
46
|
|
|
46
47
|
const stripeSecretKey = config?.stripeSecretKey;
|
|
47
48
|
const stripeApiVersion = config?.stripeApiVersion;
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import Stripe from "stripe";
|
|
2
|
+
import { expect, it, vi } from "vitest";
|
|
3
|
+
import type { Component } from "../helpers.js";
|
|
4
|
+
import type { WebhookActionCtx } from "../types.js";
|
|
5
|
+
import { componentsGeneric } from "convex/server";
|
|
6
|
+
import { STRIPE_API_VERSION } from "../constants.js";
|
|
7
|
+
const fixture = vi.hoisted(() => ({ stripe: undefined as unknown }));
|
|
8
|
+
vi.mock("./helpers.js", async (importOriginal) => ({
|
|
9
|
+
...(await importOriginal<typeof import("./helpers.js")>()),
|
|
10
|
+
getStripeClient: () => fixture.stripe,
|
|
11
|
+
}));
|
|
12
|
+
import { handleWebhookRequest } from "./handler.js";
|
|
13
|
+
it("verifies and fetches v1 meter thin events without the snapshot parser", async () => {
|
|
14
|
+
const body = JSON.stringify({
|
|
15
|
+
id: "evt_meter_error",
|
|
16
|
+
object: "v2.core.event",
|
|
17
|
+
type: "v1.billing.meter.error_report_triggered",
|
|
18
|
+
livemode: false,
|
|
19
|
+
related_object: { id: "mtr_calls", type: "billing.meter" },
|
|
20
|
+
});
|
|
21
|
+
const parse = vi.fn().mockResolvedValue({});
|
|
22
|
+
const full = {
|
|
23
|
+
id: "evt_meter_error",
|
|
24
|
+
type: "v1.billing.meter.error_report_triggered",
|
|
25
|
+
livemode: false,
|
|
26
|
+
related_object: { id: "mtr_calls", type: "billing.meter" },
|
|
27
|
+
data: {
|
|
28
|
+
reason: {
|
|
29
|
+
error_types: [
|
|
30
|
+
{
|
|
31
|
+
code: "meter_event_invalid_value",
|
|
32
|
+
sample_errors: [
|
|
33
|
+
{
|
|
34
|
+
error_message: "private raw error",
|
|
35
|
+
request: { idempotency_key: "bs_usage_event" },
|
|
36
|
+
},
|
|
37
|
+
],
|
|
38
|
+
},
|
|
39
|
+
],
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
fixture.stripe = {
|
|
44
|
+
parseEventNotificationAsync: parse,
|
|
45
|
+
v2: { core: { events: { retrieve: vi.fn().mockResolvedValue(full) } } },
|
|
46
|
+
accounts: { retrieve: vi.fn().mockResolvedValue({ id: "acct_platform" }) },
|
|
47
|
+
balance: { retrieve: vi.fn().mockResolvedValue({ livemode: false }) },
|
|
48
|
+
webhooks: {
|
|
49
|
+
constructEventAsync: vi.fn().mockRejectedValue(new Error("Wrong parser")),
|
|
50
|
+
},
|
|
51
|
+
} as unknown as Stripe;
|
|
52
|
+
const runMutation = vi.fn(async (_ref, args) =>
|
|
53
|
+
typeof args.stripeEventId === "string" && args.eventType
|
|
54
|
+
? "inserted"
|
|
55
|
+
: { matched: 1, unattributed: 0, truncated: false },
|
|
56
|
+
);
|
|
57
|
+
const ctx = { runMutation, runQuery: vi.fn() } as unknown as WebhookActionCtx;
|
|
58
|
+
const response = await handleWebhookRequest(
|
|
59
|
+
ctx,
|
|
60
|
+
new Request("https://example.test/webhook", {
|
|
61
|
+
method: "POST",
|
|
62
|
+
headers: { "stripe-signature": "verified-fixture" },
|
|
63
|
+
body,
|
|
64
|
+
}),
|
|
65
|
+
componentsGeneric().betterStripe as unknown as Component,
|
|
66
|
+
{
|
|
67
|
+
stripeSecretKey: "sk_test_fixture",
|
|
68
|
+
webhookSecret: "whsec_snapshot",
|
|
69
|
+
webhookSecretV2: "whsec_thin",
|
|
70
|
+
stripeApiVersion: STRIPE_API_VERSION,
|
|
71
|
+
},
|
|
72
|
+
);
|
|
73
|
+
expect(response.status).toBe(200);
|
|
74
|
+
expect(parse).toHaveBeenCalledWith(body, "verified-fixture", "whsec_thin");
|
|
75
|
+
const report = runMutation.mock.calls.find(([, args]) => args.samples)?.[1];
|
|
76
|
+
expect(report).toMatchObject({
|
|
77
|
+
stripeAccountId: "acct_platform",
|
|
78
|
+
livemode: false,
|
|
79
|
+
meterId: "mtr_calls",
|
|
80
|
+
samples: [
|
|
81
|
+
{ identifier: "bs_usage_event", code: "meter_event_invalid_value" },
|
|
82
|
+
],
|
|
83
|
+
});
|
|
84
|
+
expect(JSON.stringify(report)).not.toContain("private raw error");
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it.each(["event", "account", "balance"])(
|
|
88
|
+
"sanitizes %s retrieval errors before webhook history and logs",
|
|
89
|
+
async (failing) => {
|
|
90
|
+
const privateError = new Error("PRIVATE_PROVIDER_MARKER");
|
|
91
|
+
fixture.stripe = {
|
|
92
|
+
parseEventNotificationAsync: vi.fn().mockResolvedValue({}),
|
|
93
|
+
v2: {
|
|
94
|
+
core: {
|
|
95
|
+
events: {
|
|
96
|
+
retrieve: vi
|
|
97
|
+
.fn()
|
|
98
|
+
.mockImplementation(() =>
|
|
99
|
+
failing === "event"
|
|
100
|
+
? Promise.reject(privateError)
|
|
101
|
+
: Promise.resolve({}),
|
|
102
|
+
),
|
|
103
|
+
},
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
accounts: {
|
|
107
|
+
retrieve: vi
|
|
108
|
+
.fn()
|
|
109
|
+
.mockImplementation(() =>
|
|
110
|
+
failing === "account"
|
|
111
|
+
? Promise.reject(privateError)
|
|
112
|
+
: Promise.resolve({ id: "acct_platform" }),
|
|
113
|
+
),
|
|
114
|
+
},
|
|
115
|
+
balance: {
|
|
116
|
+
retrieve: vi
|
|
117
|
+
.fn()
|
|
118
|
+
.mockImplementation(() =>
|
|
119
|
+
failing === "balance"
|
|
120
|
+
? Promise.reject(privateError)
|
|
121
|
+
: Promise.resolve({ livemode: false }),
|
|
122
|
+
),
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
const runMutation = vi.fn(async (_ref, args) =>
|
|
126
|
+
args.eventType ? "inserted" : null,
|
|
127
|
+
);
|
|
128
|
+
const logged = vi.spyOn(console, "error").mockImplementation(() => {});
|
|
129
|
+
try {
|
|
130
|
+
const response = await handleWebhookRequest(
|
|
131
|
+
{ runMutation, runQuery: vi.fn() } as unknown as WebhookActionCtx,
|
|
132
|
+
new Request("https://example.test/webhook", {
|
|
133
|
+
method: "POST",
|
|
134
|
+
headers: { "stripe-signature": "fixture" },
|
|
135
|
+
body: JSON.stringify({
|
|
136
|
+
id: "evt_private",
|
|
137
|
+
type: "v1.billing.meter.error_report_triggered",
|
|
138
|
+
livemode: false,
|
|
139
|
+
}),
|
|
140
|
+
}),
|
|
141
|
+
componentsGeneric().betterStripe as unknown as Component,
|
|
142
|
+
{
|
|
143
|
+
stripeSecretKey: "sk_test_fixture",
|
|
144
|
+
webhookSecret: "whsec_snapshot",
|
|
145
|
+
webhookSecretV2: "whsec_thin",
|
|
146
|
+
},
|
|
147
|
+
);
|
|
148
|
+
expect(response.status).toBe(500);
|
|
149
|
+
expect(JSON.stringify(runMutation.mock.calls)).not.toContain(
|
|
150
|
+
"PRIVATE_PROVIDER_MARKER",
|
|
151
|
+
);
|
|
152
|
+
expect(
|
|
153
|
+
logged.mock.calls
|
|
154
|
+
.flat()
|
|
155
|
+
.map((value) =>
|
|
156
|
+
value instanceof Error ? value.message : String(value),
|
|
157
|
+
)
|
|
158
|
+
.join(" "),
|
|
159
|
+
).not.toContain("PRIVATE_PROVIDER_MARKER");
|
|
160
|
+
} finally {
|
|
161
|
+
logged.mockRestore();
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
);
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { componentRef, type WebhookContext } from "./helpers.js";
|
|
3
|
+
import type { V2ThinEvent } from "../types.js";
|
|
4
|
+
const types = [
|
|
5
|
+
"v1.billing.meter.error_report_triggered",
|
|
6
|
+
"v1.billing.meter.no_meter_found",
|
|
7
|
+
] as const;
|
|
8
|
+
export const isMeterErrorEvent = (type: string) =>
|
|
9
|
+
types.some((value) => value === type);
|
|
10
|
+
const codes = new Set([
|
|
11
|
+
"meter_event_customer_not_found",
|
|
12
|
+
"meter_event_no_customer_defined",
|
|
13
|
+
"meter_event_dimension_count_too_high",
|
|
14
|
+
"archived_meter",
|
|
15
|
+
"timestamp_too_far_in_past",
|
|
16
|
+
"timestamp_in_future",
|
|
17
|
+
"meter_event_value_not_found",
|
|
18
|
+
"meter_event_invalid_value",
|
|
19
|
+
"no_meter",
|
|
20
|
+
]);
|
|
21
|
+
const reportSchema = z.object({
|
|
22
|
+
id: z.string(),
|
|
23
|
+
type: z.enum(types),
|
|
24
|
+
livemode: z.boolean(),
|
|
25
|
+
related_object: z.object({ id: z.string().optional() }).nullish(),
|
|
26
|
+
data: z.object({
|
|
27
|
+
reason: z.object({
|
|
28
|
+
error_types: z
|
|
29
|
+
.array(
|
|
30
|
+
z.object({
|
|
31
|
+
code: z.string(),
|
|
32
|
+
sample_errors: z
|
|
33
|
+
.array(
|
|
34
|
+
z.object({
|
|
35
|
+
request: z
|
|
36
|
+
.object({
|
|
37
|
+
identifier: z.string().optional(),
|
|
38
|
+
idempotency_key: z.string().optional(),
|
|
39
|
+
})
|
|
40
|
+
.optional(),
|
|
41
|
+
}),
|
|
42
|
+
)
|
|
43
|
+
.optional(),
|
|
44
|
+
}),
|
|
45
|
+
)
|
|
46
|
+
.max(1000),
|
|
47
|
+
}),
|
|
48
|
+
}),
|
|
49
|
+
});
|
|
50
|
+
async function processMeterErrorEvent(
|
|
51
|
+
whCtx: WebhookContext,
|
|
52
|
+
thin: V2ThinEvent,
|
|
53
|
+
): Promise<void> {
|
|
54
|
+
const { stripe, ctx, component } = whCtx;
|
|
55
|
+
const [raw, account, balance] = await Promise.all([
|
|
56
|
+
stripe.v2.core.events.retrieve(thin.id),
|
|
57
|
+
stripe.accounts.retrieve(null),
|
|
58
|
+
stripe.balance.retrieve(),
|
|
59
|
+
]);
|
|
60
|
+
const parsed = reportSchema.safeParse(raw);
|
|
61
|
+
if (
|
|
62
|
+
!parsed.success ||
|
|
63
|
+
parsed.data.id !== thin.id ||
|
|
64
|
+
parsed.data.type !== thin.type ||
|
|
65
|
+
parsed.data.livemode !== balance.livemode ||
|
|
66
|
+
thin.livemode !== balance.livemode ||
|
|
67
|
+
(thin.context && thin.context !== account.id)
|
|
68
|
+
)
|
|
69
|
+
throw new Error("Native usage error report scope unavailable");
|
|
70
|
+
const report = parsed.data,
|
|
71
|
+
samples: Array<{ identifier: string; code: string }> = [];
|
|
72
|
+
let truncated = false;
|
|
73
|
+
for (const type of report.data.reason.error_types) {
|
|
74
|
+
if (!codes.has(type.code)) {
|
|
75
|
+
truncated = true;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
for (const error of type.sample_errors ?? []) {
|
|
79
|
+
const identifier =
|
|
80
|
+
error.request?.identifier ?? error.request?.idempotency_key;
|
|
81
|
+
if (
|
|
82
|
+
!identifier ||
|
|
83
|
+
!/^bs_usage_[a-zA-Z0-9_]+$/.test(identifier) ||
|
|
84
|
+
identifier.length > 100
|
|
85
|
+
) {
|
|
86
|
+
truncated = true;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (samples.length >= 100) {
|
|
90
|
+
truncated = true;
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
samples.push({ identifier, code: type.code });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
await ctx.runMutation(
|
|
97
|
+
componentRef(component, "usageDelivery/mutations/recordErrorReport"),
|
|
98
|
+
{
|
|
99
|
+
stripeAccountId: account.id,
|
|
100
|
+
livemode: report.livemode,
|
|
101
|
+
providerEventId: report.id,
|
|
102
|
+
meterId: report.related_object?.id,
|
|
103
|
+
samples,
|
|
104
|
+
truncated,
|
|
105
|
+
},
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function handleMeterErrorEvent(
|
|
110
|
+
whCtx: WebhookContext,
|
|
111
|
+
thin: V2ThinEvent,
|
|
112
|
+
): Promise<void> {
|
|
113
|
+
try {
|
|
114
|
+
await processMeterErrorEvent(whCtx, thin);
|
|
115
|
+
} catch {
|
|
116
|
+
throw new Error("Native usage error report unavailable");
|
|
117
|
+
}
|
|
118
|
+
}
|