@openlup/core 0.0.0 → 0.7.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 (192) hide show
  1. package/CHANGELOG.md +225 -0
  2. package/CODE_OF_CONDUCT.md +39 -0
  3. package/CONTRIBUTING.md +34 -0
  4. package/LICENSE +204 -0
  5. package/MAINTAINERS.md +33 -0
  6. package/README.md +85 -3
  7. package/SECURITY.md +29 -0
  8. package/dist/bundle/contracts.d.ts +9 -0
  9. package/dist/bundle/contracts.js +1 -0
  10. package/dist/bundle/ports.d.ts +41 -0
  11. package/dist/bundle/ports.js +1 -0
  12. package/dist/catalog/identifiers.d.ts +31 -0
  13. package/dist/catalog/identifiers.js +46 -0
  14. package/dist/catalog/index.d.ts +2 -0
  15. package/dist/catalog/index.js +2 -0
  16. package/dist/checkout/idempotency.d.ts +29 -0
  17. package/dist/checkout/idempotency.js +37 -0
  18. package/dist/checkout/index.d.ts +2 -0
  19. package/dist/checkout/index.js +2 -0
  20. package/dist/company-identity/contracts.d.ts +220 -0
  21. package/dist/company-identity/contracts.js +167 -0
  22. package/dist/company-identity/index.d.ts +6 -0
  23. package/dist/company-identity/index.js +2 -0
  24. package/dist/company-identity/ports.d.ts +13 -0
  25. package/dist/company-identity/ports.js +1 -0
  26. package/dist/fulfillment/facts.d.ts +103 -0
  27. package/dist/fulfillment/facts.js +195 -0
  28. package/dist/fulfillment/index.d.ts +4 -0
  29. package/dist/fulfillment/index.js +2 -0
  30. package/dist/inventory/atp.d.ts +172 -0
  31. package/dist/inventory/atp.js +211 -0
  32. package/dist/inventory/index.d.ts +2 -0
  33. package/dist/inventory/index.js +2 -0
  34. package/dist/marketing/research/contracts.d.ts +75 -0
  35. package/dist/marketing/research/contracts.js +60 -0
  36. package/dist/marketing/research/index.d.ts +4 -0
  37. package/dist/marketing/research/index.js +4 -0
  38. package/dist/marketing/research/ports.d.ts +15 -0
  39. package/dist/marketing/research/ports.js +1 -0
  40. package/dist/partners/index.d.ts +4 -0
  41. package/dist/partners/index.js +4 -0
  42. package/dist/partners/ports.d.ts +12 -0
  43. package/dist/partners/ports.js +1 -0
  44. package/dist/partners/status.d.ts +48 -0
  45. package/dist/partners/status.js +35 -0
  46. package/dist/payment/executionBaseContracts.d.ts +81 -0
  47. package/dist/payment/executionBaseContracts.js +8 -0
  48. package/dist/payment/index.d.ts +36 -0
  49. package/dist/payment/index.js +18 -0
  50. package/dist/payment/methodLifecycle.d.ts +91 -0
  51. package/dist/payment/methodLifecycle.js +76 -0
  52. package/dist/payment/paymentControlTypes.d.ts +135 -0
  53. package/dist/payment/paymentControlTypes.js +110 -0
  54. package/dist/payment/paymentFailureTaxonomy.d.ts +80 -0
  55. package/dist/payment/paymentFailureTaxonomy.js +155 -0
  56. package/dist/payment/paymentFailureTaxonomyContracts.d.ts +106 -0
  57. package/dist/payment/paymentFailureTaxonomyContracts.js +177 -0
  58. package/dist/payment/paymentRecovery.d.ts +26 -0
  59. package/dist/payment/paymentRecovery.js +73 -0
  60. package/dist/payment/paymentRecoveryContracts.d.ts +53 -0
  61. package/dist/payment/paymentRecoveryContracts.js +10 -0
  62. package/dist/payment/paymentStateMachine.d.ts +28 -0
  63. package/dist/payment/paymentStateMachine.js +184 -0
  64. package/dist/payment/providerAttemptIdempotency.d.ts +23 -0
  65. package/dist/payment/providerAttemptIdempotency.js +31 -0
  66. package/dist/payment/providerCapability.d.ts +148 -0
  67. package/dist/payment/providerCapability.js +13 -0
  68. package/dist/platform-runtime/contracts.d.ts +9 -0
  69. package/dist/platform-runtime/contracts.js +13 -0
  70. package/dist/platform-runtime/index.d.ts +10 -0
  71. package/dist/platform-runtime/index.js +4 -0
  72. package/dist/platform-runtime/platformKernel.d.ts +44 -0
  73. package/dist/platform-runtime/platformKernel.js +39 -0
  74. package/dist/platform-runtime/ports.d.ts +100 -0
  75. package/dist/platform-runtime/ports.js +1 -0
  76. package/dist/pricing/index.d.ts +8 -0
  77. package/dist/pricing/index.js +8 -0
  78. package/dist/pricing/ports.d.ts +22 -0
  79. package/dist/pricing/ports.js +7 -0
  80. package/dist/pricing/pricingBreakdown.d.ts +86 -0
  81. package/dist/pricing/pricingBreakdown.js +155 -0
  82. package/dist/pricing/targetPriceAllocation.d.ts +97 -0
  83. package/dist/pricing/targetPriceAllocation.js +202 -0
  84. package/dist/pricing/types.d.ts +32 -0
  85. package/dist/pricing/types.js +4 -0
  86. package/dist/promo/adjustmentEngine.d.ts +4 -0
  87. package/dist/promo/adjustmentEngine.js +194 -0
  88. package/dist/promo/adjustmentTypes.d.ts +103 -0
  89. package/dist/promo/adjustmentTypes.js +13 -0
  90. package/dist/promo/index.d.ts +8 -0
  91. package/dist/promo/index.js +8 -0
  92. package/dist/promo/promoEvaluator.d.ts +25 -0
  93. package/dist/promo/promoEvaluator.js +135 -0
  94. package/dist/promo/types.d.ts +86 -0
  95. package/dist/promo/types.js +12 -0
  96. package/dist/risk/core/evaluator.d.ts +3 -0
  97. package/dist/risk/core/evaluator.js +32 -0
  98. package/dist/risk/core/rules.d.ts +3 -0
  99. package/dist/risk/core/rules.js +118 -0
  100. package/dist/risk/core/types.d.ts +65 -0
  101. package/dist/risk/core/types.js +1 -0
  102. package/dist/risk/index.d.ts +8 -0
  103. package/dist/risk/index.js +8 -0
  104. package/dist/risk/types.d.ts +32 -0
  105. package/dist/risk/types.js +43 -0
  106. package/dist/shipping/index.d.ts +4 -0
  107. package/dist/shipping/index.js +4 -0
  108. package/dist/shipping/shippingResolver.d.ts +26 -0
  109. package/dist/shipping/shippingResolver.js +88 -0
  110. package/dist/shipping/types.d.ts +45 -0
  111. package/dist/shipping/types.js +4 -0
  112. package/dist/subscription/cycleHardening.d.ts +95 -0
  113. package/dist/subscription/cycleHardening.js +118 -0
  114. package/dist/subscription/index.d.ts +14 -0
  115. package/dist/subscription/index.js +14 -0
  116. package/dist/subscription/subscriptionEngineCore.d.ts +13 -0
  117. package/dist/subscription/subscriptionEngineCore.js +145 -0
  118. package/dist/subscription/subscriptionEngineLifecycle.d.ts +150 -0
  119. package/dist/subscription/subscriptionEngineLifecycle.js +433 -0
  120. package/dist/subscription/subscriptionEnginePayment.d.ts +25 -0
  121. package/dist/subscription/subscriptionEnginePayment.js +127 -0
  122. package/dist/subscription/subscriptionEngineTypes.d.ts +94 -0
  123. package/dist/subscription/subscriptionEngineTypes.js +4 -0
  124. package/dist/subscription/subscriptionEngineUtils.d.ts +32 -0
  125. package/dist/subscription/subscriptionEngineUtils.js +74 -0
  126. package/dist/subscription/types.d.ts +58 -0
  127. package/dist/subscription/types.js +47 -0
  128. package/dist/testing.d.ts +48 -0
  129. package/dist/testing.js +105 -0
  130. package/package.json +215 -4
  131. package/release-gates.json +232 -0
  132. package/src/bundle/contracts.ts +15 -0
  133. package/src/bundle/ports.ts +32 -0
  134. package/src/catalog/identifiers.ts +50 -0
  135. package/src/catalog/index.ts +2 -0
  136. package/src/checkout/idempotency.ts +49 -0
  137. package/src/checkout/index.ts +2 -0
  138. package/src/company-identity/contracts.ts +208 -0
  139. package/src/company-identity/index.ts +28 -0
  140. package/src/company-identity/ports.ts +19 -0
  141. package/src/fulfillment/facts.ts +300 -0
  142. package/src/fulfillment/index.ts +34 -0
  143. package/src/inventory/atp.ts +249 -0
  144. package/src/inventory/index.ts +2 -0
  145. package/src/marketing/research/contracts.ts +91 -0
  146. package/src/marketing/research/index.ts +4 -0
  147. package/src/marketing/research/ports.ts +26 -0
  148. package/src/partners/index.ts +4 -0
  149. package/src/partners/ports.ts +18 -0
  150. package/src/partners/status.ts +49 -0
  151. package/src/payment/executionBaseContracts.ts +93 -0
  152. package/src/payment/index.ts +128 -0
  153. package/src/payment/methodLifecycle.ts +130 -0
  154. package/src/payment/paymentControlTypes.ts +197 -0
  155. package/src/payment/paymentFailureTaxonomy.ts +201 -0
  156. package/src/payment/paymentFailureTaxonomyContracts.ts +228 -0
  157. package/src/payment/paymentRecovery.ts +95 -0
  158. package/src/payment/paymentRecoveryContracts.ts +61 -0
  159. package/src/payment/paymentStateMachine.ts +263 -0
  160. package/src/payment/providerAttemptIdempotency.ts +57 -0
  161. package/src/payment/providerCapability.ts +172 -0
  162. package/src/platform-runtime/contracts.ts +33 -0
  163. package/src/platform-runtime/index.ts +36 -0
  164. package/src/platform-runtime/platformKernel.ts +86 -0
  165. package/src/platform-runtime/ports.ts +88 -0
  166. package/src/pricing/index.ts +8 -0
  167. package/src/pricing/ports.ts +27 -0
  168. package/src/pricing/pricingBreakdown.ts +243 -0
  169. package/src/pricing/targetPriceAllocation.ts +293 -0
  170. package/src/pricing/types.ts +36 -0
  171. package/src/promo/adjustmentEngine.ts +253 -0
  172. package/src/promo/adjustmentTypes.ts +94 -0
  173. package/src/promo/index.ts +8 -0
  174. package/src/promo/promoEvaluator.ts +137 -0
  175. package/src/promo/types.ts +97 -0
  176. package/src/risk/core/evaluator.ts +41 -0
  177. package/src/risk/core/rules.ts +128 -0
  178. package/src/risk/core/types.ts +73 -0
  179. package/src/risk/index.ts +8 -0
  180. package/src/risk/types.ts +60 -0
  181. package/src/shipping/index.ts +4 -0
  182. package/src/shipping/shippingResolver.ts +101 -0
  183. package/src/shipping/types.ts +49 -0
  184. package/src/subscription/cycleHardening.ts +174 -0
  185. package/src/subscription/index.ts +14 -0
  186. package/src/subscription/subscriptionEngineCore.ts +181 -0
  187. package/src/subscription/subscriptionEngineLifecycle.ts +574 -0
  188. package/src/subscription/subscriptionEnginePayment.ts +179 -0
  189. package/src/subscription/subscriptionEngineTypes.ts +114 -0
  190. package/src/subscription/subscriptionEngineUtils.ts +110 -0
  191. package/src/subscription/types.ts +104 -0
  192. package/src/testing.ts +169 -0
