@fantastic.dev/better-stripe 0.70.0 → 0.72.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 (112) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +524 -50
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +246 -9
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +524 -50
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +246 -9
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/paymentSource/resolver.d.ts +6 -1
  12. package/dist/client/paymentSource/resolver.d.ts.map +1 -1
  13. package/dist/client/paymentSource/resolver.js +49 -41
  14. package/dist/client/paymentSource/resolver.js.map +1 -1
  15. package/dist/client/processingCostReconciliation/provider.d.ts.map +1 -1
  16. package/dist/client/processingCostReconciliation/provider.js +14 -2
  17. package/dist/client/processingCostReconciliation/provider.js.map +1 -1
  18. package/dist/client/readContracts.d.ts +1 -0
  19. package/dist/client/readContracts.d.ts.map +1 -1
  20. package/dist/client/readContracts.js.map +1 -1
  21. package/dist/client/settlement/authorization.fixture.d.ts +26 -0
  22. package/dist/client/settlement/authorization.fixture.d.ts.map +1 -1
  23. package/dist/client/settlement/execution.d.ts +2 -0
  24. package/dist/client/settlement/execution.d.ts.map +1 -1
  25. package/dist/client/settlement/execution.js.map +1 -1
  26. package/dist/client/usage/index.d.ts +1 -0
  27. package/dist/client/usage/index.d.ts.map +1 -1
  28. package/dist/client/usage/invoiceSale.d.ts +8 -0
  29. package/dist/client/usage/invoiceSale.d.ts.map +1 -1
  30. package/dist/client/usage/invoiceSale.js +3 -0
  31. package/dist/client/usage/invoiceSale.js.map +1 -1
  32. package/dist/client/usage/mixedInvoice.fixtures.d.ts +315 -0
  33. package/dist/client/usage/mixedInvoice.fixtures.d.ts.map +1 -0
  34. package/dist/client/usage/mixedInvoice.fixtures.js +55 -0
  35. package/dist/client/usage/mixedInvoice.fixtures.js.map +1 -0
  36. package/dist/client/usage/mixedInvoiceSale.d.ts +6 -0
  37. package/dist/client/usage/mixedInvoiceSale.d.ts.map +1 -0
  38. package/dist/client/usage/mixedInvoiceSale.js +160 -0
  39. package/dist/client/usage/mixedInvoiceSale.js.map +1 -0
  40. package/dist/client/usage/observationClient.d.ts +2 -2
  41. package/dist/client/usage/observationClient.d.ts.map +1 -1
  42. package/dist/client/usage/retainedInvoiceSource.d.ts +20 -0
  43. package/dist/client/usage/retainedInvoiceSource.d.ts.map +1 -0
  44. package/dist/client/usage/retainedInvoiceSource.js +92 -0
  45. package/dist/client/usage/retainedInvoiceSource.js.map +1 -0
  46. package/dist/client/usage/settlement.d.ts +5 -0
  47. package/dist/client/usage/settlement.d.ts.map +1 -1
  48. package/dist/client/usage/settlement.js +28 -9
  49. package/dist/client/usage/settlement.js.map +1 -1
  50. package/dist/component/_generated/component.d.ts +66 -0
  51. package/dist/component/_generated/component.d.ts.map +1 -1
  52. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  53. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  54. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  55. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  56. package/dist/component/earnings/triggers.d.ts +84 -6
  57. package/dist/component/earnings/triggers.d.ts.map +1 -1
  58. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  59. package/dist/component/products/queries.d.ts +1 -0
  60. package/dist/component/products/queries.d.ts.map +1 -1
  61. package/dist/component/products/queries.js +14 -8
  62. package/dist/component/products/queries.js.map +1 -1
  63. package/dist/component/recoveryWorkflow/helpers.d.ts +13 -0
  64. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -1
  65. package/dist/component/recoveryWorkflow/mutations.d.ts +13 -0
  66. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -1
  67. package/dist/component/recoveryWorkflow/queries.d.ts +26 -0
  68. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -1
  69. package/dist/component/recoveryWorkflow/schema.d.ts +464 -16
  70. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -1
  71. package/dist/component/schema.d.ts +246 -9
  72. package/dist/component/settlement/mutations.d.ts +26 -0
  73. package/dist/component/settlement/mutations.d.ts.map +1 -1
  74. package/dist/component/settlement/queries.d.ts +13 -0
  75. package/dist/component/settlement/queries.d.ts.map +1 -1
  76. package/dist/component/settlement/schema.d.ts +122 -3
  77. package/dist/component/settlement/schema.d.ts.map +1 -1
  78. package/dist/component/settlement/schema.js +2 -0
  79. package/dist/component/settlement/schema.js.map +1 -1
  80. package/dist/component/usage/allowance.fixtures.d.ts +262 -25
  81. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -1
  82. package/dist/component/usageCredits/accounting.fixtures.d.ts +246 -9
  83. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -1
  84. package/dist/shared/usageInvoiceLines.d.ts +32 -0
  85. package/dist/shared/usageInvoiceLines.d.ts.map +1 -0
  86. package/dist/shared/usageInvoiceLines.js +13 -0
  87. package/dist/shared/usageInvoiceLines.js.map +1 -0
  88. package/docs/evidence/native-metering/mixed-settlement-2026-10-20.json +284 -0
  89. package/docs/metering-setup.md +3 -2
  90. package/docs/read-contracts.md +9 -2
  91. package/docs/usage-example.md +24 -5
  92. package/docs/usage-settlement.md +74 -8
  93. package/docs/usage-verification.md +22 -2
  94. package/package.json +1 -1
  95. package/src/client/paymentSource/resolver.ts +80 -59
  96. package/src/client/processingCostReconciliation/provider.ts +20 -2
  97. package/src/client/readContracts.ts +1 -0
  98. package/src/client/readPagination.test.ts +21 -0
  99. package/src/client/settlement/execution.ts +2 -0
  100. package/src/client/usage/index.ts +2 -0
  101. package/src/client/usage/invoiceSale.ts +10 -0
  102. package/src/client/usage/mixedInvoice.fixtures.ts +54 -0
  103. package/src/client/usage/mixedInvoiceSale.test.ts +92 -0
  104. package/src/client/usage/mixedInvoiceSale.ts +196 -0
  105. package/src/client/usage/mixedSettlement.test.ts +187 -0
  106. package/src/client/usage/retainedInvoiceSource.ts +118 -0
  107. package/src/client/usage/settlement.ts +47 -9
  108. package/src/component/_generated/component.ts +51 -0
  109. package/src/component/products/provider-price-pagination.test.ts +174 -0
  110. package/src/component/products/queries.ts +24 -10
  111. package/src/component/settlement/schema.ts +2 -0
  112. package/src/shared/usageInvoiceLines.ts +14 -0
