@fantastic.dev/better-stripe 0.54.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.
Files changed (122) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +112 -34
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +40 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +112 -34
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +40 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +5 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/usage/client.d.ts +2 -2
  14. package/dist/client/usage/client.d.ts.map +1 -1
  15. package/dist/client/usage/client.js +2 -2
  16. package/dist/client/usage/client.js.map +1 -1
  17. package/dist/client/usage/index.d.ts +5 -0
  18. package/dist/client/usage/index.d.ts.map +1 -1
  19. package/dist/client/usage/invoiceObservation.d.ts +38 -0
  20. package/dist/client/usage/invoiceObservation.d.ts.map +1 -0
  21. package/dist/client/usage/invoiceObservation.js +157 -0
  22. package/dist/client/usage/invoiceObservation.js.map +1 -0
  23. package/dist/client/usage/observationClient.d.ts +83 -0
  24. package/dist/client/usage/observationClient.d.ts.map +1 -0
  25. package/dist/client/usage/observationClient.js +157 -0
  26. package/dist/client/usage/observationClient.js.map +1 -0
  27. package/dist/client/usage/observationTypes.d.ts +63 -0
  28. package/dist/client/usage/observationTypes.d.ts.map +1 -0
  29. package/dist/client/usage/observationTypes.js +59 -0
  30. package/dist/client/usage/observationTypes.js.map +1 -0
  31. package/dist/client/usage/providerObservation.d.ts +4 -0
  32. package/dist/client/usage/providerObservation.d.ts.map +1 -0
  33. package/dist/client/usage/providerObservation.js +96 -0
  34. package/dist/client/usage/providerObservation.js.map +1 -0
  35. package/dist/client/usage/reconciliation.d.ts +12 -0
  36. package/dist/client/usage/reconciliation.d.ts.map +1 -0
  37. package/dist/client/usage/reconciliation.js +48 -0
  38. package/dist/client/usage/reconciliation.js.map +1 -0
  39. package/dist/client/usage/summary.d.ts +50 -0
  40. package/dist/client/usage/summary.d.ts.map +1 -0
  41. package/dist/client/usage/summary.js +110 -0
  42. package/dist/client/usage/summary.js.map +1 -0
  43. package/dist/component/_generated/api.d.ts +8 -0
  44. package/dist/component/_generated/api.d.ts.map +1 -1
  45. package/dist/component/_generated/api.js.map +1 -1
  46. package/dist/component/_generated/component.d.ts +95 -0
  47. package/dist/component/_generated/component.d.ts.map +1 -1
  48. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  49. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  50. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  51. package/dist/component/earnings/triggers.d.ts +104 -18
  52. package/dist/component/earnings/triggers.d.ts.map +1 -1
  53. package/dist/component/refundHistory/queries.d.ts +1 -1
  54. package/dist/component/schema.d.ts +40 -1
  55. package/dist/component/schema.js +3 -0
  56. package/dist/component/schema.js.map +1 -1
  57. package/dist/component/usage/schema.d.ts +7 -2
  58. package/dist/component/usage/schema.d.ts.map +1 -1
  59. package/dist/component/usageDelivery/fields.d.ts +1 -0
  60. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  61. package/dist/component/usageDelivery/fields.js +1 -0
  62. package/dist/component/usageDelivery/fields.js.map +1 -1
  63. package/dist/component/usageDelivery/helpers.d.ts +1 -0
  64. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  65. package/dist/component/usageDelivery/mutations.d.ts.map +1 -1
  66. package/dist/component/usageDelivery/mutations.js +8 -1
  67. package/dist/component/usageDelivery/mutations.js.map +1 -1
  68. package/dist/component/usageDelivery/queries.d.ts +2 -0
  69. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  70. package/dist/component/usageDelivery/steps.d.ts.map +1 -1
  71. package/dist/component/usageDelivery/steps.js +8 -1
  72. package/dist/component/usageDelivery/steps.js.map +1 -1
  73. package/dist/component/usageObservations/helpers.d.ts +38 -0
  74. package/dist/component/usageObservations/helpers.d.ts.map +1 -0
  75. package/dist/component/usageObservations/helpers.js +80 -0
  76. package/dist/component/usageObservations/helpers.js.map +1 -0
  77. package/dist/component/usageObservations/history.d.ts +6 -0
  78. package/dist/component/usageObservations/history.d.ts.map +1 -0
  79. package/dist/component/usageObservations/history.js +29 -0
  80. package/dist/component/usageObservations/history.js.map +1 -0
  81. package/dist/component/usageObservations/mutations.d.ts +6 -0
  82. package/dist/component/usageObservations/mutations.d.ts.map +1 -0
  83. package/dist/component/usageObservations/mutations.js +39 -0
  84. package/dist/component/usageObservations/mutations.js.map +1 -0
  85. package/dist/component/usageObservations/queries.d.ts +78 -0
  86. package/dist/component/usageObservations/queries.d.ts.map +1 -0
  87. package/dist/component/usageObservations/queries.js +131 -0
  88. package/dist/component/usageObservations/queries.js.map +1 -0
  89. package/dist/component/usageObservations/schema.d.ts +72 -0
  90. package/dist/component/usageObservations/schema.d.ts.map +1 -0
  91. package/dist/component/usageObservations/schema.js +29 -0
  92. package/dist/component/usageObservations/schema.js.map +1 -0
  93. package/docs/README.md +2 -0
  94. package/docs/metering-setup.md +2 -0
  95. package/docs/usage-observations.md +152 -0
  96. package/package.json +3 -2
  97. package/src/client/index.ts +18 -0
  98. package/src/client/usage/client.ts +2 -2
  99. package/src/client/usage/index.ts +18 -0
  100. package/src/client/usage/invoiceObservation.test.ts +195 -0
  101. package/src/client/usage/invoiceObservation.ts +203 -0
  102. package/src/client/usage/observationClient.ts +233 -0
  103. package/src/client/usage/observationTypes.ts +101 -0
  104. package/src/client/usage/providerObservation.test.ts +207 -0
  105. package/src/client/usage/providerObservation.ts +124 -0
  106. package/src/client/usage/reconciliation.test.ts +117 -0
  107. package/src/client/usage/reconciliation.ts +86 -0
  108. package/src/client/usage/summary.test.ts +222 -0
  109. package/src/client/usage/summary.ts +188 -0
  110. package/src/component/_generated/api.ts +8 -0
  111. package/src/component/_generated/component.ts +135 -0
  112. package/src/component/schema.ts +6 -0
  113. package/src/component/usageDelivery/fields.ts +1 -0
  114. package/src/component/usageDelivery/mutations.ts +26 -1
  115. package/src/component/usageDelivery/steps.ts +39 -1
  116. package/src/component/usageObservations/helpers.ts +95 -0
  117. package/src/component/usageObservations/history.test.ts +87 -0
  118. package/src/component/usageObservations/history.ts +39 -0
  119. package/src/component/usageObservations/mutations.ts +39 -0
  120. package/src/component/usageObservations/queries.test.ts +162 -0
  121. package/src/component/usageObservations/queries.ts +145 -0
  122. package/src/component/usageObservations/schema.ts +40 -0
