@fantastic.dev/better-stripe 0.80.0 → 0.81.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 (36) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalPriceReplacement.d.ts +2 -0
  4. package/dist/client/billing/renewalPriceReplacement.d.ts.map +1 -1
  5. package/dist/client/billing/renewalProjection/discounts.d.ts +20 -0
  6. package/dist/client/billing/renewalProjection/discounts.d.ts.map +1 -0
  7. package/dist/client/billing/renewalProjection/discounts.js +121 -0
  8. package/dist/client/billing/renewalProjection/discounts.js.map +1 -0
  9. package/dist/client/billing/renewalProjection/itemSettings.d.ts +14 -0
  10. package/dist/client/billing/renewalProjection/itemSettings.d.ts.map +1 -0
  11. package/dist/client/billing/renewalProjection/itemSettings.js +41 -0
  12. package/dist/client/billing/renewalProjection/itemSettings.js.map +1 -0
  13. package/dist/client/billing/renewalProjection/settings.d.ts +18 -0
  14. package/dist/client/billing/renewalProjection/settings.d.ts.map +1 -0
  15. package/dist/client/billing/renewalProjection/settings.js +132 -0
  16. package/dist/client/billing/renewalProjection/settings.js.map +1 -0
  17. package/dist/client/billing/renewalProjection/settingsSchema.d.ts +200 -0
  18. package/dist/client/billing/renewalProjection/settingsSchema.d.ts.map +1 -0
  19. package/dist/client/billing/renewalProjection/settingsSchema.js +150 -0
  20. package/dist/client/billing/renewalProjection/settingsSchema.js.map +1 -0
  21. package/dist/client/billing/renewalReplacementSchema.d.ts +2 -0
  22. package/dist/client/billing/renewalReplacementSchema.d.ts.map +1 -1
  23. package/dist/client/billing/renewalReplacementSchema.js +10 -4
  24. package/dist/client/billing/renewalReplacementSchema.js.map +1 -1
  25. package/docs/renewal-preservation-mappings.md +94 -0
  26. package/docs/renewal-price-replacements.md +5 -0
  27. package/package.json +1 -1
  28. package/src/client/billing/renewal-discount-projection.test.ts +207 -0
  29. package/src/client/billing/renewal-item-settings-projection.test.ts +79 -0
  30. package/src/client/billing/renewal-price-replacement.test.ts +46 -0
  31. package/src/client/billing/renewal-settings-projection.test.ts +300 -0
  32. package/src/client/billing/renewalProjection/discounts.ts +152 -0
  33. package/src/client/billing/renewalProjection/itemSettings.ts +55 -0
  34. package/src/client/billing/renewalProjection/settings.ts +163 -0
  35. package/src/client/billing/renewalProjection/settingsSchema.ts +154 -0
  36. package/src/client/billing/renewalReplacementSchema.ts +10 -4
@@ -13,6 +13,22 @@ const expected = {
13
13
  periodEnd: 1702592000,
14
14
  livemode: false,
15
15
  };
