@fantastic.dev/better-stripe 0.81.0 → 0.82.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 (71) hide show
  1. package/CHANGELOG.md +6 -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/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  48. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
  49. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  50. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  51. package/dist/component/payoutRelease/queries.d.ts +2 -2
  52. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  53. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  54. package/dist/component/usage/allowance.fixtures.d.ts +16 -16
  55. package/docs/renewal-phase-assembly.md +180 -0
  56. package/docs/renewal-price-replacements.md +2 -0
  57. package/package.json +1 -1
  58. package/src/client/billing/renewalAggregate/configure.test.ts +372 -0
  59. package/src/client/billing/renewalAggregate/configure.ts +164 -0
  60. package/src/client/billing/renewalAggregate/index.ts +2 -0
  61. package/src/client/billing/renewalAggregate/phaseContext.ts +144 -0
  62. package/src/client/billing/renewalAggregate/phases.ts +247 -0
  63. package/src/client/billing/renewalAggregate/preflight.test.ts +233 -0
  64. package/src/client/billing/renewalAggregate/preflight.ts +211 -0
  65. package/src/client/billing/renewalAggregate/profile.ts +76 -0
  66. package/src/client/billing/renewalAggregate/receipt.ts +76 -0
  67. package/src/client/billing/renewalAggregate/shared.ts +106 -0
  68. package/src/client/billing/renewalAggregate/sourceAndTaxRetention.test.ts +247 -0
  69. package/src/client/billing/renewalAggregate/sourceDiscounts.ts +112 -0
  70. package/src/client/billing/renewalAggregate/sourceSettings.ts +88 -0
  71. package/src/client/billing/renewalAggregate/taxRetention.ts +28 -0
