@fantastic.dev/better-stripe 0.81.0 → 0.83.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 (110) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAggregate/configure.d.ts +35 -0
  4. package/dist/client/billing/renewalAggregate/configure.d.ts.map +1 -0
  5. package/dist/client/billing/renewalAggregate/configure.js +96 -0
  6. package/dist/client/billing/renewalAggregate/configure.js.map +1 -0
  7. package/dist/client/billing/renewalAggregate/index.d.ts +3 -0
  8. package/dist/client/billing/renewalAggregate/index.d.ts.map +1 -0
  9. package/dist/client/billing/renewalAggregate/index.js +3 -0
  10. package/dist/client/billing/renewalAggregate/index.js.map +1 -0
  11. package/dist/client/billing/renewalAggregate/phaseContext.d.ts +176 -0
  12. package/dist/client/billing/renewalAggregate/phaseContext.d.ts.map +1 -0
  13. package/dist/client/billing/renewalAggregate/phaseContext.js +112 -0
  14. package/dist/client/billing/renewalAggregate/phaseContext.js.map +1 -0
  15. package/dist/client/billing/renewalAggregate/phases.d.ts +7 -0
  16. package/dist/client/billing/renewalAggregate/phases.d.ts.map +1 -0
  17. package/dist/client/billing/renewalAggregate/phases.js +192 -0
  18. package/dist/client/billing/renewalAggregate/phases.js.map +1 -0
  19. package/dist/client/billing/renewalAggregate/preflight.d.ts +594 -0
  20. package/dist/client/billing/renewalAggregate/preflight.d.ts.map +1 -0
  21. package/dist/client/billing/renewalAggregate/preflight.js +164 -0
  22. package/dist/client/billing/renewalAggregate/preflight.js.map +1 -0
  23. package/dist/client/billing/renewalAggregate/profile.d.ts +8 -0
  24. package/dist/client/billing/renewalAggregate/profile.d.ts.map +1 -0
  25. package/dist/client/billing/renewalAggregate/profile.js +60 -0
  26. package/dist/client/billing/renewalAggregate/profile.js.map +1 -0
  27. package/dist/client/billing/renewalAggregate/receipt.d.ts +40 -0
  28. package/dist/client/billing/renewalAggregate/receipt.d.ts.map +1 -0
  29. package/dist/client/billing/renewalAggregate/receipt.js +62 -0
  30. package/dist/client/billing/renewalAggregate/receipt.js.map +1 -0
  31. package/dist/client/billing/renewalAggregate/shared.d.ts +51 -0
  32. package/dist/client/billing/renewalAggregate/shared.d.ts.map +1 -0
  33. package/dist/client/billing/renewalAggregate/shared.js +87 -0
  34. package/dist/client/billing/renewalAggregate/shared.js.map +1 -0
  35. package/dist/client/billing/renewalAggregate/sourceDiscounts.d.ts +42 -0
  36. package/dist/client/billing/renewalAggregate/sourceDiscounts.d.ts.map +1 -0
  37. package/dist/client/billing/renewalAggregate/sourceDiscounts.js +90 -0
  38. package/dist/client/billing/renewalAggregate/sourceDiscounts.js.map +1 -0
  39. package/dist/client/billing/renewalAggregate/sourceSettings.d.ts +136 -0
  40. package/dist/client/billing/renewalAggregate/sourceSettings.d.ts.map +1 -0
  41. package/dist/client/billing/renewalAggregate/sourceSettings.js +82 -0
  42. package/dist/client/billing/renewalAggregate/sourceSettings.js.map +1 -0
  43. package/dist/client/billing/renewalAggregate/taxRetention.d.ts +8 -0
  44. package/dist/client/billing/renewalAggregate/taxRetention.d.ts.map +1 -0
  45. package/dist/client/billing/renewalAggregate/taxRetention.js +23 -0
  46. package/dist/client/billing/renewalAggregate/taxRetention.js.map +1 -0
  47. package/dist/client/billing/renewalAttach/couponJoins.d.ts +23 -0
  48. package/dist/client/billing/renewalAttach/couponJoins.d.ts.map +1 -0
  49. package/dist/client/billing/renewalAttach/couponJoins.js +76 -0
  50. package/dist/client/billing/renewalAttach/couponJoins.js.map +1 -0
  51. package/dist/client/billing/renewalAttach/index.d.ts +3 -0
  52. package/dist/client/billing/renewalAttach/index.d.ts.map +1 -0
  53. package/dist/client/billing/renewalAttach/index.js +3 -0
  54. package/dist/client/billing/renewalAttach/index.js.map +1 -0
  55. package/dist/client/billing/renewalAttach/reader.d.ts +141 -0
  56. package/dist/client/billing/renewalAttach/reader.d.ts.map +1 -0
  57. package/dist/client/billing/renewalAttach/reader.js +80 -0
  58. package/dist/client/billing/renewalAttach/reader.js.map +1 -0
  59. package/dist/client/billing/renewalAttach/request.d.ts +30 -0
  60. package/dist/client/billing/renewalAttach/request.d.ts.map +1 -0
  61. package/dist/client/billing/renewalAttach/request.js +39 -0
  62. package/dist/client/billing/renewalAttach/request.js.map +1 -0
  63. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  64. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  65. package/dist/client/index.d.ts +3 -5
  66. package/dist/client/index.d.ts.map +1 -1
  67. package/dist/client/index.js +3 -3
  68. package/dist/client/index.js.map +1 -1
  69. package/dist/client/renewal.d.ts +8 -0
  70. package/dist/client/renewal.d.ts.map +1 -0
  71. package/dist/client/renewal.js +4 -0
  72. package/dist/client/renewal.js.map +1 -0
  73. package/dist/client/renewalContextClient.d.ts +130 -0
  74. package/dist/client/renewalContextClient.d.ts.map +1 -0
  75. package/dist/client/renewalContextClient.js +10 -0
  76. package/dist/client/renewalContextClient.js.map +1 -0
  77. package/dist/client/usage/observationClient.d.ts +2 -2
  78. package/dist/client/usage/observationClient.d.ts.map +1 -1
  79. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  80. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  81. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  82. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  83. package/dist/component/earnings/triggers.d.ts +16 -16
  84. package/docs/renewal-context-reads.md +113 -0
  85. package/docs/renewal-phase-assembly.md +180 -0
  86. package/docs/renewal-price-replacements.md +57 -16
  87. package/package.json +1 -1
  88. package/src/client/billing/renewalAggregate/configure.test.ts +372 -0
  89. package/src/client/billing/renewalAggregate/configure.ts +164 -0
  90. package/src/client/billing/renewalAggregate/index.ts +2 -0
  91. package/src/client/billing/renewalAggregate/phaseContext.ts +144 -0
  92. package/src/client/billing/renewalAggregate/phases.ts +247 -0
  93. package/src/client/billing/renewalAggregate/preflight.test.ts +233 -0
  94. package/src/client/billing/renewalAggregate/preflight.ts +211 -0
  95. package/src/client/billing/renewalAggregate/profile.ts +76 -0
  96. package/src/client/billing/renewalAggregate/receipt.ts +76 -0
  97. package/src/client/billing/renewalAggregate/shared.ts +106 -0
  98. package/src/client/billing/renewalAggregate/sourceAndTaxRetention.test.ts +247 -0
  99. package/src/client/billing/renewalAggregate/sourceDiscounts.ts +112 -0
  100. package/src/client/billing/renewalAggregate/sourceSettings.ts +88 -0
  101. package/src/client/billing/renewalAggregate/taxRetention.ts +28 -0
  102. package/src/client/billing/renewalAttach/couponEvidence.test.ts +104 -0
  103. package/src/client/billing/renewalAttach/couponJoins.ts +95 -0
  104. package/src/client/billing/renewalAttach/index.ts +9 -0
  105. package/src/client/billing/renewalAttach/reader.test.ts +409 -0
  106. package/src/client/billing/renewalAttach/reader.ts +131 -0
  107. package/src/client/billing/renewalAttach/request.ts +49 -0
  108. package/src/client/index.ts +3 -8
  109. package/src/client/renewal.ts +13 -0
  110. package/src/client/renewalContextClient.ts +23 -0