@@ -1,3 +1,4 @@
1
+ import { retainedInvoiceSource } from "../usage/retainedInvoiceSource.js";
1
2
  import { readCollectedInvoiceFunding } from "./invoiceFunding.js";
2
3
  import Stripe from "stripe";
3
4
  import type { Component, RunCtx } from "../helpers.js";
@@ -88,7 +89,7 @@ export async function observeProcessingCostProvider(
88
89
  : unknown;
89
90
  }
90
91
  const input = op.source;
91
- const source = await resolveVerifiedPaymentSource(stripe, {
92
+ const sourceOptions = {
92
93
  paymentIntentId: input.paymentIntentId,
93
94
  gross: input.gross,
94
95
  currency: op.currency,
@@ -100,7 +101,24 @@ export async function observeProcessingCostProvider(
100
101
  : {}),
101
102
  maxHistoryPages: 5,
102
103
  maxHistoryItems: 500,
103
- });
104
+ };
105
+ let source = await resolveVerifiedPaymentSource(stripe, sourceOptions);
106
+ if (
107
+ source.status === "rejected" &&
108
+ source.reason === "unsupported_source"
109
+ ) {
110
+ try {
111
+ source =
112
+ (await retainedInvoiceSource(
113
+ stripe,
114
+ component,
115
+ ctx,
116
+ sourceOptions,
117
+ )) ?? source;
118
+ } catch {
119
+ /* Keep the original held outcome when no sealed mixed proof is available. */
120
+ }
121
+ }
104
122
  if (source.status !== "ready") return { ...echo, outcome: source };
