@fantastic.dev/better-stripe 0.71.0 → 0.72.1

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 (106) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/checkoutPages.d.ts.map +1 -1
  4. package/dist/client/billing/checkoutPages.js +0 -1
  5. package/dist/client/billing/checkoutPages.js.map +1 -1
  6. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +524 -50
  7. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  8. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +246 -9
  9. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  10. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +524 -50
  11. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  12. package/dist/client/connect/payoutSyncTestHelpers.d.ts +246 -9
  13. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  14. package/dist/client/paymentSource/resolver.d.ts +6 -1
  15. package/dist/client/paymentSource/resolver.d.ts.map +1 -1
  16. package/dist/client/paymentSource/resolver.js +49 -41
  17. package/dist/client/paymentSource/resolver.js.map +1 -1
  18. package/dist/client/processingCostReconciliation/provider.d.ts.map +1 -1
  19. package/dist/client/processingCostReconciliation/provider.js +14 -2
  20. package/dist/client/processingCostReconciliation/provider.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 +65 -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/recoveryWorkflow/helpers.d.ts +13 -0
  60. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -1
  61. package/dist/component/recoveryWorkflow/mutations.d.ts +13 -0
  62. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -1
  63. package/dist/component/recoveryWorkflow/queries.d.ts +26 -0
  64. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -1
  65. package/dist/component/recoveryWorkflow/schema.d.ts +464 -16
  66. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -1
  67. package/dist/component/schema.d.ts +246 -9
  68. package/dist/component/settlement/mutations.d.ts +26 -0
  69. package/dist/component/settlement/mutations.d.ts.map +1 -1
  70. package/dist/component/settlement/queries.d.ts +13 -0
  71. package/dist/component/settlement/queries.d.ts.map +1 -1
  72. package/dist/component/settlement/schema.d.ts +122 -3
  73. package/dist/component/settlement/schema.d.ts.map +1 -1
  74. package/dist/component/settlement/schema.js +2 -0
  75. package/dist/component/settlement/schema.js.map +1 -1
  76. package/dist/component/usage/allowance.fixtures.d.ts +262 -25
  77. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -1
  78. package/dist/component/usageCredits/accounting.fixtures.d.ts +246 -9
  79. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -1
  80. package/dist/shared/usageInvoiceLines.d.ts +32 -0
  81. package/dist/shared/usageInvoiceLines.d.ts.map +1 -0
  82. package/dist/shared/usageInvoiceLines.js +13 -0
  83. package/dist/shared/usageInvoiceLines.js.map +1 -0
  84. package/docs/checkout-session-pages.md +5 -0
  85. package/docs/evidence/native-metering/mixed-settlement-2026-10-20.json +284 -0
  86. package/docs/metering-setup.md +3 -2
  87. package/docs/usage-example.md +24 -5
  88. package/docs/usage-settlement.md +74 -8
  89. package/docs/usage-verification.md +22 -2
  90. package/package.json +1 -1
  91. package/src/client/billing/checkoutPages.test.ts +20 -1
  92. package/src/client/billing/checkoutPages.ts +0 -1
  93. package/src/client/paymentSource/resolver.ts +80 -59
  94. package/src/client/processingCostReconciliation/provider.ts +20 -2
  95. package/src/client/settlement/execution.ts +2 -0
  96. package/src/client/usage/index.ts +2 -0
  97. package/src/client/usage/invoiceSale.ts +10 -0
  98. package/src/client/usage/mixedInvoice.fixtures.ts +54 -0
  99. package/src/client/usage/mixedInvoiceSale.test.ts +92 -0
  100. package/src/client/usage/mixedInvoiceSale.ts +196 -0
  101. package/src/client/usage/mixedSettlement.test.ts +187 -0
  102. package/src/client/usage/retainedInvoiceSource.ts +118 -0
  103. package/src/client/usage/settlement.ts +47 -9
  104. package/src/component/_generated/component.ts +50 -0
  105. package/src/component/settlement/schema.ts +2 -0
  106. package/src/shared/usageInvoiceLines.ts +14 -0
