@fantastic.dev/better-stripe 0.80.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.
- package/CHANGELOG.md +12 -0
- package/README.md +1 -1
- package/dist/client/billing/renewalAggregate/configure.d.ts +35 -0
- package/dist/client/billing/renewalAggregate/configure.d.ts.map +1 -0
- package/dist/client/billing/renewalAggregate/configure.js +96 -0
- package/dist/client/billing/renewalAggregate/configure.js.map +1 -0
- package/dist/client/billing/renewalAggregate/index.d.ts +3 -0
- package/dist/client/billing/renewalAggregate/index.d.ts.map +1 -0
- package/dist/client/billing/renewalAggregate/index.js +3 -0
- package/dist/client/billing/renewalAggregate/index.js.map +1 -0
- package/dist/client/billing/renewalAggregate/phaseContext.d.ts +176 -0
- package/dist/client/billing/renewalAggregate/phaseContext.d.ts.map +1 -0
- package/dist/client/billing/renewalAggregate/phaseContext.js +112 -0
- package/dist/client/billing/renewalAggregate/phaseContext.js.map +1 -0
- package/dist/client/billing/renewalAggregate/phases.d.ts +7 -0
- package/dist/client/billing/renewalAggregate/phases.d.ts.map +1 -0
- package/dist/client/billing/renewalAggregate/phases.js +192 -0
- package/dist/client/billing/renewalAggregate/phases.js.map +1 -0
- package/dist/client/billing/renewalAggregate/preflight.d.ts +594 -0
- package/dist/client/billing/renewalAggregate/preflight.d.ts.map +1 -0
- package/dist/client/billing/renewalAggregate/preflight.js +164 -0
- package/dist/client/billing/renewalAggregate/preflight.js.map +1 -0
- package/dist/client/billing/renewalAggregate/profile.d.ts +8 -0
- package/dist/client/billing/renewalAggregate/profile.d.ts.map +1 -0
- package/dist/client/billing/renewalAggregate/profile.js +60 -0
- package/dist/client/billing/renewalAggregate/profile.js.map +1 -0
- package/dist/client/billing/renewalAggregate/receipt.d.ts +40 -0
- package/dist/client/billing/renewalAggregate/receipt.d.ts.map +1 -0
- package/dist/client/billing/renewalAggregate/receipt.js +62 -0
- package/dist/client/billing/renewalAggregate/receipt.js.map +1 -0
- package/dist/client/billing/renewalAggregate/shared.d.ts +51 -0
- package/dist/client/billing/renewalAggregate/shared.d.ts.map +1 -0
- package/dist/client/billing/renewalAggregate/shared.js +87 -0
- package/dist/client/billing/renewalAggregate/shared.js.map +1 -0
- package/dist/client/billing/renewalAggregate/sourceDiscounts.d.ts +42 -0
- package/dist/client/billing/renewalAggregate/sourceDiscounts.d.ts.map +1 -0
- package/dist/client/billing/renewalAggregate/sourceDiscounts.js +90 -0
- package/dist/client/billing/renewalAggregate/sourceDiscounts.js.map +1 -0
- package/dist/client/billing/renewalAggregate/sourceSettings.d.ts +136 -0
- package/dist/client/billing/renewalAggregate/sourceSettings.d.ts.map +1 -0
- package/dist/client/billing/renewalAggregate/sourceSettings.js +82 -0
- package/dist/client/billing/renewalAggregate/sourceSettings.js.map +1 -0
- package/dist/client/billing/renewalAggregate/taxRetention.d.ts +8 -0
- package/dist/client/billing/renewalAggregate/taxRetention.d.ts.map +1 -0
- package/dist/client/billing/renewalAggregate/taxRetention.js +23 -0
- package/dist/client/billing/renewalAggregate/taxRetention.js.map +1 -0
- package/dist/client/billing/renewalPriceReplacement.d.ts +2 -0
- package/dist/client/billing/renewalPriceReplacement.d.ts.map +1 -1
- package/dist/client/billing/renewalProjection/discounts.d.ts +20 -0
- package/dist/client/billing/renewalProjection/discounts.d.ts.map +1 -0
- package/dist/client/billing/renewalProjection/discounts.js +121 -0
- package/dist/client/billing/renewalProjection/discounts.js.map +1 -0
- package/dist/client/billing/renewalProjection/itemSettings.d.ts +14 -0
- package/dist/client/billing/renewalProjection/itemSettings.d.ts.map +1 -0
- package/dist/client/billing/renewalProjection/itemSettings.js +41 -0
- package/dist/client/billing/renewalProjection/itemSettings.js.map +1 -0
- package/dist/client/billing/renewalProjection/settings.d.ts +18 -0
- package/dist/client/billing/renewalProjection/settings.d.ts.map +1 -0
- package/dist/client/billing/renewalProjection/settings.js +132 -0
- package/dist/client/billing/renewalProjection/settings.js.map +1 -0
- package/dist/client/billing/renewalProjection/settingsSchema.d.ts +200 -0
- package/dist/client/billing/renewalProjection/settingsSchema.d.ts.map +1 -0
- package/dist/client/billing/renewalProjection/settingsSchema.js +150 -0
- package/dist/client/billing/renewalProjection/settingsSchema.js.map +1 -0
- package/dist/client/billing/renewalReplacementSchema.d.ts +2 -0
- package/dist/client/billing/renewalReplacementSchema.d.ts.map +1 -1
- package/dist/client/billing/renewalReplacementSchema.js +10 -4
- package/dist/client/billing/renewalReplacementSchema.js.map +1 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -16
- package/dist/component/balanceFunding/mutations.d.ts +43 -43
- package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
- package/dist/component/payoutRelease/queries.d.ts +2 -2
- package/dist/component/payoutRelease/queries.d.ts.map +1 -1
- package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
- package/dist/component/usage/allowance.fixtures.d.ts +16 -16
- package/docs/renewal-phase-assembly.md +180 -0
- package/docs/renewal-preservation-mappings.md +94 -0
- package/docs/renewal-price-replacements.md +7 -0
- package/package.json +1 -1
- package/src/client/billing/renewal-discount-projection.test.ts +207 -0
- package/src/client/billing/renewal-item-settings-projection.test.ts +79 -0
- package/src/client/billing/renewal-price-replacement.test.ts +46 -0
- package/src/client/billing/renewal-settings-projection.test.ts +300 -0
- package/src/client/billing/renewalAggregate/configure.test.ts +372 -0
- package/src/client/billing/renewalAggregate/configure.ts +164 -0
- package/src/client/billing/renewalAggregate/index.ts +2 -0
- package/src/client/billing/renewalAggregate/phaseContext.ts +144 -0
- package/src/client/billing/renewalAggregate/phases.ts +247 -0
- package/src/client/billing/renewalAggregate/preflight.test.ts +233 -0
- package/src/client/billing/renewalAggregate/preflight.ts +211 -0
- package/src/client/billing/renewalAggregate/profile.ts +76 -0
- package/src/client/billing/renewalAggregate/receipt.ts +76 -0
- package/src/client/billing/renewalAggregate/shared.ts +106 -0
- package/src/client/billing/renewalAggregate/sourceAndTaxRetention.test.ts +247 -0
- package/src/client/billing/renewalAggregate/sourceDiscounts.ts +112 -0
- package/src/client/billing/renewalAggregate/sourceSettings.ts +88 -0
- package/src/client/billing/renewalAggregate/taxRetention.ts +28 -0
- package/src/client/billing/renewalProjection/discounts.ts +152 -0
- package/src/client/billing/renewalProjection/itemSettings.ts +55 -0
- package/src/client/billing/renewalProjection/settings.ts +163 -0
- package/src/client/billing/renewalProjection/settingsSchema.ts +154 -0
- package/src/client/billing/renewalReplacementSchema.ts +10 -4
|
@@ -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,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
|
+
}
|
|
@@ -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
|
+
}
|