@@ -0,0 +1,247 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+ import { projectRenewalDiscounts } from "../renewalProjection/discounts.js";
4
+ import { projectRenewalPhaseSettings } from "../renewalProjection/settings.js";
5
+ import { projectRenewalItemSettings } from "../renewalProjection/itemSettings.js";
6
+ import { settingsInput, taxRate } from "../renewalProjection/settingsSchema.js";
7
+ import { defaultsSchema, contextFor } from "./phaseContext.js";
8
+ import {
9
+ object,
10
+ timestamp,
11
+ referenceId,
12
+ productId,
13
+ equal,
14
+ unsupported,
15
+ } from "./shared.js";
16
+ import type { validateReads } from "./preflight.js";
17
+ import type { OriginalRedemptions } from "./sourceDiscounts.js";
18
+ import { preserveTaxLevels } from "./taxRetention.js";
19
+
20
+ const itemSchema = z
21
+ .object({
22
+ price: z.unknown(),
23
+ plan: z.unknown().optional(),
24
+ quantity: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
25
+ billing_thresholds: z.null(),
26
+ discounts: z.array(z.unknown()).max(20),
27
+ tax_rates: z.array(taxRate).max(20).nullable().optional(),
28
+ metadata: settingsInput.shape.settings.shape.metadata,
29
+ })
30
+ .strict();
31
+ const phaseSchema = settingsInput.shape.settings
32
+ .extend({
33
+ start_date: timestamp,
34
+ end_date: timestamp,
35
+ currency: z.string().regex(/^[a-z]{3}$/),
36
+ billing_cycle_anchor: z.enum(["automatic", "phase_start"]).nullable(),
37
+ discounts: z.array(z.unknown()).max(20),
38
+ items: z.tuple([itemSchema]),
39
+ add_invoice_items: z.array(z.unknown()).length(0),
40
+ proration_behavior: z.enum(["none", "always_invoice", "create_prorations"]),
41
+ trial: z.literal(false).optional(),
42
+ trial_end: z.null(),
43
+ })
44
+ .strict();
45
+
46
+ function phaseReferences(value: unknown[], originals: OriginalRedemptions) {
47
+ return value.map((entry, index) => {
48
+ const reference = object(entry);
49
+ const original = originals[index];
50
+ if (!original || reference.promotion_code != null)
51
+ unsupported("unsupported_phase_discount_reference");
52
+ const normalize = (value: unknown, source: unknown, kind: string) => {
53
+ if (value == null || typeof value === "string") return value;
54
+ const expanded = object(value);
55
+ const minimal = Object.keys(expanded).every((key) =>
56
+ ["id", "object", "deleted"].includes(key),
57
+ );
58
+ if (
59
+ expanded.object !== kind ||
60
+ expanded.deleted === true ||
61
+ (!minimal && !equal(expanded, source))
62
+ )
63
+ unsupported("phase_discount_expansion_mismatch");
64
+ return z.string().parse(expanded.id);
65
+ };
66
+ return {
67
+ discount: normalize(reference.discount, original, "discount"),
68
+ coupon:
69
+ normalize(reference.coupon, original.source.coupon, "coupon") ?? null,
70
+ promotion_code: null,
71
+ };
72
+ });
73
+ }
74
+
75
+ function metadataMatches(
76
+ actions: Record<string, string> | null,
77
+ actual: unknown,
78
+ ) {
79
+ const existing = object(actual);
80
+ if (
81
+ actions &&
82
+ Object.entries(actions).some(([key, value]) => existing[key] !== value)
83
+ )
84
+ unsupported("metadata_action_conflict");
85
+ }
86
+
87
+ export function assemblePhases(
88
+ reads: ReturnType<typeof validateReads>,
89
+ schedule: Record<string, unknown>,
90
+ ): [
91
+ Stripe.SubscriptionScheduleUpdateParams.Phase,
92
+ Stripe.SubscriptionScheduleUpdateParams.Phase,
93
+ ] {
94
+ const defaultsResult = defaultsSchema.safeParse(schedule.default_settings);
95
+ if (!defaultsResult.success) unsupported("unsupported_schedule_defaults");
96
+ if (!Array.isArray(schedule.phases) || schedule.phases.length !== 1)
97
+ unsupported("unsupported_phase_configuration");
98
+ const parsedPhase = phaseSchema.safeParse(schedule.phases[0]);
99
+ if (!parsedPhase.success) unsupported("unsupported_phase_mapping");
100
+ const phase = parsedPhase.data;
101
+ const phaseItem = phase.items[0];
102
+ preserveTaxLevels(
103
+ reads.originalSettings.taxLevels,
104
+ phase.default_tax_rates,
105
+ phaseItem.tax_rates,
106
+ );
107
+ const expected = reads.prepared.expected;
108
+ const referenceContext = {
109
+ livemode: expected.livemode,
110
+ customerAccountId: expected.customerAccountId,
111
+ };
112
+ if (
113
+ phase.start_date !== expected.periodStart ||
114
+ phase.end_date !== expected.periodEnd ||
115
+ phase.currency !== reads.subscription.currency ||
116
+ phaseItem.quantity !== reads.prepared.quantity ||
117
+ referenceId(phaseItem.price, "price", "price", referenceContext) !==
118
+ expected.currentPriceId
119
+ )
120
+ unsupported("phase_original_identity_mismatch");
121
+ if (
122
+ phaseItem.plan !== undefined &&
123
+ referenceId(phaseItem.plan, "price", "plan", referenceContext) !==
124
+ expected.currentPriceId
125
+ )
126
+ unsupported("phase_plan_price_mismatch");
127
+ for (const reference of [phaseItem.price, phaseItem.plan]) {
128
+ if (typeof reference !== "object" || reference === null) continue;
129
+ const expanded = object(reference);
130
+ if (
131
+ (expanded.product !== undefined &&
132
+ productId(expanded.product, referenceContext) !==
133
+ expected.currentProductId) ||
134
+ (expanded.currency !== undefined && expanded.currency !== phase.currency)
135
+ )
136
+ unsupported("phase_price_material_mismatch");
137
+ }
138
+ const context = contextFor(
139
+ phase,
140
+ defaultsResult.data,
141
+ reads.subscription,
142
+ reads.customer.id,
143
+ expected.customerAccountId,
144
+ expected.livemode,
145
+ reads.originalSettings,
146
+ );
147
+ metadataMatches(phase.metadata, reads.subscription.metadata);
148
+ metadataMatches(phaseItem.metadata, reads.item.metadata);
149
+ const {
150
+ start_date,
151
+ end_date,
152
+ currency,
153
+ items: _items,
154
+ discounts,
155
+ add_invoice_items: _invoiceItems,
156
+ billing_cycle_anchor,
157
+ proration_behavior,
158
+ trial: _trial,
159
+ trial_end: _trialEnd,
160
+ ...phaseSettings
161
+ } = phase;
162
+ const settings = projectRenewalPhaseSettings({
163
+ context,
164
+ settings: phaseSettings,
165
+ });
166
+ if (settings.status !== "projected") unsupported(settings.reason);
167
+ const itemSettings = projectRenewalItemSettings({
168
+ effectiveAutomaticTax: context.effectiveAutomaticTax,
169
+ livemode: expected.livemode,
170
+ settings: {
171
+ billing_thresholds: phaseItem.billing_thresholds,
172
+ ...(phaseItem.tax_rates === undefined
173
+ ? {}
174
+ : { tax_rates: phaseItem.tax_rates }),
175
+ metadata: phaseItem.metadata,
176
+ },
177
+ });
178
+ if (itemSettings.status !== "projected") unsupported(itemSettings.reason);
179
+ const discountContext = {
180
+ customerAccountId: expected.customerAccountId,
181
+ subscriptionId: expected.subscriptionId,
182
+ itemId: expected.itemId,
183
+ currentProductId: expected.currentProductId,
184
+ targetProductId: expected.targetProductId,
185
+ };
186
+ const phaseDiscount = projectRenewalDiscounts({
187
+ ...discountContext,
188
+ level: "subscription",
189
+ redemptions: reads.discounts,
190
+ phaseDiscounts: phaseReferences(discounts, reads.discounts),
191
+ });
192
+ const itemDiscount = projectRenewalDiscounts({
193
+ ...discountContext,
194
+ level: "subscription_item",
195
+ redemptions: reads.itemDiscounts,
196
+ phaseDiscounts: phaseReferences(phaseItem.discounts, reads.itemDiscounts),
197
+ });
198
+ if (phaseDiscount.status !== "projected") unsupported(phaseDiscount.reason);
199
+ if (itemDiscount.status !== "projected") unsupported(itemDiscount.reason);
200
+ const effectiveAnchor =
201
+ billing_cycle_anchor ?? defaultsResult.data.billing_cycle_anchor;
202
+ if (
203
+ effectiveAnchor === "phase_start" &&
204
+ reads.subscription.billing_cycle_anchor !== start_date
205
+ )
206
+ unsupported("current_phase_anchor_reset_unsupported");
207
+ const current: Stripe.SubscriptionScheduleUpdateParams.Phase = {
208
+ ...settings.settings,
209
+ start_date,
210
+ end_date,
211
+ currency,
212
+ proration_behavior,
213
+ items: [
214
+ {
215
+ ...itemSettings.settings,
216
+ price: expected.currentPriceId,
217
+ quantity: reads.prepared.quantity,
218
+ discounts: itemDiscount.discounts,
219
+ },
220
+ ],
221
+ discounts: phaseDiscount.discounts,
222
+ ...(billing_cycle_anchor === null ? {} : { billing_cycle_anchor }),
223
+ };
224
+ const recurring = reads.targetPrice.recurring;
225
+ const target: Stripe.SubscriptionScheduleUpdateParams.Phase = {
226
+ ...settings.settings,
227
+ start_date: end_date,
228
+ currency,
229
+ proration_behavior: "none",
230
+ billing_cycle_anchor:
231
+ reads.profile.cadence === "same" ? "automatic" : "phase_start",
232
+ duration: {
233
+ interval: recurring.interval,
234
+ interval_count: recurring.interval_count,
235
+ },
236
+ items: [
237
+ {
238
+ ...itemSettings.settings,
239
+ price: expected.targetPriceId,
240
+ quantity: reads.prepared.quantity,
241
+ discounts: itemDiscount.discounts,
242
+ },
243
+ ],
244
+ discounts: phaseDiscount.discounts,
245
+ };
246
+ return [current, target];
247
+ }
@@ -0,0 +1,233 @@
1
+ import { expect, it } from "vitest";
2
+ import { preflightRenewalReplacement } from "./index.js";
3
+ import {
4
+ alter,
5
+ fixture,
6
+ stamp,
7
+ } from "../../../../tests/renewalAggregate/fixtures.js";
8
+
9
+ it("preflights exact cross-product paid terms without claiming provider qualification", () => {
10
+ const f = fixture();
11
+ const before = structuredClone(f.preflightInput);
12
+ const result = preflightRenewalReplacement(f.preflightInput);
13
+ expect(result).toMatchObject({
14
+ status: "preflighted_for_projection",
15
+ scope: "platform",
16
+ expected: f.prepared.expected,
17
+ quantity: 3,
18
+ providerQualification: "required",
19
+ profile: {
20
+ apiVersion: "2026-09-30.endive",
21
+ billingMode: "classic",
22
+ cadence: "same",
23
+ anchor: "ordinary",
24
+ },
25
+ });
26
+ expect(f.preflightInput).toEqual(before);
27
+ expect(result.status).not.toBe("pending");
28
+ expect(result.status).not.toBe("effective");
29
+ });
30
+
31
+ it("rejects an empty discount hierarchy before attach despite observed ancestor absence", () => {
32
+ const f = fixture({
33
+ subscription: { discounts: [] },
34
+ item: { discounts: [] },
35
+ });
36
+ expect(f.billingCustomer.discount).toBeNull();
37
+ expect(preflightRenewalReplacement(f.preflightInput)).toMatchObject({
38
+ status: "unsupported",
39
+ reason: expect.stringMatching(/discount|inherit/i),
40
+ });
41
+ });
42
+
43
+ it.each([
44
+ {
45
+ billing_thresholds: { amount_gte: 100, reset_billing_cycle_anchor: false },
46
+ },
47
+ { managed_payments: { enabled: true } },
48
+ { trial_end: stamp("2026-02-01T00:00:00Z") },
49
+ { next_pending_invoice_item_invoice: stamp("2026-01-25T00:00:00Z") },
50
+ { billing_mode: { type: "future_mode", flexible: null } },
51
+ ])(
52
+ "rejects known unproven original settings before attach %j",
53
+ (subscription) => {
54
+ expect(
55
+ preflightRenewalReplacement(fixture({ subscription }).preflightInput),
56
+ ).toMatchObject({ status: "unsupported", reason: expect.any(String) });
57
+ },
58
+ );
59
+
60
+ it.each([
61
+ ["customer_account", "acct_foreign"],
62
+ ["customer", "cus_foreign"],
63
+ ["currency", "eur"],
64
+ ["schedule", "sub_sched_foreign"],
65
+ ["cancel_at_period_end", true],
66
+ ] as const)("rejects fresh original drift at %s", (field, value) => {
67
+ const input = alter(
68
+ fixture().preflightInput,
69
+ ["freshSubscription", field],
70
+ value,
71
+ );
72
+ const result = preflightRenewalReplacement(input);
73
+ expect(["unsupported", "conflict"]).toContain(result.status);
74
+ expect(result).toHaveProperty("reason", expect.any(String));
75
+ });
76
+
77
+ it("rejects a forged logical binding rather than trusting its string", () => {
78
+ const result = preflightRenewalReplacement(
79
+ alter(
80
+ fixture().preflightInput,
81
+ ["prepared", "requestIdentity", "binding"],
82
+ "renewal:v1:forged",
83
+ ),
84
+ );
85
+ expect(result).toMatchObject({
86
+ status: "conflict",
87
+ reason: expect.stringMatching(/binding|prepared|identity/i),
88
+ });
89
+ });
90
+
91
+ it.each([
92
+ [["freshSubscription", "id"], "sub_other"],
93
+ [["freshSubscription", "items", "data", 0, "id"], "si_other"],
94
+ [["freshSubscription", "items", "data", 0, "quantity"], 4],
95
+ [["freshSubscription", "items", "data", 0, "current_period_end"], 999],
96
+ [["freshSubscription", "items", "data", 0, "price", "id"], "price_other"],
97
+ [
98
+ ["freshSubscription", "items", "data", 0, "price", "product"],
99
+ "other-product",
100
+ ],
101
+ [["freshSubscription", "items", "has_more"], true],
102
+ [["targetPrice", "id"], "price_other"],
103
+ [["targetPrice", "product"], "other-product"],
104
+ [["targetPrice", "active"], false],
105
+ [["targetPrice", "currency"], "eur"],
106
+ [["targetPrice", "livemode"], true],
107
+ [["billingCustomer", "customer_account"], "acct_other"],
108
+ [["billingCustomer", "deleted"], true],
109
+ ] as const)(
110
+ "rejects exact selector or incomplete read drift at %j",
111
+ (path, value) => {
112
+ const result = preflightRenewalReplacement(
113
+ alter(fixture().preflightInput, [...path], value),
114
+ );
115
+ expect(["unsupported", "conflict"]).toContain(result.status);
116
+ expect(result).toHaveProperty("reason", expect.any(String));
117
+ },
118
+ );
119
+
120
+ it("classifies flexible billing explicitly without silently migrating it", () => {
121
+ const f = fixture({
122
+ subscription: {
123
+ billing_mode: {
124
+ type: "flexible",
125
+ flexible: { proration_discounts: "included" },
126
+ updated_at: stamp("2025-12-01T00:00:00Z"),
127
+ },
128
+ },
129
+ });
130
+ expect(preflightRenewalReplacement(f.preflightInput)).toMatchObject({
131
+ status: "preflighted_for_projection",
132
+ providerQualification: "required",
133
+ profile: { billingMode: "flexible", cadence: "same" },
134
+ });
135
+ });
136
+
137
+ it("treats a different recurring count as changed cadence", () => {
138
+ expect(
139
+ preflightRenewalReplacement(fixture({ targetCount: 3 }).preflightInput),
140
+ ).toMatchObject({
141
+ status: "preflighted_for_projection",
142
+ profile: { cadence: "changed" },
143
+ providerQualification: "required",
144
+ });
145
+ });
146
+
147
+ it.each([
148
+ [
149
+ "2026-01-31T00:00:00Z",
150
+ "2026-02-28T00:00:00Z",
151
+ "2026-02-01T00:00:00Z",
152
+ "month",
153
+ ],
154
+ [
155
+ "2024-01-31T00:00:00Z",
156
+ "2024-02-29T00:00:00Z",
157
+ "2024-02-01T00:00:00Z",
158
+ "month",
159
+ ],
160
+ [
161
+ "2024-02-29T00:00:00Z",
162
+ "2025-02-28T00:00:00Z",
163
+ "2024-06-01T00:00:00Z",
164
+ "year",
165
+ ],
166
+ ] as const)(
167
+ "retains calendar-edge qualification for %s",
168
+ (start, end, observed, interval) => {
169
+ const f = fixture({
170
+ start: stamp(start),
171
+ end: stamp(end),
172
+ observedAt: stamp(observed),
173
+ currentInterval: interval,
174
+ targetInterval: interval,
175
+ });
176
+ expect(preflightRenewalReplacement(f.preflightInput)).toMatchObject({
177
+ status: "preflighted_for_projection",
178
+ providerQualification: "required",
179
+ profile: { anchor: "calendar_edge", cadence: "same" },
180
+ });
181
+ },
182
+ );
183
+
184
+ it("keeps changed-cadence anchor configuration explicitly unsupported", () => {
185
+ const f = fixture({
186
+ targetInterval: "year",
187
+ subscription: {
188
+ billing_cycle_anchor_config: {
189
+ day_of_month: 15,
190
+ month: null,
191
+ hour: 0,
192
+ minute: 0,
193
+ second: 0,
194
+ },
195
+ },
196
+ });
197
+ expect(preflightRenewalReplacement(f.preflightInput)).toMatchObject({
198
+ status: "unsupported",
199
+ reason: expect.stringMatching(/anchor|cadence/i),
200
+ });
201
+ });
202
+
203
+ it("does not normalize an explicit preview version to endive", () => {
204
+ const result = preflightRenewalReplacement({
205
+ ...fixture().preflightInput,
206
+ apiVersion: "2026-09-30.preview",
207
+ });
208
+ expect(result).toMatchObject({
209
+ status: "unsupported",
210
+ reason: expect.stringMatching(/version|preview/i),
211
+ });
212
+ });
213
+
214
+ it.each([
215
+ { id: "custom-target", object: "customer", livemode: false },
216
+ { id: "custom-target", object: "product", livemode: true },
217
+ ])("rejects contradictory expanded target product facts %j", (product) => {
218
+ if (product.object !== "product") {
219
+ const malformedFreshRead = alter(
220
+ fixture().preflightInput,
221
+ ["targetPrice", "product"],
222
+ product,
223
+ );
224
+ expect(preflightRenewalReplacement(malformedFreshRead).status).toBe(
225
+ "unsupported",
226
+ );
227
+ return;
228
+ }
229
+ const f = fixture({ target: { product } });
230
+ expect(preflightRenewalReplacement(f.preflightInput).status).toBe(
231
+ "unsupported",
232
+ );
233
+ });
@@ -0,0 +1,211 @@
1
+ import { z } from "zod";
2
+ import { prepareRenewalPriceReplacement } from "../renewalPriceReplacement.js";
3
+ import {
4
+ renewalSubscription,
5
+ renewalPrice,
6
+ renewalBillingCustomer,
7
+ } from "../renewalReplacementSchema.js";
8
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
9
+ import {
10
+ object,
11
+ readInput,
12
+ referenceId,
13
+ equal,
14
+ conflict,
15
+ unsupported,
16
+ failure,
17
+ supportedVersion,
18
+ timestamp,
19
+ resourceId,
20
+ productId,
21
+ } from "./shared.js";
22
+ import { profileOf } from "./profile.js";
23
+ import { qualifySourceDiscounts } from "./sourceDiscounts.js";
24
+ import { qualifyOriginalSettings } from "./sourceSettings.js";
25
+
26
+ export function retainedPreparation(value: unknown) {
27
+ try {
28
+ const candidate = object(value);
29
+ const snapshot = object(candidate.providerSnapshot);
30
+ const identity = object(candidate.requestIdentity);
31
+ const prepared = prepareRenewalPriceReplacement({
32
+ subscription: snapshot.subscription,
33
+ targetPrice: snapshot.targetPrice,
34
+ ...(snapshot.billingCustomer === undefined
35
+ ? {}
36
+ : { billingCustomer: snapshot.billingCustomer }),
37
+ expected: candidate.expected as Parameters<
38
+ typeof prepareRenewalPriceReplacement
39
+ >[0]["expected"],
40
+ key: z.string().parse(identity.key),
41
+ });
42
+ if (!equal(prepared, candidate)) conflict("invalid_prepared_binding");
43
+ return prepared;
44
+ } catch {
45
+ return conflict("invalid_prepared_binding");
46
+ }
47
+ }
48
+
49
+ const attachedReference = z.union([
50
+ resourceId("sub_sched"),
51
+ z
52
+ .object({
53
+ id: resourceId("sub_sched"),
54
+ object: z.literal("subscription_schedule"),
55
+ deleted: z.literal(false).optional(),
56
+ customer_account: resourceId("acct").optional(),
57
+ livemode: z.boolean().optional(),
58
+ })
59
+ .passthrough(),
60
+ ]);
61
+
62
+ export function validateReads(
63
+ args: z.infer<typeof readInput>,
64
+ scheduleId?: string,
65
+ ) {
66
+ const prepared = retainedPreparation(args.prepared);
67
+ supportedVersion(args.apiVersion);
68
+ const subscription = renewalSubscription
69
+ .extend({ schedule: scheduleId ? attachedReference : z.null() })
70
+ .safeParse(args.freshSubscription);
71
+ if (!subscription.success)
72
+ unsupported("unsupported_original_subscription_state");
73
+ const source = subscription.data;
74
+ if (scheduleId) {
75
+ if (
76
+ referenceId(source.schedule, "sub_sched", "subscription_schedule") !==
77
+ scheduleId
78
+ )
79
+ conflict("schedule_association_mismatch");
80
+ if (
81
+ typeof source.schedule === "object" &&
82
+ source.schedule !== null &&
83
+ ((source.schedule.customer_account !== undefined &&
84
+ source.schedule.customer_account !==
85
+ prepared.expected.customerAccountId) ||
86
+ (source.schedule.livemode !== undefined &&
87
+ source.schedule.livemode !== prepared.expected.livemode))
88
+ )
89
+ conflict("schedule_association_mismatch");
90
+ }
91
+ const { schedule: originalSchedule, ...original } =
92
+ prepared.providerSnapshot.subscription;
93
+ const { schedule: freshSchedule, ...fresh } = source;
94
+ if (scheduleId ? originalSchedule !== null : freshSchedule !== null)
95
+ conflict("schedule_association_mismatch");
96
+ if (!equal(original, fresh)) conflict("original_source_drift");
97
+ const target = renewalPrice.safeParse(args.targetPrice);
98
+ if (!target.success || !target.data.active)
99
+ unsupported("unsupported_target_price");
100
+ if (!equal(target.data, prepared.providerSnapshot.targetPrice))
101
+ conflict("target_price_drift");
102
+ if (
103
+ prepared.providerSnapshot.billingCustomer === undefined ||
104
+ args.billingCustomer === undefined
105
+ )
106
+ unsupported("missing_retained_billing_customer");
107
+ const customer = renewalBillingCustomer.safeParse(args.billingCustomer);
108
+ if (!customer.success) unsupported("unsupported_billing_customer");
109
+ if (!equal(customer.data, prepared.providerSnapshot.billingCustomer))
110
+ conflict("billing_customer_drift");
111
+ const referenceContext = {
112
+ customerAccountId: prepared.expected.customerAccountId,
113
+ livemode: prepared.expected.livemode,
114
+ };
115
+ if (
116
+ referenceId(source.customer, "cus", "customer", referenceContext) !==
117
+ customer.data.id ||
118
+ customer.data.customer_account !== prepared.expected.customerAccountId ||
119
+ customer.data.livemode !== prepared.expected.livemode
120
+ )
121
+ conflict("billing_customer_identity_mismatch");
122
+ const item = source.items.data[0];
123
+ if (
124
+ productId(item.price.product, referenceContext) !==
125
+ prepared.expected.currentProductId ||
126
+ productId(target.data.product, referenceContext) !==
127
+ prepared.expected.targetProductId
128
+ )
129
+ unsupported("product_identity_mismatch");
130
+ if (
131
+ args.observedAt < prepared.expected.periodStart ||
132
+ args.observedAt >= prepared.expected.periodEnd
133
+ )
134
+ unsupported("outside_original_paid_period");
135
+ for (const field of [
136
+ "billing_thresholds",
137
+ "managed_payments",
138
+ "next_pending_invoice_item_invoice",
139
+ "pending_invoice_item_interval",
140
+ "pending_setup_intent",
141
+ "canceled_at",
142
+ "ended_at",
143
+ "trial_settings",
144
+ ])
145
+ if (source[field] !== null) unsupported(`unsupported_original_${field}`);
146
+ if (item.billing_thresholds !== null)
147
+ unsupported("unsupported_item_billing_thresholds");
148
+ if (item.current_trial !== null)
149
+ unsupported("unsupported_or_missing_item_current_trial");
150
+ if (
151
+ !Array.isArray(source.billing_schedules) ||
152
+ source.billing_schedules.length
153
+ )
154
+ unsupported("unsupported_original_billing_schedules");
155
+ if (
156
+ source.trial_end !== null &&
157
+ (!timestamp.safeParse(source.trial_end).success ||
158
+ Number(source.trial_end) > prepared.expected.periodStart)
159
+ )
160
+ unsupported("unsupported_original_trial");
161
+ if (source.status_details != null || source.presentment_details != null)
162
+ unsupported("unsupported_special_billing_state");
163
+ const originalSettings = qualifyOriginalSettings(source, item, customer.data);
164
+ const profile = profileOf(source, item.price, target.data, args.apiVersion);
165
+ const anchor = timestamp.parse(source.billing_cycle_anchor);
166
+ if (anchor > prepared.expected.periodStart)
167
+ unsupported("unqualified_anchor_after_paid_period_start");
168
+ const discounts = qualifySourceDiscounts(
169
+ source.discounts,
170
+ "subscription",
171
+ prepared.expected,
172
+ customer.data.id,
173
+ args.observedAt,
174
+ );
175
+ const itemDiscounts = qualifySourceDiscounts(
176
+ item.discounts,
177
+ "item",
178
+ prepared.expected,
179
+ customer.data.id,
180
+ args.observedAt,
181
+ );
182
+ return {
183
+ prepared,
184
+ subscription: source,
185
+ item,
186
+ customer: customer.data,
187
+ targetPrice: target.data,
188
+ profile,
189
+ discounts,
190
+ itemDiscounts,
191
+ originalSettings,
192
+ };
193
+ }
194
+
195
+ export function preflightRenewalReplacement(input: unknown) {
196
+ try {
197
+ const args = readInput.parse(renewalSnapshot(input));
198
+ const reads = validateReads(args);
199
+ return {
200
+ version: 1 as const,
201
+ status: "preflighted_for_projection" as const,
202
+ scope: "platform" as const,
203
+ expected: reads.prepared.expected,
204
+ quantity: reads.prepared.quantity,
205
+ profile: reads.profile,
206
+ providerQualification: "required" as const,
207
+ };
208
+ } catch (error) {
209
+ return failure(error);
210
+ }
211
+ }