@@ -0,0 +1,76 @@
1
+ import { z } from "zod";
2
+ import { object, timestamp, unsupported } from "./shared.js";
3
+
4
+ const mode = z
5
+ .object({
6
+ type: z.enum(["classic", "flexible"]),
7
+ flexible: z
8
+ .object({
9
+ proration_discounts: z.enum(["included", "itemized"]).optional(),
10
+ })
11
+ .strict()
12
+ .nullable(),
13
+ updated_at: timestamp.optional(),
14
+ })
15
+ .strict()
16
+ .refine((value) => value.type !== "classic" || value.flexible === null);
17
+ const anchorConfig = z
18
+ .object({
19
+ day_of_month: z.number().int().min(1).max(31),
20
+ month: z.number().int().min(1).max(12).nullable(),
21
+ hour: z.number().int().min(0).max(23).nullable(),
22
+ minute: z.number().int().min(0).max(59).nullable(),
23
+ second: z.number().int().min(0).max(59).nullable(),
24
+ })
25
+ .strict()
26
+ .nullable();
27
+ export type RenewalProfile = {
28
+ apiVersion: string;
29
+ billingMode: "classic" | "flexible";
30
+ cadence: "same" | "changed";
31
+ anchor: "ordinary" | "calendar_edge";
32
+ };
33
+
34
+ export function profileOf(
35
+ subscription: Record<string, unknown>,
36
+ currentPrice: unknown,
37
+ targetPrice: unknown,
38
+ apiVersion: string,
39
+ ): RenewalProfile {
40
+ const parsedMode = mode.safeParse(subscription.billing_mode);
41
+ if (!parsedMode.success) unsupported("unsupported_billing_mode");
42
+ const parsedConfig = anchorConfig.safeParse(
43
+ subscription.billing_cycle_anchor_config,
44
+ );
45
+ if (!parsedConfig.success) unsupported("unsupported_anchor_config");
46
+ const anchor = timestamp.safeParse(subscription.billing_cycle_anchor);
47
+ if (
48
+ !anchor.success ||
49
+ !Number.isFinite(new Date(anchor.data * 1000).getTime())
50
+ )
51
+ unsupported("unsupported_numeric_anchor");
52
+ const current = object(object(currentPrice).recurring);
53
+ const target = object(object(targetPrice).recurring);
54
+ const cadence =
55
+ current.interval === target.interval &&
56
+ current.interval_count === target.interval_count
57
+ ? "same"
58
+ : "changed";
59
+ if (parsedConfig.data !== null) {
60
+ if (current.interval !== "month" && current.interval !== "year")
61
+ unsupported("unsupported_anchor_config_cadence");
62
+ if (cadence === "changed")
63
+ unsupported("unsupported_changed_cadence_anchor_config");
64
+ }
65
+ const calendar = current.interval === "month" || current.interval === "year";
66
+ const edge =
67
+ calendar &&
68
+ (new Date(anchor.data * 1000).getUTCDate() >= 29 ||
69
+ (parsedConfig.data?.day_of_month ?? 0) >= 29);
70
+ return {
71
+ apiVersion,
72
+ billingMode: parsedMode.data.type,
73
+ cadence,
74
+ anchor: edge ? "calendar_edge" : "ordinary",
75
+ };
76
+ }
@@ -0,0 +1,76 @@
1
+ import { z } from "zod";
2
+ import { idempotencyOptions } from "../../core/idempotency.js";
3
+ import { binding, conflict, resourceId, timestamp } from "./shared.js";
4
+
5
+ const requestSchema = z
6
+ .object({
7
+ version: z.literal(1),
8
+ stage: z.literal("attach"),
9
+ scope: z.literal("platform"),
10
+ apiVersion: z.string(),
11
+ logicalBinding: z.string(),
12
+ method: z.literal("POST"),
13
+ path: z.literal("/v1/subscription_schedules"),
14
+ payload: z.object({ from_subscription: resourceId("sub") }).strict(),
15
+ key: z.string(),
16
+ firstDispatchedAt: timestamp,
17
+ requestIdentity: z
18
+ .object({ key: z.string(), binding: z.string() })
19
+ .strict(),
20
+ })
21
+ .strict();
22
+ const receiptSchema = z
23
+ .object({
24
+ version: z.literal(1),
25
+ stage: z.literal("attached_unconfigured"),
26
+ scope: z.literal("platform"),
27
+ logicalBinding: z.string(),
28
+ request: requestSchema,
29
+ scheduleId: resourceId("sub_sched"),
30
+ subscriptionId: resourceId("sub"),
31
+ customerAccountId: resourceId("acct"),
32
+ livemode: z.boolean(),
33
+ providerSnapshot: z.unknown(),
34
+ binding: z.string(),
35
+ })
36
+ .strict();
37
+
38
+ export function validateAttachReceipt(
39
+ value: unknown,
40
+ prepared: {
41
+ requestIdentity: { binding: string };
42
+ expected: {
43
+ subscriptionId: string;
44
+ customerAccountId: string;
45
+ livemode: boolean;
46
+ };
47
+ },
48
+ apiVersion: string,
49
+ observedAt: number,
50
+ ) {
51
+ try {
52
+ const receipt = receiptSchema.parse(value);
53
+ const { requestIdentity, ...unsignedRequest } = receipt.request;
54
+ const { binding: receivedBinding, ...unsignedReceipt } = receipt;
55
+ const key = idempotencyOptions(receipt.request.key)?.idempotencyKey;
56
+ if (
57
+ !key ||
58
+ requestIdentity.key !== key ||
59
+ requestIdentity.binding !== binding("renewal-attach", unsignedRequest) ||
60
+ receivedBinding !== binding("renewal-attach-receipt", unsignedReceipt) ||
61
+ receipt.logicalBinding !== prepared.requestIdentity.binding ||
62
+ receipt.request.logicalBinding !== prepared.requestIdentity.binding ||
63
+ receipt.request.apiVersion !== apiVersion ||
64
+ receipt.request.payload.from_subscription !==
65
+ prepared.expected.subscriptionId ||
66
+ receipt.subscriptionId !== prepared.expected.subscriptionId ||
67
+ receipt.customerAccountId !== prepared.expected.customerAccountId ||
68
+ receipt.livemode !== prepared.expected.livemode ||
69
+ receipt.request.firstDispatchedAt > observedAt
70
+ )
71
+ conflict("invalid_attach_receipt_binding");
72
+ return receipt;
73
+ } catch {
74
+ return conflict("invalid_attach_receipt_binding");
75
+ }
76
+ }
@@ -0,0 +1,106 @@
1
+ import { z } from "zod";
2
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
3
+
4
+ export const timestamp = z
5
+ .number()
6
+ .int()
7
+ .nonnegative()
8
+ .max(Number.MAX_SAFE_INTEGER);
9
+ export const resourceId = (prefix: string) =>
10
+ z
11
+ .string()
12
+ .max(255)
13
+ .regex(new RegExp(`^${prefix}_[A-Za-z0-9_]+$`));
14
+ export type ObjectData = Record<string, unknown>;
15
+ export class ProjectionError extends Error {
16
+ constructor(
17
+ readonly kind: "unsupported" | "conflict",
18
+ reason: string,
19
+ ) {
20
+ super(reason);
21
+ }
22
+ }
23
+ export function unsupported(reason: string): never {
24
+ throw new ProjectionError("unsupported", reason);
25
+ }
26
+ export function conflict(reason: string): never {
27
+ throw new ProjectionError("conflict", reason);
28
+ }
29
+ export const object = (value: unknown): ObjectData =>
30
+ z.record(z.string(), z.unknown()).parse(value);
31
+ export const canonical = (value: unknown) =>
32
+ JSON.stringify(renewalSnapshot(value));
33
+ export const binding = (namespace: string, value: unknown) =>
34
+ `${namespace}:v1:${canonical(value)}`;
35
+ export const equal = (left: unknown, right: unknown) =>
36
+ canonical(left) === canonical(right);
37
+
38
+ export type ReferenceContext = { livemode: boolean; customerAccountId: string };
39
+ function referenceFacts(reference: ObjectData, context?: ReferenceContext) {
40
+ if (
41
+ context &&
42
+ ((reference.livemode !== undefined &&
43
+ reference.livemode !== context.livemode) ||
44
+ (reference.customer_account !== undefined &&
45
+ reference.customer_account !== context.customerAccountId))
46
+ )
47
+ unsupported("expanded_reference_scope_mismatch");
48
+ }
49
+ export function referenceId(
50
+ value: unknown,
51
+ prefix: string,
52
+ kind: string,
53
+ context?: ReferenceContext,
54
+ ): string {
55
+ if (typeof value === "string") return resourceId(prefix).parse(value);
56
+ const reference = object(value);
57
+ if (reference.object !== kind || reference.deleted === true)
58
+ unsupported(`invalid_${kind}_reference`);
59
+ referenceFacts(reference, context);
60
+ return resourceId(prefix).parse(reference.id);
61
+ }
62
+ export function productId(value: unknown, context: ReferenceContext): string {
63
+ const id = z.string().min(1).max(255).regex(/\S/);
64
+ if (typeof value === "string") return id.parse(value);
65
+ const reference = object(value);
66
+ if (reference.object !== "product" || reference.deleted === true)
67
+ unsupported("invalid_product_reference");
68
+ referenceFacts(reference, context);
69
+ return id.parse(reference.id);
70
+ }
71
+ export type Failure =
72
+ | { status: "unsupported" | "conflict"; reason: string }
73
+ | { status: "attached_unconfigured"; scheduleId: string; reason: string };
74
+ export function failure(error: unknown, scheduleId?: string): Failure {
75
+ const known = error instanceof ProjectionError;
76
+ const kind = known ? error.kind : "unsupported";
77
+ const reason = known ? error.message : "incomplete_or_unsupported_schema";
78
+ if (kind === "unsupported" && scheduleId)
79
+ return { status: "attached_unconfigured", scheduleId, reason };
80
+ return { status: kind, reason };
81
+ }
82
+
83
+ export const readInput = z
84
+ .object({
85
+ prepared: z.unknown(),
86
+ freshSubscription: z.unknown(),
87
+ targetPrice: z.unknown(),
88
+ billingCustomer: z.unknown().optional(),
89
+ apiVersion: z.string(),
90
+ observedAt: timestamp,
91
+ })
92
+ .strict();
93
+ export const configureInput = readInput
94
+ .extend({
95
+ attachReceipt: z.unknown(),
96
+ schedule: z.unknown(),
97
+ configureKey: z.string(),
98
+ firstDispatchedAt: timestamp,
99
+ })
100
+ .strict();
101
+
102
+ export function supportedVersion(version: string) {
103
+ if (version !== "2026-09-30.endive")
104
+ unsupported("unqualified_api_version_profile");
105
+ return version;
106
+ }
@@ -0,0 +1,247 @@
1
+ import { expect, it } from "vitest";
2
+ import {
3
+ preflightRenewalReplacement,
4
+ projectRenewalConfiguration,
5
+ } from "./index.js";
6
+ import { fixture } from "../../../../tests/renewalAggregate/fixtures.js";
7
+
8
+ const rate = (id: string) => ({ id, object: "tax_rate", livemode: false });
9
+ const automatic = (liability: unknown = null) => ({
10
+ enabled: true,
11
+ liability,
12
+ disabled_reason: null,
13
+ });
14
+
15
+ it.each([
16
+ {
17
+ start_date: 1768435200,
18
+ end_date: 1771113600,
19
+ trial_offer: "trial_offer_active",
20
+ },
21
+ {
22
+ start_date: 1771113600,
23
+ end_date: 1773532800,
24
+ trial_offer: "trial_offer_future",
25
+ },
26
+ ])(
27
+ "rejects an actual item current_trial while the subscription remains active: %j",
28
+ (current_trial) => {
29
+ const f = fixture({ item: { current_trial } });
30
+ expect(f.subscription.status).toBe("active");
31
+ expect(preflightRenewalReplacement(f.preflightInput)).toMatchObject({
32
+ status: "unsupported",
33
+ reason: expect.stringMatching(/trial/i),
34
+ });
35
+ },
36
+ );
37
+
38
+ it("requires explicit no-current-trial evidence instead of inventing null for a missing item field", () => {
39
+ const f = fixture({ omitItemCurrentTrial: true });
40
+ expect(f.originalItem).not.toHaveProperty("current_trial");
41
+ expect(preflightRenewalReplacement(f.preflightInput)).toMatchObject({
42
+ status: "unsupported",
43
+ reason: expect.stringMatching(/trial/i),
44
+ });
45
+ });
46
+
47
+ it.each([
48
+ {
49
+ name: "disabled automatic tax",
50
+ subscription: {
51
+ automatic_tax: {
52
+ enabled: false,
53
+ liability: null,
54
+ disabled_reason: "requires_location_inputs",
55
+ },
56
+ },
57
+ },
58
+ {
59
+ name: "unknown liability",
60
+ subscription: { automatic_tax: automatic({ type: "future_owner" }) },
61
+ },
62
+ {
63
+ name: "foreign payment method",
64
+ subscription: {
65
+ default_payment_method: {
66
+ id: "pm_foreign",
67
+ object: "payment_method",
68
+ customer: "cus_foreign",
69
+ livemode: false,
70
+ },
71
+ },
72
+ },
73
+ {
74
+ name: "malformed invoice issuer",
75
+ subscription: {
76
+ invoice_settings: {
77
+ account_tax_ids: null,
78
+ custom_fields: null,
79
+ description: null,
80
+ footer: null,
81
+ issuer: { type: "future_issuer" },
82
+ },
83
+ },
84
+ },
85
+ {
86
+ name: "invalid transfer precision",
87
+ subscription: {
88
+ transfer_data: {
89
+ destination: "acct_destination",
90
+ amount_percent: 12.345,
91
+ },
92
+ },
93
+ },
94
+ {
95
+ name: "deleted routing account",
96
+ subscription: {
97
+ on_behalf_of: {
98
+ id: "acct_issuer",
99
+ object: "account",
100
+ deleted: true,
101
+ },
102
+ },
103
+ },
104
+ {
105
+ name: "automatic plus subscription manual tax",
106
+ subscription: {
107
+ automatic_tax: automatic(),
108
+ default_tax_rates: [rate("txr_manual")],
109
+ },
110
+ },
111
+ {
112
+ name: "automatic plus item manual tax",
113
+ subscription: { automatic_tax: automatic() },
114
+ item: { tax_rates: [rate("txr_manual")] },
115
+ },
116
+ {
117
+ name: "unproven subscription tax inheritance",
118
+ subscription: { default_tax_rates: null },
119
+ },
120
+ {
121
+ name: "unproven item tax inheritance",
122
+ subscription: {},
123
+ item: { tax_rates: null },
124
+ },
125
+ {
126
+ name: "invoice due days under automatic collection",
127
+ subscription: { days_until_due: 3 },
128
+ },
129
+ {
130
+ name: "unknown collection method",
131
+ subscription: { collection_method: "future_collection" },
132
+ },
133
+ ])(
134
+ "rejects knowable original billing facts before attach: $name",
135
+ (options) => {
136
+ const result = preflightRenewalReplacement(fixture(options).preflightInput);
137
+ expect(result).toMatchObject({
138
+ status: "unsupported",
139
+ reason: expect.any(String),
140
+ });
141
+ },
142
+ );
143
+
144
+ it("accepts mappable original routing, payment and manual-tax facts without an invented phase", () => {
145
+ const f = fixture({
146
+ subscription: {
147
+ default_payment_method: {
148
+ id: "pm_owned",
149
+ object: "payment_method",
150
+ customer: "cus_buyer",
151
+ livemode: false,
152
+ },
153
+ on_behalf_of: "acct_issuer",
154
+ transfer_data: { destination: "acct_destination", amount_percent: 0 },
155
+ default_tax_rates: [rate("txr_original")],
156
+ },
157
+ });
158
+ expect(preflightRenewalReplacement(f.preflightInput)).toMatchObject({
159
+ status: "preflighted_for_projection",
160
+ providerQualification: "required",
161
+ });
162
+ });
163
+
164
+ it.each([
165
+ {
166
+ name: "different phase rates",
167
+ subscription: { default_tax_rates: [rate("txr_original")] },
168
+ phase: { default_tax_rates: [rate("txr_other")] },
169
+ },
170
+ {
171
+ name: "different item rates",
172
+ item: { tax_rates: [rate("txr_original")] },
173
+ phaseItem: { tax_rates: [rate("txr_other")] },
174
+ },
175
+ {
176
+ name: "new item override with the same current effective rate",
177
+ subscription: { default_tax_rates: [rate("txr_original")] },
178
+ phase: { default_tax_rates: [rate("txr_original")] },
179
+ phaseItem: { tax_rates: [rate("txr_original")] },
180
+ },
181
+ {
182
+ name: "removed item override with the same current effective rate",
183
+ subscription: { default_tax_rates: [rate("txr_original")] },
184
+ item: { tax_rates: [rate("txr_original")] },
185
+ phase: { default_tax_rates: [rate("txr_original")] },
186
+ },
187
+ {
188
+ name: "changed ordered phase rates",
189
+ subscription: {
190
+ default_tax_rates: [rate("txr_first"), rate("txr_second")],
191
+ },
192
+ phase: { default_tax_rates: [rate("txr_second"), rate("txr_first")] },
193
+ },
194
+ {
195
+ name: "unproven null phase tax hierarchy",
196
+ phase: { default_tax_rates: null },
197
+ },
198
+ { name: "unproven null phase item override", phaseItem: { tax_rates: null } },
199
+ ])("retains exact tax values and override level: $name", (options) => {
200
+ expect(
201
+ projectRenewalConfiguration(fixture(options).configureInput),
202
+ ).toMatchObject({
203
+ status: "attached_unconfigured",
204
+ reason: expect.stringMatching(/tax/i),
205
+ });
206
+ });
207
+
208
+ it("preserves the subscription tax level and an empty item fallback", () => {
209
+ const f = fixture({
210
+ subscription: { default_tax_rates: [rate("txr_original")] },
211
+ phase: { default_tax_rates: [rate("txr_original")] },
212
+ });
213
+ const result = projectRenewalConfiguration(f.configureInput);
214
+ expect(result).toMatchObject({
215
+ status: "projected_configure_request",
216
+ payload: {
217
+ phases: [
218
+ { default_tax_rates: ["txr_original"], items: [{ tax_rates: "" }] },
219
+ { default_tax_rates: ["txr_original"], items: [{ tax_rates: "" }] },
220
+ ],
221
+ },
222
+ });
223
+ });
224
+
225
+ it("preserves an explicit item override separately from phase default rates", () => {
226
+ const f = fixture({
227
+ subscription: { default_tax_rates: [rate("txr_phase")] },
228
+ item: { tax_rates: [rate("txr_item")] },
229
+ phase: { default_tax_rates: [rate("txr_phase")] },
230
+ phaseItem: { tax_rates: [rate("txr_item")] },
231
+ });
232
+ expect(projectRenewalConfiguration(f.configureInput)).toMatchObject({
233
+ status: "projected_configure_request",
234
+ payload: {
235
+ phases: [
236
+ {
237
+ default_tax_rates: ["txr_phase"],
238
+ items: [{ tax_rates: ["txr_item"] }],
239
+ },
240
+ {
241
+ default_tax_rates: ["txr_phase"],
242
+ items: [{ tax_rates: ["txr_item"] }],
243
+ },
244
+ ],
245
+ },
246
+ });
247
+ });
@@ -0,0 +1,112 @@
1
+ import { z } from "zod";
2
+ import { resourceId, unsupported } from "./shared.js";
3
+
4
+ const customId = z.string().min(1).max(255).regex(/\S/);
5
+ const originalRedemptions = z
6
+ .array(
7
+ z
8
+ .object({
9
+ id: resourceId("di"),
10
+ object: z.literal("discount"),
11
+ deleted: z.literal(false).optional(),
12
+ customer_account: resourceId("acct"),
13
+ customer: z
14
+ .union([
15
+ resourceId("cus"),
16
+ z
17
+ .object({
18
+ id: resourceId("cus"),
19
+ object: z.literal("customer"),
20
+ deleted: z.literal(false).optional(),
21
+ livemode: z.boolean().optional(),
22
+ customer_account: resourceId("acct").nullable().optional(),
23
+ })
24
+ .passthrough(),
25
+ ])
26
+ .nullable()
27
+ .optional(),
28
+ subscription: resourceId("sub").nullable(),
29
+ subscription_item: resourceId("si").nullable(),
30
+ start: z.number().int().nonnegative(),
31
+ end: z.null(),
32
+ source: z
33
+ .object({
34
+ type: z.literal("coupon"),
35
+ coupon: z
36
+ .object({
37
+ id: customId,
38
+ object: z.literal("coupon"),
39
+ deleted: z.literal(false).optional(),
40
+ livemode: z.boolean().optional(),
41
+ duration: z.literal("forever"),
42
+ applies_to: z
43
+ .object({ products: z.array(customId) })
44
+ .strict()
45
+ .optional(),
46
+ })
47
+ .passthrough(),
48
+ })
49
+ .passthrough(),
50
+ })
51
+ .passthrough(),
52
+ )
53
+ .max(20);
54
+ export type OriginalRedemptions = z.infer<typeof originalRedemptions>;
55
+
56
+ export function qualifySourceDiscounts(
57
+ value: unknown,
58
+ level: "subscription" | "item",
59
+ context: {
60
+ customerAccountId: string;
61
+ subscriptionId: string;
62
+ itemId: string;
63
+ currentProductId: string;
64
+ targetProductId: string;
65
+ livemode: boolean;
66
+ },
67
+ customerId: string,
68
+ observedAt: number,
69
+ ): OriginalRedemptions {
70
+ const parsed = originalRedemptions.safeParse(value);
71
+ if (!parsed.success)
72
+ unsupported("incomplete_or_unsupported_discount_evidence");
73
+ if (!parsed.data.length) unsupported("ambiguous_empty_discount_hierarchy");
74
+ if (
75
+ new Set(parsed.data.map((discount) => discount.id)).size !==
76
+ parsed.data.length
77
+ )
78
+ unsupported("duplicate_discount_redemptions");
79
+ for (const discount of parsed.data) {
80
+ const customer = discount.customer;
81
+ if (
82
+ discount.customer_account !== context.customerAccountId ||
83
+ discount.start > observedAt ||
84
+ (typeof customer === "string" && customer !== customerId) ||
85
+ (typeof customer === "object" &&
86
+ customer !== null &&
87
+ (customer.id !== customerId ||
88
+ (customer.livemode !== undefined &&
89
+ customer.livemode !== context.livemode) ||
90
+ (customer.customer_account !== undefined &&
91
+ customer.customer_account !== context.customerAccountId))) ||
92
+ (level === "subscription" &&
93
+ (discount.subscription !== context.subscriptionId ||
94
+ discount.subscription_item !== null)) ||
95
+ (level === "item" &&
96
+ (discount.subscription_item !== context.itemId ||
97
+ (discount.subscription !== null &&
98
+ discount.subscription !== context.subscriptionId)))
99
+ )
100
+ unsupported("discount_owner_or_start_mismatch");
101
+ const coupon = discount.source.coupon;
102
+ if (coupon.livemode !== undefined && coupon.livemode !== context.livemode)
103
+ unsupported("discount_coupon_mode_mismatch");
104
+ if (
105
+ coupon.applies_to &&
106
+ (!coupon.applies_to.products.includes(context.currentProductId) ||
107
+ !coupon.applies_to.products.includes(context.targetProductId))
108
+ )
109
+ unsupported("discount_product_applicability");
110
+ }
111
+ return parsed.data;
112
+ }