@@ -50,8 +50,13 @@ export async function resolveVerifiedPaymentSource(
50
50
  stripe: Stripe,
51
51
  input: VerifiedPaymentSourceOptions,
52
52
  eligibility?: {
53
- requirePayable: true;
53
+ requirePayable: boolean;
54
54
  customerId: string;
55
+ /** Internal native-line verifier; never exposed as browser input. */
56
+ verifyInvoiceLines?: (
57
+ invoice: Stripe.Invoice,
58
+ lines: Stripe.InvoiceLineItem[],
59
+ ) => { stripePriceId: string; stripeProductId: string } | null;
55
60
  invoiceLine?: {
56
61
  id: string;
57
62
  zeroAmountLineIds?: string[];
@@ -132,12 +137,13 @@ export async function resolveVerifiedPaymentSource(
132
137
  );
133
138
  const customerAccountId = payment.customer_account!;
134
139
  if (eligibility) {
135
- requireSource(
136
- charge.amount_refunded === 0 &&
137
- charge.disputed === false &&
138
- charge.refunded === false,
139
- reject("payment_not_payable"),
140
- );
140
+ if (eligibility.requirePayable)
141
+ requireSource(
142
+ charge.amount_refunded === 0 &&
143
+ charge.disputed === false &&
144
+ charge.refunded === false,
145
+ reject("payment_not_payable"),
146
+ );
141
147
  requireSource(
142
148
  objectId(payment.customer) === eligibility.customerId &&
143
149
  objectId(charge.customer) === eligibility.customerId,
@@ -326,63 +332,78 @@ export async function resolveVerifiedPaymentSource(
326
332
  ),
327
333
  );
328
334
  if (lines.status !== "complete") return lines;
329
- const zeroIds = eligibility?.invoiceLine?.zeroAmountLineIds ?? [];
330
- const line = zeroIds.length
331
- ? lines.data.find((row) => row.id === eligibility!.invoiceLine!.id)
332
- : lines.data[0];
333
- requireSource(
334
- line &&
335
- (zeroIds.length
336
- ? zeroTierLinesMatch(lines.data, line, zeroIds)
337
- : lines.data.length === 1),
338
- reject("unsupported_source"),
339
- );
340
- if (!line) return reject("unsupported_source");
341
- requireSource(
342
- line.object === "line_item" &&
343
- line.invoice === invoice.id &&
344
- line.livemode === payment.livemode,
345
- identity(),
335
+ const verifiedLines = eligibility?.verifyInvoiceLines?.(
336
+ invoice,
337
+ lines.data,
346
338
  );
347
- requireSource(line.currency === opts.currency, reject("currency_mismatch"));
348
- requireSource(
349
- integer(line.amount) &&
350
- line.amount > 0 &&
351
- (line.quantity_decimal != null
352
- ? /^\d{1,30}(\.\d{1,12})?$/.test(line.quantity_decimal.toString()) &&
353
- /[1-9]/.test(line.quantity_decimal.toString())
354
- : Number.isSafeInteger(line.quantity) && line.quantity! > 0),
355
- reject("unsupported_source"),
356
- );
357
- const parent = line.parent;
358
- if (eligibility?.invoiceLine) {
359
- const expected = eligibility.invoiceLine;
339
+ if (eligibility?.verifyInvoiceLines)
340
+ requireSource(verifiedLines, reject("unsupported_source"));
341
+ let priceId = verifiedLines?.stripePriceId;
342
+ let productId = verifiedLines?.stripeProductId;
343
+ if (!verifiedLines) {
344
+ const zeroIds = eligibility?.invoiceLine?.zeroAmountLineIds ?? [];
345
+ const line = zeroIds.length
346
+ ? lines.data.find((row) => row.id === eligibility!.invoiceLine!.id)
347
+ : lines.data[0];
360
348
  requireSource(
361
- line.id === expected.id &&
362
- line.parent?.subscription_item_details?.subscription_item ===
363
- expected.subscriptionItemId &&
364
- line.period.start === expected.period.start &&
365
- line.period.end === expected.period.end,
349
+ line &&
350
+ (zeroIds.length
351
+ ? zeroTierLinesMatch(lines.data, line, zeroIds)
352
+ : lines.data.length === 1),
353
+ reject("unsupported_source"),
354
+ );
355
+ if (!line) return reject("unsupported_source");
356
+ requireSource(
357
+ line.object === "line_item" &&
358
+ line.invoice === invoice.id &&
359
+ line.livemode === payment.livemode,
366
360
  identity(),
367
361
  );
362
+ requireSource(
363
+ line.currency === opts.currency,
364
+ reject("currency_mismatch"),
365
+ );
366
+ requireSource(
367
+ integer(line.amount) &&
368
+ line.amount > 0 &&
369
+ (line.quantity_decimal != null
370
+ ? /^\d{1,30}(\.\d{1,12})?$/.test(
371
+ line.quantity_decimal.toString(),
372
+ ) && /[1-9]/.test(line.quantity_decimal.toString())
373
+ : Number.isSafeInteger(line.quantity) && line.quantity! > 0),
374
+ reject("unsupported_source"),
375
+ );
376
+ const parent = line.parent;
377
+ if (eligibility?.invoiceLine) {
378
+ const expected = eligibility.invoiceLine;
379
+ requireSource(
380
+ line.id === expected.id &&
381
+ line.parent?.subscription_item_details?.subscription_item ===
382
+ expected.subscriptionItemId &&
383
+ line.period.start === expected.period.start &&
384
+ line.period.end === expected.period.end,
385
+ identity(),
386
+ );
387
+ }
388
+ const lineSubscription =
389
+ parent?.subscription_item_details?.subscription ??
390
+ parent?.invoice_item_details?.subscription ??
391
+ undefined;
392
+ requireSource(lineSubscription === subscriptionId, identity());
393
+ requireSource(
394
+ !parent?.subscription_item_details?.proration &&
395
+ !parent?.invoice_item_details?.proration,
396
+ reject("unsupported_source"),
397
+ );
398
+ const price = line.pricing?.price_details;
399
+ priceId = objectId(price?.price);
400
+ productId = objectId(price?.product);
401
+ requireSource(
402
+ line.pricing?.type === "price_details" && priceId && productId,
403
+ reject("unsupported_source"),
404
+ );
368
405
  }
369
- const lineSubscription =
370
- parent?.subscription_item_details?.subscription ??
371
- parent?.invoice_item_details?.subscription ??
372
- undefined;
373
- requireSource(lineSubscription === subscriptionId, identity());
374
- requireSource(
375
- !parent?.subscription_item_details?.proration &&
376
- !parent?.invoice_item_details?.proration,
377
- reject("unsupported_source"),
378
- );
379
- const price = line.pricing?.price_details;
380
- const priceId = objectId(price?.price);
381
- const productId = objectId(price?.product);
382
- requireSource(
383
- line.pricing?.type === "price_details" && priceId && productId,
384
- reject("unsupported_source"),
385
- );
406
+ requireSource(priceId && productId, reject("unsupported_source"));
386
407
  return {
387
408
  status: "ready",
388
409
  value: {
@@ -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 &&
@@ -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
+ }