@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,372 @@
1
+ import { expect, it } from "vitest";
2
+ import { projectRenewalConfiguration } from "./index.js";
3
+ import { alter, fixture } from "../../../../tests/renewalAggregate/fixtures.js";
4
+
5
+ it("projects the exact current paid phase and target phase without default writes", () => {
6
+ const f = fixture();
7
+ const before = structuredClone(f.configureInput);
8
+ const result = projectRenewalConfiguration(f.configureInput);
9
+ expect(result).toMatchObject({
10
+ version: 1,
11
+ stage: "configure",
12
+ scope: "platform",
13
+ status: "projected_configure_request",
14
+ providerQualification: "required",
15
+ apiVersion: "2026-09-30.endive",
16
+ scheduleId: "sub_sched_owned",
17
+ attachReceiptBinding: f.attachReceipt.binding,
18
+ baselineBinding: expect.any(String),
19
+ defaultSettingsBinding: expect.any(String),
20
+ firstDispatchedAt: f.configureInput.firstDispatchedAt,
21
+ requestIdentity: {
22
+ key: "renewal:configure-original",
23
+ binding: expect.any(String),
24
+ },
25
+ payload: {
26
+ end_behavior: "release",
27
+ proration_behavior: "none",
28
+ phases: [
29
+ {
30
+ start_date: f.prepared.expected.periodStart,
31
+ end_date: f.prepared.expected.periodEnd,
32
+ currency: "usd",
33
+ items: [
34
+ {
35
+ price: "price_original",
36
+ quantity: 3,
37
+ tax_rates: "",
38
+ discounts: [{ discount: "di_item" }],
39
+ },
40
+ ],
41
+ default_tax_rates: "",
42
+ discounts: [{ discount: "di_subscription" }],
43
+ proration_behavior: "create_prorations",
44
+ },
45
+ {
46
+ start_date: f.prepared.expected.periodEnd,
47
+ duration: { interval: "month", interval_count: 1 },
48
+ billing_cycle_anchor: "automatic",
49
+ currency: "usd",
50
+ items: [
51
+ {
52
+ price: "price_target",
53
+ quantity: 3,
54
+ tax_rates: "",
55
+ discounts: [{ discount: "di_item" }],
56
+ },
57
+ ],
58
+ default_tax_rates: "",
59
+ discounts: [{ discount: "di_subscription" }],
60
+ proration_behavior: "none",
61
+ },
62
+ ],
63
+ },
64
+ });
65
+ expect(result).not.toHaveProperty("payload.default_settings");
66
+ expect(result).not.toHaveProperty("payload.phases.1.end_date");
67
+ expect(result).not.toHaveProperty("payload.phases.0.items.0.plan");
68
+ expect(result).not.toHaveProperty("payload.phases.1.items.0.id");
69
+ for (const phase of [0, 1]) {
70
+ expect(result).not.toHaveProperty(
71
+ `payload.phases.${phase}.discounts.0.coupon`,
72
+ );
73
+ expect(result).not.toHaveProperty(
74
+ `payload.phases.${phase}.discounts.0.promotion_code`,
75
+ );
76
+ expect(result).not.toHaveProperty(
77
+ `payload.phases.${phase}.items.0.discounts.0.coupon`,
78
+ );
79
+ }
80
+ expect(f.configureInput).toEqual(before);
81
+ });
82
+
83
+ it.each(["none", "always_invoice", "create_prorations"])(
84
+ "preserves acknowledged current phase proration mode %s",
85
+ (proration_behavior) => {
86
+ expect(
87
+ projectRenewalConfiguration(
88
+ fixture({ phase: { proration_behavior } }).configureInput,
89
+ ),
90
+ ).toMatchObject({
91
+ status: "projected_configure_request",
92
+ payload: {
93
+ proration_behavior: "none",
94
+ phases: [{ proration_behavior }, { proration_behavior: "none" }],
95
+ },
96
+ });
97
+ },
98
+ );
99
+
100
+ it("binds the explicit configure key without reusing the attach key", () => {
101
+ const f = fixture();
102
+ const first = projectRenewalConfiguration(f.configureInput);
103
+ const second = projectRenewalConfiguration({
104
+ ...f.configureInput,
105
+ configureKey: "renewal:configure-other",
106
+ });
107
+ expect(first).toMatchObject({ status: "projected_configure_request" });
108
+ expect(second).toMatchObject({ status: "projected_configure_request" });
109
+ if (
110
+ first.status !== "projected_configure_request" ||
111
+ second.status !== "projected_configure_request"
112
+ )
113
+ return;
114
+ expect(first.payload).toEqual(second.payload);
115
+ expect(first.requestIdentity.binding).not.toBe(
116
+ second.requestIdentity.binding,
117
+ );
118
+ expect(
119
+ projectRenewalConfiguration({
120
+ ...f.configureInput,
121
+ configureKey: f.attachRequest.requestIdentity.key,
122
+ }).status,
123
+ ).not.toBe("projected_configure_request");
124
+ });
125
+
126
+ it("uses the provider-verified renewal and a changed-cadence phase-start anchor", () => {
127
+ const f = fixture({ targetInterval: "year" });
128
+ const result = projectRenewalConfiguration(f.configureInput);
129
+ expect(result).toMatchObject({
130
+ status: "projected_configure_request",
131
+ profile: { cadence: "changed" },
132
+ providerQualification: "required",
133
+ payload: {
134
+ phases: [
135
+ expect.any(Object),
136
+ {
137
+ start_date: f.prepared.expected.periodEnd,
138
+ duration: { interval: "year", interval_count: 1 },
139
+ billing_cycle_anchor: "phase_start",
140
+ proration_behavior: "none",
141
+ },
142
+ ],
143
+ },
144
+ });
145
+ });
146
+
147
+ it("validates the actual post-attach association instead of pretending schedule is null", () => {
148
+ const input = fixture().configureInput;
149
+ expect(projectRenewalConfiguration(input).status).toBe(
150
+ "projected_configure_request",
151
+ );
152
+ const result = projectRenewalConfiguration(
153
+ alter(input, ["freshSubscription", "schedule"], null),
154
+ );
155
+ expect(result).toMatchObject({
156
+ status: "conflict",
157
+ reason: expect.stringMatching(/schedule|association/i),
158
+ });
159
+ });
160
+
161
+ it.each(
162
+ [
163
+ ["request", "payload", "from_subscription"],
164
+ ["providerSnapshot", "default_settings", "description"],
165
+ ["binding"],
166
+ ].map((path) => ({ path })),
167
+ )("rejects altered retained acknowledgement at %j", ({ path }) => {
168
+ const next = alter(
169
+ fixture().configureInput,
170
+ ["attachReceipt", ...path],
171
+ "forged",
172
+ );
173
+ expect(projectRenewalConfiguration(next)).toMatchObject({
174
+ status: "conflict",
175
+ reason: expect.stringMatching(/binding|receipt|acknowledg/i),
176
+ });
177
+ });
178
+
179
+ it.each(
180
+ [
181
+ ["default_settings", "description"],
182
+ ["phases", 0, "items", 0, "quantity"],
183
+ ["current_phase", "end_date"],
184
+ ].map((path) => ({ path })),
185
+ )("rejects fresh acknowledged-baseline drift at %j", ({ path }) => {
186
+ const result = projectRenewalConfiguration(
187
+ alter(
188
+ fixture().configureInput,
189
+ ["schedule", ...path],
190
+ path[path.length - 1] === "description" ? "changed" : 999,
191
+ ),
192
+ );
193
+ expect(result).toMatchObject({
194
+ status: "conflict",
195
+ reason: expect.stringMatching(/baseline|default|drift|period|phase/i),
196
+ });
197
+ });
198
+
199
+ it("does not adopt unrelated extra future phases or release them as a workaround", () => {
200
+ const f = fixture();
201
+ const result = projectRenewalConfiguration(
202
+ alter(
203
+ f.configureInput,
204
+ ["schedule", "phases"],
205
+ [
206
+ ...f.schedule.phases,
207
+ {
208
+ ...f.schedule.phases[0],
209
+ start_date: f.prepared.expected.periodEnd,
210
+ end_date: f.prepared.expected.periodEnd + 100,
211
+ },
212
+ ],
213
+ ),
214
+ );
215
+ expect(result.status).toBe("conflict");
216
+ expect(result).not.toHaveProperty("payload");
217
+ expect(result).not.toHaveProperty("releaseRequest");
218
+ });
219
+
220
+ it("keeps an acknowledged schedule partial when a paid-term mapping is unsupported", () => {
221
+ const f = fixture({
222
+ phase: { add_invoice_items: [{ price: "price_extra" }] },
223
+ });
224
+ expect(projectRenewalConfiguration(f.configureInput)).toMatchObject({
225
+ status: "attached_unconfigured",
226
+ scheduleId: "sub_sched_owned",
227
+ reason: expect.stringMatching(/invoice|unsupported|mapping/i),
228
+ });
229
+ });
230
+
231
+ it("rejects unknown defaults even though the request would leave defaults untouched", () => {
232
+ const f = fixture({ defaults: { future_unmapped_setting: true } });
233
+ expect(projectRenewalConfiguration(f.configureInput)).toMatchObject({
234
+ status: "attached_unconfigured",
235
+ reason: expect.stringMatching(/default|unsupported|unknown/i),
236
+ });
237
+ });
238
+
239
+ it("rejects resetting a current phase-start anchor away from the original anchor", () => {
240
+ const f = fixture({
241
+ subscription: { billing_cycle_anchor: 1765756800 },
242
+ phase: { billing_cycle_anchor: "phase_start" },
243
+ });
244
+ expect(projectRenewalConfiguration(f.configureInput)).toMatchObject({
245
+ status: "attached_unconfigured",
246
+ reason: expect.stringMatching(/anchor/i),
247
+ });
248
+ });
249
+
250
+ it("copies only acknowledged metadata actions that already match current terms", () => {
251
+ const f = fixture({
252
+ subscription: {
253
+ metadata: {
254
+ keep: "original",
255
+ unrelated: "do-not-turn-into-a-phase-action",
256
+ },
257
+ },
258
+ phase: { metadata: { keep: "original" } },
259
+ phaseItem: { metadata: { seat: "retained" } },
260
+ });
261
+ const result = projectRenewalConfiguration(f.configureInput);
262
+ expect(result).toMatchObject({
263
+ status: "projected_configure_request",
264
+ payload: {
265
+ phases: [
266
+ expect.any(Object),
267
+ {
268
+ metadata: { keep: "original" },
269
+ items: [{ metadata: { seat: "retained" } }],
270
+ },
271
+ ],
272
+ },
273
+ });
274
+ expect(result).not.toHaveProperty("payload.phases.1.metadata.unrelated");
275
+ const conflict = fixture({ phase: { metadata: { keep: "overwrite" } } });
276
+ const rejected = projectRenewalConfiguration(conflict.configureInput);
277
+ expect(rejected.status).not.toBe("projected_configure_request");
278
+ expect(rejected).toHaveProperty(
279
+ "reason",
280
+ expect.stringMatching(/metadata|conflict/i),
281
+ );
282
+ });
283
+
284
+ it("rejects manual phase rates under effective automatic tax inherited from defaults", () => {
285
+ const automatic = { enabled: true, liability: null, disabled_reason: null };
286
+ const f = fixture({
287
+ subscription: { automatic_tax: automatic },
288
+ defaults: { automatic_tax: automatic },
289
+ phase: {
290
+ default_tax_rates: [
291
+ { id: "txr_manual", object: "tax_rate", livemode: false },
292
+ ],
293
+ },
294
+ });
295
+ expect(projectRenewalConfiguration(f.configureInput)).toMatchObject({
296
+ status: "attached_unconfigured",
297
+ reason: expect.stringMatching(/tax/i),
298
+ });
299
+ });
300
+
301
+ it("rejects a future first-dispatch time instead of resetting retained time", () => {
302
+ const f = fixture();
303
+ const result = projectRenewalConfiguration({
304
+ ...f.configureInput,
305
+ firstDispatchedAt: f.configureInput.observedAt + 1,
306
+ });
307
+ expect(result.status).not.toBe("projected_configure_request");
308
+ expect(result).toHaveProperty(
309
+ "reason",
310
+ expect.stringMatching(/time|dispatch/i),
311
+ );
312
+ });
313
+
314
+ it.each([
315
+ { price: { id: "price_original", object: "price", livemode: true } },
316
+ {
317
+ price: {
318
+ id: "price_original",
319
+ object: "price",
320
+ product: "foreign-product",
321
+ },
322
+ },
323
+ { plan: { id: "price_original", object: "plan", livemode: true } },
324
+ ])("rejects contradictory expanded phase price/plan facts %j", (phaseItem) => {
325
+ const f = fixture({ phaseItem });
326
+ expect(projectRenewalConfiguration(f.configureInput).status).not.toBe(
327
+ "projected_configure_request",
328
+ );
329
+ });
330
+
331
+ it("rejects an inherited tax liability that contradicts the original effective liability", () => {
332
+ const f = fixture({
333
+ subscription: {
334
+ automatic_tax: {
335
+ enabled: true,
336
+ liability: { type: "self" },
337
+ disabled_reason: null,
338
+ },
339
+ },
340
+ defaults: {
341
+ automatic_tax: {
342
+ enabled: true,
343
+ liability: { type: "account", account: "acct_other" },
344
+ disabled_reason: null,
345
+ },
346
+ },
347
+ });
348
+ expect(projectRenewalConfiguration(f.configureInput).status).not.toBe(
349
+ "projected_configure_request",
350
+ );
351
+ });
352
+
353
+ it("rejects invoice tax IDs that contradict the current subscription's invoice settings", () => {
354
+ const base = fixture();
355
+ const f = fixture({
356
+ subscription: {
357
+ invoice_settings: {
358
+ ...base.subscription.invoice_settings,
359
+ account_tax_ids: ["txi_original"],
360
+ },
361
+ },
362
+ defaults: {
363
+ invoice_settings: {
364
+ ...base.schedule.default_settings.invoice_settings,
365
+ account_tax_ids: ["txi_other"],
366
+ },
367
+ },
368
+ });
369
+ expect(projectRenewalConfiguration(f.configureInput).status).not.toBe(
370
+ "projected_configure_request",
371
+ );
372
+ });
@@ -0,0 +1,164 @@
1
+ import { z } from "zod";
2
+ import type Stripe from "stripe";
3
+ import { idempotencyOptions } from "../../core/idempotency.js";
4
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
5
+ import { retainedPreparation, validateReads } from "./preflight.js";
6
+ import { validateAttachReceipt } from "./receipt.js";
7
+ import { assemblePhases } from "./phases.js";
8
+ import type { RenewalProfile } from "./profile.js";
9
+ import {
10
+ binding,
11
+ object,
12
+ configureInput,
13
+ equal,
14
+ conflict,
15
+ unsupported,
16
+ failure,
17
+ referenceId,
18
+ type Failure,
19
+ } from "./shared.js";
20
+
21
+ export type ProjectedRenewalConfiguration = {
22
+ version: 1;
23
+ stage: "configure";
24
+ scope: "platform";
25
+ apiVersion: string;
26
+ logicalBinding: string;
27
+ scheduleId: string;
28
+ method: "POST";
29
+ path: string;
30
+ key: string;
31
+ payload: {
32
+ end_behavior: "release";
33
+ proration_behavior: "none";
34
+ phases: [
35
+ Stripe.SubscriptionScheduleUpdateParams.Phase,
36
+ Stripe.SubscriptionScheduleUpdateParams.Phase,
37
+ ];
38
+ };
39
+ firstDispatchedAt: number;
40
+ attachReceiptBinding: string;
41
+ baselineBinding: string;
42
+ defaultSettingsBinding: string;
43
+ status: "projected_configure_request";
44
+ providerQualification: "required";
45
+ profile: RenewalProfile;
46
+ requestIdentity: { key: string; binding: string };
47
+ };
48
+
49
+ export function projectRenewalConfiguration(
50
+ input: unknown,
51
+ ): ProjectedRenewalConfiguration | Failure {
52
+ let ownedScheduleId: string | undefined;
53
+ try {
54
+ const args = configureInput.parse(renewalSnapshot(input));
55
+ const prepared = retainedPreparation(args.prepared);
56
+ const receipt = validateAttachReceipt(
57
+ args.attachReceipt,
58
+ prepared,
59
+ args.apiVersion,
60
+ args.observedAt,
61
+ );
62
+ ownedScheduleId = receipt.scheduleId;
63
+ const key = idempotencyOptions(args.configureKey)?.idempotencyKey;
64
+ if (!key || key === receipt.request.requestIdentity.key)
65
+ unsupported("configure_key_must_be_distinct");
66
+ if (
67
+ args.firstDispatchedAt > args.observedAt ||
68
+ args.firstDispatchedAt < receipt.request.firstDispatchedAt
69
+ )
70
+ unsupported("invalid_retained_dispatch_time");
71
+ const rawSubscription = object(args.freshSubscription);
72
+ if (
73
+ rawSubscription.schedule == null ||
74
+ referenceId(
75
+ rawSubscription.schedule,
76
+ "sub_sched",
77
+ "subscription_schedule",
78
+ ) !== receipt.scheduleId
79
+ )
80
+ conflict("schedule_association_mismatch");
81
+ const reads = validateReads(args, receipt.scheduleId);
82
+ const schedule = object(args.schedule);
83
+ if (!equal(schedule, receipt.providerSnapshot))
84
+ conflict("acknowledged_baseline_or_defaults_drift");
85
+ const expected = prepared.expected;
86
+ const referenceContext = {
87
+ livemode: expected.livemode,
88
+ customerAccountId: expected.customerAccountId,
89
+ };
90
+ if (
91
+ schedule.id !== receipt.scheduleId ||
92
+ schedule.object !== "subscription_schedule" ||
93
+ schedule.customer_account !== expected.customerAccountId ||
94
+ schedule.livemode !== expected.livemode ||
95
+ referenceId(schedule.customer, "cus", "customer", referenceContext) !==
96
+ reads.customer.id ||
97
+ referenceId(
98
+ schedule.subscription,
99
+ "sub",
100
+ "subscription",
101
+ referenceContext,
102
+ ) !== expected.subscriptionId
103
+ )
104
+ conflict("acknowledged_schedule_identity_mismatch");
105
+ if (
106
+ schedule.status !== "active" ||
107
+ schedule.end_behavior !== "release" ||
108
+ schedule.application !== null ||
109
+ schedule.canceled_at !== null ||
110
+ schedule.completed_at !== null ||
111
+ schedule.released_at !== null ||
112
+ schedule.released_subscription !== null ||
113
+ (schedule.pause_schedules !== undefined &&
114
+ (!Array.isArray(schedule.pause_schedules) ||
115
+ schedule.pause_schedules.length))
116
+ )
117
+ unsupported("unsupported_acknowledged_schedule_state");
118
+ if (!equal(schedule.billing_mode, reads.subscription.billing_mode))
119
+ unsupported("schedule_billing_mode_mismatch");
120
+ const current = z
121
+ .object({ start_date: z.number(), end_date: z.number() })
122
+ .strict()
123
+ .parse(schedule.current_phase);
124
+ if (
125
+ current.start_date !== expected.periodStart ||
126
+ current.end_date !== expected.periodEnd
127
+ )
128
+ conflict("current_phase_period_drift");
129
+ const phases = assemblePhases(reads, schedule);
130
+ const payload = {
131
+ end_behavior: "release" as const,
132
+ proration_behavior: "none" as const,
133
+ phases,
134
+ };
135
+ const request = {
136
+ version: 1 as const,
137
+ stage: "configure" as const,
138
+ scope: "platform" as const,
139
+ apiVersion: args.apiVersion,
140
+ logicalBinding: prepared.requestIdentity.binding,
141
+ scheduleId: receipt.scheduleId,
142
+ method: "POST" as const,
143
+ path: `/v1/subscription_schedules/${receipt.scheduleId}`,
144
+ key,
145
+ payload,
146
+ firstDispatchedAt: args.firstDispatchedAt,
147
+ attachReceiptBinding: receipt.binding,
148
+ baselineBinding: binding("renewal-baseline", receipt.providerSnapshot),
149
+ defaultSettingsBinding: binding(
150
+ "renewal-defaults",
151
+ schedule.default_settings,
152
+ ),
153
+ };
154
+ return renewalSnapshot({
155
+ ...request,
156
+ status: "projected_configure_request" as const,
157
+ providerQualification: "required" as const,
158
+ profile: reads.profile,
159
+ requestIdentity: { key, binding: binding("renewal-configure", request) },
160
+ });
161
+ } catch (error) {
162
+ return failure(error, ownedScheduleId);
163
+ }
164
+ }
@@ -0,0 +1,2 @@
1
+ export { preflightRenewalReplacement } from "./preflight.js";
2
+ export { projectRenewalConfiguration } from "./configure.js";
@@ -0,0 +1,144 @@
1
+ import { z } from "zod";
2
+ import { settingsInput } from "../renewalProjection/settingsSchema.js";
3
+ import { projectRenewalPhaseSettings } from "../renewalProjection/settings.js";
4
+ import { object, equal, referenceId, unsupported } from "./shared.js";
5
+ import type { qualifyOriginalSettings } from "./sourceSettings.js";
6
+
7
+ export const defaultsSchema = settingsInput.shape.settings
8
+ .omit({
9
+ metadata: true,
10
+ default_tax_rates: true,
11
+ })
12
+ .extend({
13
+ billing_cycle_anchor: z.enum(["automatic", "phase_start"]),
14
+ invoice_settings:
15
+ settingsInput.shape.settings.shape.invoice_settings.unwrap(),
16
+ })
17
+ .strict();
18
+ export type Defaults = z.infer<typeof defaultsSchema>;
19
+
20
+ const issuerId = (value: unknown) => {
21
+ const issuer = object(value);
22
+ return issuer.type === "self"
23
+ ? "self"
24
+ : referenceId(issuer.account, "acct", "account");
25
+ };
26
+ const refOrNull = (value: unknown, prefix: string, kind: string) =>
27
+ value == null ? null : referenceId(value, prefix, kind);
28
+
29
+ export function contextFor(
30
+ phase: Record<string, unknown>,
31
+ defaults: Defaults,
32
+ subscription: Record<string, unknown>,
33
+ customerId: string,
34
+ customerAccountId: string,
35
+ livemode: boolean,
36
+ originalSettings: ReturnType<typeof qualifyOriginalSettings>,
37
+ ) {
38
+ const phaseInvoice =
39
+ phase.invoice_settings == null ? null : object(phase.invoice_settings);
40
+ const sourceInvoice = originalSettings.invoice;
41
+ const sourceTax = originalSettings.automaticTax;
42
+ const phaseTax =
43
+ phase.automatic_tax === undefined ? undefined : object(phase.automatic_tax);
44
+ const effectiveCollectionMethod =
45
+ phase.collection_method ??
46
+ defaults.collection_method ??
47
+ subscription.collection_method;
48
+ const effectiveAutomaticTax =
49
+ phaseTax?.enabled ?? defaults.automatic_tax?.enabled ?? sourceTax.enabled;
50
+ const effectiveInvoiceIssuer =
51
+ phaseInvoice?.issuer ??
52
+ defaults.invoice_settings.issuer ??
53
+ sourceInvoice.issuer;
54
+ const context = settingsInput.shape.context.parse({
55
+ customerId,
56
+ customerAccountId,
57
+ livemode,
58
+ effectiveCollectionMethod,
59
+ effectiveAutomaticTax,
60
+ effectiveInvoiceIssuer,
61
+ });
62
+ if (
63
+ context.effectiveCollectionMethod !== subscription.collection_method ||
64
+ context.effectiveAutomaticTax !== sourceTax.enabled ||
65
+ issuerId(context.effectiveInvoiceIssuer) !== issuerId(sourceInvoice.issuer)
66
+ )
67
+ unsupported("effective_phase_context_mismatch");
68
+ const liability =
69
+ phaseTax?.liability ?? defaults.automatic_tax?.liability ?? null;
70
+ const liabilityId = (value: unknown) =>
71
+ value == null ? null : issuerId(value);
72
+ if (liabilityId(liability) !== liabilityId(sourceTax.liability))
73
+ unsupported("unproven_tax_liability_retention");
74
+ const defaultProjection = projectRenewalPhaseSettings({
75
+ context,
76
+ settings: {
77
+ application_fee_percent: defaults.application_fee_percent,
78
+ billing_thresholds: defaults.billing_thresholds,
79
+ collection_method: defaults.collection_method,
80
+ default_payment_method: defaults.default_payment_method,
81
+ on_behalf_of: defaults.on_behalf_of,
82
+ transfer_data: defaults.transfer_data,
83
+ ...(defaults.automatic_tax === undefined
84
+ ? {}
85
+ : { automatic_tax: defaults.automatic_tax }),
86
+ default_tax_rates: null,
87
+ invoice_settings: defaults.invoice_settings,
88
+ description: defaults.description,
89
+ metadata: null,
90
+ },
91
+ });
92
+ if (defaultProjection.status !== "projected")
93
+ unsupported(`unsupported_defaults_${defaultProjection.reason}`);
94
+ for (const [field, prefix, kind] of [
95
+ ["default_payment_method", "pm", "payment_method"],
96
+ ["on_behalf_of", "acct", "account"],
97
+ ] as const) {
98
+ const effective = phase[field] ?? defaults[field];
99
+ if (
100
+ refOrNull(effective, prefix, kind) !==
101
+ refOrNull(subscription[field], prefix, kind)
102
+ )
103
+ unsupported(`unproven_${field}_retention`);
104
+ }
105
+ const effectiveTransfer = phase.transfer_data ?? defaults.transfer_data;
106
+ const normalizeTransfer = (value: unknown) => {
107
+ if (value == null) return null;
108
+ const transfer = object(value);
109
+ return {
110
+ destination: referenceId(transfer.destination, "acct", "account"),
111
+ amount_percent: transfer.amount_percent,
112
+ };
113
+ };
114
+ if (
115
+ !equal(
116
+ normalizeTransfer(effectiveTransfer),
117
+ normalizeTransfer(subscription.transfer_data),
118
+ )
119
+ )
120
+ unsupported("unproven_transfer_data_retention");
121
+ if ((phase.description ?? defaults.description) !== subscription.description)
122
+ unsupported("unproven_description_retention");
123
+ const due =
124
+ phaseInvoice?.days_until_due ?? defaults.invoice_settings.days_until_due;
125
+ if (due !== subscription.days_until_due)
126
+ unsupported("unproven_invoice_due_retention");
127
+ for (const field of ["custom_fields", "description", "footer"] as const) {
128
+ const effective = phaseInvoice?.[field] ?? defaults.invoice_settings[field];
129
+ if (!equal(effective, sourceInvoice[field]))
130
+ unsupported(`unproven_invoice_${field}_retention`);
131
+ }
132
+ const effectiveTaxIds =
133
+ phaseInvoice?.account_tax_ids ?? defaults.invoice_settings.account_tax_ids;
134
+ const taxIds = (value: unknown) =>
135
+ value == null
136
+ ? null
137
+ : z
138
+ .array(z.unknown())
139
+ .parse(value)
140
+ .map((tax) => referenceId(tax, "txi", "tax_id"));
141
+ if (!equal(taxIds(effectiveTaxIds), taxIds(sourceInvoice.account_tax_ids)))
142
+ unsupported("unproven_invoice_tax_id_retention");
143
+ return context;
144
+ }