@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,195 @@
|
|
|
1
|
+
import Stripe from "stripe";
|
|
2
|
+
import { convexToJson } from "convex/values";
|
|
3
|
+
import { expect, it } from "vitest";
|
|
4
|
+
import { STRIPE_API_VERSION } from "../constants.js";
|
|
5
|
+
import { prepareUsageRecord } from "./records.js";
|
|
6
|
+
import { observeUsageInvoice } from "./invoiceObservation.js";
|
|
7
|
+
const scope = {
|
|
8
|
+
stripeAccountId: "acct_platform",
|
|
9
|
+
customerAccount: "acct_buyer",
|
|
10
|
+
meterId: "mtr_calls",
|
|
11
|
+
livemode: false,
|
|
12
|
+
},
|
|
13
|
+
period = { start: 600, end: 1200 };
|
|
14
|
+
const binding = prepareUsageRecord({
|
|
15
|
+
scope,
|
|
16
|
+
binding: {
|
|
17
|
+
stripeCustomerId: "cus_buyer",
|
|
18
|
+
stripePriceId: "price_calls",
|
|
19
|
+
eventName: "calls",
|
|
20
|
+
plan: {
|
|
21
|
+
key: "calls",
|
|
22
|
+
version: "v1",
|
|
23
|
+
model: "pay_as_you_go",
|
|
24
|
+
unit: { name: "call", precision: 0 },
|
|
25
|
+
rate: { currency: "usd", unitAmountDecimal: "2" },
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
sourceEventId: "read",
|
|
29
|
+
quantity: "0",
|
|
30
|
+
occurredAt: 600,
|
|
31
|
+
}).binding;
|
|
32
|
+
const options = {
|
|
33
|
+
scope,
|
|
34
|
+
binding,
|
|
35
|
+
subscription: {
|
|
36
|
+
subscriptionId: "sub_calls",
|
|
37
|
+
subscriptionItemId: "si_calls",
|
|
38
|
+
stripePriceId: "price_calls",
|
|
39
|
+
period,
|
|
40
|
+
interval: "month" as const,
|
|
41
|
+
},
|
|
42
|
+
period,
|
|
43
|
+
};
|
|
44
|
+
function setup(hasMore = false, wrongPayer = false, missingQuantity = false) {
|
|
45
|
+
const requests: Array<{ method: string; path: string }> = [];
|
|
46
|
+
const stripe = new Stripe("sk_test_invoice_read", {
|
|
47
|
+
apiVersion: STRIPE_API_VERSION,
|
|
48
|
+
maxNetworkRetries: 0,
|
|
49
|
+
httpClient: Stripe.createFetchHttpClient(async (input, init) => {
|
|
50
|
+
const url = new URL(String(input)),
|
|
51
|
+
path = url.pathname;
|
|
52
|
+
requests.push({ method: init?.method ?? "GET", path });
|
|
53
|
+
const result =
|
|
54
|
+
path === "/v1/account"
|
|
55
|
+
? { id: "acct_platform" }
|
|
56
|
+
: path === "/v1/balance"
|
|
57
|
+
? { livemode: false }
|
|
58
|
+
: path === "/v1/billing/meters/mtr_calls"
|
|
59
|
+
? {
|
|
60
|
+
id: "mtr_calls",
|
|
61
|
+
livemode: false,
|
|
62
|
+
status: "active",
|
|
63
|
+
event_name: "calls",
|
|
64
|
+
default_aggregation: { formula: "sum" },
|
|
65
|
+
customer_mapping: {
|
|
66
|
+
type: "by_id",
|
|
67
|
+
event_payload_key: "stripe_customer_id",
|
|
68
|
+
},
|
|
69
|
+
value_settings: { event_payload_key: "value" },
|
|
70
|
+
event_time_window: null,
|
|
71
|
+
}
|
|
72
|
+
: path === "/v1/subscriptions/sub_calls"
|
|
73
|
+
? {
|
|
74
|
+
id: "sub_calls",
|
|
75
|
+
livemode: false,
|
|
76
|
+
customer: "cus_buyer",
|
|
77
|
+
customer_account: "acct_buyer",
|
|
78
|
+
}
|
|
79
|
+
: {
|
|
80
|
+
id: "in_one",
|
|
81
|
+
object: "invoice",
|
|
82
|
+
livemode: false,
|
|
83
|
+
customer_account: wrongPayer ? "acct_other" : "acct_buyer",
|
|
84
|
+
customer: "cus_buyer",
|
|
85
|
+
currency: "usd",
|
|
86
|
+
status: path.endsWith("create_preview") ? "draft" : "paid",
|
|
87
|
+
status_transitions: {
|
|
88
|
+
finalized_at: path.endsWith("create_preview")
|
|
89
|
+
? null
|
|
90
|
+
: 1200,
|
|
91
|
+
},
|
|
92
|
+
amount_due: 20,
|
|
93
|
+
amount_paid: 20,
|
|
94
|
+
total: 20,
|
|
95
|
+
parent: {
|
|
96
|
+
subscription_details: { subscription: "sub_calls" },
|
|
97
|
+
},
|
|
98
|
+
lines: {
|
|
99
|
+
data: [
|
|
100
|
+
{
|
|
101
|
+
id: "il_one",
|
|
102
|
+
object: "line_item",
|
|
103
|
+
currency: "usd",
|
|
104
|
+
amount: 10,
|
|
105
|
+
quantity: 2,
|
|
106
|
+
quantity_decimal: missingQuantity ? null : "2.5",
|
|
107
|
+
pricing: {
|
|
108
|
+
type: "price_details",
|
|
109
|
+
price_details: { price: "price_calls" },
|
|
110
|
+
unit_amount_decimal: null,
|
|
111
|
+
},
|
|
112
|
+
parent: {
|
|
113
|
+
subscription_item_details: {
|
|
114
|
+
subscription: "sub_calls",
|
|
115
|
+
subscription_item: "si_calls",
|
|
116
|
+
proration: false,
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
period,
|
|
120
|
+
pretax_credit_amounts: [],
|
|
121
|
+
},
|
|
122
|
+
],
|
|
123
|
+
has_more: hasMore,
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
return new Response(JSON.stringify(result), {
|
|
127
|
+
status: 200,
|
|
128
|
+
headers: { "content-type": "application/json" },
|
|
129
|
+
});
|
|
130
|
+
}),
|
|
131
|
+
});
|
|
132
|
+
return { stripe, requests };
|
|
133
|
+
}
|
|
134
|
+
it("distinguishes full invoice amounts and matching metered lines with decimal quantities", async () => {
|
|
135
|
+
const f = setup(),
|
|
136
|
+
result = await observeUsageInvoice(f.stripe, options, "in_one");
|
|
137
|
+
expect(result).toMatchObject({
|
|
138
|
+
status: "available",
|
|
139
|
+
value: {
|
|
140
|
+
kind: "invoice",
|
|
141
|
+
invoiceId: "in_one",
|
|
142
|
+
finalized: true,
|
|
143
|
+
amountDue: "20",
|
|
144
|
+
amountPaid: "20",
|
|
145
|
+
total: "20",
|
|
146
|
+
meterAmount: {
|
|
147
|
+
status: "available",
|
|
148
|
+
value: { amount: "10", currency: "usd" },
|
|
149
|
+
},
|
|
150
|
+
lines: [{ quantity: "2.5", unitAmountDecimal: null }],
|
|
151
|
+
},
|
|
152
|
+
});
|
|
153
|
+
expect(() => convexToJson(result)).not.toThrow();
|
|
154
|
+
expect(f.requests.every((r) => r.method === "GET")).toBe(true);
|
|
155
|
+
});
|
|
156
|
+
it("does not call a preview finalized or an incomplete line page a complete meter amount", async () => {
|
|
157
|
+
const f = setup(true),
|
|
158
|
+
result = await observeUsageInvoice(f.stripe, options);
|
|
159
|
+
expect(result).toMatchObject({
|
|
160
|
+
status: "available",
|
|
161
|
+
value: {
|
|
162
|
+
kind: "preview",
|
|
163
|
+
finalized: false,
|
|
164
|
+
linesComplete: false,
|
|
165
|
+
meterAmount: {
|
|
166
|
+
status: "unavailable",
|
|
167
|
+
reason: "invoice_history_incomplete",
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
expect(f.requests.filter((r) => r.method === "POST")).toEqual([
|
|
172
|
+
{ method: "POST", path: "/v1/invoices/create_preview" },
|
|
173
|
+
]);
|
|
174
|
+
});
|
|
175
|
+
it("rejects another payer's invoice", async () => {
|
|
176
|
+
expect(
|
|
177
|
+
await observeUsageInvoice(setup(false, true).stripe, options, "in_one"),
|
|
178
|
+
).toMatchObject({
|
|
179
|
+
status: "unsupported",
|
|
180
|
+
reason: "invoice_binding_mismatch",
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it("does not treat the legacy truncated invoice quantity as full precision", async () => {
|
|
185
|
+
expect(
|
|
186
|
+
await observeUsageInvoice(
|
|
187
|
+
setup(false, false, true).stripe,
|
|
188
|
+
options,
|
|
189
|
+
"in_one",
|
|
190
|
+
),
|
|
191
|
+
).toMatchObject({
|
|
192
|
+
status: "available",
|
|
193
|
+
value: { lines: [{ quantity: null, providerQuantityDecimal: null }] },
|
|
194
|
+
});
|
|
195
|
+
});
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import {
|
|
4
|
+
observationOptions,
|
|
5
|
+
verifyObservationSource,
|
|
6
|
+
type UsageObservationOptions,
|
|
7
|
+
} from "./observationTypes.js";
|
|
8
|
+
import type { UsageAvailability } from "./boundaries.js";
|
|
9
|
+
import { UsageCatalogError } from "./catalogTypes.js";
|
|
10
|
+
import { decimalFromScaled } from "./summary.js";
|
|
11
|
+
export type UsageInvoiceLine = {
|
|
12
|
+
lineId: string;
|
|
13
|
+
stripePriceId: string;
|
|
14
|
+
subscriptionItemId: string;
|
|
15
|
+
amount: string;
|
|
16
|
+
currency: string;
|
|
17
|
+
quantity: string | null;
|
|
18
|
+
providerQuantityDecimal: string | null;
|
|
19
|
+
unitAmountDecimal: string | null;
|
|
20
|
+
creditAppliedAmount: string;
|
|
21
|
+
nativePeriod: { start: number; end: number };
|
|
22
|
+
proration: boolean;
|
|
23
|
+
};
|
|
24
|
+
export type UsageInvoiceObservation = {
|
|
25
|
+
kind: "preview" | "invoice";
|
|
26
|
+
invoiceId: string;
|
|
27
|
+
status: "draft" | "open" | "paid" | "void" | "uncollectible";
|
|
28
|
+
finalized: boolean;
|
|
29
|
+
amountDue: string;
|
|
30
|
+
amountPaid: string;
|
|
31
|
+
total: string;
|
|
32
|
+
currency: string;
|
|
33
|
+
linesComplete: boolean;
|
|
34
|
+
lines: UsageInvoiceLine[];
|
|
35
|
+
meterAmount: UsageAvailability<{ amount: string; currency: string }>;
|
|
36
|
+
paymentEvidence: "not_resolved";
|
|
37
|
+
};
|
|
38
|
+
const idOf = (value: string | { id: string } | null | undefined) =>
|
|
39
|
+
typeof value === "string" ? value : value?.id;
|
|
40
|
+
function amount(value: number): string {
|
|
41
|
+
if (!Number.isSafeInteger(value)) throw new Error("Unsafe native amount");
|
|
42
|
+
return String(value);
|
|
43
|
+
}
|
|
44
|
+
function decimal(value: Stripe.Decimal | null | undefined): string | null {
|
|
45
|
+
if (value == null) return null;
|
|
46
|
+
const text = value.toString();
|
|
47
|
+
if (!/^\d+(\.\d{1,12})?$/.test(text) || text.length > 64)
|
|
48
|
+
throw new Error("Unsupported native decimal");
|
|
49
|
+
return text;
|
|
50
|
+
}
|
|
51
|
+
export async function observeUsageInvoice(
|
|
52
|
+
stripe: Stripe,
|
|
53
|
+
input: UsageObservationOptions,
|
|
54
|
+
invoiceId?: string,
|
|
55
|
+
): Promise<UsageAvailability<UsageInvoiceObservation>> {
|
|
56
|
+
const opts = observationOptions(input),
|
|
57
|
+
observedAt = Math.floor(Date.now() / 1000);
|
|
58
|
+
if (invoiceId !== undefined)
|
|
59
|
+
z.string()
|
|
60
|
+
.regex(/^in_[a-zA-Z0-9]+$/)
|
|
61
|
+
.max(100)
|
|
62
|
+
.parse(invoiceId);
|
|
63
|
+
try {
|
|
64
|
+
if (!(await verifyObservationSource(stripe, opts)))
|
|
65
|
+
return {
|
|
66
|
+
status: "unsupported",
|
|
67
|
+
reason: "provider_binding_mismatch",
|
|
68
|
+
retryable: false,
|
|
69
|
+
};
|
|
70
|
+
const invoice = invoiceId
|
|
71
|
+
? await stripe.invoices.retrieve(invoiceId)
|
|
72
|
+
: await stripe.invoices.createPreview({
|
|
73
|
+
subscription: opts.subscription.subscriptionId,
|
|
74
|
+
customer_account: opts.scope.customerAccount,
|
|
75
|
+
});
|
|
76
|
+
const status = z
|
|
77
|
+
.enum(["draft", "open", "paid", "void", "uncollectible"])
|
|
78
|
+
.safeParse(invoice.status);
|
|
79
|
+
if (
|
|
80
|
+
!status.success ||
|
|
81
|
+
!invoice.id ||
|
|
82
|
+
invoice.id.length > 100 ||
|
|
83
|
+
(invoiceId && invoice.id !== invoiceId) ||
|
|
84
|
+
invoice.livemode !== opts.scope.livemode ||
|
|
85
|
+
invoice.customer_account !== opts.scope.customerAccount ||
|
|
86
|
+
idOf(invoice.customer) !== opts.binding.stripeCustomerId ||
|
|
87
|
+
idOf(invoice.parent?.subscription_details?.subscription) !==
|
|
88
|
+
opts.subscription.subscriptionId ||
|
|
89
|
+
invoice.currency !== opts.binding.plan.rate.currency
|
|
90
|
+
)
|
|
91
|
+
return {
|
|
92
|
+
status: "unsupported",
|
|
93
|
+
reason: "invoice_binding_mismatch",
|
|
94
|
+
retryable: false,
|
|
95
|
+
};
|
|
96
|
+
const lines: UsageInvoiceLine[] = [];
|
|
97
|
+
let ambiguous = false;
|
|
98
|
+
const linesComplete =
|
|
99
|
+
!invoice.lines.has_more && invoice.lines.data.length <= 100;
|
|
100
|
+
for (const line of invoice.lines.data.slice(0, 100)) {
|
|
101
|
+
if (line.pricing?.price_details?.price !== opts.binding.stripePriceId)
|
|
102
|
+
continue;
|
|
103
|
+
const parent = line.parent?.subscription_item_details;
|
|
104
|
+
if (
|
|
105
|
+
parent?.subscription !== opts.subscription.subscriptionId ||
|
|
106
|
+
parent.subscription_item !== opts.subscription.subscriptionItemId ||
|
|
107
|
+
line.currency !== invoice.currency
|
|
108
|
+
) {
|
|
109
|
+
ambiguous = true;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
const providerQuantity = decimal(line.quantity_decimal);
|
|
113
|
+
let quantity: string | null = null;
|
|
114
|
+
if (providerQuantity !== null) {
|
|
115
|
+
const [whole, fraction = ""] = providerQuantity.split(".");
|
|
116
|
+
quantity = decimalFromScaled(
|
|
117
|
+
BigInt(whole + fraction),
|
|
118
|
+
fraction.length + opts.binding.plan.unit.precision,
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
const creditApplied = (line.pretax_credit_amounts ?? [])
|
|
122
|
+
.filter((value) => value.type === "credit_balance_transaction")
|
|
123
|
+
.reduce((sum, value) => sum + BigInt(amount(value.amount)), 0n);
|
|
124
|
+
lines.push({
|
|
125
|
+
lineId: line.id,
|
|
126
|
+
stripePriceId: opts.binding.stripePriceId,
|
|
127
|
+
subscriptionItemId: parent.subscription_item,
|
|
128
|
+
amount: amount(line.amount),
|
|
129
|
+
currency: line.currency,
|
|
130
|
+
quantity,
|
|
131
|
+
providerQuantityDecimal: providerQuantity,
|
|
132
|
+
unitAmountDecimal: decimal(line.pricing.unit_amount_decimal),
|
|
133
|
+
creditAppliedAmount: creditApplied.toString(),
|
|
134
|
+
nativePeriod: { start: line.period.start, end: line.period.end },
|
|
135
|
+
proration: parent.proration,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
const meterAmount: UsageInvoiceObservation["meterAmount"] = !linesComplete
|
|
139
|
+
? {
|
|
140
|
+
status: "unavailable",
|
|
141
|
+
reason: "invoice_history_incomplete",
|
|
142
|
+
retryable: true,
|
|
143
|
+
}
|
|
144
|
+
: ambiguous
|
|
145
|
+
? {
|
|
146
|
+
status: "unavailable",
|
|
147
|
+
reason: "ambiguous_invoice_items",
|
|
148
|
+
retryable: false,
|
|
149
|
+
}
|
|
150
|
+
: !lines.length
|
|
151
|
+
? {
|
|
152
|
+
status: "unavailable",
|
|
153
|
+
reason: "metered_lines_not_observed",
|
|
154
|
+
retryable: true,
|
|
155
|
+
}
|
|
156
|
+
: {
|
|
157
|
+
status: "available",
|
|
158
|
+
observedAt,
|
|
159
|
+
value: {
|
|
160
|
+
amount: lines
|
|
161
|
+
.reduce((sum, line) => sum + BigInt(line.amount), 0n)
|
|
162
|
+
.toString(),
|
|
163
|
+
currency: invoice.currency,
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
return {
|
|
167
|
+
status: "available",
|
|
168
|
+
observedAt,
|
|
169
|
+
value: {
|
|
170
|
+
kind: invoiceId ? "invoice" : "preview",
|
|
171
|
+
invoiceId: invoice.id,
|
|
172
|
+
status: status.data,
|
|
173
|
+
finalized:
|
|
174
|
+
invoiceId !== undefined &&
|
|
175
|
+
invoice.status !== "draft" &&
|
|
176
|
+
Number.isSafeInteger(invoice.status_transitions?.finalized_at),
|
|
177
|
+
amountDue: amount(invoice.amount_due),
|
|
178
|
+
amountPaid: amount(invoice.amount_paid),
|
|
179
|
+
total: amount(invoice.total),
|
|
180
|
+
currency: invoice.currency,
|
|
181
|
+
linesComplete,
|
|
182
|
+
lines,
|
|
183
|
+
meterAmount,
|
|
184
|
+
paymentEvidence: "not_resolved",
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
} catch (error) {
|
|
188
|
+
if (
|
|
189
|
+
error instanceof UsageCatalogError &&
|
|
190
|
+
error.code === "unsupported_scope"
|
|
191
|
+
)
|
|
192
|
+
return {
|
|
193
|
+
status: "unsupported",
|
|
194
|
+
reason: "unsupported_scope",
|
|
195
|
+
retryable: false,
|
|
196
|
+
};
|
|
197
|
+
return {
|
|
198
|
+
status: "unavailable",
|
|
199
|
+
reason: "invoice_unavailable",
|
|
200
|
+
retryable: true,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import type { Doc } from "../../component/_generated/dataModel.js";
|
|
2
|
+
import type { UsageDeliveryRef } from "./deliveryClient.js";
|
|
3
|
+
import { observeUsageInvoice } from "./invoiceObservation.js";
|
|
4
|
+
import Stripe from "stripe";
|
|
5
|
+
import type { RunCtx } from "../helpers.js";
|
|
6
|
+
import { runMutationOrThrow } from "../helpers.js";
|
|
7
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
8
|
+
import type { StripeApiVersion } from "../stripe-types.js";
|
|
9
|
+
import { UsageDeliveryClient } from "./deliveryClient.js";
|
|
10
|
+
import type { UsageDeliveryProviderOptions } from "./deliveryProvider.js";
|
|
11
|
+
import { observeProviderUsage } from "./providerObservation.js";
|
|
12
|
+
import {
|
|
13
|
+
observationOptions,
|
|
14
|
+
observationKeyOptions,
|
|
15
|
+
type UsageObservationOptions,
|
|
16
|
+
type UsageAggregateObservation,
|
|
17
|
+
} from "./observationTypes.js";
|
|
18
|
+
import type { UsageLocalSummary } from "./summary.js";
|
|
19
|
+
import type { UsageScope } from "./records.js";
|
|
20
|
+
import { scopeSchema } from "./records.js";
|
|
21
|
+
import { validateUsagePageRequest, type UsagePeriod } from "./boundaries.js";
|
|
22
|
+
import { compareUsageObservations } from "./reconciliation.js";
|
|
23
|
+
export type UsageReconciliationOptions = UsageObservationOptions & {
|
|
24
|
+
maxRecords?: number;
|
|
25
|
+
maxAgeSeconds?: number;
|
|
26
|
+
};
|
|
27
|
+
/** Host authorizes the exact scope and original binding before every call. */
|
|
28
|
+
export class UsageObservationClient extends UsageDeliveryClient {
|
|
29
|
+
async getSummary(
|
|
30
|
+
ctx: RunCtx,
|
|
31
|
+
input: { scope: UsageScope; period: UsagePeriod; maxRecords?: number },
|
|
32
|
+
): Promise<UsageLocalSummary> {
|
|
33
|
+
const scope = scopeSchema.parse(input.scope),
|
|
34
|
+
{ period } = validateUsagePageRequest({
|
|
35
|
+
period: input.period,
|
|
36
|
+
limit: 1,
|
|
37
|
+
cursor: null,
|
|
38
|
+
});
|
|
39
|
+
const json = await ctx.runQuery(
|
|
40
|
+
componentRef(this.component, "usageObservations/queries/summary"),
|
|
41
|
+
{ scope, period, maxRecords: input.maxRecords ?? 100 },
|
|
42
|
+
);
|
|
43
|
+
return JSON.parse(json) as UsageLocalSummary;
|
|
44
|
+
}
|
|
45
|
+
async getProviderUsage(
|
|
46
|
+
ctx: RunCtx,
|
|
47
|
+
input: UsageReconciliationOptions,
|
|
48
|
+
): Promise<UsageAggregateObservation> {
|
|
49
|
+
const opts = observationOptions(input),
|
|
50
|
+
{ maxAgeSeconds } = observationKeyOptions.parse({
|
|
51
|
+
maxAgeSeconds: input.maxAgeSeconds,
|
|
52
|
+
});
|
|
53
|
+
const json = await ctx.runQuery(
|
|
54
|
+
componentRef(this.component, "usageObservations/queries/cached"),
|
|
55
|
+
{ sourceJson: JSON.stringify(opts) },
|
|
56
|
+
);
|
|
57
|
+
if (json === null)
|
|
58
|
+
return {
|
|
59
|
+
status: "unavailable",
|
|
60
|
+
reason: "provider_not_observed",
|
|
61
|
+
retryable: true,
|
|
62
|
+
};
|
|
63
|
+
const result = JSON.parse(json) as UsageAggregateObservation;
|
|
64
|
+
if (result.status === "available")
|
|
65
|
+
return {
|
|
66
|
+
...result,
|
|
67
|
+
value: {
|
|
68
|
+
...result.value,
|
|
69
|
+
stale:
|
|
70
|
+
Math.floor(Date.now() / 1000) - result.observedAt > maxAgeSeconds,
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
async observeProviderUsage(
|
|
76
|
+
ctx: RunCtx,
|
|
77
|
+
input: UsageObservationOptions,
|
|
78
|
+
options: UsageDeliveryProviderOptions,
|
|
79
|
+
): Promise<UsageAggregateObservation> {
|
|
80
|
+
const opts = observationOptions(input),
|
|
81
|
+
startedAt = Date.now();
|
|
82
|
+
const observation = options.stripeSecretKey
|
|
83
|
+
? await observeProviderUsage(
|
|
84
|
+
new Stripe(options.stripeSecretKey, {
|
|
85
|
+
apiVersion: opts.binding.apiVersion as StripeApiVersion,
|
|
86
|
+
maxNetworkRetries: 0,
|
|
87
|
+
timeout: 15000,
|
|
88
|
+
...(options.httpClient ? { httpClient: options.httpClient } : {}),
|
|
89
|
+
}),
|
|
90
|
+
opts,
|
|
91
|
+
)
|
|
92
|
+
: {
|
|
93
|
+
status: "unavailable" as const,
|
|
94
|
+
reason: "provider_unavailable",
|
|
95
|
+
retryable: true,
|
|
96
|
+
};
|
|
97
|
+
await runMutationOrThrow(
|
|
98
|
+
ctx,
|
|
99
|
+
componentRef(this.component, "usageObservations/mutations/save"),
|
|
100
|
+
{
|
|
101
|
+
sourceJson: JSON.stringify(opts),
|
|
102
|
+
observationJson: JSON.stringify(observation),
|
|
103
|
+
startedAt,
|
|
104
|
+
},
|
|
105
|
+
);
|
|
106
|
+
return observation;
|
|
107
|
+
}
|
|
108
|
+
async readDeliveryHistory(
|
|
109
|
+
ctx: RunCtx,
|
|
110
|
+
input: UsageDeliveryRef & { limit: number; cursor: string | null },
|
|
111
|
+
) {
|
|
112
|
+
const page = validateUsagePageRequest({
|
|
113
|
+
period: { start: 0, end: 1 },
|
|
114
|
+
limit: input.limit,
|
|
115
|
+
cursor: input.cursor,
|
|
116
|
+
});
|
|
117
|
+
const result = (await ctx.runQuery(
|
|
118
|
+
componentRef(this.component, "usageObservations/queries/deliveryHistory"),
|
|
119
|
+
{
|
|
120
|
+
scope: scopeSchema.parse(input.scope),
|
|
121
|
+
eventId: input.eventId,
|
|
122
|
+
paginationOpts: { numItems: page.limit, cursor: page.cursor },
|
|
123
|
+
},
|
|
124
|
+
)) as {
|
|
125
|
+
page: Doc<"usageDeliveryHistory">[];
|
|
126
|
+
isDone: boolean;
|
|
127
|
+
continueCursor: string;
|
|
128
|
+
legacyHistoryMissing: boolean;
|
|
129
|
+
};
|
|
130
|
+
return {
|
|
131
|
+
records: result.page.map(
|
|
132
|
+
({ sequence, attempt, phase, recordedAt, created }) => ({
|
|
133
|
+
sequence,
|
|
134
|
+
attempt,
|
|
135
|
+
phase,
|
|
136
|
+
recordedAt,
|
|
137
|
+
created: created ?? null,
|
|
138
|
+
}),
|
|
139
|
+
),
|
|
140
|
+
isDone: result.isDone,
|
|
141
|
+
cursor: result.isDone ? null : result.continueCursor,
|
|
142
|
+
legacyHistoryMissing: result.legacyHistoryMissing,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
async readValidationHistory(
|
|
146
|
+
ctx: RunCtx,
|
|
147
|
+
input: UsageDeliveryRef & { limit: number; cursor: string | null },
|
|
148
|
+
) {
|
|
149
|
+
const page = validateUsagePageRequest({
|
|
150
|
+
period: { start: 0, end: 1 },
|
|
151
|
+
limit: input.limit,
|
|
152
|
+
cursor: input.cursor,
|
|
153
|
+
});
|
|
154
|
+
const result = (await ctx.runQuery(
|
|
155
|
+
componentRef(
|
|
156
|
+
this.component,
|
|
157
|
+
"usageObservations/queries/validationHistory",
|
|
158
|
+
),
|
|
159
|
+
{
|
|
160
|
+
scope: scopeSchema.parse(input.scope),
|
|
161
|
+
eventId: input.eventId,
|
|
162
|
+
paginationOpts: { numItems: page.limit, cursor: page.cursor },
|
|
163
|
+
},
|
|
164
|
+
)) as {
|
|
165
|
+
page: Doc<"usageDeliveryErrors">[];
|
|
166
|
+
isDone: boolean;
|
|
167
|
+
continueCursor: string;
|
|
168
|
+
};
|
|
169
|
+
return {
|
|
170
|
+
records: result.page.map(({ providerEventId, code, observedAt }) => ({
|
|
171
|
+
providerEventId,
|
|
172
|
+
code,
|
|
173
|
+
observedAt,
|
|
174
|
+
})),
|
|
175
|
+
isDone: result.isDone,
|
|
176
|
+
cursor: result.isDone ? null : result.continueCursor,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
async readInvoiceUsage(
|
|
180
|
+
_ctx: RunCtx,
|
|
181
|
+
input: UsageObservationOptions & { invoiceId?: string },
|
|
182
|
+
options: UsageDeliveryProviderOptions,
|
|
183
|
+
) {
|
|
184
|
+
const opts = observationOptions(input);
|
|
185
|
+
if (!options.stripeSecretKey)
|
|
186
|
+
return {
|
|
187
|
+
status: "unavailable" as const,
|
|
188
|
+
reason: "provider_unavailable",
|
|
189
|
+
retryable: true,
|
|
190
|
+
};
|
|
191
|
+
const stripe = new Stripe(options.stripeSecretKey, {
|
|
192
|
+
apiVersion: opts.binding.apiVersion as StripeApiVersion,
|
|
193
|
+
maxNetworkRetries: 0,
|
|
194
|
+
timeout: 15000,
|
|
195
|
+
...(options.httpClient ? { httpClient: options.httpClient } : {}),
|
|
196
|
+
});
|
|
197
|
+
return observeUsageInvoice(stripe, opts, input.invoiceId);
|
|
198
|
+
}
|
|
199
|
+
async getReconciliation(ctx: RunCtx, input: UsageReconciliationOptions) {
|
|
200
|
+
const opts = observationOptions(input);
|
|
201
|
+
const [local, aggregate] = await Promise.all([
|
|
202
|
+
this.getSummary(ctx, {
|
|
203
|
+
scope: opts.scope,
|
|
204
|
+
period: opts.period,
|
|
205
|
+
maxRecords: input.maxRecords,
|
|
206
|
+
}),
|
|
207
|
+
this.getProviderUsage(ctx, input),
|
|
208
|
+
]);
|
|
209
|
+
return {
|
|
210
|
+
local,
|
|
211
|
+
aggregate,
|
|
212
|
+
comparison: compareUsageObservations(local, aggregate, opts.binding),
|
|
213
|
+
invoice: {
|
|
214
|
+
status: "unavailable" as const,
|
|
215
|
+
reason: "invoice_not_observed",
|
|
216
|
+
retryable: true,
|
|
217
|
+
},
|
|
218
|
+
correctionHistory: {
|
|
219
|
+
status: "unsupported" as const,
|
|
220
|
+
reason: "corrections_not_configured",
|
|
221
|
+
retryable: false,
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
async reconcile(
|
|
226
|
+
ctx: RunCtx,
|
|
227
|
+
input: UsageReconciliationOptions,
|
|
228
|
+
options: UsageDeliveryProviderOptions,
|
|
229
|
+
) {
|
|
230
|
+
await this.observeProviderUsage(ctx, input, options);
|
|
231
|
+
return this.getReconciliation(ctx, input);
|
|
232
|
+
}
|
|
233
|
+
}
|