@openlup/platform 0.24.0 → 0.26.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 (61) hide show
  1. package/CHANGELOG.md +127 -432
  2. package/README.md +46 -11
  3. package/dist/communications/contracts/subscriptionPaymentExpired.d.ts +3 -2
  4. package/dist/communications/contracts/subscriptionPaymentExpired.js +1 -1
  5. package/dist/communications/contracts/subscriptionPaymentFailed.d.ts +4 -3
  6. package/dist/communications/contracts/subscriptionPaymentFailed.js +4 -5
  7. package/dist/composition/index.d.ts +1 -0
  8. package/dist/composition/index.js +1 -0
  9. package/dist/composition/subscriptionContribution.d.ts +18 -0
  10. package/dist/composition/subscriptionContribution.js +19 -0
  11. package/dist/inventory/index.d.ts +2 -0
  12. package/dist/inventory/index.js +1 -0
  13. package/dist/inventory/postgresStockAvailability.d.ts +24 -0
  14. package/dist/inventory/postgresStockAvailability.js +48 -0
  15. package/dist/subscriptions/commandExamples.d.ts +6 -0
  16. package/dist/subscriptions/commandExamples.js +20 -0
  17. package/dist/subscriptions/contracts/commands.d.ts +8 -1
  18. package/dist/subscriptions/contracts/index.d.ts +2 -2
  19. package/dist/subscriptions/contracts/renewal.d.ts +2 -0
  20. package/dist/subscriptions/contracts/stockWait.d.ts +12 -1
  21. package/dist/subscriptions/index.d.ts +22 -4
  22. package/dist/subscriptions/index.js +22 -3
  23. package/dist/subscriptions/lifecycleMessages.d.ts +9 -0
  24. package/dist/subscriptions/lifecycleMessages.js +38 -0
  25. package/dist/subscriptions/paymentOutcomes.js +1 -1
  26. package/dist/subscriptions/postgresCommandStore.d.ts +44 -0
  27. package/dist/subscriptions/postgresCommandStore.js +172 -0
  28. package/dist/subscriptions/postgresRetryStore.d.ts +6 -0
  29. package/dist/subscriptions/postgresRetryStore.js +11 -0
  30. package/dist/subscriptions/postgresStockWaitStore.d.ts +62 -0
  31. package/dist/subscriptions/postgresStockWaitStore.js +174 -0
  32. package/dist/subscriptions/renewalCycleFailureMechanism.js +3 -2
  33. package/dist/subscriptions/services.d.ts +31 -0
  34. package/dist/subscriptions/services.js +15 -0
  35. package/package.json +2 -2
  36. package/release-gates.json +2 -2
  37. package/sql/20261024170000_subscription_command_lifecycle.sql +404 -0
  38. package/sql/20261024180000_subscription_stock_wait.sql +330 -0
  39. package/sql/20261024183000_inventory_available_to_promise.sql +70 -0
  40. package/sql/20261024184000_subscription_renewal_reserve_uses_seam.sql +147 -0
  41. package/sql/20261024184500_subscription_retry_late_positive_stock.sql +59 -0
  42. package/sql/20261024184600_subscription_retry_candidate_payment_filter.sql +22 -0
  43. package/src/communications/contracts/subscriptionPaymentExpired.ts +4 -3
  44. package/src/communications/contracts/subscriptionPaymentFailed.ts +8 -8
  45. package/src/composition/index.ts +1 -0
  46. package/src/composition/subscriptionContribution.ts +25 -0
  47. package/src/inventory/index.ts +2 -0
  48. package/src/inventory/postgresStockAvailability.ts +54 -0
  49. package/src/subscriptions/commandExamples.ts +19 -0
  50. package/src/subscriptions/contracts/commands.ts +35 -2
  51. package/src/subscriptions/contracts/index.ts +2 -2
  52. package/src/subscriptions/contracts/renewal.ts +2 -1
  53. package/src/subscriptions/contracts/stockWait.ts +14 -2
  54. package/src/subscriptions/index.ts +30 -3
  55. package/src/subscriptions/lifecycleMessages.ts +37 -0
  56. package/src/subscriptions/paymentOutcomes.ts +1 -1
  57. package/src/subscriptions/postgresCommandStore.ts +183 -0
  58. package/src/subscriptions/postgresRetryStore.ts +11 -0
  59. package/src/subscriptions/postgresStockWaitStore.ts +170 -0
  60. package/src/subscriptions/renewalCycleFailureMechanism.ts +3 -1
  61. package/src/subscriptions/services.ts +21 -0
