@fantastic.dev/better-stripe 0.59.0 → 0.60.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 (124) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +3 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +650 -44
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +309 -6
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +618 -12
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +325 -22
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +4 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/paymentSource/resolver.d.ts +12 -1
  14. package/dist/client/paymentSource/resolver.d.ts.map +1 -1
  15. package/dist/client/paymentSource/resolver.fixtures.d.ts +220 -0
  16. package/dist/client/paymentSource/resolver.fixtures.d.ts.map +1 -0
  17. package/dist/client/paymentSource/resolver.fixtures.js +189 -0
  18. package/dist/client/paymentSource/resolver.fixtures.js.map +1 -0
  19. package/dist/client/paymentSource/resolver.js +28 -3
  20. package/dist/client/paymentSource/resolver.js.map +1 -1
  21. package/dist/client/settlement/execution.d.ts +25 -0
  22. package/dist/client/settlement/execution.d.ts.map +1 -1
  23. package/dist/client/settlement/execution.js +2 -0
  24. package/dist/client/settlement/execution.js.map +1 -1
  25. package/dist/client/usage/catalogPrices.d.ts +1 -1
  26. package/dist/client/usage/catalogPrices.d.ts.map +1 -1
  27. package/dist/client/usage/catalogPrices.js +4 -4
  28. package/dist/client/usage/catalogPrices.js.map +1 -1
  29. package/dist/client/usage/client.d.ts +2 -2
  30. package/dist/client/usage/client.js +2 -2
  31. package/dist/client/usage/creditRevenue.d.ts +22 -0
  32. package/dist/client/usage/creditRevenue.d.ts.map +1 -0
  33. package/dist/client/usage/creditRevenue.js +118 -0
  34. package/dist/client/usage/creditRevenue.js.map +1 -0
  35. package/dist/client/usage/creditSettlement.d.ts +29 -0
  36. package/dist/client/usage/creditSettlement.d.ts.map +1 -0
  37. package/dist/client/usage/creditSettlement.fixtures.d.ts +215 -0
  38. package/dist/client/usage/creditSettlement.fixtures.d.ts.map +1 -0
  39. package/dist/client/usage/creditSettlement.fixtures.js +59 -0
  40. package/dist/client/usage/creditSettlement.fixtures.js.map +1 -0
  41. package/dist/client/usage/creditSettlement.js +70 -0
  42. package/dist/client/usage/creditSettlement.js.map +1 -0
  43. package/dist/client/usage/creditTransport.fixtures.d.ts +7 -1
  44. package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -1
  45. package/dist/client/usage/creditTransport.fixtures.js +25 -4
  46. package/dist/client/usage/creditTransport.fixtures.js.map +1 -1
  47. package/dist/client/usage/index.d.ts +4 -0
  48. package/dist/client/usage/index.d.ts.map +1 -1
  49. package/dist/client/usage/invoiceSale.d.ts +22 -0
  50. package/dist/client/usage/invoiceSale.d.ts.map +1 -0
  51. package/dist/client/usage/invoiceSale.fixtures.d.ts +285 -0
  52. package/dist/client/usage/invoiceSale.fixtures.d.ts.map +1 -0
  53. package/dist/client/usage/invoiceSale.fixtures.js +104 -0
  54. package/dist/client/usage/invoiceSale.fixtures.js.map +1 -0
  55. package/dist/client/usage/invoiceSale.js +117 -0
  56. package/dist/client/usage/invoiceSale.js.map +1 -0
  57. package/dist/client/usage/observationClient.d.ts +2 -2
  58. package/dist/client/usage/observationClient.d.ts.map +1 -1
  59. package/dist/client/usage/settlement.d.ts +32 -0
  60. package/dist/client/usage/settlement.d.ts.map +1 -0
  61. package/dist/client/usage/settlement.js +60 -0
  62. package/dist/client/usage/settlement.js.map +1 -0
  63. package/dist/client/usage/settlementClient.d.ts +51 -0
  64. package/dist/client/usage/settlementClient.d.ts.map +1 -0
  65. package/dist/client/usage/settlementClient.js +35 -0
  66. package/dist/client/usage/settlementClient.js.map +1 -0
  67. package/dist/component/_generated/component.d.ts +125 -0
  68. package/dist/component/_generated/component.d.ts.map +1 -1
  69. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  70. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  71. package/dist/component/earnings/triggers.d.ts +156 -6
  72. package/dist/component/earnings/triggers.d.ts.map +1 -1
  73. package/dist/component/financialObservations/settlementHelpers.d.ts.map +1 -1
  74. package/dist/component/financialObservations/settlementHelpers.js +2 -0
  75. package/dist/component/financialObservations/settlementHelpers.js.map +1 -1
  76. package/dist/component/recoveryWorkflow/helpers.d.ts +25 -0
  77. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -1
  78. package/dist/component/recoveryWorkflow/mutations.d.ts +25 -0
  79. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -1
  80. package/dist/component/recoveryWorkflow/queries.d.ts +50 -0
  81. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -1
  82. package/dist/component/recoveryWorkflow/schema.d.ts +566 -10
  83. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -1
  84. package/dist/component/schema.d.ts +309 -6
  85. package/dist/component/settlement/mutations.d.ts +50 -0
  86. package/dist/component/settlement/mutations.d.ts.map +1 -1
  87. package/dist/component/settlement/mutations.js +8 -1
  88. package/dist/component/settlement/mutations.js.map +1 -1
  89. package/dist/component/settlement/queries.d.ts +25 -0
  90. package/dist/component/settlement/queries.d.ts.map +1 -1
  91. package/dist/component/settlement/schema.d.ts +128 -1
  92. package/dist/component/settlement/schema.d.ts.map +1 -1
  93. package/dist/component/settlement/schema.js +22 -0
  94. package/dist/component/settlement/schema.js.map +1 -1
  95. package/docs/README.md +2 -0
  96. package/docs/settlement.md +4 -0
  97. package/docs/usage-settlement.md +162 -0
  98. package/package.json +2 -1
  99. package/src/client/index.ts +9 -0
  100. package/src/client/paymentSource/resolver.fixtures.ts +216 -0
  101. package/src/client/paymentSource/resolver.test.ts +11 -207
  102. package/src/client/paymentSource/resolver.ts +54 -2
  103. package/src/client/settlement/execution.ts +24 -0
  104. package/src/client/usage/catalogPrices.ts +4 -2
  105. package/src/client/usage/client.ts +2 -2
  106. package/src/client/usage/creditRevenue.test.ts +105 -0
  107. package/src/client/usage/creditRevenue.ts +163 -0
  108. package/src/client/usage/creditSettlement.fixtures.ts +70 -0
  109. package/src/client/usage/creditSettlement.test.ts +66 -0
  110. package/src/client/usage/creditSettlement.ts +94 -0
  111. package/src/client/usage/creditSettlementRecovery.test.ts +173 -0
  112. package/src/client/usage/creditTransport.fixtures.ts +29 -4
  113. package/src/client/usage/index.ts +9 -0
  114. package/src/client/usage/invoiceSale.fixtures.ts +103 -0
  115. package/src/client/usage/invoiceSale.test.ts +184 -0
  116. package/src/client/usage/invoiceSale.ts +155 -0
  117. package/src/client/usage/settlement.test.ts +179 -0
  118. package/src/client/usage/settlement.ts +81 -0
  119. package/src/client/usage/settlementClient.ts +84 -0
  120. package/src/component/_generated/component.ts +110 -0
  121. package/src/component/financialObservations/settlementHelpers.ts +2 -0
  122. package/src/component/settlement/mutations.ts +10 -1
  123. package/src/component/settlement/schema.ts +26 -0
  124. package/src/component/settlement/settlement-claims.test.ts +54 -0