@@ -0,0 +1,574 @@
1
+ import type { SubscriptionEngineEventType, SubscriptionLineSnapshot, SubscriptionStatus } from "./types.js";
2
+ import { isEditWindowOpen } from "./subscriptionEngineCore.js";
3
+ import {
4
+ DEFAULT_CYCLE_RETRY_CADENCE,
5
+ isDunningLadderExhausted,
6
+ type CycleRetryCadence,
7
+ } from "./cycleHardening.js";
8
+ import type {
9
+ EngineCycle,
10
+ EngineEvent,
11
+ EngineSubscription,
12
+ SubscriptionEngineResult,
13
+ SubscriptionMutationResult,
14
+ } from "./subscriptionEngineTypes.js";
15
+ import {
16
+ addCadenceDays,
17
+ cloneTemplate,
18
+ failure,
19
+ makeEvent,
20
+ parseIso,
21
+ statusPatch,
22
+ success,
23
+ touchSubscription,
24
+ validateTemplate,
25
+ } from "./subscriptionEngineUtils.js";
26
+
27
+ /** @beta */
28
+ export function swapTemplateLine(input: {
29
+ subscription: EngineSubscription;
30
+ fromVariantId: string;
31
+ toVariantId: string;
32
+ now: string;
33
+ }): SubscriptionEngineResult<SubscriptionMutationResult> {
34
+ if (!isEditWindowOpen(input.subscription, input.now)) {
35
+ return failure("edit_window_closed", "template swaps are locked after the edit cutoff");
36
+ }
37
+
38
+ if (input.subscription.template.lines.some((line) => line.variant_id === input.toVariantId)) {
39
+ return failure("duplicate_line", "target variant is already present in the template");
40
+ }
41
+
42
+ let replaced = false;
43
+ const lines = input.subscription.template.lines.map((line) => {
44
+ if (line.variant_id !== input.fromVariantId) return { ...line };
45
+ replaced = true;
46
+ return { ...line, variant_id: input.toVariantId };
47
+ });
48
+
49
+ if (!replaced) {
50
+ return failure("line_not_found", "source variant is not present in the template");
51
+ }
52
+
53
+ return updateTemplate({
54
+ subscription: input.subscription,
55
+ template: { ...cloneTemplate(input.subscription.template), lines },
56
+ now: input.now,
57
+ eventType: "subscription.template_updated",
58
+ payload: { operation: "swap", fromVariantId: input.fromVariantId, toVariantId: input.toVariantId },
59
+ });
60
+ }
61
+
62
+ /** @beta */
63
+ export function addPermanentAddon(input: {
64
+ subscription: EngineSubscription;
65
+ line: Omit<SubscriptionLineSnapshot, "is_addon" | "sort_order"> & { sort_order?: number };
66
+ now: string;
67
+ }): SubscriptionEngineResult<SubscriptionMutationResult> {
68
+ if (!isEditWindowOpen(input.subscription, input.now)) {
69
+ return failure("edit_window_closed", "template add-ons are locked after the edit cutoff");
70
+ }
71
+
72
+ if (input.subscription.template.lines.some((line) => line.variant_id === input.line.variant_id)) {
73
+ return failure("duplicate_line", "add-on variant is already present in the template");
74
+ }
75
+
76
+ const nextSortOrder =
77
+ input.line.sort_order ??
78
+ Math.max(0, ...input.subscription.template.lines.map((line) => line.sort_order)) + 1;
79
+ const template = cloneTemplate(input.subscription.template);
80
+ template.lines = [
81
+ ...template.lines,
82
+ {
83
+ variant_id: input.line.variant_id,
84
+ qty: input.line.qty,
85
+ sort_order: nextSortOrder,
86
+ is_addon: true,
87
+ },
88
+ ];
89
+
90
+ return updateTemplate({
91
+ subscription: input.subscription,
92
+ template,
93
+ now: input.now,
94
+ eventType: "subscription.template_updated",
95
+ payload: { operation: "add_permanent_addon", variantId: input.line.variant_id },
96
+ });
97
+ }
98
+
99
+ /** @beta */
100
+ export function skipNextCycle(input: {
101
+ subscription: EngineSubscription;
102
+ now: string;
103
+ reason?: string;
104
+ }): SubscriptionEngineResult<SubscriptionMutationResult> {
105
+ const now = parseIso(input.now);
106
+ if (!now) return failure("invalid_timestamp", "now must be a valid ISO timestamp");
107
+ if (input.subscription.status !== "active") {
108
+ return failure("inactive_subscription", "only active subscriptions can skip cycles");
109
+ }
110
+
111
+ const nextCycleAt = addCadenceDays(input.subscription.nextCycleAt, input.subscription.template.cadence_days);
112
+ if (!nextCycleAt) return failure("invalid_timestamp", "subscription.nextCycleAt must be a valid ISO timestamp");
113
+
114
+ const subscription = touchSubscription(input.subscription, input.now, { nextCycleAt });
115
+
116
+ return success({
117
+ subscription,
118
+ events: [
119
+ makeEvent({
120
+ eventType: "subscription.cycle_skipped",
121
+ subscription: input.subscription,
122
+ idempotencyKey: `${input.subscription.id}:${input.subscription.nextCycleAt}:cycle_skipped`,
123
+ occurredAt: now.toISOString(),
124
+ payload: { skippedScheduledAt: input.subscription.nextCycleAt, reason: input.reason ?? null },
125
+ }),
126
+ makeEvent({
127
+ eventType: "subscription.next_cycle_at_updated",
128
+ subscription,
129
+ idempotencyKey: `${subscription.id}:${subscription.nextCycleAt}:next_cycle_at_updated`,
130
+ occurredAt: now.toISOString(),
131
+ payload: { nextCycleAt },
132
+ }),
133
+ ],
134
+ });
135
+ }
136
+
137
+ /** @beta */
138
+ export function slideNextCycle(input: {
139
+ subscription: EngineSubscription;
140
+ newNextCycleAt: string;
141
+ now: string;
142
+ reason?: string;
143
+ }): SubscriptionEngineResult<SubscriptionMutationResult> {
144
+ const now = parseIso(input.now);
145
+ const newNextCycleAt = parseIso(input.newNextCycleAt);
146
+ if (!now || !newNextCycleAt) {
147
+ return failure("invalid_timestamp", "now and newNextCycleAt must be valid ISO timestamps");
148
+ }
149
+ if (input.subscription.status !== "active") {
150
+ return failure("inactive_subscription", "only active subscriptions can slide cycles");
151
+ }
152
+ if (newNextCycleAt.getTime() <= now.getTime()) {
153
+ return failure("invalid_slide_target", "newNextCycleAt must be in the future");
154
+ }
155
+
156
+ const subscription = touchSubscription(input.subscription, now.toISOString(), {
157
+ nextCycleAt: newNextCycleAt.toISOString(),
158
+ });
159
+
160
+ return success({
161
+ subscription,
162
+ events: [
163
+ makeEvent({
164
+ eventType: "subscription.next_cycle_at_updated",
165
+ subscription,
166
+ idempotencyKey: `${subscription.id}:${subscription.nextCycleAt}:slide`,
167
+ occurredAt: now.toISOString(),
168
+ payload: {
169
+ previousNextCycleAt: input.subscription.nextCycleAt,
170
+ nextCycleAt: subscription.nextCycleAt,
171
+ reason: input.reason ?? null,
172
+ },
173
+ }),
174
+ ],
175
+ });
176
+ }
177
+
178
+ /** @beta */
179
+ export function pauseSubscription(input: {
180
+ subscription: EngineSubscription;
181
+ now: string;
182
+ reason?: string;
183
+ }): SubscriptionEngineResult<SubscriptionMutationResult> {
184
+ return changeSubscriptionStatus(input.subscription, "paused", input.now, "subscription.paused", {
185
+ reason: input.reason ?? null,
186
+ });
187
+ }
188
+
189
+ /** @beta */
190
+ export function resumeSubscription(input: {
191
+ subscription: EngineSubscription;
192
+ now: string;
193
+ }): SubscriptionEngineResult<SubscriptionMutationResult> {
194
+ // Resume leaves `paused` only. Leaving `cancelled` is a win-back and goes
195
+ // through reactivateSubscription, which re-arms the schedule. A subscription
196
+ // the exhausted ladder paused must resume through
197
+ // resumeSubscriptionFromExpiredDunning, which skips the uncollected cycle.
198
+ return changeSubscriptionStatus(input.subscription, "active", input.now, "subscription.resumed", {}, ["paused"]);
199
+ }
200
+
201
+ /** @beta */
202
+ export function cancelSubscription(input: {
203
+ subscription: EngineSubscription;
204
+ now: string;
205
+ reason?: string;
206
+ }): SubscriptionEngineResult<SubscriptionMutationResult> {
207
+ return changeSubscriptionStatus(input.subscription, "cancelled", input.now, "subscription.cancelled", {
208
+ reason: input.reason ?? null,
209
+ });
210
+ }
211
+
212
+ /** @beta */
213
+ export function completeSubscription(input: {
214
+ subscription: EngineSubscription;
215
+ now: string;
216
+ }): SubscriptionEngineResult<SubscriptionMutationResult> {
217
+ return changeSubscriptionStatus(input.subscription, "completed", input.now, "subscription.completed", {});
218
+ }
219
+
220
+ /**
221
+ * Win-back: the owner reactivates their own cancelled subscription.
222
+ *
223
+ * Mirrors the `cancelled -> active` edge of the managed SQL guard
224
+ * `public.subscription_guard_status_transition` and the customer `reactivate`
225
+ * action behind it. A reactivation charges again, so it needs a stored payment
226
+ * method, and it re-arms the next cycle {@link RESTART_LEAD_DAYS} out rather
227
+ * than leaving a stale instant that would make the renewal due immediately.
228
+ * The SQL action also clears the end instant and cancellation reason, requires
229
+ * the customer's confirmation of the charge timing, refuses while a cycle is
230
+ * locked and bumps the template version; those durable duties stay with the
231
+ * host.
232
+ *
233
+ * @beta
234
+ */
235
+ export function reactivateSubscription(input: {
236
+ subscription: EngineSubscription;
237
+ now: string;
238
+ reason?: string;
239
+ }): SubscriptionEngineResult<SubscriptionMutationResult> {
240
+ const now = parseIso(input.now);
241
+ if (!now) return failure("invalid_timestamp", "now must be a valid ISO timestamp");
242
+ if (input.subscription.status !== "cancelled") {
243
+ return failure(
244
+ "invalid_transition",
245
+ `Cannot reactivate a subscription that is ${input.subscription.status}; only cancelled subscriptions can be won back`,
246
+ );
247
+ }
248
+ if (!input.subscription.paymentMethodRef) {
249
+ return failure("missing_payment_method", "reactivation requires a stored payment method");
250
+ }
251
+
252
+ const nextCycleAt = restartNextCycleAt(input.subscription, now);
253
+ if (!nextCycleAt) return failure("invalid_timestamp", "restart exceeds the supported timestamp range");
254
+
255
+ return restart({
256
+ subscription: input.subscription,
257
+ now,
258
+ nextCycleAt,
259
+ idempotencyPrefix: `${input.subscription.id}:reactivated:${now.toISOString()}`,
260
+ payload: { reactivatedFrom: "cancelled", reason: input.reason ?? null },
261
+ leadingEvents: [],
262
+ });
263
+ }
264
+
265
+ /**
266
+ * The sanctioned non-payment rule: a cycle that exhausted the retry ladder
267
+ * pauses an ACTIVE subscription.
268
+ *
269
+ * This is the only path in the engine that suspends a live subscription for a
270
+ * reason the owner did not choose, and it fires only when
271
+ * {@link isDunningLadderExhausted} holds for the refused cycle. A ladder cut
272
+ * short by a terminating refusal class, or a failure on any rung that still has
273
+ * a retry after it, is refused as `dunning_not_exhausted` and leaves the
274
+ * subscription untouched. A subscription that is not active (already paused,
275
+ * cancelled or completed) is returned unchanged with no event, which is what
276
+ * the managed SQL dunning boundary does and what makes a replay harmless.
277
+ *
278
+ * The schedule is not touched: pausing never moves `nextCycleAt`.
279
+ *
280
+ * @beta
281
+ */
282
+ export function pauseSubscriptionForExpiredDunning(input: {
283
+ subscription: EngineSubscription;
284
+ cycle: EngineCycle;
285
+ now: string;
286
+ cadence?: CycleRetryCadence;
287
+ }): SubscriptionEngineResult<SubscriptionMutationResult> {
288
+ const now = parseIso(input.now);
289
+ if (!now) return failure("invalid_timestamp", "now must be a valid ISO timestamp");
290
+ const mismatch = cycleOwnershipError(input.subscription, input.cycle);
291
+ if (mismatch) return mismatch;
292
+ if (!isDunningLadderExhausted(input.cycle, input.cadence ?? DEFAULT_CYCLE_RETRY_CADENCE)) {
293
+ return failure(
294
+ "dunning_not_exhausted",
295
+ "only a cycle that exhausted the retry ladder may pause a subscription for non-payment",
296
+ );
297
+ }
298
+ if (input.subscription.status !== "active") {
299
+ return success({ subscription: touchSubscription(input.subscription, input.subscription.updatedAt, {}), events: [] });
300
+ }
301
+
302
+ const subscription = touchSubscription(input.subscription, now.toISOString(), statusPatch("paused"));
303
+ return success({
304
+ subscription,
305
+ events: [
306
+ makeEvent({
307
+ eventType: "subscription.paused",
308
+ subscription,
309
+ cycleNumber: input.cycle.cycleNumber,
310
+ idempotencyKey: `${input.cycle.engineIdempotencyKey}:subscription_paused`,
311
+ occurredAt: now.toISOString(),
312
+ payload: {
313
+ reason: "payment_failed_expired",
314
+ retryAttempt: input.cycle.retryAttempt,
315
+ failureReason: input.cycle.failureReason,
316
+ },
317
+ }),
318
+ ],
319
+ });
320
+ }
321
+
322
+ /**
323
+ * Customer-initiated recovery out of the non-payment pause.
324
+ *
325
+ * Mirrors the managed SQL `subscription_resume_after_expired_dunning`: the
326
+ * subscription must be paused and the cycle it passes must be the refused cycle
327
+ * that exhausted the ladder (the caller passes the LATEST such cycle, as the SQL
328
+ * boundary reads the latest dunning case). A new payment method, when given,
329
+ * replaces the stored one; without any method the resume is refused. Whether
330
+ * the method is chargeable unattended is the host's check, as it is in SQL.
331
+ * The given cycle becomes `skipped` rather than being charged late; the SQL
332
+ * boundary skips every uncollected cycle, so a host that holds more than one
333
+ * must skip the rest itself. The next cycle is re-armed
334
+ * {@link RESTART_LEAD_DAYS} out.
335
+ *
336
+ * @beta
337
+ */
338
+ export function resumeSubscriptionFromExpiredDunning(input: {
339
+ subscription: EngineSubscription;
340
+ cycle: EngineCycle;
341
+ now: string;
342
+ paymentMethodRef?: string | null;
343
+ paymentMethodKind?: string | null;
344
+ cadence?: CycleRetryCadence;
345
+ }): SubscriptionEngineResult<SubscriptionMutationResult & { cycle: EngineCycle }> {
346
+ const now = parseIso(input.now);
347
+ if (!now) return failure("invalid_timestamp", "now must be a valid ISO timestamp");
348
+ if (input.subscription.status !== "paused") {
349
+ return failure(
350
+ "invalid_transition",
351
+ `Cannot resume a ${input.subscription.status} subscription from expired dunning; it must be paused`,
352
+ );
353
+ }
354
+ const mismatch = cycleOwnershipError(input.subscription, input.cycle);
355
+ if (mismatch) return mismatch;
356
+ if (!isDunningLadderExhausted(input.cycle, input.cadence ?? DEFAULT_CYCLE_RETRY_CADENCE)) {
357
+ return failure("dunning_not_exhausted", "the cycle did not exhaust the retry ladder");
358
+ }
359
+
360
+ const replacementRef = input.paymentMethodRef?.trim() ? input.paymentMethodRef : null;
361
+ const method: Partial<EngineSubscription> = replacementRef
362
+ ? {
363
+ paymentMethodRef: replacementRef,
364
+ paymentMethodKind: input.paymentMethodKind?.trim() || input.subscription.paymentMethodKind,
365
+ }
366
+ : {};
367
+ const withMethod = { ...input.subscription, ...method };
368
+ if (!withMethod.paymentMethodRef) {
369
+ return failure("missing_payment_method", "resuming requires a chargeable payment method");
370
+ }
371
+
372
+ const nextCycleAt = restartNextCycleAt(withMethod, now);
373
+ if (!nextCycleAt) return failure("invalid_timestamp", "restart exceeds the supported timestamp range");
374
+
375
+ const cycle: EngineCycle = { ...input.cycle, status: "skipped", nextRetryAt: null };
376
+ const restarted = restart({
377
+ subscription: withMethod,
378
+ now,
379
+ nextCycleAt,
380
+ idempotencyPrefix: `${input.cycle.engineIdempotencyKey}:resumed_after_expired_dunning`,
381
+ payload: {
382
+ resumedAfterExpiredDunning: true,
383
+ skippedCycleNumber: cycle.cycleNumber,
384
+ },
385
+ leadingEvents: [
386
+ makeEvent({
387
+ eventType: "subscription.cycle_skipped",
388
+ subscription: withMethod,
389
+ cycleNumber: cycle.cycleNumber,
390
+ idempotencyKey: `${input.cycle.engineIdempotencyKey}:cycle_skipped`,
391
+ occurredAt: now.toISOString(),
392
+ payload: {
393
+ skippedScheduledAt: cycle.scheduledAt,
394
+ reason: "subscription_resumed_after_expired_dunning",
395
+ },
396
+ }),
397
+ ],
398
+ });
399
+ if (restarted.ok === false) return restarted;
400
+ return success({ ...restarted.value, cycle });
401
+ }
402
+
403
+ /**
404
+ * How far out a restarted subscription's next cycle is re-armed, in days. Both
405
+ * managed SQL restart paths (the customer `reactivate` action and
406
+ * `subscription_resume_after_expired_dunning`) spell it `interval '2 days'`.
407
+ *
408
+ * @beta
409
+ */
410
+ export const RESTART_LEAD_DAYS = 2;
411
+
412
+ function updateTemplate(input: {
413
+ subscription: EngineSubscription;
414
+ template: EngineSubscription["template"];
415
+ now: string;
416
+ eventType: SubscriptionEngineEventType;
417
+ payload: Record<string, unknown>;
418
+ }): SubscriptionEngineResult<SubscriptionMutationResult> {
419
+ const now = parseIso(input.now);
420
+ if (!now) return failure("invalid_timestamp", "now must be a valid ISO timestamp");
421
+
422
+ const template = cloneTemplate(input.template);
423
+ const templateError = validateTemplate(template);
424
+ if (templateError) return templateError;
425
+
426
+ const subscription = touchSubscription(input.subscription, now.toISOString(), {
427
+ template,
428
+ templateVersion: input.subscription.templateVersion + 1,
429
+ });
430
+
431
+ return success({
432
+ subscription,
433
+ events: [
434
+ makeEvent({
435
+ eventType: input.eventType,
436
+ subscription,
437
+ idempotencyKey: `${subscription.id}:template:${subscription.templateVersion}`,
438
+ occurredAt: now.toISOString(),
439
+ payload: { ...input.payload, templateVersion: subscription.templateVersion },
440
+ }),
441
+ ],
442
+ });
443
+ }
444
+
445
+ function changeSubscriptionStatus(
446
+ subscription: EngineSubscription,
447
+ status: SubscriptionStatus,
448
+ nowIso: string,
449
+ eventType: SubscriptionEngineEventType,
450
+ payload: Record<string, unknown>,
451
+ allowedFrom?: readonly SubscriptionStatus[],
452
+ ): SubscriptionEngineResult<SubscriptionMutationResult> {
453
+ const now = parseIso(nowIso);
454
+ if (!now) return failure("invalid_timestamp", "now must be a valid ISO timestamp");
455
+ if (
456
+ (allowedFrom !== undefined && !allowedFrom.includes(subscription.status)) ||
457
+ !canTransitionSubscriptionStatus(subscription.status, status)
458
+ ) {
459
+ return failure(
460
+ "invalid_transition",
461
+ `Cannot move subscription from ${subscription.status} to ${status}`,
462
+ );
463
+ }
464
+
465
+ const next = touchSubscription(subscription, now.toISOString(), statusPatch(status));
466
+ return success({
467
+ subscription: next,
468
+ events: [
469
+ makeEvent({
470
+ eventType,
471
+ subscription: next,
472
+ idempotencyKey: `${next.id}:${eventType}:${now.toISOString()}`,
473
+ occurredAt: now.toISOString(),
474
+ payload,
475
+ }),
476
+ ],
477
+ });
478
+ }
479
+
480
+ function restart(input: {
481
+ subscription: EngineSubscription;
482
+ now: Date;
483
+ nextCycleAt: string;
484
+ idempotencyPrefix: string;
485
+ payload: Record<string, unknown>;
486
+ leadingEvents: EngineEvent[];
487
+ }): SubscriptionEngineResult<SubscriptionMutationResult> {
488
+ if (!canTransitionSubscriptionStatus(input.subscription.status, "active")) {
489
+ return failure("invalid_transition", `Cannot move subscription from ${input.subscription.status} to active`);
490
+ }
491
+ const occurredAt = input.now.toISOString();
492
+ const subscription = touchSubscription(input.subscription, occurredAt, {
493
+ ...statusPatch("active"),
494
+ nextCycleAt: input.nextCycleAt,
495
+ });
496
+ const events = [
497
+ ...input.leadingEvents,
498
+ makeEvent({
499
+ eventType: "subscription.resumed",
500
+ subscription,
501
+ idempotencyKey: `${input.idempotencyPrefix}:resumed`,
502
+ occurredAt,
503
+ payload: { ...input.payload, nextCycleAt: input.nextCycleAt },
504
+ }),
505
+ ];
506
+ if (input.nextCycleAt !== input.subscription.nextCycleAt) {
507
+ events.push(
508
+ makeEvent({
509
+ eventType: "subscription.next_cycle_at_updated",
510
+ subscription,
511
+ idempotencyKey: `${input.idempotencyPrefix}:next_cycle_at_updated`,
512
+ occurredAt,
513
+ payload: { previousNextCycleAt: input.subscription.nextCycleAt, nextCycleAt: input.nextCycleAt },
514
+ }),
515
+ );
516
+ }
517
+ return success({ subscription, events });
518
+ }
519
+
520
+ // A restart re-arms the schedule RESTART_LEAD_DAYS out, but never earlier than
521
+ // the instant already stored: the same monotonic clamp recordPaymentSuccess
522
+ // applies, so a restart cannot pull a charge into a window already paid for.
523
+ // The managed SQL restart paths assign `now + 2 days` without the clamp, so
524
+ // the two differ exactly when the stored instant is later than that: a win-back
525
+ // of a subscription paid through a later date, or a schedule skipped or slid
526
+ // while the ladder was still running. There SQL charges earlier; this does not.
527
+ function restartNextCycleAt(subscription: EngineSubscription, now: Date): string | null {
528
+ return new Date(Math.max(
529
+ Date.parse(subscription.nextCycleAt) || 0,
530
+ now.getTime() + RESTART_LEAD_DAYS * 24 * 60 * 60 * 1000,
531
+ )).toJSON();
532
+ }
533
+
534
+ function cycleOwnershipError(
535
+ subscription: EngineSubscription,
536
+ cycle: EngineCycle,
537
+ ): SubscriptionEngineResult<never> | null {
538
+ if (cycle.subscriptionId === subscription.id) return null;
539
+ return failure("invalid_transition", "the cycle belongs to a different subscription");
540
+ }
541
+
542
+ /**
543
+ * The engine's subscription status matrix: every edge a status may take, and
544
+ * nothing else.
545
+ *
546
+ * It mirrors the managed SQL guard `public.subscription_guard_status_transition`
547
+ * over the four statuses the engine manages. The guard's remaining edges belong
548
+ * to the activation flow the engine never drives (`pending_activation` ->
549
+ * `active` / `activation_failed` / `cancelled`, and the audited expired-checkout
550
+ * reopen `cancelled` -> `pending_activation`). `completed` is terminal on both
551
+ * sides. `cancelled` -> `active` is the owner's win-back.
552
+ *
553
+ * Which OPERATION may take an edge is narrower than the matrix: `active` ->
554
+ * `paused` is the owner's pause or {@link pauseSubscriptionForExpiredDunning},
555
+ * and `cancelled` -> `active` is only {@link reactivateSubscription}.
556
+ *
557
+ * @beta
558
+ */
559
+ export const SUBSCRIPTION_STATUS_TRANSITIONS: Readonly<
560
+ Record<SubscriptionStatus, readonly SubscriptionStatus[]>
561
+ > = Object.freeze({
562
+ active: Object.freeze(["paused", "cancelled", "completed"] as const),
563
+ paused: Object.freeze(["active", "cancelled"] as const),
564
+ cancelled: Object.freeze(["active"] as const),
565
+ completed: Object.freeze([] as const),
566
+ });
567
+
568
+ /** @beta */
569
+ export function canTransitionSubscriptionStatus(from: SubscriptionStatus, to: SubscriptionStatus): boolean {
570
+ // Own keys only: a status read from storage is an untyped string, and
571
+ // "constructor" or "__proto__" must answer false rather than throw.
572
+ return Object.prototype.hasOwnProperty.call(SUBSCRIPTION_STATUS_TRANSITIONS, from) &&
573
+ SUBSCRIPTION_STATUS_TRANSITIONS[from].includes(to);
574
+ }