16
+
17
+ it.each(["current", "target"] as const)(
18
+ "accepts provider-valid custom %s product IDs",
19
+ (which) => {
20
+ const args = structuredClone(input());
21
+ if (which === "current") {
22
+ args.expected.currentProductId = "custom-original-catalog-item";
23
+ args.subscription.items.data[0].price.product =
24
+ args.expected.currentProductId;
25
+ } else {
26
+ args.expected.targetProductId = "custom-target-catalog-item";
27
+ args.targetPrice.product = args.expected.targetProductId;
28
+ }
29
+ expect(sdk.prepareRenewalPriceReplacement(args).status).toBe("prepared");
30
+ },
31
+ );
16
32
  function price(id = "price_original", product = "prod_original") {
17
33
  return {
18
34
  id,
@@ -70,6 +86,36 @@ function input() {
70
86
  };
71
87
  }
72
88
 
89
+ it("accepts an undeleted expanded custom product reference", () => {
90
+ const args = structuredClone(input());
91
+ args.expected.targetProductId = "custom-target";
92
+ expect(
93
+ sdk.prepareRenewalPriceReplacement({
94
+ ...args,
95
+ targetPrice: {
96
+ ...args.targetPrice,
97
+ product: { id: "custom-target", object: "product" },
98
+ },
99
+ }).status,
100
+ ).toBe("prepared");
101
+ });
102
+
103
+ it.each(["coupon", "customer"])(
104
+ "rejects a wrong expanded product object %s",
105
+ (object) => {
106
+ const args = input();
107
+ expect(() =>
108
+ sdk.prepareRenewalPriceReplacement({
109
+ ...args,
110
+ targetPrice: {
111
+ ...args.targetPrice,
112
+ product: { id: args.expected.targetProductId, object },
113
+ },
114
+ }),
115
+ ).toThrow();
116
+ },
117
+ );
118
+
73
119
  it("exports read-only renewal preparation without exposing a schedule writer", () => {
74
120
  expect(sdk).toHaveProperty(
75
121
  "prepareRenewalPriceReplacement",
@@ -0,0 +1,300 @@
1
+ import { expect, it } from "vitest";
2
+ import * as projection from "./renewalProjection/settings.js";
3
+
4
+ const context = {
5
+ customerAccountId: "acct_buyer",
6
+ customerId: "cus_buyer",
7
+ livemode: false,
8
+ effectiveCollectionMethod: "charge_automatically",
9
+ effectiveAutomaticTax: false,
10
+ effectiveInvoiceIssuer: { type: "self" },
11
+ };
12
+ function settings() {
13
+ return {
14
+ application_fee_percent: null,
15
+ billing_thresholds: null,
16
+ collection_method: null,
17
+ default_payment_method: null,
18
+ on_behalf_of: null,
19
+ transfer_data: null,
20
+ automatic_tax: { enabled: false, liability: null, disabled_reason: null },
21
+ default_tax_rates: [],
22
+ invoice_settings: {
23
+ account_tax_ids: null,
24
+ custom_fields: null,
25
+ days_until_due: null,
26
+ description: null,
27
+ footer: null,
28
+ issuer: null,
29
+ },
30
+ description: null,
31
+ metadata: null,
32
+ };
33
+ }
34
+ const project = (value: unknown) =>
35
+ projection.projectRenewalPhaseSettings({
36
+ context,
37
+ settings: value,
38
+ });
39
+
40
+ it("maps disabled tax and explicit empty rates without inventing null writes", () => {
41
+ expect(project(settings())).toEqual({
42
+ status: "projected",
43
+ settings: { automatic_tax: { enabled: false }, default_tax_rates: "" },
44
+ requiresProviderQualification: true,
45
+ });
46
+ });
47
+
48
+ it("maps exact routing, descriptions and nonempty metadata without mutating reads", () => {
49
+ const value = {
50
+ ...settings(),
51
+ on_behalf_of: { id: "acct_issuer", object: "account" },
52
+ transfer_data: { destination: "acct_destination", amount_percent: 0 },
53
+ description: "",
54
+ metadata: { original: "retained" },
55
+ };
56
+ const before = structuredClone(value);
57
+ expect(project(value)).toMatchObject({
58
+ status: "projected",
59
+ settings: {
60
+ on_behalf_of: "acct_issuer",
61
+ transfer_data: { destination: "acct_destination", amount_percent: 0 },
62
+ description: "",
63
+ metadata: { original: "retained" },
64
+ },
65
+ });
66
+ expect(value).toEqual(before);
67
+ });
68
+
69
+ it("omits a null transfer percentage rather than fabricating full-transfer values", () => {
70
+ expect(
71
+ project({
72
+ ...settings(),
73
+ transfer_data: {
74
+ destination: "acct_destination",
75
+ amount_percent: null,
76
+ },
77
+ }),
78
+ ).toMatchObject({
79
+ status: "projected",
80
+ settings: {
81
+ transfer_data: { destination: "acct_destination" },
82
+ },
83
+ });
84
+ });
85
+
86
+ it.each([
87
+ [0, "projected"],
88
+ [0.01, "projected"],
89
+ [0.29, "projected"],
90
+ [99.99, "projected"],
91
+ [100, "projected"],
92
+ [0.001, "unsupported"],
93
+ [1.234, "unsupported"],
94
+ ] as const)(
95
+ "qualifies exact transfer percentage precision %s",
96
+ (amount_percent, status) => {
97
+ expect(
98
+ project({
99
+ ...settings(),
100
+ transfer_data: {
101
+ destination: "acct_destination",
102
+ amount_percent,
103
+ },
104
+ }).status,
105
+ ).toBe(status);
106
+ },
107
+ );
108
+
109
+ it.each([
110
+ { application_fee_percent: 0 },
111
+ { billing_thresholds: { amount_gte: 100 } },
112
+ { collection_method: "future_mode" },
113
+ { on_behalf_of: { id: "acct_issuer", object: "account", deleted: true } },
114
+ {
115
+ default_payment_method: {
116
+ id: "pm_existing",
117
+ object: "payment_method",
118
+ customer: "cus_foreign",
119
+ },
120
+ },
121
+ {
122
+ automatic_tax: {
123
+ enabled: false,
124
+ disabled_reason: "requires_location_inputs",
125
+ },
126
+ },
127
+ {
128
+ automatic_tax: {
129
+ enabled: true,
130
+ liability: { type: "account", account: null },
131
+ },
132
+ },
133
+ { metadata: { remove: "" } },
134
+ { future_setting: true },
135
+ ])("rejects incomplete or unqualified settings %j", (extra) => {
136
+ expect(project({ ...settings(), ...extra }).status).toBe("unsupported");
137
+ });
138
+
139
+ it("rejects manual tax alongside enabled automatic tax", () => {
140
+ expect(
141
+ project({
142
+ ...settings(),
143
+ automatic_tax: { enabled: true },
144
+ default_tax_rates: [
145
+ { id: "txr_existing", object: "tax_rate", livemode: false },
146
+ ],
147
+ }).status,
148
+ ).toBe("unsupported");
149
+ });
150
+
151
+ it("rejects manual tax inherited alongside automatic tax from unchanged defaults", () => {
152
+ const value = settings();
153
+ const { automatic_tax: _, ...rest } = value;
154
+ expect(
155
+ projection.projectRenewalPhaseSettings({
156
+ context: { ...context, effectiveAutomaticTax: true },
157
+ settings: {
158
+ ...rest,
159
+ default_tax_rates: [
160
+ { id: "txr_existing", object: "tax_rate", livemode: false },
161
+ ],
162
+ },
163
+ }).status,
164
+ ).toBe("unsupported");
165
+ });
166
+
167
+ it("maps account tax liability and preserves invoice tax IDs in order", () => {
168
+ const value = settings();
169
+ expect(
170
+ projection.projectRenewalPhaseSettings({
171
+ context: { ...context, effectiveAutomaticTax: true },
172
+ settings: {
173
+ ...value,
174
+ automatic_tax: {
175
+ enabled: true,
176
+ liability: { type: "account", account: "acct_liable" },
177
+ },
178
+ invoice_settings: {
179
+ ...value.invoice_settings,
180
+ account_tax_ids: [
181
+ {
182
+ id: "txi_first",
183
+ object: "tax_id",
184
+ livemode: false,
185
+ customer: null,
186
+ customer_account: null,
187
+ owner: { type: "self", customer_account: null },
188
+ },
189
+ "txi_second",
190
+ ],
191
+ },
192
+ },
193
+ }),
194
+ ).toMatchObject({
195
+ status: "projected",
196
+ settings: {
197
+ automatic_tax: {
198
+ enabled: true,
199
+ liability: { type: "account", account: "acct_liable" },
200
+ },
201
+ invoice_settings: { account_tax_ids: ["txi_first", "txi_second"] },
202
+ },
203
+ });
204
+ });
205
+
206
+ it("rejects a tax reference from the wrong mode", () => {
207
+ expect(
208
+ project({
209
+ ...settings(),
210
+ default_tax_rates: [
211
+ { id: "txr_live", object: "tax_rate", livemode: true },
212
+ ],
213
+ }).status,
214
+ ).toBe("unsupported");
215
+ });
216
+
217
+ it.each([{ livemode: true }, { customer_account: "acct_foreign" }])(
218
+ "rejects contradictory nested payment-method customer facts %j",
219
+ (extra) => {
220
+ expect(
221
+ project({
222
+ ...settings(),
223
+ default_payment_method: {
224
+ id: "pm_existing",
225
+ object: "payment_method",
226
+ livemode: false,
227
+ customer: { id: "cus_buyer", object: "customer", ...extra },
228
+ },
229
+ }).status,
230
+ ).toBe("unsupported");
231
+ },
232
+ );
233
+
234
+ it.each([
235
+ undefined,
236
+ { type: "account", account: "acct_foreign", customer_account: null },
237
+ { type: "customer", customer: "cus_buyer", customer_account: "acct_buyer" },
238
+ ])("rejects unqualified invoice tax ownership %j", (owner) => {
239
+ const value = settings();
240
+ const tax = {
241
+ id: "txi_existing",
242
+ object: "tax_id",
243
+ livemode: false,
244
+ ...(owner === undefined ? {} : { owner }),
245
+ };
246
+ expect(
247
+ project({
248
+ ...value,
249
+ invoice_settings: {
250
+ ...value.invoice_settings,
251
+ account_tax_ids: [tax],
252
+ },
253
+ }).status,
254
+ ).toBe("unsupported");
255
+ });
256
+
257
+ it("maps invoice Emptyables, an explicit issuer and zero-day send_invoice terms", () => {
258
+ expect(
259
+ projection.projectRenewalPhaseSettings({
260
+ context: { ...context, effectiveCollectionMethod: "send_invoice" },
261
+ settings: {
262
+ ...settings(),
263
+ collection_method: "send_invoice",
264
+ invoice_settings: {
265
+ account_tax_ids: [],
266
+ custom_fields: [],
267
+ days_until_due: 0,
268
+ description: "",
269
+ footer: "original footer",
270
+ issuer: { type: "self" },
271
+ },
272
+ },
273
+ }),
274
+ ).toMatchObject({
275
+ status: "projected",
276
+ settings: {
277
+ invoice_settings: {
278
+ account_tax_ids: "",
279
+ custom_fields: "",
280
+ days_until_due: 0,
281
+ description: "",
282
+ footer: "original footer",
283
+ issuer: { type: "self" },
284
+ },
285
+ },
286
+ });
287
+ });
288
+
289
+ it("rejects due days for charge_automatically", () => {
290
+ const value = settings();
291
+ expect(
292
+ project({
293
+ ...value,
294
+ invoice_settings: {
295
+ ...value.invoice_settings,
296
+ days_until_due: 3,
297
+ },
298
+ }).status,
299
+ ).toBe("unsupported");
300
+ });
@@ -0,0 +1,152 @@
1
+ import { z } from "zod";
2
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
3
+
4
+ // Coupons and products may have caller-supplied IDs. Do not require a prefix.
5
+ const id = z.string().min(1).max(255).regex(/\S/);
6
+ const resourceId = (prefix: string) =>
7
+ z
8
+ .string()
9
+ .max(255)
10
+ .regex(new RegExp(`^${prefix}_[A-Za-z0-9_]+$`));
11
+ const coupon = z
12
+ .object({
13
+ id,
14
+ object: z.literal("coupon"),
15
+ deleted: z.literal(false).optional(),
16
+ duration: z.enum(["once", "repeating", "forever"]),
17
+ applies_to: z
18
+ .object({ products: z.array(id) })
19
+ .strict()
20
+ .optional(),
21
+ })
22
+ .passthrough();
23
+ const redemption = z
24
+ .object({
25
+ id: resourceId("di"),
26
+ object: z.literal("discount"),
27
+ deleted: z.literal(false).optional(),
28
+ customer_account: resourceId("acct"),
29
+ subscription: resourceId("sub").nullable(),
30
+ subscription_item: resourceId("si").nullable(),
31
+ start: z.number().int().nonnegative(),
32
+ end: z.number().int().nonnegative().nullable(),
33
+ source: z.object({ type: z.literal("coupon"), coupon }).passthrough(),
34
+ })
35
+ .passthrough();
36
+ const reference = (object: string, identity = id) =>
37
+ z.union([
38
+ identity,
39
+ z
40
+ .object({
41
+ id: identity,
42
+ object: z.literal(object),
43
+ deleted: z.literal(false).optional(),
44
+ })
45
+ .strict(),
46
+ ]);
47
+ const inputSchema = z
48
+ .object({
49
+ customerAccountId: resourceId("acct"),
50
+ subscriptionId: resourceId("sub"),
51
+ level: z.enum(["subscription", "subscription_item"]),
52
+ itemId: resourceId("si").optional(),
53
+ currentProductId: id,
54
+ targetProductId: id,
55
+ redemptions: z.array(redemption).max(20),
56
+ phaseDiscounts: z
57
+ .array(
58
+ z
59
+ .object({
60
+ discount: reference("discount", resourceId("di")),
61
+ coupon: reference("coupon").nullable().optional(),
62
+ promotion_code: z.null().optional(),
63
+ })
64
+ .passthrough(),
65
+ )
66
+ .max(20),
67
+ })
68
+ .strict();
69
+
70
+ type Reason =
71
+ | "incomplete_discount_evidence"
72
+ | "ambiguous_empty_discount_hierarchy"
73
+ | "discount_not_owned_at_level"
74
+ | "discount_duration_not_qualified"
75
+ | "coupon_product_applicability"
76
+ | "phase_redemption_mismatch"
77
+ | "duplicate_redemptions";
78
+ export type RenewalDiscountProjection =
79
+ | { status: "unsupported"; reason: Reason }
80
+ | {
81
+ status: "projected";
82
+ discounts: { discount: string }[];
83
+ requiresProviderQualification: true;
84
+ };
85
+
86
+ /**
87
+ * Project only a direct, unambiguous existing forever redemption. Ancestor-owned
88
+ * redemptions are unsupported. Phase references must be IDs or minimal reference
89
+ * objects; full expanded objects require separate normalization and correlation.
90
+ * This field projection requires provider qualification before writer eligibility.
91
+ */
92
+ export function projectRenewalDiscounts(
93
+ input: unknown,
94
+ ): RenewalDiscountProjection {
95
+ let parsed: ReturnType<typeof inputSchema.safeParse>;
96
+ try {
97
+ parsed = inputSchema.safeParse(renewalSnapshot(input));
98
+ } catch {
99
+ return { status: "unsupported", reason: "incomplete_discount_evidence" };
100
+ }
101
+ if (!parsed.success)
102
+ return { status: "unsupported", reason: "incomplete_discount_evidence" };
103
+ const args = parsed.data;
104
+ const unsupported = (reason: Reason): RenewalDiscountProjection => ({
105
+ status: "unsupported",
106
+ reason,
107
+ });
108
+ if (args.redemptions.length === 0 && args.phaseDiscounts.length === 0)
109
+ return unsupported("ambiguous_empty_discount_hierarchy");
110
+ if (args.redemptions.length !== args.phaseDiscounts.length)
111
+ return unsupported("phase_redemption_mismatch");
112
+ if (
113
+ new Set(args.redemptions.map((v) => v.id)).size !== args.redemptions.length
114
+ )
115
+ return unsupported("duplicate_redemptions");
116
+ const refId = (value: z.infer<ReturnType<typeof reference>>) =>
117
+ typeof value === "string" ? value : value.id;
118
+ for (const [index, value] of args.redemptions.entries()) {
119
+ if (
120
+ value.customer_account !== args.customerAccountId ||
121
+ (args.level === "subscription" &&
122
+ (value.subscription !== args.subscriptionId ||
123
+ value.subscription_item !== null)) ||
124
+ (args.level === "subscription_item" &&
125
+ (!args.itemId ||
126
+ value.subscription_item !== args.itemId ||
127
+ (value.subscription !== null &&
128
+ value.subscription !== args.subscriptionId)))
129
+ )
130
+ return unsupported("discount_not_owned_at_level");
131
+ if (value.source.coupon.duration !== "forever" || value.end !== null)
132
+ return unsupported("discount_duration_not_qualified");
133
+ const products = value.source.coupon.applies_to?.products;
134
+ if (
135
+ products &&
136
+ (!products.includes(args.currentProductId) ||
137
+ !products.includes(args.targetProductId))
138
+ )
139
+ return unsupported("coupon_product_applicability");
140
+ const phase = args.phaseDiscounts[index]!;
141
+ if (
142
+ refId(phase.discount) !== value.id ||
143
+ (phase.coupon != null && refId(phase.coupon) !== value.source.coupon.id)
144
+ )
145
+ return unsupported("phase_redemption_mismatch");
146
+ }
147
+ return {
148
+ status: "projected",
149
+ discounts: args.redemptions.map(({ id: discount }) => ({ discount })),
150
+ requiresProviderQualification: true,
151
+ };
152
+ }
@@ -0,0 +1,55 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
4
+ import { taxRate } from "./settingsSchema.js";
5
+
6
+ const inputSchema = z
7
+ .object({
8
+ effectiveAutomaticTax: z.boolean(),
9
+ livemode: z.boolean(),
10
+ settings: z
11
+ .object({
12
+ billing_thresholds: z.null(),
13
+ tax_rates: z.array(taxRate).max(20).nullable().optional(),
14
+ metadata: z
15
+ .record(z.string().max(40), z.string().min(1).max(500))
16
+ .nullable(),
17
+ })
18
+ .strict(),
19
+ })
20
+ .strict();
21
+ type Settings = Pick<
22
+ Stripe.SubscriptionScheduleUpdateParams.Phase.Item,
23
+ "tax_rates" | "metadata"
24
+ >;
25
+ type Result =
26
+ | { status: "unsupported"; reason: string }
27
+ | {
28
+ status: "projected";
29
+ settings: Settings;
30
+ requiresProviderQualification: true;
31
+ };
32
+
33
+ /** Field projection only. The assembler must derive effective tax from defaults. */
34
+ export function projectRenewalItemSettings(input: unknown): Result {
35
+ let args: z.infer<typeof inputSchema>;
36
+ try {
37
+ args = inputSchema.parse(renewalSnapshot(input));
38
+ } catch {
39
+ return { status: "unsupported", reason: "unsupported_item_settings" };
40
+ }
41
+ const { settings: source } = args;
42
+ if (
43
+ (args.effectiveAutomaticTax && source.tax_rates?.length) ||
44
+ source.tax_rates?.some((tax) => tax.livemode !== args.livemode)
45
+ )
46
+ return { status: "unsupported", reason: "incompatible_item_tax" };
47
+ const settings: Settings = {};
48
+ if (source.tax_rates != null)
49
+ settings.tax_rates = source.tax_rates.length
50
+ ? source.tax_rates.map((tax) => tax.id)
51
+ : "";
52
+ if (source.metadata !== null && Object.keys(source.metadata).length)
53
+ settings.metadata = source.metadata;
54
+ return { status: "projected", settings, requiresProviderQualification: true };
55
+ }