@@ -7,7 +7,12 @@ const response = (value: unknown) =>
7
7
  new Response(JSON.stringify(value), {
8
8
  headers: { "content-type": "application/json" },
9
9
  });
10
- export function creditFixture() {
10
+ export function creditFixture(
11
+ intercept?: (
12
+ input: string,
13
+ init?: RequestInit,
14
+ ) => Promise<Response | undefined>,
15
+ ) {
11
16
  vi.useFakeTimers();
12
17
  vi.setSystemTime(700000);
13
18
  const calls: Array<{
@@ -25,6 +30,12 @@ export function creditFixture() {
25
30
  incomplete: false,
26
31
  canceled: false,
27
32
  refunded: false,
33
+ refundedAmount: 0,
34
+ disputed: false,
35
+ feePending: false,
36
+ processingFee: 1,
37
+ paymentCustomer: "cus_buyer",
38
+ chargeCustomer: "cus_buyer",
28
39
  failGrant: false,
29
40
  wrongPayer: false,
30
41
  paymentId: "pi_topup1",
@@ -32,6 +43,8 @@ export function creditFixture() {
32
43
  metadata: {} as Record<string, string>,
33
44
  };
34
45
  const f = fixture(false, false, async (input, init) => {
46
+ const override = await intercept?.(input, init);
47
+ if (override) return override;
35
48
  const path = new URL(input).pathname,
36
49
  method = init?.method ?? "GET",
37
50
  body = new URLSearchParams(String(init?.body ?? ""));
@@ -219,7 +232,7 @@ export function creditFixture() {
219
232
  id: state.paymentId,
220
233
  object: "payment_intent",
221
234
  customer_account: state.wrongPayer ? "acct_other" : "acct_buyer",
222
- customer: "cus_buyer",
235
+ customer: state.paymentCustomer,
223
236
  livemode: false,
224
237
  currency: "usd",
225
238
  amount: 20,
@@ -244,8 +257,20 @@ export function creditFixture() {
244
257
  currency: "usd",
245
258
  livemode: false,
246
259
  refunded: state.refunded,
247
- amount_refunded: state.refunded ? 20 : 0,
248
- disputed: false,
260
+ amount_refunded: state.refunded ? 20 : state.refundedAmount,
261
+ disputed: state.disputed,
262
+ customer: state.chargeCustomer,
263
+ balance_transaction: state.feePending
264
+ ? null
265
+ : {
266
+ id: "txn_topup1",
267
+ object: "balance_transaction",
268
+ source: "ch_topup1",
269
+ currency: "usd",
270
+ amount: 20,
271
+ fee: state.processingFee,
272
+ net: 20 - state.processingFee,
273
+ },
249
274
  }
250
275
  : null,
251
276
  };
@@ -99,3 +99,12 @@ export type {
99
99
  UsageCorrectionHistoryPage,
100
100
  UsageCorrectionHistoryRecord,
101
101
  } from "./correctionRead.js";
102
+
103
+ export type {
104
+ UsageInvoiceSaleOptions,
105
+ VerifiedUsageInvoiceSale,
106
+ } from "./invoiceSale.js";
107
+ export type { UsageInvoiceSettlementOptions } from "./settlement.js";
108
+ export type { UsageCreditRevenue } from "./creditRevenue.js";
109
+
110
+ export type { UsageCreditSettlementOptions } from "./creditSettlement.js";
@@ -0,0 +1,103 @@
1
+ import { fixture as sourceFixture } from "../paymentSource/resolver.fixtures.js";
2
+ import { prepareUsageRecord } from "./records.js";
3
+ export function fixture() {
4
+ const f = sourceFixture();
5
+ const scope = {
6
+ stripeAccountId: "acct_platform",
7
+ customerAccount: "acct_customer",
8
+ meterId: "mtr_calls",
9
+ livemode: false,
10
+ };
11
+ const period = { start: 600, end: 1200 };
12
+ const binding = prepareUsageRecord({
13
+ scope,
14
+ binding: {
15
+ stripeCustomerId: "cus_buyer",
16
+ stripePriceId: "price_original",
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: "proof",
27
+ quantity: "0",
28
+ occurredAt: 600,
29
+ }).binding;
30
+ const meter = {
31
+ id: "mtr_calls",
32
+ livemode: false,
33
+ status: "active",
34
+ event_name: "calls",
35
+ default_aggregation: { formula: "sum" },
36
+ customer_mapping: {
37
+ type: "by_id",
38
+ event_payload_key: "stripe_customer_id",
39
+ },
40
+ value_settings: { event_payload_key: "value" },
41
+ event_time_window: null,
42
+ };
43
+ const price = {
44
+ id: "price_original",
45
+ active: true,
46
+ livemode: false,
47
+ currency: "usd",
48
+ type: "recurring",
49
+ product: "prod_original",
50
+ lookup_key: "calls",
51
+ billing_scheme: "per_unit",
52
+ unit_amount_decimal: "2",
53
+ transform_quantity: null,
54
+ recurring: {
55
+ interval: "month",
56
+ interval_count: 1,
57
+ usage_type: "metered",
58
+ meter: "mtr_calls",
59
+ },
60
+ };
61
+ f.extra.set("/v1/account", { id: "acct_platform" });
62
+ f.extra.set("/v1/balance", { livemode: false });
63
+ f.extra.set("/v1/billing/meters/mtr_calls", meter);
64
+ f.extra.set("/v1/customers/acct_customer", {
65
+ id: "cus_buyer",
66
+ customer_account: "acct_customer",
67
+ livemode: false,
68
+ });
69
+ f.extra.set("/v1/prices/price_original", price);
70
+ Object.assign(f.payment, { customer: "cus_buyer" });
71
+ Object.assign(f.payment.latest_charge, {
72
+ customer: "cus_buyer",
73
+ refunded: false,
74
+ });
75
+ Object.assign(f.subscription, { customer: "cus_buyer" });
76
+ Object.assign(f.line, {
77
+ period,
78
+ quantity: null,
79
+ quantity_decimal: "500",
80
+ pretax_credit_amounts: [],
81
+ });
82
+ Object.assign(f.invoice, {
83
+ customer: "cus_buyer",
84
+ status_transitions: { finalized_at: 1200 },
85
+ lines: { data: [f.line], has_more: false },
86
+ });
87
+ const input = {
88
+ scope,
89
+ binding,
90
+ subscription: {
91
+ subscriptionId: "sub_source",
92
+ subscriptionItemId: "si_source",
93
+ stripePriceId: "price_original",
94
+ period,
95
+ interval: "month" as const,
96
+ },
97
+ period,
98
+ invoiceId: "in_source",
99
+ paymentIntentId: "pi_source",
100
+ gross: 1000,
101
+ };
102
+ return { ...f, meter, price, input };
103
+ }
@@ -0,0 +1,184 @@
1
+ import { BetterStripe } from "../index.js";
2
+ import { componentsGeneric } from "convex/server";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import { expect, it } from "vitest";
5
+ import { fixture } from "./invoiceSale.fixtures.js";
6
+ import { getUsageInvoiceSale } from "./invoiceSale.js";
7
+ it("resolves original metered invoice funding and actual costs even after current subscription prices change", async () => {
8
+ const f = fixture();
9
+ expect(await getUsageInvoiceSale(f.sdk, f.input)).toMatchObject({
10
+ status: "ready",
11
+ value: {
12
+ meterId: "mtr_calls",
13
+ stripePriceId: "price_original",
14
+ stripeProductId: "prod_original",
15
+ invoicePaymentId: "inpay_source",
16
+ gross: 1000,
17
+ processingFee: 50,
18
+ period: { start: 600, end: 1200 },
19
+ },
20
+ });
21
+ expect(
22
+ f.requests.every((r) => r.method === "GET" && r.account === "undefined"),
23
+ ).toBe(true);
24
+ });
25
+
26
+ it("verifies included-overage cash against its original graduated price", async () => {
27
+ const f = fixture();
28
+ const plan = {
29
+ ...f.input.binding.plan,
30
+ model: "included_overage" as const,
31
+ includedQuantity: "10",
32
+ reset: "billing_period" as const,
33
+ };
34
+ Object.assign(f.price, {
35
+ billing_scheme: "tiered",
36
+ tiers_mode: "graduated",
37
+ unit_amount_decimal: null,
38
+ tiers: [
39
+ { up_to: 10, unit_amount_decimal: "0", flat_amount: null },
40
+ { up_to: null, unit_amount_decimal: "2", flat_amount: null },
41
+ ],
42
+ });
43
+ expect(
44
+ await getUsageInvoiceSale(f.sdk, {
45
+ ...f.input,
46
+ binding: { ...f.input.binding, plan },
47
+ }),
48
+ ).toMatchObject({
49
+ status: "ready",
50
+ value: { model: "included_overage", gross: 1000 },
51
+ });
52
+ });
53
+ it("does not recognize zero invoices, credit consumption, refunds, disputes or incomplete funding as a new sale", async () => {
54
+ for (const condition of [
55
+ "zero",
56
+ "prepaid",
57
+ "refund",
58
+ "dispute",
59
+ "incomplete",
60
+ "automatic_transfer",
61
+ ]) {
62
+ const f = fixture();
63
+ if (condition === "zero") f.invoice.amount_paid = 0;
64
+ if (condition === "refund") f.payment.latest_charge.amount_refunded = 100;
65
+ if (condition === "dispute") f.payment.latest_charge.disputed = true;
66
+ if (condition === "incomplete")
67
+ f.pages.set("funding:", { data: [f.funding], has_more: true });
68
+ if (condition === "automatic_transfer")
69
+ Object.assign(f.payment, {
70
+ transfer_data: { destination: "acct_seller" },
71
+ });
72
+ const input =
73
+ condition === "prepaid"
74
+ ? {
75
+ ...f.input,
76
+ binding: {
77
+ ...f.input.binding,
78
+ plan: {
79
+ ...f.input.binding.plan,
80
+ model: "prepaid" as const,
81
+ insufficientBalance: "reject" as const,
82
+ },
83
+ },
84
+ }
85
+ : f.input;
86
+ expect((await getUsageInvoiceSale(f.sdk, input)).status).not.toBe("ready");
87
+ expect(f.requests.every((r) => r.method === "GET")).toBe(true);
88
+ }
89
+ });
90
+ it("rejects foreign original bindings, periods and mapped payer identities", async () => {
91
+ for (const condition of [
92
+ "realm",
93
+ "mode",
94
+ "payer",
95
+ "customer",
96
+ "meter",
97
+ "price_meter",
98
+ "product",
99
+ "period",
100
+ "item",
101
+ "proration",
102
+ ]) {
103
+ const f = fixture();
104
+ if (condition === "realm")
105
+ f.extra.set("/v1/account", { id: "acct_foreign" });
106
+ if (condition === "mode") f.payment.livemode = true;
107
+ if (condition === "payer") f.invoice.customer_account = "acct_other";
108
+ if (condition === "customer")
109
+ Object.assign(f.payment.latest_charge, { customer: "cus_other" });
110
+ if (condition === "meter") f.meter.id = "mtr_other";
111
+ if (condition === "price_meter") f.price.recurring.meter = "mtr_other";
112
+ if (condition === "product")
113
+ f.line.pricing.price_details.product = "prod_other";
114
+ if (condition === "period")
115
+ Object.assign(f.line, { period: { start: 1200, end: 1800 } });
116
+ if (condition === "item")
117
+ f.line.parent.subscription_item_details.subscription_item = "si_other";
118
+ if (condition === "proration")
119
+ f.line.parent.subscription_item_details.proration = true;
120
+ expect(
121
+ (await getUsageInvoiceSale(f.sdk, f.input)).status,
122
+ condition,
123
+ ).not.toBe("ready");
124
+ }
125
+ });
126
+
127
+ it("can settle original paid invoices after their immutable price is archived", async () => {
128
+ const f = fixture();
129
+ f.price.active = false;
130
+ expect(await getUsageInvoiceSale(f.sdk, f.input)).toMatchObject({
131
+ status: "ready",
132
+ value: { stripePriceId: "price_original" },
133
+ });
134
+ });
135
+
136
+ it("requires the complete original invoice-line read to retain the same item and billing period", async () => {
137
+ for (const change of ["item", "period", "id"]) {
138
+ const f = fixture();
139
+ const line = structuredClone(f.line);
140
+ if (change === "item")
141
+ line.parent.subscription_item_details.subscription_item = "si_other";
142
+ if (change === "period")
143
+ Object.assign(line, { period: { start: 1200, end: 1800 } });
144
+ if (change === "id") line.id = "il_other";
145
+ f.extra.set("/v1/invoices/in_source/lines", {
146
+ object: "list",
147
+ data: [line],
148
+ has_more: false,
149
+ });
150
+ expect((await getUsageInvoiceSale(f.sdk, f.input)).status, change).not.toBe(
151
+ "ready",
152
+ );
153
+ }
154
+ });
155
+
156
+ it("keeps an unpaid invoice pending until native payment is verified", async () => {
157
+ const f = fixture();
158
+ f.invoice.status = "open";
159
+ f.invoice.amount_paid = 0;
160
+ expect(await getUsageInvoiceSale(f.sdk, f.input)).toEqual({
161
+ status: "not_ready",
162
+ reason: "provider_pending",
163
+ retryable: true,
164
+ });
165
+ });
166
+
167
+ it("exposes the scoped reader through stripe.usage with runtime-only credentials and the original API version", async () => {
168
+ const f = fixture(),
169
+ client = new BetterStripe(
170
+ componentsGeneric().betterStripe as unknown as Component,
171
+ );
172
+ expect(
173
+ await client.usage.getInvoiceSale({} as RunCtx, f.input, {
174
+ stripeSecretKey: "sk_test_usage_sale",
175
+ httpClient: f.httpClient,
176
+ }),
177
+ ).toMatchObject({ status: "ready" });
178
+ expect(
179
+ f.requests.every(
180
+ (r) =>
181
+ r.version === f.input.binding.apiVersion && r.account === "undefined",
182
+ ),
183
+ ).toBe(true);
184
+ });
@@ -0,0 +1,155 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+ import type {
4
+ FinancialOutcome,
5
+ FinancialUnavailable,
6
+ } from "../financialOutcomes/contracts.js";
7
+ import { resolveVerifiedPaymentSource } from "../paymentSource/resolver.js";
8
+ import type { VerifiedPaymentSource } from "../paymentSource/contracts.js";
9
+ import {
10
+ observationOptions,
11
+ type UsageObservationOptions,
12
+ } from "./observationTypes.js";
13
+ import { observeUsageInvoice } from "./invoiceObservation.js";
14
+ import { verifyPinnedUsagePrice } from "./catalogPrices.js";
15
+ export type UsageInvoiceSaleOptions = UsageObservationOptions & {
16
+ invoiceId: string;
17
+ paymentIntentId: string;
18
+ gross: number;
19
+ };
20
+ export type VerifiedUsageInvoiceSale = VerifiedPaymentSource & {
21
+ stripeAccountId: string;
22
+ meterId: string;
23
+ subscriptionItemId: string;
24
+ period: { start: number; end: number };
25
+ model: "pay_as_you_go" | "included_overage";
26
+ };
27
+ const unsupported = (): FinancialUnavailable => ({
28
+ status: "rejected",
29
+ reason: "unsupported_source",
30
+ retryable: false,
31
+ });
32
+ /** Native invoice/payment provenance only. Host authorizes original seller/product policy. */
33
+ export async function getUsageInvoiceSale(
34
+ stripe: Stripe,
35
+ input: UsageInvoiceSaleOptions,
36
+ ): Promise<FinancialOutcome<VerifiedUsageInvoiceSale>> {
37
+ try {
38
+ const opts = observationOptions(input);
39
+ z.string()
40
+ .regex(/^pi_[a-zA-Z0-9]+$/)
41
+ .max(100)
42
+ .parse(input.paymentIntentId);
43
+ if (opts.binding.plan.model === "prepaid") return unsupported();
44
+ const invoice = await observeUsageInvoice(stripe, opts, input.invoiceId);
45
+ if (invoice.status !== "available") return unsupported();
46
+ const value = invoice.value;
47
+ if (value.status === "draft" || value.status === "open")
48
+ return {
49
+ status: "not_ready",
50
+ reason: "provider_pending",
51
+ retryable: true,
52
+ };
53
+ if (
54
+ value.status !== "paid" ||
55
+ !value.finalized ||
56
+ BigInt(value.amountPaid) <= 0n
57
+ )
58
+ return {
59
+ status: "rejected",
60
+ reason: "payment_not_payable",
61
+ retryable: false,
62
+ };
63
+ const line = value.lines[0];
64
+ if (
65
+ !value.linesComplete ||
66
+ value.meterAmount.status !== "available" ||
67
+ value.lines.length !== 1 ||
68
+ !line ||
69
+ line.proration ||
70
+ line.creditAppliedAmount !== "0" ||
71
+ line.nativePeriod.start !== opts.subscription.period.start ||
72
+ line.nativePeriod.end !== opts.subscription.period.end ||
73
+ opts.period.start !== opts.subscription.period.start ||
74
+ opts.period.end !== opts.subscription.period.end
75
+ )
76
+ return unsupported();
77
+ const [price, customer] = await Promise.all([
78
+ stripe.prices.retrieve(opts.binding.stripePriceId, { expand: ["tiers"] }),
79
+ stripe.customers.retrieve(opts.scope.customerAccount),
80
+ ]);
81
+ if (
82
+ price.id !== opts.binding.stripePriceId ||
83
+ customer.deleted ||
84
+ customer.id !== opts.binding.stripeCustomerId ||
85
+ customer.customer_account !== opts.scope.customerAccount ||
86
+ customer.livemode !== opts.scope.livemode
87
+ )
88
+ return {
89
+ status: "conflict",
90
+ reason: "identity_changed",
91
+ retryable: false,
92
+ };
93
+ verifyPinnedUsagePrice(
94
+ price,
95
+ {
96
+ stripeAccountId: opts.scope.stripeAccountId,
97
+ livemode: opts.scope.livemode,
98
+ },
99
+ opts.binding.plan,
100
+ opts.scope.meterId,
101
+ false,
102
+ );
103
+ const source = await resolveVerifiedPaymentSource(
104
+ stripe,
105
+ {
106
+ paymentIntentId: input.paymentIntentId,
107
+ invoiceId: input.invoiceId,
108
+ subscriptionId: opts.subscription.subscriptionId,
109
+ customerAccountId: opts.scope.customerAccount,
110
+ gross: input.gross,
111
+ currency: opts.binding.plan.rate.currency,
112
+ },
113
+ {
114
+ requirePayable: true,
115
+ customerId: opts.binding.stripeCustomerId,
116
+ invoiceLine: {
117
+ id: line.lineId,
118
+ subscriptionItemId: opts.subscription.subscriptionItemId,
119
+ period: opts.subscription.period,
120
+ },
121
+ },
122
+ );
123
+ if (source.status !== "ready") return source;
124
+ const productId =
125
+ typeof price.product === "string" ? price.product : price.product.id;
126
+ if (
127
+ source.value.stripePriceId !== opts.binding.stripePriceId ||
128
+ source.value.stripeProductId !== productId ||
129
+ source.value.livemode !== opts.scope.livemode ||
130
+ String(source.value.gross) !== value.amountPaid
131
+ )
132
+ return {
133
+ status: "conflict",
134
+ reason: "identity_changed",
135
+ retryable: false,
136
+ };
137
+ return {
138
+ status: "ready",
139
+ value: {
140
+ ...source.value,
141
+ stripeAccountId: opts.scope.stripeAccountId,
142
+ meterId: opts.scope.meterId,
143
+ subscriptionItemId: opts.subscription.subscriptionItemId,
144
+ period: opts.subscription.period,
145
+ model: opts.binding.plan.model,
146
+ },
147
+ };
148
+ } catch {
149
+ return {
150
+ status: "unknown",
151
+ reason: "provider_outcome_unknown",
152
+ retryable: false,
153
+ };
154
+ }
155
+ }
@@ -0,0 +1,179 @@
1
+ import { expect, it } from "vitest";
2
+ import { componentsGeneric } from "convex/server";
3
+ import { initConvexTest } from "../setup.test.js";
4
+ import { schema, modules } from "../../test.js";
5
+ import type { Component, RunCtx } from "../helpers.js";
6
+ import { fixture } from "./invoiceSale.fixtures.js";
7
+ import { settleUsageInvoice } from "./settlement.js";
8
+ function setup() {
9
+ const f = fixture(),
10
+ t = initConvexTest();
11
+ t.registerComponent("betterStripe", schema, modules);
12
+ const component = componentsGeneric().betterStripe as unknown as Component;
13
+ const native: Record<string, unknown>[] = [];
14
+ f.extra.set("/v1/charges/ch_source", {
15
+ ...f.payment.latest_charge,
16
+ created: 1200,
17
+ });
18
+ f.extra.set("/v1/transfers", (method: string, raw: string) => {
19
+ if (method === "GET")
20
+ return { object: "list", data: native, has_more: false };
21
+ const body = new URLSearchParams(raw);
22
+ const transfer = {
23
+ id: `tr_${native.length}`,
24
+ object: "transfer",
25
+ amount: Number(body.get("amount")),
26
+ currency: body.get("currency"),
27
+ destination: body.get("destination"),
28
+ source_transaction: body.get("source_transaction"),
29
+ transfer_group: body.get("transfer_group"),
30
+ metadata: {
31
+ bsRole: body.get("metadata[bsRole]"),
32
+ bsSourceCharge: body.get("metadata[bsSourceCharge]"),
33
+ },
34
+ };
35
+ native.push(transfer);
36
+ return transfer;
37
+ });
38
+ const input = {
39
+ ...f.input,
40
+ policy: { creatorAccountId: "acct_seller", feeBasisPoints: 900 },
41
+ };
42
+ return { ...f, t, component, native, input };
43
+ }
44
+ it("settles actual paid metered proceeds once using the existing immutable allocation and transfer ledger", async () => {
45
+ const f = setup();
46
+ const first = await f.t.action((ctx) =>
47
+ settleUsageInvoice(f.sdk, f.component, ctx as RunCtx, f.input),
48
+ );
49
+ expect(first).toMatchObject({
50
+ status: "settled",
51
+ gross: 1000,
52
+ processingFee: 50,
53
+ platformNet: 40,
54
+ usageSource: {
55
+ meterId: "mtr_calls",
56
+ invoicePaymentId: "inpay_source",
57
+ stripeProductId: "prod_original",
58
+ },
59
+ transfers: [
60
+ { destinationAccountId: "acct_seller", amount: 910, role: "store" },
61
+ ],
62
+ });
63
+ expect(
64
+ await f.t.action((ctx) =>
65
+ settleUsageInvoice(f.sdk, f.component, ctx as RunCtx, {
66
+ ...f.input,
67
+ policy: { ...f.input.policy, feeBasisPoints: 9900 },
68
+ }),
69
+ ),
70
+ ).toEqual(first);
71
+ expect(f.native).toHaveLength(1);
72
+ });
73
+ it("never creates transfers from a zero invoice or a prepaid consumption invoice", async () => {
74
+ for (const prepaid of [false, true]) {
75
+ const f = setup();
76
+ if (!prepaid) f.invoice.amount_paid = 0;
77
+ const input = prepaid
78
+ ? {
79
+ ...f.input,
80
+ binding: {
81
+ ...f.input.binding,
82
+ plan: {
83
+ ...f.input.binding.plan,
84
+ model: "prepaid" as const,
85
+ insufficientBalance: "reject" as const,
86
+ },
87
+ },
88
+ }
89
+ : f.input;
90
+ expect(
91
+ await f.t.action((ctx) =>
92
+ settleUsageInvoice(f.sdk, f.component, ctx as RunCtx, input),
93
+ ),
94
+ ).toMatchObject({ status: "rejected" });
95
+ expect(f.native).toHaveLength(0);
96
+ }
97
+ });
98
+
99
+ it("keeps a zero initial metered invoice from consuming the one-time affiliate commission", async () => {
100
+ const f = setup();
101
+ const paid = {
102
+ ...f.invoice,
103
+ created: 1200,
104
+ status_transitions: { finalized_at: 1200, paid_at: 1250 },
105
+ };
106
+ f.extra.set("/v1/invoices", {
107
+ object: "list",
108
+ has_more: false,
109
+ data: [
110
+ {
111
+ ...paid,
112
+ id: "in_zero",
113
+ created: 600,
114
+ amount_paid: 0,
115
+ status_transitions: { finalized_at: 600, paid_at: 600 },
116
+ },
117
+ paid,
118
+ ],
119
+ });
120
+ const result = await f.t.action((ctx) =>
121
+ settleUsageInvoice(f.sdk, f.component, ctx as RunCtx, {
122
+ ...f.input,
123
+ policy: {
124
+ ...f.input.policy,
125
+ commissionTerm: "one_time",
126
+ affiliate: {
127
+ destinationAccountId: "acct_affiliate",
128
+ basisPoints: 2000,
129
+ },
130
+ },
131
+ }),
132
+ );
133
+ expect(result).toMatchObject({
134
+ status: "settled",
135
+ transfers: [
136
+ { destinationAccountId: "acct_seller", role: "store", amount: 728 },
137
+ {
138
+ destinationAccountId: "acct_affiliate",
139
+ role: "affiliate",
140
+ amount: 182,
141
+ },
142
+ ],
143
+ });
144
+ expect(f.native).toHaveLength(2);
145
+ });
146
+ it("recovers a native transfer whose ledger write failed without paying the metered invoice twice", async () => {
147
+ const f = setup();
148
+ let fail = true;
149
+ const settle = () =>
150
+ f.t.action((ctx) =>
151
+ settleUsageInvoice(
152
+ f.sdk,
153
+ f.component,
154
+ {
155
+ ...ctx,
156
+ runMutation: async (ref, args) => {
157
+ if (
158
+ fail &&
159
+ String(
160
+ ref[Symbol.for("toReferencePath") as keyof typeof ref],
161
+ ).includes("upsertTransfer")
162
+ ) {
163
+ fail = false;
164
+ throw new Error("receipt storage unavailable");
165
+ }
166
+ return ctx.runMutation(ref, args);
167
+ },
168
+ } as RunCtx,
169
+ f.input,
170
+ ),
171
+ );
172
+ await expect(settle()).rejects.toThrow("receipt storage unavailable");
173
+ expect(f.native).toHaveLength(1);
174
+ expect(await settle()).toMatchObject({
175
+ status: "settled",
176
+ usageSource: { invoicePaymentId: "inpay_source" },
177
+ });
178
+ expect(f.native).toHaveLength(1);
179
+ });