105
123
  if (
106
124
  (input.stripePriceId !== undefined &&
@@ -73,6 +73,7 @@ export class ReadContractClient {
73
73
  ctx: RunCtx,
74
74
  opts: {
75
75
  productId?: string;
76
+ stripeProductId?: string;
76
77
  active?: boolean;
77
78
  paginationOpts: PaginationOptions;
78
79
  },
@@ -60,3 +60,24 @@ it("forwards exact currency summary reads through the public client", async () =
60
60
  { accountId: "acct_a" },
61
61
  );
62
62
  });
63
+
64
+ it("forwards unfiltered provider-product pages and native continuation hints", async () => {
65
+ const bs = new BetterStripe(components.betterStripe);
66
+ const page = {
67
+ page: [],
68
+ isDone: false,
69
+ continueCursor: "next",
70
+ pageStatus: "SplitRequired",
71
+ splitCursor: "split",
72
+ };
73
+ const ctx = { runQuery: vi.fn().mockResolvedValue(page) };
74
+ const options = {
75
+ stripeProductId: "prod_selected",
76
+ paginationOpts: { numItems: 25, cursor: "prior", endCursor: "pinned" },
77
+ };
78
+ expect(await bs.paginatePrices(ctx, options)).toBe(page);
79
+ expect(ctx.runQuery).toHaveBeenCalledExactlyOnceWith(
80
+ components.betterStripe.products.queries.paginatePrices,
81
+ options,
82
+ );
83
+ });
@@ -1,3 +1,4 @@
1
+ import type { UsageInvoiceLineProof } from "../../shared/usageInvoiceLines.js";
1
2
  import {
2
3
  policyContextBinding,
3
4
  type SettlementPolicyContext,
@@ -23,6 +24,7 @@ export type ResolvedSettlement = {
23
24
  paymentIntentId?: string;
24
25
  sourceInvoiceId?: string;
25
26
  usageSource?: {
27
+ invoiceLines?: UsageInvoiceLineProof[];
26
28
  stripeAccountId: string;
27
29
  customerAccount: string;
28
30
  livemode: boolean;
@@ -115,3 +115,5 @@ export type { UsageCreditReconciliation } from "./creditObservation.js";
115
115
  export type { UsageConfigurationValue } from "./configuration.js";
116
116
 
117
117
  export type { UsageViewScope, UsageBillingSnapshot } from "./views.js";
118
+
119
+ export type { UsageInvoiceLineProof } from "../../shared/usageInvoiceLines.js";
@@ -1,3 +1,5 @@
1
+ import { getMixedInvoiceSale } from "./mixedInvoiceSale.js";
2
+ import type { UsageInvoiceLineProof } from "../../shared/usageInvoiceLines.js";
1
3
  import type Stripe from "stripe";
2
4
  import { z } from "zod";
3
5
  import type {
@@ -16,8 +18,15 @@ export type UsageInvoiceSaleOptions = UsageObservationOptions & {
16
18
  invoiceId: string;
17
19
  paymentIntentId: string;
18
20
  gross: number;
21
+ /** Original licensed monthly item for this same product; server-derived enrollment terms. */
22
+ fixedPrice?: {
23
+ stripePriceId: string;
24
+ subscriptionItemId: string;
25
+ unitAmount: number;
26
+ };
19
27
  };
20
28
  export type VerifiedUsageInvoiceSale = VerifiedPaymentSource & {
29
+ invoiceLines?: UsageInvoiceLineProof[];
21
30
  stripeAccountId: string;
22
31
  meterId: string;
23
32
  subscriptionItemId: string;
@@ -36,6 +45,7 @@ export async function getUsageInvoiceSale(
36
45
  ): Promise<FinancialOutcome<VerifiedUsageInvoiceSale>> {
37
46
  try {
38
47
  const opts = observationOptions(input);
48
+ if (input.fixedPrice) return await getMixedInvoiceSale(stripe, input);
39
49
  z.string()
40
50
  .regex(/^pi_[a-zA-Z0-9]+$/)
41
51
  .max(100)
@@ -0,0 +1,54 @@
1
+ import { fixture } from "./invoiceSale.fixtures.js";
2
+ export function mixed() {
3
+ const f = fixture();
4
+ const base = structuredClone(f.line);
5
+ Object.assign(base, {
6
+ id: "il_base",
7
+ amount: 2000,
8
+ quantity: 1,
9
+ quantity_decimal: "1",
10
+ period: { start: 1200, end: 1800 },
11
+ });
12
+ base.parent.subscription_item_details.subscription_item = "si_base";
13
+ base.pricing.price_details.price = "price_base";
14
+ Object.assign(f.invoice, {
15
+ amount_paid: 3000,
16
+ amount_due: 3000,
17
+ total: 3000,
18
+ billing_reason: "subscription_cycle",
19
+ });
20
+ Object.assign(f.payment, { amount: 3000, amount_received: 3000 });
21
+ Object.assign(f.payment.latest_charge, {
22
+ amount: 3000,
23
+ amount_captured: 3000,
24
+ });
25
+ Object.assign(f.payment.latest_charge.balance_transaction, {
26
+ amount: 3000,
27
+ fee: 120,
28
+ net: 2880,
29
+ });
30
+ Object.assign(f.funding, { amount_paid: 3000, amount_requested: 3000 });
31
+ f.extra.set("/v1/prices/price_base", {
32
+ ...f.price,
33
+ id: "price_base",
34
+ unit_amount: 2000,
35
+ unit_amount_decimal: "2000",
36
+ recurring: {
37
+ interval: "month",
38
+ interval_count: 1,
39
+ usage_type: "licensed",
40
+ meter: null,
41
+ },
42
+ });
43
+ f.history.lines.push(base);
44
+ const input = {
45
+ ...f.input,
46
+ gross: 3000,
47
+ fixedPrice: {
48
+ stripePriceId: "price_base",
49
+ subscriptionItemId: "si_base",
50
+ unitAmount: 2000,
51
+ },
52
+ };
53
+ return { ...f, base, input };
54
+ }
@@ -0,0 +1,92 @@
1
+ import { expect, it } from "vitest";
2
+ import { mixed } from "./mixedInvoice.fixtures.js";
3
+ import { getUsageInvoiceSale } from "./invoiceSale.js";
4
+
5
+ it("settles the complete mixed invoice with advance base and arrears usage, using one actual fee", async () => {
6
+ const f = mixed();
7
+ expect(await getUsageInvoiceSale(f.sdk, f.input)).toMatchObject({
8
+ status: "ready",
9
+ value: {
10
+ gross: 3000,
11
+ processingFee: 120,
12
+ invoiceLines: [
13
+ { lineId: "il_base", period: { start: 1200, end: 1800 }, amount: 2000 },
14
+ {
15
+ lineId: "il_source",
16
+ period: { start: 600, end: 1200 },
17
+ amount: 1000,
18
+ },
19
+ ],
20
+ },
21
+ });
22
+ });
23
+ it("recognizes initial base-only cash and paginates full invoice lines", async () => {
24
+ const f = mixed();
25
+ Object.assign(f.line, { amount: 0, quantity_decimal: "0" });
26
+ Object.assign(f.invoice, { billing_reason: "subscription_create" });
27
+ f.base.amount = 3000;
28
+ const basePrice = f.extra.get("/v1/prices/price_base") as Record<
29
+ string,
30
+ unknown
31
+ >;
32
+ Object.assign(basePrice, { unit_amount: 3000, unit_amount_decimal: "3000" });
33
+ f.pages.set("lines:", { data: [f.base], has_more: true });
34
+ f.pages.set("lines:il_base", { data: [f.line], has_more: false });
35
+ expect(
36
+ await getUsageInvoiceSale(f.sdk, {
37
+ ...f.input,
38
+ fixedPrice: { ...f.input.fixedPrice, unitAmount: 3000 },
39
+ }),
40
+ ).toMatchObject({ status: "ready", value: { gross: 3000 } });
41
+ });
42
+ it("holds foreign, duplicate, discounted, taxed, credited or prorated lines without transferring", async () => {
43
+ for (const change of [
44
+ "product",
45
+ "item",
46
+ "extra",
47
+ "discount",
48
+ "tax",
49
+ "credit",
50
+ "proration",
51
+ "amount",
52
+ "duplicate",
53
+ ]) {
54
+ const f = mixed();
55
+ if (change === "product")
56
+ f.base.pricing.price_details.product = "prod_foreign";
57
+ if (change === "item")
58
+ f.base.parent.subscription_item_details.subscription_item = "si_foreign";
59
+ if (change === "extra")
60
+ f.history.lines.push({ ...f.base, id: "il_foreign" });
61
+ if (change === "discount")
62
+ Object.assign(f.base, { discount_amounts: [{ amount: 1 }] });
63
+ if (change === "tax")
64
+ Object.assign(f.invoice, { total_taxes: [{ amount: 1 }] });
65
+ if (change === "credit")
66
+ Object.assign(f.base, { pretax_credit_amounts: [{ amount: 1 }] });
67
+ if (change === "proration")
68
+ f.base.parent.subscription_item_details.proration = true;
69
+ if (change === "amount") f.base.amount--;
70
+ if (change === "duplicate") f.base.id = f.line.id;
71
+ expect((await getUsageInvoiceSale(f.sdk, f.input)).status, change).not.toBe(
72
+ "ready",
73
+ );
74
+ expect(f.requests.every((r) => r.method === "GET")).toBe(true);
75
+ }
76
+ });
77
+
78
+ for (const field of [
79
+ "pre_payment_credit_notes_amount",
80
+ "post_payment_credit_notes_amount",
81
+ ]) {
82
+ it(`holds ${field} even when captured cash has no refund`, async () => {
83
+ const f = mixed();
84
+ Object.assign(f.invoice, { [field]: 700 });
85
+ expect(f.payment.latest_charge.amount_refunded ?? 0).toBe(0);
86
+ expect(await getUsageInvoiceSale(f.sdk, f.input)).toMatchObject({
87
+ status: "rejected",
88
+ reason: "unsupported_source",
89
+ });
90
+ expect(f.requests.every((r) => r.method === "GET")).toBe(true);
91
+ });
92
+ }
@@ -0,0 +1,196 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+ import type { FinancialOutcome } from "../financialOutcomes/contracts.js";
4
+ import { resolveVerifiedPaymentSource } from "../paymentSource/resolver.js";
5
+ import { verifyPinnedUsagePrice } from "./catalogPrices.js";
6
+ import {
7
+ observationOptions,
8
+ verifyObservationSource,
9
+ } from "./observationTypes.js";
10
+ import type {
11
+ UsageInvoiceSaleOptions,
12
+ VerifiedUsageInvoiceSale,
13
+ } from "./invoiceSale.js";
14
+ import type { UsageInvoiceLineProof } from "../../shared/usageInvoiceLines.js";
15
+
16
+ const id = (value: string | { id: string } | null | undefined) =>
17
+ typeof value === "string" ? value : value?.id;
18
+ const fixedTerms = z.strictObject({
19
+ stripePriceId: z
20
+ .string()
21
+ .regex(/^price_[a-zA-Z0-9]+$/)
22
+ .max(100),
23
+ subscriptionItemId: z
24
+ .string()
25
+ .regex(/^si_[a-zA-Z0-9]+$/)
26
+ .max(100),
27
+ unitAmount: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
28
+ });
29
+ const unsupported = () => ({
30
+ status: "rejected" as const,
31
+ reason: "unsupported_source" as const,
32
+ retryable: false as const,
33
+ });
34
+ /** One immutable product, one licensed monthly item and one metered item. */
35
+ export async function getMixedInvoiceSale(
36
+ stripe: Stripe,
37
+ input: UsageInvoiceSaleOptions,
38
+ ): Promise<FinancialOutcome<VerifiedUsageInvoiceSale>> {
39
+ const opts = observationOptions(input),
40
+ fixed = fixedTerms.parse(input.fixedPrice);
41
+ const plan = opts.binding.plan;
42
+ if (
43
+ plan.model === "prepaid" ||
44
+ fixed.subscriptionItemId === opts.subscription.subscriptionItemId ||
45
+ fixed.stripePriceId === opts.binding.stripePriceId ||
46
+ !(await verifyObservationSource(stripe, opts))
47
+ )
48
+ return unsupported();
49
+ const [meterPrice, base, customer] = await Promise.all([
50
+ stripe.prices.retrieve(opts.binding.stripePriceId, { expand: ["tiers"] }),
51
+ stripe.prices.retrieve(fixed.stripePriceId),
52
+ stripe.customers.retrieve(opts.scope.customerAccount),
53
+ ]);
54
+ verifyPinnedUsagePrice(
55
+ meterPrice,
56
+ {
57
+ stripeAccountId: opts.scope.stripeAccountId,
58
+ livemode: opts.scope.livemode,
59
+ },
60
+ plan,
61
+ opts.scope.meterId,
62
+ false,
63
+ );
64
+ const productId = id(meterPrice.product);
65
+ if (
66
+ !productId ||
67
+ meterPrice.id !== opts.binding.stripePriceId ||
68
+ base.id !== fixed.stripePriceId ||
69
+ id(base.product) !== productId ||
70
+ base.livemode !== opts.scope.livemode ||
71
+ base.currency !== plan.rate.currency ||
72
+ base.type !== "recurring" ||
73
+ base.billing_scheme !== "per_unit" ||
74
+ base.unit_amount !== fixed.unitAmount ||
75
+ base.transform_quantity ||
76
+ base.recurring?.usage_type !== "licensed" ||
77
+ base.recurring.interval !== opts.subscription.interval ||
78
+ base.recurring.interval_count !== 1 ||
79
+ customer.deleted ||
80
+ customer.id !== opts.binding.stripeCustomerId ||
81
+ customer.customer_account !== opts.scope.customerAccount ||
82
+ customer.livemode !== opts.scope.livemode
83
+ )
84
+ return unsupported();
85
+ let proof: UsageInvoiceLineProof[] = [];
86
+ const source = await resolveVerifiedPaymentSource(
87
+ stripe,
88
+ {
89
+ paymentIntentId: input.paymentIntentId,
90
+ invoiceId: input.invoiceId,
91
+ subscriptionId: opts.subscription.subscriptionId,
92
+ customerAccountId: opts.scope.customerAccount,
93
+ gross: input.gross,
94
+ currency: plan.rate.currency,
95
+ },
96
+ {
97
+ requirePayable: true,
98
+ customerId: opts.binding.stripeCustomerId,
99
+ verifyInvoiceLines(invoice, lines) {
100
+ if (
101
+ !Number.isSafeInteger(invoice.status_transitions?.finalized_at) ||
102
+ (invoice.starting_balance ?? 0) !== 0 ||
103
+ (invoice.ending_balance ?? 0) !== 0 ||
104
+ (invoice.pre_payment_credit_notes_amount ?? 0) !== 0 ||
105
+ (invoice.post_payment_credit_notes_amount ?? 0) !== 0 ||
106
+ (invoice.total_discount_amounts ?? []).length ||
107
+ (invoice.total_taxes ?? []).length ||
108
+ lines.length < 1 ||
109
+ lines.length > (plan.model === "included_overage" ? 3 : 2)
110
+ )
111
+ return null;
112
+ const result: UsageInvoiceLineProof[] = [];
113
+ for (const line of lines) {
114
+ const parent = line.parent?.subscription_item_details,
115
+ price = line.pricing?.price_details;
116
+ const isBase = id(price?.price) === fixed.stripePriceId;
117
+ const quantity =
118
+ line.quantity_decimal?.toString() ?? String(line.quantity);
119
+ if (
120
+ line.object !== "line_item" ||
121
+ line.invoice !== invoice.id ||
122
+ line.livemode !== opts.scope.livemode ||
123
+ line.currency !== plan.rate.currency ||
124
+ !Number.isSafeInteger(line.amount) ||
125
+ line.amount < 0 ||
126
+ !parent ||
127
+ parent.proration ||
128
+ parent.subscription !== opts.subscription.subscriptionId ||
129
+ parent.subscription_item !==
130
+ (isBase
131
+ ? fixed.subscriptionItemId
132
+ : opts.subscription.subscriptionItemId) ||
133
+ line.pricing?.type !== "price_details" ||
134
+ id(price?.product) !== productId ||
135
+ id(price?.price) !==
136
+ (isBase ? fixed.stripePriceId : opts.binding.stripePriceId) ||
137
+ (line.discount_amounts ?? []).length ||
138
+ (line.pretax_credit_amounts ?? []).length ||
139
+ (line.taxes ?? []).length ||
140
+ !/^\d{1,30}(\.\d{1,12})?$/.test(quantity) ||
141
+ !Number.isSafeInteger(line.period.start) ||
142
+ !Number.isSafeInteger(line.period.end) ||
143
+ line.period.start < 0 ||
144
+ line.period.end <= line.period.start ||
145
+ (isBase && (quantity !== "1" || line.amount !== fixed.unitAmount))
146
+ )
147
+ return null;
148
+ result.push({
149
+ lineId: line.id,
150
+ stripePriceId: id(price!.price)!,
151
+ stripeProductId: productId,
152
+ subscriptionItemId: parent.subscription_item,
153
+ period: { ...line.period },
154
+ amount: line.amount,
155
+ quantity,
156
+ kind: isBase ? "fixed" : "metered",
157
+ });
158
+ }
159
+ const bases = result.filter((l) => l.kind === "fixed"),
160
+ meters = result.filter((l) => l.kind === "metered");
161
+ if (
162
+ bases.length !== 1 ||
163
+ (!meters.length &&
164
+ invoice.billing_reason !== "subscription_create") ||
165
+ meters.filter((l) => l.amount > 0).length > 1 ||
166
+ (meters.length === 2 &&
167
+ (plan.model !== "included_overage" ||
168
+ meters[0].period.start !== meters[1].period.start ||
169
+ meters[0].period.end !== meters[1].period.end)) ||
170
+ result.reduce((sum, l) => sum + BigInt(l.amount), 0n) !==
171
+ BigInt(input.gross)
172
+ )
173
+ return null;
174
+ proof = result.sort((a, b) => a.lineId.localeCompare(b.lineId));
175
+ return {
176
+ stripePriceId: opts.binding.stripePriceId,
177
+ stripeProductId: productId,
178
+ };
179
+ },
180
+ },
181
+ );
182
+ if (source.status !== "ready") return source;
183
+ if (source.value.livemode !== opts.scope.livemode) return unsupported();
184
+ return {
185
+ status: "ready",
186
+ value: {
187
+ ...source.value,
188
+ stripeAccountId: opts.scope.stripeAccountId,
189
+ meterId: opts.scope.meterId,
190
+ subscriptionItemId: opts.subscription.subscriptionItemId,
191
+ period: (proof.find((l) => l.kind === "metered") ?? proof[0]).period,
192
+ model: plan.model,
193
+ invoiceLines: proof,
194
+ },
195
+ };
196
+ }
@@ -0,0 +1,187 @@
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 { mixed } from "./mixedInvoice.fixtures.js";
7
+ import { settleUsageInvoice } from "./settlement.js";
8
+ import { retainedInvoiceSource } from "./retainedInvoiceSource.js";
9
+ function setup() {
10
+ const f = mixed(),
11
+ t = initConvexTest();
12
+ t.registerComponent("betterStripe", schema, modules);
13
+ const component = componentsGeneric().betterStripe as unknown as Component;
14
+ const native: Record<string, unknown>[] = [];
15
+ f.extra.set("/v1/charges/ch_source", {
16
+ ...f.payment.latest_charge,
17
+ created: 1200,
18
+ });
19
+ f.extra.set("/v1/transfers", (method: string, raw: string) => {
20
+ if (method === "GET")
21
+ return { object: "list", data: native, has_more: false };
22
+ const body = new URLSearchParams(raw);
23
+ const transfer = {
24
+ id: `tr_${native.length}`,
25
+ object: "transfer",
26
+ amount: Number(body.get("amount")),
27
+ currency: body.get("currency"),
28
+ destination: body.get("destination"),
29
+ source_transaction: body.get("source_transaction"),
30
+ transfer_group: body.get("transfer_group"),
31
+ metadata: {
32
+ bsRole: body.get("metadata[bsRole]"),
33
+ bsSourceCharge: body.get("metadata[bsSourceCharge]"),
34
+ },
35
+ };
36
+ native.push(transfer);
37
+ return transfer;
38
+ });
39
+ const input = {
40
+ ...f.input,
41
+ policy: { creatorAccountId: "acct_seller", feeBasisPoints: 900 },
42
+ };
43
+ return { ...f, t, component, native, input };
44
+ }
45
+ it("retains complete mixed lineage, conserves whole proceeds, and recovers a lost receipt without a second transfer", async () => {
46
+ const f = setup();
47
+ let fail = true;
48
+ const settle = () =>
49
+ f.t.action((ctx) =>
50
+ settleUsageInvoice(
51
+ f.sdk,
52
+ f.component,
53
+ {
54
+ ...ctx,
55
+ runMutation: async (ref, args) => {
56
+ if (
57
+ fail &&
58
+ String(
59
+ ref[Symbol.for("toReferencePath") as keyof typeof ref],
60
+ ).includes("upsertTransfer")
61
+ ) {
62
+ fail = false;
63
+ throw new Error("lost receipt");
64
+ }
65
+ return ctx.runMutation(ref, args);
66
+ },
67
+ } as RunCtx,
68
+ f.input,
69
+ ),
70
+ );
71
+ await expect(settle()).rejects.toThrow("lost receipt");
72
+ expect(f.native).toHaveLength(1);
73
+ const result = await settle();
74
+ expect(result).toMatchObject({
75
+ status: "settled",
76
+ gross: 3000,
77
+ processingFee: 120,
78
+ platformNet: 150,
79
+ transfers: [{ amount: 2730 }],
80
+ usageSource: {
81
+ invoiceLines: [
82
+ { lineId: "il_base", amount: 2000 },
83
+ { lineId: "il_source", amount: 1000 },
84
+ ],
85
+ },
86
+ });
87
+ expect(f.native).toHaveLength(1);
88
+ Object.assign(f.line, { period: { start: 601, end: 1200 } });
89
+ await expect(settle()).rejects.toThrow(/source identity/i);
90
+ expect(f.native).toHaveLength(1);
91
+ });
92
+ it("reauthorizes at reserve and before a new transfer, holding a seller remap", async () => {
93
+ const f = setup();
94
+ const phases: string[] = [];
95
+ await expect(
96
+ f.t.action((ctx) =>
97
+ settleUsageInvoice(f.sdk, f.component, ctx as RunCtx, {
98
+ ...f.input,
99
+ authorize: async (context) => {
100
+ phases.push(context.phase);
101
+ if (context.phase === "transfer") throw new Error("seller remapped");
102
+ },
103
+ }),
104
+ ),
105
+ ).rejects.toThrow("seller remapped");
106
+ expect(phases).toEqual(["reserve", "transfer"]);
107
+ expect(f.native).toHaveLength(0);
108
+ });
109
+ it("allows refund/dispute cost reads only against sealed complete native lines and never recognizes refund proceeds as a new sale", async () => {
110
+ const f = setup();
111
+ await f.t.action((ctx) =>
112
+ settleUsageInvoice(f.sdk, f.component, ctx as RunCtx, f.input),
113
+ );
114
+ Object.assign(f.payment.latest_charge, {
115
+ amount_refunded: 700,
116
+ disputed: true,
117
+ });
118
+ const read = () =>
119
+ f.t.action((ctx) =>
120
+ retainedInvoiceSource(f.sdk, f.component, ctx as RunCtx, {
121
+ paymentIntentId: "pi_source",
122
+ customerAccountId: "acct_customer",
123
+ gross: 3000,
124
+ currency: "usd",
125
+ }),
126
+ );
127
+ expect(await read()).toMatchObject({
128
+ status: "ready",
129
+ value: { gross: 3000, processingFee: 120 },
130
+ });
131
+ expect(
132
+ await f.t.action((ctx) =>
133
+ settleUsageInvoice(f.sdk, f.component, ctx as RunCtx, f.input),
134
+ ),
135
+ ).toMatchObject({ status: "rejected", reason: "payment_not_payable" });
136
+ f.base.pricing.price_details.product = "prod_foreign";
137
+ expect(await read()).toMatchObject({ status: "rejected" });
138
+ expect(f.native).toHaveLength(1);
139
+ });
140
+
141
+ it("rejects a substituted original funding receipt during recovery", async () => {
142
+ const f = setup();
143
+ await f.t.action((ctx) =>
144
+ settleUsageInvoice(f.sdk, f.component, ctx as RunCtx, f.input),
145
+ );
146
+ f.funding.id = "inpay_substituted";
147
+ const result = await f.t.action((ctx) =>
148
+ retainedInvoiceSource(f.sdk, f.component, ctx as RunCtx, {
149
+ paymentIntentId: "pi_source",
150
+ customerAccountId: "acct_customer",
151
+ gross: 3000,
152
+ currency: "usd",
153
+ }),
154
+ );
155
+ expect(result).toMatchObject({
156
+ status: "conflict",
157
+ reason: "identity_changed",
158
+ });
159
+ expect(f.native).toHaveLength(1);
160
+ });
161
+
162
+ for (const field of [
163
+ "pre_payment_credit_notes_amount",
164
+ "post_payment_credit_notes_amount",
165
+ ]) {
166
+ it(`holds sealed recovery with ${field} and no charge refund`, async () => {
167
+ const f = setup();
168
+ await f.t.action((ctx) =>
169
+ settleUsageInvoice(f.sdk, f.component, ctx as RunCtx, f.input),
170
+ );
171
+ Object.assign(f.invoice, { [field]: 700 });
172
+ expect(f.payment.latest_charge.amount_refunded ?? 0).toBe(0);
173
+ const result = await f.t.action((ctx) =>
174
+ retainedInvoiceSource(f.sdk, f.component, ctx as RunCtx, {
175
+ paymentIntentId: "pi_source",
176
+ customerAccountId: "acct_customer",
177
+ gross: 3000,
178
+ currency: "usd",
179
+ }),
180
+ );
181
+ expect(result).toMatchObject({
182
+ status: "rejected",
183
+ reason: "unsupported_source",
184
+ });
185
+ expect(f.native).toHaveLength(1);
186
+ });
187
+ }