@@ -21,8 +21,9 @@ export interface SubscriptionPaymentExpiredEmailVars {
21
21
  */
22
22
  cause?: PaymentFailureCustomerCause | null;
23
23
  /**
24
- * Recovery-link URL for the case's `resume_subscription` token. When present
25
- * the template renders the resume CTA; when absent it keeps the support-led
24
+ * Recovery-link URL for the case's payment-recovery token. Current exhaustion
25
+ * uses `repair_payment`; legacy expired cases may carry `resume_subscription`.
26
+ * When present the template renders the recovery CTA; otherwise it keeps the support-led
26
27
  * wording, because a button with no destination is worse than no button.
27
28
  */
28
29
  recoveryUrl?: string | null;
@@ -51,7 +52,7 @@ export function createSubscriptionPaymentExpiredContentFactory(input: {
51
52
  const causeSentence = subscriptionPaymentCauseSentence(locale, vars.cause ?? "unknown");
52
53
  const detail = [
53
54
  // Leads the box for the same reason as in the failed notice: it answers the
54
- // question the paused subscription raises, before the figures.
55
+ // question the unsuccessful payment raises, before the figures.
55
56
  ...(causeSentence ? [causeSentence] : []),
56
57
  ...(recoveryUrl
57
58
  ? [
@@ -19,9 +19,10 @@ export interface SubscriptionPaymentFailedEmailVars {
19
19
  recoveryUrl?: string | null;
20
20
  /**
21
21
  * Pre-formatted calendar day of the scheduled next charge, in the merchant's
22
- * zone (e.g. "11.08.2026"). The dunning row that selects THIS template always
23
- * carries a scheduled retry, so in production this is present; null keeps the
24
- * pre-date sentence rather than printing a placeholder date.
22
+ * zone (e.g. "11.08.2026"). Present only when a retry is actually scheduled:
23
+ * a first-rung hard decline selects this template with no next retry, and
24
+ * `retryScheduled: false` renders the no-retry copy. null/absent keeps the
25
+ * sentence without a date rather than printing a placeholder date.
25
26
  */
26
27
  nextRetryDateLabel?: string | null;
27
28
  /** Card scheme as stored on the method's consent snapshot, e.g. "visa". */
@@ -72,11 +73,10 @@ export function createSubscriptionPaymentFailedContentFactory(input: {
72
73
  // also why it is PREPENDED and never appended — the retry sentence must stay
73
74
  // last (see below).
74
75
  const causeSentence = subscriptionPaymentCauseSentence(locale, vars.cause ?? "unknown");
75
- // Only an explicit `false` turns the promises off. Absent means "no producer
76
- // told us", and the only rail that exists always schedules a retry, so absent
77
- // must keep rendering today's copy rather than the safer-sounding new copy:
78
- // telling a customer no attempt is coming when one is would push them to
79
- // cancel a subscription that was about to recover on its own.
76
+ // Only an explicit `false` turns the retry promises off. Absence preserves
77
+ // the legacy rendering default; it does not prove a retry is scheduled.
78
+ // Producers must pass the actual schedule fact when retries have stopped,
79
+ // including class termination or exhaustion.
80
80
  const retryScheduled = vars.retryScheduled !== false;
81
81
  const detail = [
82
82
  ...(causeSentence ? [causeSentence] : []),
@@ -20,3 +20,4 @@ export { createCatalogContribution, type CatalogContributionInput } from "./cata
20
20
  export { createInventoryContribution } from "./inventoryContribution.js";
21
21
  export { createShippingContribution } from "./shippingContribution.js";
22
22
  export { createFulfillmentContribution } from "./fulfillmentContribution.js";
23
+ export { createSubscriptionContribution } from "./subscriptionContribution.js";
@@ -0,0 +1,25 @@
1
+ import type { Contribution, RequiredSchema } from "@openlup/core/readiness";
2
+
3
+ /** One selected subscription job; no second scheduler or automatic registration. */
4
+ export function createSubscriptionContribution(input: {
5
+ version: string;
6
+ requiredSchema: RequiredSchema;
7
+ run: (() => Promise<unknown>) | null;
8
+ cadenceSeconds: number;
9
+ }) {
10
+ if (!Number.isFinite(input.cadenceSeconds) || input.cadenceSeconds <= 0) throw new Error("subscription_cadence_invalid");
11
+ const schedules = input.run ? [{ id: "subscriptions-renewal", cadenceSeconds: input.cadenceSeconds, run: input.run }] : [];
12
+ const contribution: Contribution = {
13
+ manifest: {
14
+ name: "@openlup/platform", version: input.version, kind: "rail",
15
+ module: { id: "subscriptions", kind: "capability", provides: ["./subscriptions", "./subscriptions/contracts"], dependsOn: [] },
16
+ emits: [], handles: [], schedules: schedules.map(({ id, cadenceSeconds }) => ({ id, cadenceSeconds })),
17
+ env: [], requiredPorts: ["run"], routes: [], requiredSchema: input.requiredSchema,
18
+ }, handlers: [], schedules, routes: [],
19
+ };
20
+ return {
21
+ contributions: [contribution],
22
+ ports: input.run ? { "@openlup/platform/subscriptions:run": input.run } : {},
23
+ triggers: Object.fromEntries(schedules.map(schedule => [`@openlup/platform/subscriptions:${schedule.id}`, schedule.run])),
24
+ };
25
+ }
@@ -20,3 +20,5 @@ export { forecastSubscriptionInventoryShortages, buildSubscriptionInventoryForec
20
20
  export { calculateSubscriptionForecastSkus, calculateSubscriptionForecastTotals } from "./subscriptionForecastCalculation.js";
21
21
  export { INVENTORY_MIGRATIONS } from "./sql.js";
22
22
  export { createInventoryBindings, type InventoryBindingDependencies, type InventoryBindings } from "./bindings.js";
23
+ export { createPostgresStockAvailability } from "./postgresStockAvailability.js";
24
+ export type { NativeStockPromise } from "./postgresStockAvailability.js";
@@ -0,0 +1,54 @@
1
+ import type { NewPurchaseStockRow } from "./contracts/newPurchaseStock.js";
2
+ import type { NewPurchaseStockReadPort } from "./newPurchaseStockAvailability.js";
3
+
4
+ interface StockQueryExecutor {
5
+ query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
6
+ }
7
+ export interface NativeStockPromise {
8
+ availableQuantity: number; forSaleQuantity: number; hardHoldQuantity: number;
9
+ safetyQuantity: number; softSubscriptionDemandQuantity: number; channelExposureQuantity: number;
10
+ }
11
+ function object(value: unknown): Record<string, unknown> {
12
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("inventory_stock_response_invalid");
13
+ return value as Record<string, unknown>;
14
+ }
15
+ function quantity(value: unknown): number {
16
+ if ((typeof value !== "number" && typeof value !== "string") || String(value).trim() === "") throw new Error("inventory_stock_quantity_invalid");
17
+ const n = Number(value);
18
+ if (!Number.isSafeInteger(n) || n < 0) throw new Error("inventory_stock_quantity_invalid");
19
+ return n;
20
+ }
21
+ /** Native read-only ATP. The fixed 14-day priority cannot be waived by a new
22
+ * purchase caller. Only the fenced native SQL allocator uses the renewal exemption. */
23
+ export function createPostgresStockAvailability(executor: StockQueryExecutor, options: { sourceKey: string; now: () => string }): {
24
+ readPort: NewPurchaseStockReadPort;
25
+ availableToPromise(sku: string, asOf: string): Promise<NativeStockPromise>;
26
+ } {
27
+ return {
28
+ async availableToPromise(sku, asOf) {
29
+ const row = object((await executor.query(`SELECT public.inventory_available_to_promise(
30
+ $1::text,$2::text,$3::timestamptz,false) AS response`, [options.sourceKey, sku, asOf])).rows[0]?.response);
31
+ return { availableQuantity: quantity(row.available_quantity), forSaleQuantity: quantity(row.for_sale_quantity),
32
+ hardHoldQuantity: quantity(row.hard_hold_quantity), safetyQuantity: quantity(row.safety_quantity),
33
+ softSubscriptionDemandQuantity: quantity(row.soft_subscription_demand_quantity), channelExposureQuantity: quantity(row.channel_exposure_quantity) };
34
+ },
35
+ readPort: {
36
+ async read(input) {
37
+ if (input.horizonDays !== 14 || input.excludeOrderId !== null) throw new Error("native_stock_read_options_unsupported");
38
+ if (!input.skus.length) return new Map();
39
+ const value = (await executor.query(`SELECT public.inventory_new_purchase_stock_read(
40
+ $1::text,$2::jsonb,$3::timestamptz) AS response`, [options.sourceKey, JSON.stringify(input.skus), options.now()])).rows[0]?.response;
41
+ if (!Array.isArray(value)) throw new Error("inventory_stock_response_invalid");
42
+ return new Map(value.map(value => {
43
+ const row = object(value);
44
+ if (typeof row.sku !== "string" || !["provider", "missing"].includes(String(row.source)) || typeof row.stale !== "boolean") throw new Error("inventory_stock_response_invalid");
45
+ const result: NewPurchaseStockRow = { sku: row.sku, catalogSkuId: row.catalogSkuId == null ? null : String(row.catalogSkuId),
46
+ source: row.source as "provider" | "missing", providerForSale: row.providerForSale == null ? null : quantity(row.providerForSale),
47
+ activeHolds: quantity(row.activeHolds), safetyStock: quantity(row.safetyStock), available: quantity(row.available), stale: row.stale,
48
+ renewalDemand: quantity(row.renewalDemand), availableForNewPurchases: quantity(row.availableForNewPurchases), excludedOrderHolds: quantity(row.excludedOrderHolds) };
49
+ return [result.sku, result];
50
+ }));
51
+ },
52
+ },
53
+ };
54
+ }
@@ -0,0 +1,19 @@
1
+ import type { SubscriptionCommand, SubscriptionCommandContext, SubscriptionCommandPort } from "./contracts/commands.js";
2
+
3
+ /** Neutral examples. The host authenticates and authorizes actor/client ownership first. */
4
+ export function createSubscriptionCommandExamples(commands: SubscriptionCommandPort) {
5
+ const apply = (context: SubscriptionCommandContext, command: SubscriptionCommand) => {
6
+ if (context.actor.actorId.trim() === "" || context.actor.clientId.trim() === "") throw new Error("subscription_command_actor_required");
7
+ return commands.apply(command);
8
+ };
9
+ return {
10
+ customerSkip(context: SubscriptionCommandContext) {
11
+ if (context.actor.kind !== "customer") throw new Error("subscription_command_customer_required");
12
+ return apply(context, { ...context, action: "skip", reason: null, confirmedChargeTiming: true });
13
+ },
14
+ operatorSlide(context: SubscriptionCommandContext, newNextCycleAt: string) {
15
+ if (context.actor.kind !== "operator") throw new Error("subscription_command_operator_required");
16
+ return apply(context, { ...context, action: "slide", newNextCycleAt, confirmedChargeTiming: true });
17
+ },
18
+ };
19
+ }
@@ -7,7 +7,9 @@ export type SubscriptionCommand = SubscriptionCommandContext & (
7
7
  | { action: "resume" | "skip" | "cancel"; reason: string | null; confirmedChargeTiming: boolean }
8
8
  | { action: "slide"; newNextCycleAt: string; confirmedChargeTiming: boolean }
9
9
  | { action: "edit_future_terms"; shippingAddressId: string; planDays: number; cadenceDays: number;
10
- expectedTemplateVersion: number; acceptedQuoteHash: string; confirmedChargeTiming: boolean;
10
+ expectedTemplateVersion: number;
11
+ /** Empty string means no quote (semantic no-op). */
12
+ acceptedQuoteHash: string; confirmedChargeTiming: boolean;
11
13
  coreLines: readonly SubscriptionBundleLine[]; addonLines: readonly SubscriptionBundleLine[];
12
14
  compositionConstraint: string }
13
15
  );
@@ -17,6 +19,37 @@ export interface SubscriptionCommandReceipt {
17
19
  outcome: "applied" | "replayed" | "noop"; subscriptionId: string;
18
20
  originalState: string; nextCycleAt: string | null; revision: string; eventId: string | null;
19
21
  }
22
+ export interface SubscriptionCommandRefusal {
23
+ outcome: "refused";
24
+ /** Stable machine code; never provider, PostgreSQL diagnostic or customer text.
25
+ * Unrecognized native or host diagnostics map to subscription_command_invalid_input. */
26
+ reason:
27
+ | "multi_cycle_prepaid_unsupported"
28
+ | "subscription_command_addon_not_found"
29
+ | "subscription_command_bundle_total_mismatch"
30
+ | "subscription_command_charge_timing_not_confirmed"
31
+ | "subscription_command_idempotency_conflict"
32
+ | "subscription_command_invalid_composition_constraint"
33
+ | "subscription_command_invalid_input"
34
+ | "subscription_command_not_active"
35
+ | "subscription_command_operation_busy"
36
+ | "subscription_command_pause_forbidden"
37
+ | "subscription_command_payment_blocked"
38
+ | "subscription_command_preview_unsupported"
39
+ | "subscription_command_renewal_terms_missing"
40
+ | "subscription_command_unsupported_action"
41
+ | "subscription_edit_catalog_unavailable"
42
+ | "subscription_edit_invalid_lines"
43
+ | "subscription_edit_invalid_request"
44
+ | "subscription_edit_quote_expired"
45
+ | "subscription_edit_quote_required"
46
+ | "subscription_edit_stale_template"
47
+ | "subscription_edit_window_closed"
48
+ | "subscription_lifecycle_invalid_transition"
49
+ | "subscription_lifecycle_invalid_skip"
50
+ | "subscription_lifecycle_invalid_slide"
51
+ | "subscription_lifecycle_payment_blocked";
52
+ }
20
53
  export type SubscriptionUnsupportedCode = "multi_cycle_prepaid_unsupported" | "native_generic_bundle_commands_unsupported" | "native_command_bound_receipts_unsupported" | "native_prepared_attempt_store_unsupported";
21
54
  export interface SubscriptionUnsupported { supported: false; refusalCode: SubscriptionUnsupportedCode }
22
55
  /** Readiness must be selected explicitly; a port declaration does not install a store. */
@@ -35,7 +68,7 @@ export interface SubscriptionCapabilities {
35
68
  export interface SubscriptionCommandPort {
36
69
  readonly capabilities: SubscriptionCapabilities;
37
70
  /** Future term writes, actor/command receipt and events must commit atomically. */
38
- apply(command: SubscriptionCommand): Promise<SubscriptionCommandReceipt | SubscriptionUnsupported>;
71
+ apply(command: SubscriptionCommand): Promise<SubscriptionCommandReceipt | SubscriptionCommandRefusal | SubscriptionUnsupported>;
39
72
  }
40
73
  export interface SubscriptionActivationPort {
41
74
  activate(input: { idempotencyKey: string; orderId: string; paymentIntentId: string;
@@ -1,6 +1,6 @@
1
1
  export type { RenewalSchedule, RenewalIdentity, RenewalAdmission, RenewalLine, RenewalCycleCorrelation, RenewalTemplateSnapshot, RenewalPricingSnapshot, RenewalOrderSnapshot, RenewalFrozenSnapshot, RenewalDue, RenewalOperationState, RenewalReadback, RenewalPaymentEvidence, RenewalTransactionUnits, RenewalReservationResult, RenewalPreparedSettlement, RenewalStorePort, RenewalSettlementPort, RenewalExecutionRequest, RenewalPaymentRail, RenewalResult } from "./renewal.js";
2
2
  export type { DunningCaseOpenInput, DunningCaseOpened, DunningCaseAdvanced, DunningRefusalCode, DunningCaseLifecyclePort, RenewalRetryState, RenewalRetryObligation, RenewalRecoveryAuthorization, RenewalFailureHandoffPort } from "./dunning.js";
3
- export type { StockWaitRecoveryBinding, StockWaitDeficit, StockWaitCase, StockWaitStorePort } from "./stockWait.js";
4
- export type { SubscriptionCommandContext, SubscriptionCommand, SubscriptionBundleLine, SubscriptionCommandReceipt, SubscriptionUnsupportedCode, SubscriptionUnsupported, SubscriptionCapabilities, SubscriptionCommandPort, SubscriptionActivationPort } from "./commands.js";
3
+ export type { StockWaitRecoveryBinding, StockWaitDeficit, StockWaitCase, StockWaitFrozenCase, StockWaitStorePort } from "./stockWait.js";
4
+ export type { SubscriptionCommandContext, SubscriptionCommand, SubscriptionBundleLine, SubscriptionCommandReceipt, SubscriptionCommandRefusal, SubscriptionUnsupportedCode, SubscriptionUnsupported, SubscriptionCapabilities, SubscriptionCommandPort, SubscriptionActivationPort } from "./commands.js";
5
5
  export type { SubscriptionLifecycleFact, SubscriptionLifecycleMessageDescriptor, SubscriptionLifecycleMessagePort } from "./messages.js";
6
6
  export type { SubscriptionRenewalOutcome, HostedRenewalDue, SubscriptionRenewalChargeResult, SubscriptionCycleSnapshotResult, SubscriptionCycleOrderInput, SubscriptionCycleOrderResult, SubscriptionReservationPreflightResult, SubscriptionRenewalPersistencePort, FailurePropagationKind, FailurePropagationContext, CycleRetryState, DunningCaseOpenOutcome, CycleChargeFailurePropagationPort, FailurePropagationResult, RenewalPrepareInput, RenewalAttemptResult, RenewalIntentResult, RenewalPaymentPort, RenewalExecutionPort, RenewalDeliveryAdmission, RenewalAllowedAdmission, RenewalDeliveryClient, RenewalFailureDeps, RenewalPreflightDeps, RenewalCycleDeps, RenewalExecutionContext, RenewalOutcomeContext, RenewalReplayContext, RenewalPreparedAttemptPrepareInput, RenewalPreparedAttemptPersistenceResult, RenewalPreparedAttemptFinalizeInput, RenewalPreparedAttemptPersistencePort } from "./renewal.js";
@@ -87,9 +87,10 @@ export interface CycleChargeFailurePropagationPort {
87
87
  occurredAt: string;
88
88
  failureReason: string;
89
89
  failureClassification: { failureClass: string; decidedBy: string };
90
- }): Promise<{ replayed: boolean }>;
90
+ }): Promise<{ replayed: boolean; paymentAttemptId?: string | null }>;
91
91
  readCycleRetryState(cycleId: string): Promise<CycleRetryState>;
92
92
  openDunningCase(input: {
93
+ failedPaymentAttemptId: string | null;
93
94
  idempotencyKey: string;
94
95
  cycleId: string;
95
96
  subscriptionId: string;
@@ -5,7 +5,13 @@ export interface StockWaitRecoveryBinding {
5
5
  }
6
6
  export interface StockWaitDeficit {
7
7
  skuId: string; sku: string; displayName: string; size: string | null;
8
- required: number; reserved: number; available: number; missing: number;
8
+ required: number;
9
+ /** This operation's own reserved units. */
10
+ reserved: number;
11
+ /** Free ATP, excluding this operation's own reservation. */
12
+ available: number;
13
+ /** Required units minus both reserved and available units. */
14
+ missing: number;
9
15
  }
10
16
  export interface StockWaitCase extends RenewalSchedule {
11
17
  caseId: string; clientId: string; state: "waiting" | "stock_secured" | "resumed" | "closed";
@@ -16,12 +22,18 @@ export interface StockWaitCase extends RenewalSchedule {
16
22
  securedAt: string | null; resumedAt: string | null; closedAt: string | null;
17
23
  startedNoticeKey: string; resumedNoticeKey: string; noticeEligible: boolean;
18
24
  }
25
+ /** Discovery can precede the durable waiting case; never invent a case ID. */
26
+ export interface StockWaitFrozenCase extends RenewalSchedule {
27
+ operationId: string; case: StockWaitCase | null;
28
+ frozenSnapshot: RenewalFrozenSnapshot; frozenFingerprint: string;
29
+ binding: StockWaitRecoveryBinding;
30
+ }
19
31
  /** All-line reserve/reacquire and the wait transition share a DB transaction.
20
32
  * A shortage rolls back the subtransaction, retaining previous commitments;
21
33
  * record the wait outside that failed subtransaction. Technical failure is unknown.
22
34
  */
23
35
  export interface StockWaitStorePort {
24
- listCandidates(input: { limit: number; asOf: string }): Promise<StockWaitCase[]>;
36
+ listCandidates(input: { limit: number; asOf: string }): Promise<StockWaitFrozenCase[]>;
25
37
  readFrozenCase(input: StockWaitRecoveryBinding): Promise<StockWaitCase | null>;
26
38
  reserveAndTransition(input: { caseId: string; frozenFingerprint: string; now: string }): Promise<StockWaitCase>;
27
39
  /** Only elapsed, unprepared, unacknowledged, stock-only refusals may reset.
@@ -2,10 +2,12 @@ export { renewalIdentity } from "./renewalIdentity.js";
2
2
  export const NATIVE_SUBSCRIPTION_CAPABILITIES = Object.freeze({
3
3
  graph: "native",
4
4
  multiCyclePrepaid: Object.freeze({ supported: false, refusalCode: "multi_cycle_prepaid_unsupported" }),
5
- genericBundleCommands: Object.freeze({ supported: false, refusalCode: "native_generic_bundle_commands_unsupported" }),
6
- commandBoundReceipts: Object.freeze({ supported: false, refusalCode: "native_command_bound_receipts_unsupported" }),
5
+ genericBundleCommands: Object.freeze({ supported: true }),
6
+ commandBoundReceipts: Object.freeze({ supported: true }),
7
7
  preparedAttemptStore: Object.freeze({ supported: false, refusalCode: "native_prepared_attempt_store_unsupported" }),
8
- retryRecovery: "selected", stockRecovery: "unavailable",
8
+ retryRecovery: "selected",
9
+ // Native N3 adapters exist; selection requires passing real-PG evidence.
10
+ stockRecovery: "unavailable",
9
11
  deliveryAdmission: "required", executorCount: 1, defaultEnabled: false,
10
12
  } as const satisfies import("./contracts/commands.js").SubscriptionCapabilities);
11
13
  export { executeRenewalCycle, prepareRenewalAttempt, checkRenewalDeliveryAdmission } from "./renewalCycleMechanism.js";
@@ -22,3 +24,28 @@ export { createPostgresRetryStore } from "./postgresRetryStore.js";
22
24
  export type { NativeRetryFailure, NativeRetryRequest, NativeRetryPositive, NativeRetryPreparation, NativeRetryRow } from "./postgresRetryStore.js";
23
25
  export { createPostgresRetryLifecycleBinding } from "./postgresRetryStore.js";
24
26
  export type { NativeRetryLifecycleBinding } from "./postgresRetryStore.js";
27
+
28
+ export { createPostgresSubscriptionCommandStore, createPostgresSubscriptionCommands } from "./postgresCommandStore.js";
29
+ export type { NativeSubscriptionCommand, NativeSubscriptionCommandBinding } from "./postgresCommandStore.js";
30
+
31
+ export { createPostgresStockWaitStore } from "./postgresStockWaitStore.js";
32
+ export type { NativeStockWaitBinding, NativeStockWaitAdmission } from "./postgresStockWaitStore.js";
33
+
34
+ /** Managed SQL is exposed for service-role hosts; no StockWaitStorePort or
35
+ * NewPurchaseStockReadPort TypeScript adapter is composed for this graph.
36
+ * SQL behavior is proved by the managed pgTAP/real-PostgreSQL witnesses.
37
+ */
38
+ export const MANAGED_SUBSCRIPTION_STOCK_CAPABILITIES = Object.freeze({
39
+ graph: "managed",
40
+ stockRecovery: "unavailable",
41
+ stockWaitSurface: "sql",
42
+ stockAvailabilitySurface: "sql",
43
+ defaultEnabled: false,
44
+ } as const);
45
+
46
+ export { runRenewalBatchRows } from "./automaticRenewalExecution.js";
47
+ export type { SubscriptionLifecycleFact } from "./contracts/messages.js";
48
+
49
+ export { subscriptionLifecycleTemplate, createSubscriptionLifecycleMessages } from "./lifecycleMessages.js";
50
+ export { createSubscriptionCommandExamples } from "./commandExamples.js";
51
+ export { createSubscriptionServices } from "./services.js";
@@ -0,0 +1,37 @@
1
+ import type { SubscriptionLifecycleMessageDescriptor, SubscriptionLifecycleMessagePort } from "./contracts/messages.js";
2
+
3
+ /** Matches M5 and the existing M04 lifecycle templates. A mapping is not a send. */
4
+ const templates: Readonly<Record<string, string>> = Object.freeze({
5
+ "subscription.created": "subscription-welcome",
6
+ "subscription.activation_action_required": "subscription-activation-action-required",
7
+ "subscription.cancelled": "subscription-cancelled",
8
+ "subscription.paused": "subscription-paused",
9
+ "subscription.resumed": "subscription-resumed",
10
+ "subscription.pause_reminder_due": "subscription-pause-reminder",
11
+ "subscription.delivery_rescheduled": "subscription-delivery-rescheduled",
12
+ "subscription.cycle_skipped": "subscription-cycle-skipped",
13
+ "subscription.address_changed": "subscription-address-changed",
14
+ "subscription.package_changed": "subscription-package-changed",
15
+ "subscription.renewal_upcoming": "subscription-renewal-upcoming",
16
+ "subscription_stock_wait.started": "subscription-stock-wait-started",
17
+ "subscription_stock_wait.resumed": "subscription-stock-wait-resumed",
18
+ payment_expired: "subscription-payment-expired",
19
+ payment_recovered: "subscription-payment-recovered", winback_eligible: "subscription-winback",
20
+ stock_wait_started: "subscription-stock-wait-started", stock_wait_resumed: "subscription-stock-wait-resumed",
21
+ });
22
+ export function subscriptionLifecycleTemplate(eventType: string, retryAttempt?: number | null): string | null {
23
+ // Installed dunning SQL uses rung 3 for every value other than exactly 1 or 2.
24
+ if (eventType === "payment_failed") return `subscription-payment-failed-${retryAttempt === 1 ? 1 : retryAttempt === 2 ? 2 : 3}`;
25
+ return Object.hasOwn(templates, eventType) ? templates[eventType]! : null;
26
+ }
27
+ /** M04 owns delivery, consent, rendering and durable replay. M10 never synthesizes a pause. */
28
+ export function createSubscriptionLifecycleMessages(delivery: SubscriptionLifecycleMessagePort) {
29
+ return {
30
+ deliver(input: Omit<SubscriptionLifecycleMessageDescriptor, "templateSlug">) {
31
+ const templateSlug = subscriptionLifecycleTemplate(input.fact.kind, input.fact.kind === "payment_failed" ? input.fact.retryAttempt : null);
32
+ if (!templateSlug) throw new Error("subscription_lifecycle_message_unsupported");
33
+ if (input.messageKey !== input.fact.idempotencyKey) throw new Error("subscription_lifecycle_message_identity_mismatch");
34
+ return delivery.enqueue({ ...input, templateSlug });
35
+ },
36
+ };
37
+ }
@@ -7,7 +7,7 @@ export async function readAndApplyProviderOutcome(deps: AutomaticRenewalRunDeps,
7
7
  const observed = await rail.readOutcome({ externalAttemptRef, settlementIntentId: prepared.settlementIntentId, orderId: prepared.orderId, subscriptionId: operation.subscriptionId, amountMinor: money.totalAmountMinor, currency: money.currency });
8
8
  if (observed.amountMinor !== null && observed.amountMinor !== money.totalAmountMinor) throw new Error("subscription_renewal_provider_amount_mismatch");
9
9
  if (observed.currency !== null && observed.currency.toUpperCase() !== money.currency.toUpperCase()) throw new Error("subscription_renewal_provider_currency_mismatch");
10
- if (observed.status === "pending" || observed.status === "unknown") return automaticRenewalResult(operation, "awaiting_provider", `provider_${observed.status}`);
10
+ if (observed.status !== "succeeded" && observed.status !== "failed") return automaticRenewalResult(operation, "awaiting_provider", `provider_${observed.status}`);
11
11
  if (observed.operationId !== operation.operationId || observed.requestFingerprint !== operation.operationFingerprint
12
12
  || observed.externalAttemptRef !== externalAttemptRef || !observed.verifiedEvidenceRef || !observed.eventKey
13
13
  || !observed.firstRecordedAt || !observed.observedAt) throw new Error("subscription_renewal_verified_evidence_required");
@@ -0,0 +1,183 @@
1
+ import type { SubscriptionCommand, SubscriptionCommandPort, SubscriptionCommandReceipt, SubscriptionCommandRefusal } from "./contracts/commands.js";
2
+ import { subscriptionRecord, type SubscriptionQueryExecutor } from "./postgresRenewalStore.js";
3
+ import { NATIVE_SUBSCRIPTION_CAPABILITIES } from "./index.js";
4
+
5
+ export interface NativeSubscriptionCommand {
6
+ actorId: string; clientId: string; idempotencyKey: string; subscriptionId: string;
7
+ action: string; payload: Record<string, unknown>; now: string;
8
+ }
9
+ export interface NativeSubscriptionCommandBinding {
10
+ /** The callback must use one connection and commit/rollback the complete unit. */
11
+ withTransaction<T>(work: (executor: SubscriptionQueryExecutor) => Promise<T>): Promise<T>;
12
+ /** Validate address ownership and refuse address mutation; resolve SKUs and
13
+ * composition policy using trusted host evidence. No current-cycle write. */
14
+ futureTerms(command: Extract<SubscriptionCommand, { action: "edit_future_terms" }>): Promise<
15
+ | { coreLines: readonly { variantId: string; qty: number }[];
16
+ addonLines: readonly { variantId: string; qty: number }[]; compositionConstraint: Record<string, unknown> }
17
+ | SubscriptionCommandRefusal>;
18
+ }
19
+
20
+ const refusalCodes = new Set<SubscriptionCommandRefusal["reason"]>([
21
+ "multi_cycle_prepaid_unsupported",
22
+ "subscription_command_addon_not_found",
23
+ "subscription_command_bundle_total_mismatch",
24
+ "subscription_command_charge_timing_not_confirmed",
25
+ "subscription_command_idempotency_conflict",
26
+ "subscription_command_invalid_composition_constraint",
27
+ "subscription_command_invalid_input",
28
+ "subscription_command_not_active",
29
+ "subscription_command_operation_busy",
30
+ "subscription_command_pause_forbidden",
31
+ "subscription_command_payment_blocked",
32
+ "subscription_command_preview_unsupported",
33
+ "subscription_command_renewal_terms_missing",
34
+ "subscription_command_unsupported_action",
35
+ "subscription_edit_catalog_unavailable",
36
+ "subscription_edit_invalid_lines",
37
+ "subscription_edit_invalid_request",
38
+ "subscription_edit_quote_expired",
39
+ "subscription_edit_quote_required",
40
+ "subscription_edit_stale_template",
41
+ "subscription_edit_window_closed",
42
+ "subscription_lifecycle_invalid_transition",
43
+ "subscription_lifecycle_invalid_skip",
44
+ "subscription_lifecycle_invalid_slide",
45
+ "subscription_lifecycle_payment_blocked",
46
+ ]);
47
+ function refusalReason(reason: unknown): SubscriptionCommandRefusal["reason"] {
48
+ return typeof reason === "string" && refusalCodes.has(reason as SubscriptionCommandRefusal["reason"])
49
+ ? reason as SubscriptionCommandRefusal["reason"] : "subscription_command_invalid_input";
50
+ }
51
+ function commandResult(result: Record<string, unknown>): Record<string, unknown> {
52
+ return result.status === "refused" || result.outcome === "refused"
53
+ ? { ...result, reason: refusalReason(result.reason) } : result;
54
+ }
55
+
56
+ /** N2 owns normalization, locking, quote acceptance, receipts and all writes.
57
+ * Preview is a separate persisted transaction; apply never executes payment. */
58
+ export function createPostgresSubscriptionCommandStore(binding: Pick<NativeSubscriptionCommandBinding, "withTransaction">) {
59
+ return {
60
+ preview(input: NativeSubscriptionCommand) { return invokeCommand(binding, input, true); },
61
+ apply(input: NativeSubscriptionCommand) { return invokeCommand(binding, input, false); },
62
+ };
63
+ }
64
+
65
+ async function invokeCommand(binding: Pick<NativeSubscriptionCommandBinding, "withTransaction">,
66
+ input: NativeSubscriptionCommand, preview: boolean,
67
+ futureTerms?: () => ReturnType<NativeSubscriptionCommandBinding["futureTerms"]>): Promise<Record<string, unknown>> {
68
+ if (input.action === "multi_cycle_prepaid") return {
69
+ status: "refused", reason: NATIVE_SUBSCRIPTION_CAPABILITIES.multiCyclePrepaid.refusalCode,
70
+ };
71
+ return binding.withTransaction(async executor => {
72
+ const values = [input.actorId, input.clientId, input.idempotencyKey, input.subscriptionId, input.action, input.payload, input.now];
73
+ // Share N2's actor/key lock so a concurrent preview/apply cannot change
74
+ // the receipt between this read and native dispatch. Replay ends here,
75
+ // before any lifecycle function or other potentially writing call.
76
+ await executor.query("SELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text||':'||$2::text,0))", [input.actorId, input.idempotencyKey]);
77
+ const stored = await executor.query(`WITH stored AS (
78
+ SELECT r.*, CASE WHEN $9::boolean THEN jsonb_set(r.command,'{payload}',
79
+ (r.command->'payload')-ARRAY['coreLines','addonLines','compositionConstraint']) ELSE r.command END AS requested_command
80
+ FROM public.subscription_command_receipts r WHERE r.actor_id=$1::uuid AND r.idempotency_key=$3::text
81
+ AND $7::timestamptz IS NOT NULL AND isfinite($7::timestamptz)
82
+ AND $3::text=btrim($3::text) AND char_length($3::text) BETWEEN 8 AND 180
83
+ AND $5::text IS NOT NULL AND jsonb_typeof($6::jsonb)='object'
84
+ AND (NOT $8::boolean OR NOT ($6::jsonb ? 'acceptedQuoteHash'))
85
+ AND EXISTS(SELECT 1 FROM public.subscriptions WHERE id=$4::uuid AND client_id=$2::uuid)
86
+ ), receipt AS (
87
+ SELECT *, CASE WHEN $8::boolean OR status='previewed' THEN
88
+ jsonb_set(requested_command,'{payload}',(requested_command->'payload')-'acceptedQuoteHash')=
89
+ jsonb_build_object('clientId',$2::uuid,'subscriptionId',$4::uuid,'action',$5::text,'payload',$6::jsonb-'acceptedQuoteHash')
90
+ ELSE requested_command=jsonb_build_object('clientId',$2::uuid,'subscriptionId',$4::uuid,'action',$5::text,'payload',$6::jsonb)
91
+ END AND ($8::boolean OR quote_hash IS NOT DISTINCT FROM ($6::jsonb->>'acceptedQuoteHash')) AS matches
92
+ FROM stored
93
+ ) SELECT command, CASE WHEN NOT matches THEN jsonb_build_object('status','refused','reason','subscription_command_idempotency_conflict')
94
+ WHEN $8::boolean OR status='refused' THEN result
95
+ WHEN status<>'previewed' THEN result||jsonb_build_object('status','replayed','originalStatus',status,'commandFingerprint',command_fingerprint)
96
+ END AS response FROM receipt`, [...values, preview, !!futureTerms]);
97
+ if (stored.rows[0]?.response) return commandResult(subscriptionRecord(stored.rows[0].response));
98
+ if (futureTerms) {
99
+ if (stored.rows[0]) {
100
+ // A matching preview already bound the host translation. Apply that
101
+ // exact quote even if the host's mutable policy has since changed.
102
+ values[5] = { ...subscriptionRecord(subscriptionRecord(stored.rows[0].command).payload),
103
+ acceptedQuoteHash: input.payload.acceptedQuoteHash };
104
+ } else {
105
+ const terms = await futureTerms();
106
+ if ("outcome" in terms) return commandResult({ ...terms });
107
+ values[5] = { ...input.payload, ...terms };
108
+ }
109
+ }
110
+ let result: Record<string, unknown> | undefined;
111
+ if (!preview && !Object.hasOwn(input.payload, "acceptedQuoteHash")) {
112
+ // N2 owns every command's no-op decision. Keep only its terminal noop;
113
+ // other direct applies must retain their quote requirement without
114
+ // persisting a speculative quote or refusal from this preview probe.
115
+ await executor.query("SAVEPOINT subscription_command_noop");
116
+ const { rows } = await executor.query("SELECT public.subscription_command_preview($1::uuid,$2::uuid,$3::text,$4::uuid,$5::text,$6::jsonb,$7::timestamptz) AS response", values);
117
+ const candidate = commandResult(subscriptionRecord(rows[0]?.response));
118
+ if (candidate.status === "noop") result = candidate;
119
+ else await executor.query("ROLLBACK TO SAVEPOINT subscription_command_noop");
120
+ await executor.query("RELEASE SAVEPOINT subscription_command_noop");
121
+ }
122
+ if (!result) {
123
+ const name = preview ? "subscription_command_preview" : "subscription_command_apply";
124
+ const { rows } = await executor.query(`SELECT public.${name}($1::uuid,$2::uuid,$3::text,$4::uuid,$5::text,$6::jsonb,$7::timestamptz) AS response`, values);
125
+ result = commandResult(subscriptionRecord(rows[0]?.response));
126
+ }
127
+ if (preview || result.status === "refused") return result;
128
+ const receipt = await executor.query(`SELECT command_fingerprint FROM public.subscription_command_receipts
129
+ WHERE actor_id=$1::uuid AND idempotency_key=$2::text`, [input.actorId, input.idempotencyKey]);
130
+ if (typeof receipt.rows[0]?.command_fingerprint !== "string") throw new Error("subscription_command_receipt_missing");
131
+ return { ...result, commandFingerprint: receipt.rows[0].command_fingerprint };
132
+ });
133
+ }
134
+
135
+ /** Trusted customer/operator authorization precedes this adapter. The native
136
+ * result's subscriptionStatus is the state recorded by the original execution,
137
+ * including on replay; it is not a fresh read of mutable subscription state. */
138
+ export function createPostgresSubscriptionCommands(binding: NativeSubscriptionCommandBinding): SubscriptionCommandPort & {
139
+ preview(command: Extract<SubscriptionCommand, { action: "edit_future_terms" }>): Promise<Record<string, unknown> | SubscriptionCommandRefusal>;
140
+ } {
141
+ function encode(command: SubscriptionCommand): NativeSubscriptionCommand | SubscriptionCommandRefusal {
142
+ // This serving adapter never pauses an active subscription. Existing native
143
+ // callers retain their separate, unchanged lifecycle contract.
144
+ if (command.action === "pause") return { outcome: "refused", reason: "subscription_command_pause_forbidden" };
145
+ const { actor, subscriptionId, idempotencyKey, now, action, ...fields } = command;
146
+ let payload: Record<string, unknown> = { ...fields, actorKind: actor.kind };
147
+ let nativeAction: string = action === "skip" ? "skip_next_cycle" : action === "slide" ? "slide_next_cycle" : action;
148
+ if (command.action === "edit_future_terms") {
149
+ // Preserve the host carriers as well as their native translation in the
150
+ // actual-command fingerprint. The accepted hash is stripped for preview.
151
+ payload = { ...payload, requestedCoreLines: command.coreLines, requestedAddonLines: command.addonLines,
152
+ compositionConstraintRef: command.compositionConstraint };
153
+ delete payload.coreLines;
154
+ delete payload.addonLines;
155
+ delete payload.compositionConstraint;
156
+ // An empty typed hash means no quote; preserve native no-op replay/probing.
157
+ if (command.acceptedQuoteHash === "") delete payload.acceptedQuoteHash;
158
+ nativeAction = "update_package_template";
159
+ }
160
+ return { actorId: actor.actorId, clientId: actor.clientId, subscriptionId, idempotencyKey, now, action: nativeAction, payload };
161
+ }
162
+ return {
163
+ capabilities: NATIVE_SUBSCRIPTION_CAPABILITIES,
164
+ async preview(command) {
165
+ const input = encode(command);
166
+ if ("outcome" in input) return input;
167
+ delete input.payload.acceptedQuoteHash;
168
+ return invokeCommand(binding, input, true, () => binding.futureTerms(command));
169
+ },
170
+ async apply(command) {
171
+ const input = encode(command);
172
+ if ("outcome" in input) return input;
173
+ const result = await invokeCommand(binding, input, false,
174
+ command.action === "edit_future_terms" ? () => binding.futureTerms(command) : undefined);
175
+ if (result.status === "refused" || result.outcome === "refused") return { outcome: "refused", reason: refusalReason(result.reason) };
176
+ if (result.status !== "applied" && result.status !== "replayed" && result.status !== "noop") throw new Error("subscription_command_response_invalid");
177
+ return { actorId: command.actor.actorId, idempotencyKey: command.idempotencyKey,
178
+ commandFingerprint: String(result.commandFingerprint), outcome: result.status, subscriptionId: String(result.subscriptionId),
179
+ originalState: String(result.subscriptionStatus), nextCycleAt: result.nextCycleAt == null ? null : String(result.nextCycleAt),
180
+ revision: String(result.templateVersion), eventId: result.eventId == null ? null : String(result.eventId) } satisfies SubscriptionCommandReceipt;
181
+ },
182
+ };
183
+ }
@@ -56,6 +56,17 @@ export function createPostgresRetryStore(executor: SubscriptionQueryExecutor) {
56
56
  async applyFailure(operationId: string, key: string, input: NativeRetryFailure) {
57
57
  return row(await invoke("subscription_retry_apply_failure", [operationId, key, input]));
58
58
  },
59
+ /** Read the immutable rung receipt against the current case. An interrupted
60
+ * apply still needs propagation; an already advanced case must not be rewritten. */
61
+ async failureProgress(operationId: string, key: string): Promise<{ replayed: boolean; caseAdvanced: boolean }> {
62
+ const result = await executor.query(`SELECT true AS replayed,
63
+ (c.retry_attempt >= (r.result->>'retry_attempt')::integer OR o.state='recovered') AS case_advanced
64
+ FROM public.subscription_retry_obligations o
65
+ JOIN public.subscription_retry_receipts r ON r.obligation_id=o.id AND r.kind='failure' AND r.receipt_key=$2::text
66
+ LEFT JOIN public.subscription_dunning_cases c ON c.id=o.case_id
67
+ WHERE o.renewal_operation_id=$1::uuid`, [operationId, key]);
68
+ return { replayed: result.rows.length === 1, caseAdvanced: result.rows[0]?.case_advanced === true };
69
+ },
59
70
  async openCase(operationId: string, template: string, recoveryPath: string | null) {
60
71
  return subscriptionRecord(await invoke("subscription_retry_open_case", [operationId, template, recoveryPath]));
61
72
  },