@@ -0,0 +1,207 @@
1
+ import { componentsGeneric, type FunctionReference } from "convex/server";
2
+ import { BetterStripe } from "../index.js";
3
+ import { initConvexTest } from "../setup.test.js";
4
+ import { schema, modules } from "../../test.js";
5
+ import type { Component, RunCtx } from "../helpers.js";
6
+ import Stripe from "stripe";
7
+ import { expect, it, vi } from "vitest";
8
+ import { STRIPE_API_VERSION } from "../constants.js";
9
+ import { prepareUsageRecord } from "./records.js";
10
+ import { observeProviderUsage } from "./providerObservation.js";
11
+ const scope = {
12
+ stripeAccountId: "acct_platform",
13
+ customerAccount: "acct_buyer",
14
+ meterId: "mtr_calls",
15
+ livemode: false,
16
+ };
17
+ const period = { start: 600, end: 1200 };
18
+ const binding = prepareUsageRecord({
19
+ scope,
20
+ binding: {
21
+ stripeCustomerId: "cus_buyer",
22
+ stripePriceId: "price_calls",
23
+ eventName: "calls",
24
+ plan: {
25
+ key: "calls",
26
+ version: "v1",
27
+ model: "pay_as_you_go",
28
+ unit: { name: "call", precision: 2 },
29
+ rate: { currency: "usd", unitAmountDecimal: "2" },
30
+ },
31
+ },
32
+ sourceEventId: "validation",
33
+ quantity: "0",
34
+ occurredAt: 600,
35
+ }).binding;
36
+ const options = {
37
+ scope,
38
+ binding,
39
+ subscription: {
40
+ subscriptionId: "sub_calls",
41
+ subscriptionItemId: "si_calls",
42
+ stripePriceId: "price_calls",
43
+ period,
44
+ interval: "month" as const,
45
+ },
46
+ period,
47
+ limit: 100,
48
+ cursor: null,
49
+ };
50
+ function setup(value = 125, hasMore = false, empty = false) {
51
+ const requests: Array<URL> = [];
52
+ const httpClient = Stripe.createFetchHttpClient(async (input) => {
53
+ const url = new URL(String(input));
54
+ requests.push(url);
55
+ const result =
56
+ url.pathname === "/v1/account"
57
+ ? { id: "acct_platform" }
58
+ : url.pathname === "/v1/balance"
59
+ ? { livemode: false }
60
+ : url.pathname === "/v1/billing/meters/mtr_calls"
61
+ ? {
62
+ id: "mtr_calls",
63
+ livemode: false,
64
+ status: "active",
65
+ event_name: "calls",
66
+ default_aggregation: { formula: "sum" },
67
+ customer_mapping: {
68
+ type: "by_id",
69
+ event_payload_key: "stripe_customer_id",
70
+ },
71
+ value_settings: { event_payload_key: "value" },
72
+ event_time_window: null,
73
+ }
74
+ : url.pathname === "/v1/subscriptions/sub_calls"
75
+ ? {
76
+ id: "sub_calls",
77
+ livemode: false,
78
+ customer: "cus_buyer",
79
+ customer_account: "acct_buyer",
80
+ }
81
+ : {
82
+ object: "list",
83
+ data: empty
84
+ ? []
85
+ : [
86
+ {
87
+ id: "mtrusg_one",
88
+ object: "billing.meter_event_summary",
89
+ meter: "mtr_calls",
90
+ livemode: false,
91
+ start_time: 600,
92
+ end_time: 1200,
93
+ aggregated_value: value,
94
+ },
95
+ ],
96
+ has_more: hasMore,
97
+ };
98
+ return new Response(JSON.stringify(result), {
99
+ status: 200,
100
+ headers: { "content-type": "application/json" },
101
+ });
102
+ });
103
+ const stripe = new Stripe("sk_test_observe", {
104
+ apiVersion: STRIPE_API_VERSION,
105
+ maxNetworkRetries: 0,
106
+ httpClient,
107
+ });
108
+ return { stripe, requests, httpClient };
109
+ }
110
+ it("reads exact native quantities and preserves the original customer/period", async () => {
111
+ const f = setup();
112
+ expect(await observeProviderUsage(f.stripe, options)).toMatchObject({
113
+ status: "available",
114
+ value: {
115
+ quantity: "1.25",
116
+ scaledQuantity: "125",
117
+ complete: true,
118
+ aggregationLagPossible: true,
119
+ period,
120
+ },
121
+ });
122
+ const request = f.requests.find((r) =>
123
+ r.pathname.endsWith("event_summaries"),
124
+ )!;
125
+ expect(request.searchParams.get("customer")).toBe("cus_buyer");
126
+ expect(request.searchParams.get("start_time")).toBe("600");
127
+ expect(request.searchParams.get("end_time")).toBe("1200");
128
+ });
129
+ it("reports absent aggregation instead of zero and preserves incomplete pagination", async () => {
130
+ expect(
131
+ await observeProviderUsage(setup(0, false, true).stripe, options),
132
+ ).toMatchObject({ status: "unavailable", reason: "aggregation_pending" });
133
+ expect(
134
+ await observeProviderUsage(setup(0, true).stripe, options),
135
+ ).toMatchObject({
136
+ status: "available",
137
+ value: { quantity: "0", complete: false, nextCursor: "mtrusg_one" },
138
+ });
139
+ });
140
+ it("rejects unaligned windows and unsafe provider numbers without rounding", async () => {
141
+ const f = setup();
142
+ expect(
143
+ await observeProviderUsage(f.stripe, {
144
+ ...options,
145
+ period: { start: 601, end: 1200 },
146
+ }),
147
+ ).toMatchObject({
148
+ status: "unsupported",
149
+ reason: "minute_alignment_required",
150
+ });
151
+ expect(f.requests).toHaveLength(0);
152
+ expect(
153
+ await observeProviderUsage(
154
+ setup(Number.MAX_SAFE_INTEGER + 1).stripe,
155
+ options,
156
+ ),
157
+ ).toMatchObject({
158
+ status: "unavailable",
159
+ reason: "provider_precision_unsupported",
160
+ });
161
+ });
162
+
163
+ it("caches through the public facade without resending usage and exposes stale data", async () => {
164
+ const t = initConvexTest();
165
+ t.registerComponent("betterStripe", schema, modules);
166
+ const client = new BetterStripe(
167
+ componentsGeneric().betterStripe as unknown as Component,
168
+ );
169
+ const ctx = {
170
+ runQuery: (
171
+ ref: FunctionReference<"query">,
172
+ args: Record<string, unknown>,
173
+ ) => t.query(ref, args),
174
+ runMutation: (
175
+ ref: FunctionReference<"mutation">,
176
+ args: Record<string, unknown>,
177
+ ) => t.mutation(ref, args),
178
+ } as RunCtx;
179
+ const f = setup();
180
+ expect(await client.usage.getProviderUsage(ctx, options)).toMatchObject({
181
+ status: "unavailable",
182
+ reason: "provider_not_observed",
183
+ });
184
+ const result = await client.usage.reconcile(ctx, options, {
185
+ stripeSecretKey: "sk_test_observe",
186
+ httpClient: f.httpClient,
187
+ });
188
+ expect(result).toMatchObject({
189
+ local: { complete: true, eventCount: 0 },
190
+ aggregate: { status: "available", value: { quantity: "1.25" } },
191
+ comparison: { status: "mismatch" },
192
+ invoice: { status: "unavailable" },
193
+ });
194
+ expect(
195
+ f.requests.every((url) => !url.pathname.endsWith("meter_events")),
196
+ ).toBe(true);
197
+ const now = Date.now(),
198
+ clock = vi.spyOn(Date, "now").mockReturnValue(now + 61000);
199
+ try {
200
+ expect(await client.usage.getReconciliation(ctx, options)).toMatchObject({
201
+ aggregate: { status: "available", value: { stale: true } },
202
+ comparison: { status: "unavailable", reason: "aggregate_stale" },
203
+ });
204
+ } finally {
205
+ clock.mockRestore();
206
+ }
207
+ });
@@ -0,0 +1,124 @@
1
+ import type Stripe from "stripe";
2
+ import { UsageCatalogError } from "./catalogTypes.js";
3
+ import { decimalFromScaled } from "./summary.js";
4
+ import {
5
+ observationOptions,
6
+ verifyObservationSource,
7
+ type UsageObservationOptions,
8
+ type UsageAggregateObservation,
9
+ } from "./observationTypes.js";
10
+ export async function observeProviderUsage(
11
+ stripe: Stripe,
12
+ input: UsageObservationOptions,
13
+ ): Promise<UsageAggregateObservation> {
14
+ const opts = observationOptions(input),
15
+ observedAt = Math.floor(Date.now() / 1000);
16
+ const unavailable = (reason: string): UsageAggregateObservation => ({
17
+ status: "unavailable",
18
+ reason,
19
+ retryable: true,
20
+ });
21
+ if (opts.period.start % 60 || opts.period.end % 60)
22
+ return {
23
+ status: "unsupported",
24
+ reason: "minute_alignment_required",
25
+ retryable: false,
26
+ };
27
+ try {
28
+ if (!(await verifyObservationSource(stripe, opts)))
29
+ return {
30
+ status: "unsupported",
31
+ reason: "provider_binding_mismatch",
32
+ retryable: false,
33
+ };
34
+ const result = await stripe.billing.meters.listEventSummaries(
35
+ opts.scope.meterId,
36
+ {
37
+ customer: opts.binding.stripeCustomerId,
38
+ start_time: opts.period.start,
39
+ end_time: opts.period.end,
40
+ limit: opts.limit,
41
+ starting_after: opts.cursor ?? undefined,
42
+ },
43
+ );
44
+ if (!result.data.length)
45
+ return unavailable(
46
+ result.has_more ? "provider_history_incomplete" : "aggregation_pending",
47
+ );
48
+ if (result.data.length > opts.limit)
49
+ return unavailable("provider_history_incomplete");
50
+ const seen = new Set<string>();
51
+ let scaled = 0n;
52
+ const intervals: Array<{ start: number; end: number }> = [],
53
+ entries: Array<{
54
+ id: string;
55
+ start: number;
56
+ end: number;
57
+ scaledQuantity: string;
58
+ }> = [];
59
+ for (const summary of result.data) {
60
+ if (
61
+ summary.object !== "billing.meter_event_summary" ||
62
+ summary.meter !== opts.scope.meterId ||
63
+ summary.livemode !== opts.scope.livemode ||
64
+ !summary.id ||
65
+ summary.id.length > 2048 ||
66
+ seen.has(summary.id) ||
67
+ !Number.isSafeInteger(summary.start_time) ||
68
+ !Number.isSafeInteger(summary.end_time) ||
69
+ summary.start_time < opts.period.start ||
70
+ summary.end_time > opts.period.end ||
71
+ summary.end_time <= summary.start_time ||
72
+ intervals.some(
73
+ (w) => summary.start_time < w.end && summary.end_time > w.start,
74
+ )
75
+ )
76
+ return unavailable("provider_history_incomplete");
77
+ if (
78
+ !Number.isSafeInteger(summary.aggregated_value) ||
79
+ summary.aggregated_value < 0
80
+ )
81
+ return unavailable("provider_precision_unsupported");
82
+ seen.add(summary.id);
83
+ intervals.push({ start: summary.start_time, end: summary.end_time });
84
+ const value = BigInt(summary.aggregated_value);
85
+ scaled += value;
86
+ entries.push({
87
+ id: summary.id,
88
+ start: summary.start_time,
89
+ end: summary.end_time,
90
+ scaledQuantity: value.toString(),
91
+ });
92
+ }
93
+ const covered =
94
+ intervals.reduce((sum, w) => sum + w.end - w.start, 0) ===
95
+ opts.period.end - opts.period.start;
96
+ return {
97
+ status: "available",
98
+ observedAt,
99
+ value: {
100
+ period: opts.period,
101
+ quantity: decimalFromScaled(scaled, opts.binding.plan.unit.precision),
102
+ scaledQuantity: scaled.toString(),
103
+ complete: !result.has_more && opts.cursor === null && covered,
104
+ nextCursor: result.has_more
105
+ ? result.data[result.data.length - 1].id
106
+ : null,
107
+ aggregationLagPossible: true,
108
+ stale: false,
109
+ entries,
110
+ },
111
+ };
112
+ } catch (error) {
113
+ if (
114
+ error instanceof UsageCatalogError &&
115
+ error.code === "unsupported_scope"
116
+ )
117
+ return {
118
+ status: "unsupported",
119
+ reason: "unsupported_scope",
120
+ retryable: false,
121
+ };
122
+ return unavailable("provider_unavailable");
123
+ }
124
+ }
@@ -0,0 +1,117 @@
1
+ import { expect, it } from "vitest";
2
+ import { compareUsageObservations } from "./reconciliation.js";
3
+ import { summarizeUsageRecords } from "./summary.js";
4
+ import { prepareUsageRecord } from "./records.js";
5
+ const period = { start: 600, end: 1200 },
6
+ scope = {
7
+ stripeAccountId: "acct_platform",
8
+ customerAccount: "acct_buyer",
9
+ meterId: "mtr_calls",
10
+ livemode: false,
11
+ };
12
+ const record = prepareUsageRecord({
13
+ scope,
14
+ binding: {
15
+ stripeCustomerId: "cus_buyer",
16
+ stripePriceId: "price_calls",
17
+ eventName: "calls",
18
+ plan: {
19
+ key: "calls",
20
+ version: "v1",
21
+ model: "pay_as_you_go",
22
+ unit: { name: "call", precision: 0 },
23
+ rate: { currency: "usd", unitAmountDecimal: "2" },
24
+ },
25
+ },
26
+ sourceEventId: "one",
27
+ quantity: "2",
28
+ occurredAt: 700,
29
+ });
30
+ const subscription = {
31
+ subscriptionId: "sub_calls",
32
+ subscriptionItemId: "si_calls",
33
+ stripePriceId: "price_calls",
34
+ period,
35
+ interval: "month" as const,
36
+ };
37
+ const local = summarizeUsageRecords(
38
+ [
39
+ {
40
+ record,
41
+ subscription,
42
+ delivery: "provider_accepted",
43
+ hasValidationError: false,
44
+ },
45
+ ],
46
+ { period, complete: true, observedAt: 1201 },
47
+ );
48
+ const aggregate = {
49
+ status: "available" as const,
50
+ observedAt: 1201,
51
+ value: {
52
+ period,
53
+ quantity: "2",
54
+ scaledQuantity: "2",
55
+ complete: true,
56
+ nextCursor: null,
57
+ aggregationLagPossible: true as const,
58
+ stale: false,
59
+ entries: [{ id: "mtrusg_one", start: 600, end: 1200, scaledQuantity: "2" }],
60
+ },
61
+ };
62
+ it("separates observed matches from mismatches without changing usage", () => {
63
+ expect(
64
+ compareUsageObservations(local, aggregate, record.binding),
65
+ ).toMatchObject({
66
+ status: "observed_match",
67
+ localAcceptedQuantity: "2",
68
+ providerAcceptedQuantity: "2",
69
+ providerAggregateQuantity: "2",
70
+ });
71
+ expect(
72
+ compareUsageObservations(
73
+ local,
74
+ {
75
+ ...aggregate,
76
+ value: { ...aggregate.value, quantity: "0", scaledQuantity: "0" },
77
+ },
78
+ record.binding,
79
+ ),
80
+ ).toMatchObject({
81
+ status: "mismatch",
82
+ reason: "aggregation_lag_or_external_usage",
83
+ });
84
+ expect(record.quantity).toBe("2");
85
+ });
86
+ it("cannot compare stale, incomplete, absent or differently routed observations", () => {
87
+ expect(
88
+ compareUsageObservations(
89
+ local,
90
+ { ...aggregate, value: { ...aggregate.value, stale: true } },
91
+ record.binding,
92
+ ),
93
+ ).toMatchObject({ status: "unavailable", reason: "aggregate_stale" });
94
+ expect(
95
+ compareUsageObservations(
96
+ { ...local, complete: false },
97
+ aggregate,
98
+ record.binding,
99
+ ),
100
+ ).toMatchObject({
101
+ status: "unavailable",
102
+ reason: "local_history_incomplete",
103
+ });
104
+ expect(
105
+ compareUsageObservations(
106
+ local,
107
+ { status: "unavailable", reason: "aggregation_pending", retryable: true },
108
+ record.binding,
109
+ ),
110
+ ).toMatchObject({ status: "unavailable", providerAggregateQuantity: null });
111
+ expect(
112
+ compareUsageObservations(local, aggregate, {
113
+ ...record.binding,
114
+ stripePriceId: "price_changed",
115
+ }),
116
+ ).toMatchObject({ status: "unavailable", reason: "ambiguous_local_terms" });
117
+ });
@@ -0,0 +1,86 @@
1
+ import { convexToJson } from "convex/values";
2
+ import type { UsageLocalSummary } from "./summary.js";
3
+ import { decimalFromScaled } from "./summary.js";
4
+ import type { UsageAggregateObservation } from "./observationTypes.js";
5
+ import type { PreparedUsageRecord } from "./records.js";
6
+ export type UsageComparison = {
7
+ status: "observed_match" | "mismatch" | "unavailable";
8
+ reason: string;
9
+ localAcceptedQuantity: string | null;
10
+ providerAcceptedQuantity: string | null;
11
+ providerAggregateQuantity: string | null;
12
+ };
13
+ export function compareUsageObservations(
14
+ local: UsageLocalSummary,
15
+ aggregate: UsageAggregateObservation,
16
+ binding: PreparedUsageRecord["binding"],
17
+ ): UsageComparison {
18
+ const value: UsageComparison = {
19
+ status: "unavailable",
20
+ reason: "provider_unavailable",
21
+ localAcceptedQuantity: null,
22
+ providerAcceptedQuantity: null,
23
+ providerAggregateQuantity:
24
+ aggregate.status === "available" ? aggregate.value.quantity : null,
25
+ };
26
+ const unavailable = (reason: string) => ({ ...value, reason });
27
+ if (!local.complete) return unavailable("local_history_incomplete");
28
+ if (
29
+ local.groups.some(
30
+ (group) =>
31
+ JSON.stringify(convexToJson(group.binding)) !==
32
+ JSON.stringify(convexToJson(binding)),
33
+ )
34
+ )
35
+ return unavailable("ambiguous_local_terms");
36
+ const accepted = local.groups.reduce(
37
+ (sum, group) => sum + BigInt(group.acceptedScaledQuantity),
38
+ 0n,
39
+ ),
40
+ provider = local.groups.reduce(
41
+ (sum, group) => sum + BigInt(group.providerAcceptedScaledQuantity),
42
+ 0n,
43
+ );
44
+ value.localAcceptedQuantity = decimalFromScaled(
45
+ accepted,
46
+ binding.plan.unit.precision,
47
+ );
48
+ value.providerAcceptedQuantity = decimalFromScaled(
49
+ provider,
50
+ binding.plan.unit.precision,
51
+ );
52
+ if (aggregate.status !== "available") return unavailable(aggregate.reason);
53
+ if (aggregate.value.stale) return unavailable("aggregate_stale");
54
+ if (!aggregate.value.complete)
55
+ return unavailable("provider_history_incomplete");
56
+ if (
57
+ local.period.start !== aggregate.value.period.start ||
58
+ local.period.end !== aggregate.value.period.end
59
+ )
60
+ return unavailable("period_mismatch");
61
+ if (
62
+ local.groups.some(
63
+ (g) =>
64
+ g.deliveryQuantities.unknown !== "0" ||
65
+ g.deliveryQuantities.sending !== "0",
66
+ )
67
+ )
68
+ return unavailable("delivery_unresolved");
69
+ if (local.groups.some((g) => g.validationErrorEventCount > 0))
70
+ return {
71
+ ...value,
72
+ status: "mismatch",
73
+ reason: "provider_validation_errors",
74
+ };
75
+ return {
76
+ ...value,
77
+ status:
78
+ provider === BigInt(aggregate.value.scaledQuantity)
79
+ ? "observed_match"
80
+ : "mismatch",
81
+ reason:
82
+ provider === BigInt(aggregate.value.scaledQuantity)
83
+ ? "observations_equal"
84
+ : "aggregation_lag_or_external_usage",
85
+ };
86
+ }