@openlup/platform 0.24.0 → 0.25.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 (57) hide show
  1. package/CHANGELOG.md +109 -210
  2. package/README.md +40 -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/stockWait.d.ts +12 -1
  20. package/dist/subscriptions/index.d.ts +22 -4
  21. package/dist/subscriptions/index.js +22 -3
  22. package/dist/subscriptions/lifecycleMessages.d.ts +9 -0
  23. package/dist/subscriptions/lifecycleMessages.js +38 -0
  24. package/dist/subscriptions/paymentOutcomes.js +1 -1
  25. package/dist/subscriptions/postgresCommandStore.d.ts +44 -0
  26. package/dist/subscriptions/postgresCommandStore.js +172 -0
  27. package/dist/subscriptions/postgresRetryStore.d.ts +6 -0
  28. package/dist/subscriptions/postgresRetryStore.js +11 -0
  29. package/dist/subscriptions/postgresStockWaitStore.d.ts +62 -0
  30. package/dist/subscriptions/postgresStockWaitStore.js +174 -0
  31. package/dist/subscriptions/services.d.ts +31 -0
  32. package/dist/subscriptions/services.js +15 -0
  33. package/package.json +2 -2
  34. package/release-gates.json +2 -2
  35. package/sql/20261024170000_subscription_command_lifecycle.sql +404 -0
  36. package/sql/20261024180000_subscription_stock_wait.sql +330 -0
  37. package/sql/20261024183000_inventory_available_to_promise.sql +70 -0
  38. package/sql/20261024184000_subscription_renewal_reserve_uses_seam.sql +147 -0
  39. package/sql/20261024184500_subscription_retry_late_positive_stock.sql +59 -0
  40. package/sql/20261024184600_subscription_retry_candidate_payment_filter.sql +22 -0
  41. package/src/communications/contracts/subscriptionPaymentExpired.ts +4 -3
  42. package/src/communications/contracts/subscriptionPaymentFailed.ts +8 -8
  43. package/src/composition/index.ts +1 -0
  44. package/src/composition/subscriptionContribution.ts +25 -0
  45. package/src/inventory/index.ts +2 -0
  46. package/src/inventory/postgresStockAvailability.ts +54 -0
  47. package/src/subscriptions/commandExamples.ts +19 -0
  48. package/src/subscriptions/contracts/commands.ts +35 -2
  49. package/src/subscriptions/contracts/index.ts +2 -2
  50. package/src/subscriptions/contracts/stockWait.ts +14 -2
  51. package/src/subscriptions/index.ts +30 -3
  52. package/src/subscriptions/lifecycleMessages.ts +37 -0
  53. package/src/subscriptions/paymentOutcomes.ts +1 -1
  54. package/src/subscriptions/postgresCommandStore.ts +183 -0
  55. package/src/subscriptions/postgresRetryStore.ts +11 -0
  56. package/src/subscriptions/postgresStockWaitStore.ts +170 -0
  57. package/src/subscriptions/services.ts +21 -0
@@ -0,0 +1,20 @@
1
+ /** Neutral examples. The host authenticates and authorizes actor/client ownership first. */
2
+ export function createSubscriptionCommandExamples(commands) {
3
+ const apply = (context, command) => {
4
+ if (context.actor.actorId.trim() === "" || context.actor.clientId.trim() === "")
5
+ throw new Error("subscription_command_actor_required");
6
+ return commands.apply(command);
7
+ };
8
+ return {
9
+ customerSkip(context) {
10
+ if (context.actor.kind !== "customer")
11
+ throw new Error("subscription_command_customer_required");
12
+ return apply(context, { ...context, action: "skip", reason: null, confirmedChargeTiming: true });
13
+ },
14
+ operatorSlide(context, newNextCycleAt) {
15
+ if (context.actor.kind !== "operator")
16
+ throw new Error("subscription_command_operator_required");
17
+ return apply(context, { ...context, action: "slide", newNextCycleAt, confirmedChargeTiming: true });
18
+ },
19
+ };
20
+ }
@@ -28,6 +28,7 @@ export type SubscriptionCommand = SubscriptionCommandContext & ({
28
28
  planDays: number;
29
29
  cadenceDays: number;
30
30
  expectedTemplateVersion: number;
31
+ /** Empty string means no quote (semantic no-op). */
31
32
  acceptedQuoteHash: string;
32
33
  confirmedChargeTiming: boolean;
33
34
  coreLines: readonly SubscriptionBundleLine[];
@@ -49,6 +50,12 @@ export interface SubscriptionCommandReceipt {
49
50
  revision: string;
50
51
  eventId: string | null;
51
52
  }
53
+ export interface SubscriptionCommandRefusal {
54
+ outcome: "refused";
55
+ /** Stable machine code; never provider, PostgreSQL diagnostic or customer text.
56
+ * Unrecognized native or host diagnostics map to subscription_command_invalid_input. */
57
+ reason: "multi_cycle_prepaid_unsupported" | "subscription_command_addon_not_found" | "subscription_command_bundle_total_mismatch" | "subscription_command_charge_timing_not_confirmed" | "subscription_command_idempotency_conflict" | "subscription_command_invalid_composition_constraint" | "subscription_command_invalid_input" | "subscription_command_not_active" | "subscription_command_operation_busy" | "subscription_command_pause_forbidden" | "subscription_command_payment_blocked" | "subscription_command_preview_unsupported" | "subscription_command_renewal_terms_missing" | "subscription_command_unsupported_action" | "subscription_edit_catalog_unavailable" | "subscription_edit_invalid_lines" | "subscription_edit_invalid_request" | "subscription_edit_quote_expired" | "subscription_edit_quote_required" | "subscription_edit_stale_template" | "subscription_edit_window_closed" | "subscription_lifecycle_invalid_transition" | "subscription_lifecycle_invalid_skip" | "subscription_lifecycle_invalid_slide" | "subscription_lifecycle_payment_blocked";
58
+ }
52
59
  export type SubscriptionUnsupportedCode = "multi_cycle_prepaid_unsupported" | "native_generic_bundle_commands_unsupported" | "native_command_bound_receipts_unsupported" | "native_prepared_attempt_store_unsupported";
53
60
  export interface SubscriptionUnsupported {
54
61
  supported: false;
@@ -88,7 +95,7 @@ export interface SubscriptionCapabilities {
88
95
  export interface SubscriptionCommandPort {
89
96
  readonly capabilities: SubscriptionCapabilities;
90
97
  /** Future term writes, actor/command receipt and events must commit atomically. */
91
- apply(command: SubscriptionCommand): Promise<SubscriptionCommandReceipt | SubscriptionUnsupported>;
98
+ apply(command: SubscriptionCommand): Promise<SubscriptionCommandReceipt | SubscriptionCommandRefusal | SubscriptionUnsupported>;
92
99
  }
93
100
  export interface SubscriptionActivationPort {
94
101
  activate(input: {
@@ -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";
@@ -12,8 +12,11 @@ export interface StockWaitDeficit {
12
12
  displayName: string;
13
13
  size: string | null;
14
14
  required: number;
15
+ /** This operation's own reserved units. */
15
16
  reserved: number;
17
+ /** Free ATP, excluding this operation's own reservation. */
16
18
  available: number;
19
+ /** Required units minus both reserved and available units. */
17
20
  missing: number;
18
21
  }
19
22
  export interface StockWaitCase extends RenewalSchedule {
@@ -36,6 +39,14 @@ export interface StockWaitCase extends RenewalSchedule {
36
39
  resumedNoticeKey: string;
37
40
  noticeEligible: boolean;
38
41
  }
42
+ /** Discovery can precede the durable waiting case; never invent a case ID. */
43
+ export interface StockWaitFrozenCase extends RenewalSchedule {
44
+ operationId: string;
45
+ case: StockWaitCase | null;
46
+ frozenSnapshot: RenewalFrozenSnapshot;
47
+ frozenFingerprint: string;
48
+ binding: StockWaitRecoveryBinding;
49
+ }
39
50
  /** All-line reserve/reacquire and the wait transition share a DB transaction.
40
51
  * A shortage rolls back the subtransaction, retaining previous commitments;
41
52
  * record the wait outside that failed subtransaction. Technical failure is unknown.
@@ -44,7 +55,7 @@ export interface StockWaitStorePort {
44
55
  listCandidates(input: {
45
56
  limit: number;
46
57
  asOf: string;
47
- }): Promise<StockWaitCase[]>;
58
+ }): Promise<StockWaitFrozenCase[]>;
48
59
  readFrozenCase(input: StockWaitRecoveryBinding): Promise<StockWaitCase | null>;
49
60
  reserveAndTransition(input: {
50
61
  caseId: string;
@@ -6,12 +6,10 @@ export declare const NATIVE_SUBSCRIPTION_CAPABILITIES: Readonly<{
6
6
  refusalCode: "multi_cycle_prepaid_unsupported";
7
7
  }>;
8
8
  readonly genericBundleCommands: Readonly<{
9
- supported: false;
10
- refusalCode: "native_generic_bundle_commands_unsupported";
9
+ supported: true;
11
10
  }>;
12
11
  readonly commandBoundReceipts: Readonly<{
13
- supported: false;
14
- refusalCode: "native_command_bound_receipts_unsupported";
12
+ supported: true;
15
13
  }>;
16
14
  readonly preparedAttemptStore: Readonly<{
17
15
  supported: false;
@@ -37,3 +35,23 @@ export { createPostgresRetryStore } from "./postgresRetryStore.js";
37
35
  export type { NativeRetryFailure, NativeRetryRequest, NativeRetryPositive, NativeRetryPreparation, NativeRetryRow } from "./postgresRetryStore.js";
38
36
  export { createPostgresRetryLifecycleBinding } from "./postgresRetryStore.js";
39
37
  export type { NativeRetryLifecycleBinding } from "./postgresRetryStore.js";
38
+ export { createPostgresSubscriptionCommandStore, createPostgresSubscriptionCommands } from "./postgresCommandStore.js";
39
+ export type { NativeSubscriptionCommand, NativeSubscriptionCommandBinding } from "./postgresCommandStore.js";
40
+ export { createPostgresStockWaitStore } from "./postgresStockWaitStore.js";
41
+ export type { NativeStockWaitBinding, NativeStockWaitAdmission } from "./postgresStockWaitStore.js";
42
+ /** Managed SQL is exposed for service-role hosts; no StockWaitStorePort or
43
+ * NewPurchaseStockReadPort TypeScript adapter is composed for this graph.
44
+ * SQL behavior is proved by the managed pgTAP/real-PostgreSQL witnesses.
45
+ */
46
+ export declare const MANAGED_SUBSCRIPTION_STOCK_CAPABILITIES: Readonly<{
47
+ readonly graph: "managed";
48
+ readonly stockRecovery: "unavailable";
49
+ readonly stockWaitSurface: "sql";
50
+ readonly stockAvailabilitySurface: "sql";
51
+ readonly defaultEnabled: false;
52
+ }>;
53
+ export { runRenewalBatchRows } from "./automaticRenewalExecution.js";
54
+ export type { SubscriptionLifecycleFact } from "./contracts/messages.js";
55
+ export { subscriptionLifecycleTemplate, createSubscriptionLifecycleMessages } from "./lifecycleMessages.js";
56
+ export { createSubscriptionCommandExamples } from "./commandExamples.js";
57
+ export { createSubscriptionServices } from "./services.js";
@@ -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
  });
11
13
  export { executeRenewalCycle, prepareRenewalAttempt, checkRenewalDeliveryAdmission } from "./renewalCycleMechanism.js";
@@ -15,3 +17,20 @@ export { runAutomaticSubscriptionRenewals, runOneAutomaticSubscriptionRenewal, c
15
17
  export { createPostgresRenewalStore } from "./postgresRenewalStore.js";
16
18
  export { createPostgresRetryStore } from "./postgresRetryStore.js";
17
19
  export { createPostgresRetryLifecycleBinding } from "./postgresRetryStore.js";
20
+ export { createPostgresSubscriptionCommandStore, createPostgresSubscriptionCommands } from "./postgresCommandStore.js";
21
+ export { createPostgresStockWaitStore } from "./postgresStockWaitStore.js";
22
+ /** Managed SQL is exposed for service-role hosts; no StockWaitStorePort or
23
+ * NewPurchaseStockReadPort TypeScript adapter is composed for this graph.
24
+ * SQL behavior is proved by the managed pgTAP/real-PostgreSQL witnesses.
25
+ */
26
+ export const MANAGED_SUBSCRIPTION_STOCK_CAPABILITIES = Object.freeze({
27
+ graph: "managed",
28
+ stockRecovery: "unavailable",
29
+ stockWaitSurface: "sql",
30
+ stockAvailabilitySurface: "sql",
31
+ defaultEnabled: false,
32
+ });
33
+ export { runRenewalBatchRows } from "./automaticRenewalExecution.js";
34
+ export { subscriptionLifecycleTemplate, createSubscriptionLifecycleMessages } from "./lifecycleMessages.js";
35
+ export { createSubscriptionCommandExamples } from "./commandExamples.js";
36
+ export { createSubscriptionServices } from "./services.js";
@@ -0,0 +1,9 @@
1
+ import type { SubscriptionLifecycleMessageDescriptor, SubscriptionLifecycleMessagePort } from "./contracts/messages.js";
2
+ export declare function subscriptionLifecycleTemplate(eventType: string, retryAttempt?: number | null): string | null;
3
+ /** M04 owns delivery, consent, rendering and durable replay. M10 never synthesizes a pause. */
4
+ export declare function createSubscriptionLifecycleMessages(delivery: SubscriptionLifecycleMessagePort): {
5
+ deliver(input: Omit<SubscriptionLifecycleMessageDescriptor, "templateSlug">): Promise<{
6
+ notificationId: string;
7
+ replayed: boolean;
8
+ }>;
9
+ };
@@ -0,0 +1,38 @@
1
+ /** Matches M5 and the existing M04 lifecycle templates. A mapping is not a send. */
2
+ const templates = Object.freeze({
3
+ "subscription.created": "subscription-welcome",
4
+ "subscription.activation_action_required": "subscription-activation-action-required",
5
+ "subscription.cancelled": "subscription-cancelled",
6
+ "subscription.paused": "subscription-paused",
7
+ "subscription.resumed": "subscription-resumed",
8
+ "subscription.pause_reminder_due": "subscription-pause-reminder",
9
+ "subscription.delivery_rescheduled": "subscription-delivery-rescheduled",
10
+ "subscription.cycle_skipped": "subscription-cycle-skipped",
11
+ "subscription.address_changed": "subscription-address-changed",
12
+ "subscription.package_changed": "subscription-package-changed",
13
+ "subscription.renewal_upcoming": "subscription-renewal-upcoming",
14
+ "subscription_stock_wait.started": "subscription-stock-wait-started",
15
+ "subscription_stock_wait.resumed": "subscription-stock-wait-resumed",
16
+ payment_expired: "subscription-payment-expired",
17
+ payment_recovered: "subscription-payment-recovered", winback_eligible: "subscription-winback",
18
+ stock_wait_started: "subscription-stock-wait-started", stock_wait_resumed: "subscription-stock-wait-resumed",
19
+ });
20
+ export function subscriptionLifecycleTemplate(eventType, retryAttempt) {
21
+ // Installed dunning SQL uses rung 3 for every value other than exactly 1 or 2.
22
+ if (eventType === "payment_failed")
23
+ return `subscription-payment-failed-${retryAttempt === 1 ? 1 : retryAttempt === 2 ? 2 : 3}`;
24
+ return Object.hasOwn(templates, eventType) ? templates[eventType] : null;
25
+ }
26
+ /** M04 owns delivery, consent, rendering and durable replay. M10 never synthesizes a pause. */
27
+ export function createSubscriptionLifecycleMessages(delivery) {
28
+ return {
29
+ deliver(input) {
30
+ const templateSlug = subscriptionLifecycleTemplate(input.fact.kind, input.fact.kind === "payment_failed" ? input.fact.retryAttempt : null);
31
+ if (!templateSlug)
32
+ throw new Error("subscription_lifecycle_message_unsupported");
33
+ if (input.messageKey !== input.fact.idempotencyKey)
34
+ throw new Error("subscription_lifecycle_message_identity_mismatch");
35
+ return delivery.enqueue({ ...input, templateSlug });
36
+ },
37
+ };
38
+ }
@@ -7,7 +7,7 @@ export async function readAndApplyProviderOutcome(deps, operation, prepared, rai
7
7
  throw new Error("subscription_renewal_provider_amount_mismatch");
8
8
  if (observed.currency !== null && observed.currency.toUpperCase() !== money.currency.toUpperCase())
9
9
  throw new Error("subscription_renewal_provider_currency_mismatch");
10
- if (observed.status === "pending" || observed.status === "unknown")
10
+ if (observed.status !== "succeeded" && observed.status !== "failed")
11
11
  return automaticRenewalResult(operation, "awaiting_provider", `provider_${observed.status}`);
12
12
  if (observed.operationId !== operation.operationId || observed.requestFingerprint !== operation.operationFingerprint
13
13
  || observed.externalAttemptRef !== externalAttemptRef || !observed.verifiedEvidenceRef || !observed.eventKey
@@ -0,0 +1,44 @@
1
+ import type { SubscriptionCommand, SubscriptionCommandPort, SubscriptionCommandRefusal } from "./contracts/commands.js";
2
+ import { type SubscriptionQueryExecutor } from "./postgresRenewalStore.js";
3
+ export interface NativeSubscriptionCommand {
4
+ actorId: string;
5
+ clientId: string;
6
+ idempotencyKey: string;
7
+ subscriptionId: string;
8
+ action: string;
9
+ payload: Record<string, unknown>;
10
+ now: string;
11
+ }
12
+ export interface NativeSubscriptionCommandBinding {
13
+ /** The callback must use one connection and commit/rollback the complete unit. */
14
+ withTransaction<T>(work: (executor: SubscriptionQueryExecutor) => Promise<T>): Promise<T>;
15
+ /** Validate address ownership and refuse address mutation; resolve SKUs and
16
+ * composition policy using trusted host evidence. No current-cycle write. */
17
+ futureTerms(command: Extract<SubscriptionCommand, {
18
+ action: "edit_future_terms";
19
+ }>): Promise<{
20
+ coreLines: readonly {
21
+ variantId: string;
22
+ qty: number;
23
+ }[];
24
+ addonLines: readonly {
25
+ variantId: string;
26
+ qty: number;
27
+ }[];
28
+ compositionConstraint: Record<string, unknown>;
29
+ } | SubscriptionCommandRefusal>;
30
+ }
31
+ /** N2 owns normalization, locking, quote acceptance, receipts and all writes.
32
+ * Preview is a separate persisted transaction; apply never executes payment. */
33
+ export declare function createPostgresSubscriptionCommandStore(binding: Pick<NativeSubscriptionCommandBinding, "withTransaction">): {
34
+ preview(input: NativeSubscriptionCommand): Promise<Record<string, unknown>>;
35
+ apply(input: NativeSubscriptionCommand): Promise<Record<string, unknown>>;
36
+ };
37
+ /** Trusted customer/operator authorization precedes this adapter. The native
38
+ * result's subscriptionStatus is the state recorded by the original execution,
39
+ * including on replay; it is not a fresh read of mutable subscription state. */
40
+ export declare function createPostgresSubscriptionCommands(binding: NativeSubscriptionCommandBinding): SubscriptionCommandPort & {
41
+ preview(command: Extract<SubscriptionCommand, {
42
+ action: "edit_future_terms";
43
+ }>): Promise<Record<string, unknown> | SubscriptionCommandRefusal>;
44
+ };
@@ -0,0 +1,172 @@
1
+ import { subscriptionRecord } from "./postgresRenewalStore.js";
2
+ import { NATIVE_SUBSCRIPTION_CAPABILITIES } from "./index.js";
3
+ const refusalCodes = new Set([
4
+ "multi_cycle_prepaid_unsupported",
5
+ "subscription_command_addon_not_found",
6
+ "subscription_command_bundle_total_mismatch",
7
+ "subscription_command_charge_timing_not_confirmed",
8
+ "subscription_command_idempotency_conflict",
9
+ "subscription_command_invalid_composition_constraint",
10
+ "subscription_command_invalid_input",
11
+ "subscription_command_not_active",
12
+ "subscription_command_operation_busy",
13
+ "subscription_command_pause_forbidden",
14
+ "subscription_command_payment_blocked",
15
+ "subscription_command_preview_unsupported",
16
+ "subscription_command_renewal_terms_missing",
17
+ "subscription_command_unsupported_action",
18
+ "subscription_edit_catalog_unavailable",
19
+ "subscription_edit_invalid_lines",
20
+ "subscription_edit_invalid_request",
21
+ "subscription_edit_quote_expired",
22
+ "subscription_edit_quote_required",
23
+ "subscription_edit_stale_template",
24
+ "subscription_edit_window_closed",
25
+ "subscription_lifecycle_invalid_transition",
26
+ "subscription_lifecycle_invalid_skip",
27
+ "subscription_lifecycle_invalid_slide",
28
+ "subscription_lifecycle_payment_blocked",
29
+ ]);
30
+ function refusalReason(reason) {
31
+ return typeof reason === "string" && refusalCodes.has(reason)
32
+ ? reason : "subscription_command_invalid_input";
33
+ }
34
+ function commandResult(result) {
35
+ return result.status === "refused" || result.outcome === "refused"
36
+ ? { ...result, reason: refusalReason(result.reason) } : result;
37
+ }
38
+ /** N2 owns normalization, locking, quote acceptance, receipts and all writes.
39
+ * Preview is a separate persisted transaction; apply never executes payment. */
40
+ export function createPostgresSubscriptionCommandStore(binding) {
41
+ return {
42
+ preview(input) { return invokeCommand(binding, input, true); },
43
+ apply(input) { return invokeCommand(binding, input, false); },
44
+ };
45
+ }
46
+ async function invokeCommand(binding, input, preview, futureTerms) {
47
+ if (input.action === "multi_cycle_prepaid")
48
+ return {
49
+ status: "refused", reason: NATIVE_SUBSCRIPTION_CAPABILITIES.multiCyclePrepaid.refusalCode,
50
+ };
51
+ return binding.withTransaction(async (executor) => {
52
+ const values = [input.actorId, input.clientId, input.idempotencyKey, input.subscriptionId, input.action, input.payload, input.now];
53
+ // Share N2's actor/key lock so a concurrent preview/apply cannot change
54
+ // the receipt between this read and native dispatch. Replay ends here,
55
+ // before any lifecycle function or other potentially writing call.
56
+ await executor.query("SELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text||':'||$2::text,0))", [input.actorId, input.idempotencyKey]);
57
+ const stored = await executor.query(`WITH stored AS (
58
+ SELECT r.*, CASE WHEN $9::boolean THEN jsonb_set(r.command,'{payload}',
59
+ (r.command->'payload')-ARRAY['coreLines','addonLines','compositionConstraint']) ELSE r.command END AS requested_command
60
+ FROM public.subscription_command_receipts r WHERE r.actor_id=$1::uuid AND r.idempotency_key=$3::text
61
+ AND $7::timestamptz IS NOT NULL AND isfinite($7::timestamptz)
62
+ AND $3::text=btrim($3::text) AND char_length($3::text) BETWEEN 8 AND 180
63
+ AND $5::text IS NOT NULL AND jsonb_typeof($6::jsonb)='object'
64
+ AND (NOT $8::boolean OR NOT ($6::jsonb ? 'acceptedQuoteHash'))
65
+ AND EXISTS(SELECT 1 FROM public.subscriptions WHERE id=$4::uuid AND client_id=$2::uuid)
66
+ ), receipt AS (
67
+ SELECT *, CASE WHEN $8::boolean OR status='previewed' THEN
68
+ jsonb_set(requested_command,'{payload}',(requested_command->'payload')-'acceptedQuoteHash')=
69
+ jsonb_build_object('clientId',$2::uuid,'subscriptionId',$4::uuid,'action',$5::text,'payload',$6::jsonb-'acceptedQuoteHash')
70
+ ELSE requested_command=jsonb_build_object('clientId',$2::uuid,'subscriptionId',$4::uuid,'action',$5::text,'payload',$6::jsonb)
71
+ END AND ($8::boolean OR quote_hash IS NOT DISTINCT FROM ($6::jsonb->>'acceptedQuoteHash')) AS matches
72
+ FROM stored
73
+ ) SELECT command, CASE WHEN NOT matches THEN jsonb_build_object('status','refused','reason','subscription_command_idempotency_conflict')
74
+ WHEN $8::boolean OR status='refused' THEN result
75
+ WHEN status<>'previewed' THEN result||jsonb_build_object('status','replayed','originalStatus',status,'commandFingerprint',command_fingerprint)
76
+ END AS response FROM receipt`, [...values, preview, !!futureTerms]);
77
+ if (stored.rows[0]?.response)
78
+ return commandResult(subscriptionRecord(stored.rows[0].response));
79
+ if (futureTerms) {
80
+ if (stored.rows[0]) {
81
+ // A matching preview already bound the host translation. Apply that
82
+ // exact quote even if the host's mutable policy has since changed.
83
+ values[5] = { ...subscriptionRecord(subscriptionRecord(stored.rows[0].command).payload),
84
+ acceptedQuoteHash: input.payload.acceptedQuoteHash };
85
+ }
86
+ else {
87
+ const terms = await futureTerms();
88
+ if ("outcome" in terms)
89
+ return commandResult({ ...terms });
90
+ values[5] = { ...input.payload, ...terms };
91
+ }
92
+ }
93
+ let result;
94
+ if (!preview && !Object.hasOwn(input.payload, "acceptedQuoteHash")) {
95
+ // N2 owns every command's no-op decision. Keep only its terminal noop;
96
+ // other direct applies must retain their quote requirement without
97
+ // persisting a speculative quote or refusal from this preview probe.
98
+ await executor.query("SAVEPOINT subscription_command_noop");
99
+ 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);
100
+ const candidate = commandResult(subscriptionRecord(rows[0]?.response));
101
+ if (candidate.status === "noop")
102
+ result = candidate;
103
+ else
104
+ await executor.query("ROLLBACK TO SAVEPOINT subscription_command_noop");
105
+ await executor.query("RELEASE SAVEPOINT subscription_command_noop");
106
+ }
107
+ if (!result) {
108
+ const name = preview ? "subscription_command_preview" : "subscription_command_apply";
109
+ 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);
110
+ result = commandResult(subscriptionRecord(rows[0]?.response));
111
+ }
112
+ if (preview || result.status === "refused")
113
+ return result;
114
+ const receipt = await executor.query(`SELECT command_fingerprint FROM public.subscription_command_receipts
115
+ WHERE actor_id=$1::uuid AND idempotency_key=$2::text`, [input.actorId, input.idempotencyKey]);
116
+ if (typeof receipt.rows[0]?.command_fingerprint !== "string")
117
+ throw new Error("subscription_command_receipt_missing");
118
+ return { ...result, commandFingerprint: receipt.rows[0].command_fingerprint };
119
+ });
120
+ }
121
+ /** Trusted customer/operator authorization precedes this adapter. The native
122
+ * result's subscriptionStatus is the state recorded by the original execution,
123
+ * including on replay; it is not a fresh read of mutable subscription state. */
124
+ export function createPostgresSubscriptionCommands(binding) {
125
+ function encode(command) {
126
+ // This serving adapter never pauses an active subscription. Existing native
127
+ // callers retain their separate, unchanged lifecycle contract.
128
+ if (command.action === "pause")
129
+ return { outcome: "refused", reason: "subscription_command_pause_forbidden" };
130
+ const { actor, subscriptionId, idempotencyKey, now, action, ...fields } = command;
131
+ let payload = { ...fields, actorKind: actor.kind };
132
+ let nativeAction = action === "skip" ? "skip_next_cycle" : action === "slide" ? "slide_next_cycle" : action;
133
+ if (command.action === "edit_future_terms") {
134
+ // Preserve the host carriers as well as their native translation in the
135
+ // actual-command fingerprint. The accepted hash is stripped for preview.
136
+ payload = { ...payload, requestedCoreLines: command.coreLines, requestedAddonLines: command.addonLines,
137
+ compositionConstraintRef: command.compositionConstraint };
138
+ delete payload.coreLines;
139
+ delete payload.addonLines;
140
+ delete payload.compositionConstraint;
141
+ // An empty typed hash means no quote; preserve native no-op replay/probing.
142
+ if (command.acceptedQuoteHash === "")
143
+ delete payload.acceptedQuoteHash;
144
+ nativeAction = "update_package_template";
145
+ }
146
+ return { actorId: actor.actorId, clientId: actor.clientId, subscriptionId, idempotencyKey, now, action: nativeAction, payload };
147
+ }
148
+ return {
149
+ capabilities: NATIVE_SUBSCRIPTION_CAPABILITIES,
150
+ async preview(command) {
151
+ const input = encode(command);
152
+ if ("outcome" in input)
153
+ return input;
154
+ delete input.payload.acceptedQuoteHash;
155
+ return invokeCommand(binding, input, true, () => binding.futureTerms(command));
156
+ },
157
+ async apply(command) {
158
+ const input = encode(command);
159
+ if ("outcome" in input)
160
+ return input;
161
+ const result = await invokeCommand(binding, input, false, command.action === "edit_future_terms" ? () => binding.futureTerms(command) : undefined);
162
+ if (result.status === "refused" || result.outcome === "refused")
163
+ return { outcome: "refused", reason: refusalReason(result.reason) };
164
+ if (result.status !== "applied" && result.status !== "replayed" && result.status !== "noop")
165
+ throw new Error("subscription_command_response_invalid");
166
+ return { actorId: command.actor.actorId, idempotencyKey: command.idempotencyKey,
167
+ commandFingerprint: String(result.commandFingerprint), outcome: result.status, subscriptionId: String(result.subscriptionId),
168
+ originalState: String(result.subscriptionStatus), nextCycleAt: result.nextCycleAt == null ? null : String(result.nextCycleAt),
169
+ revision: String(result.templateVersion), eventId: result.eventId == null ? null : String(result.eventId) };
170
+ },
171
+ };
172
+ }
@@ -53,6 +53,12 @@ export declare function createPostgresRetryStore(executor: SubscriptionQueryExec
53
53
  read(operationId: string): Promise<NativeRetryRow | null>;
54
54
  candidates(limit: number, now: string): Promise<NativeRetryRow[]>;
55
55
  applyFailure(operationId: string, key: string, input: NativeRetryFailure): Promise<NativeRetryRow>;
56
+ /** Read the immutable rung receipt against the current case. An interrupted
57
+ * apply still needs propagation; an already advanced case must not be rewritten. */
58
+ failureProgress(operationId: string, key: string): Promise<{
59
+ replayed: boolean;
60
+ caseAdvanced: boolean;
61
+ }>;
56
62
  openCase(operationId: string, template: string, recoveryPath: string | null): Promise<Record<string, unknown>>;
57
63
  authorizeRecovery(operationId: string, tokenId: string, methodRef: string, methodEvidenceRef: string, now: string): Promise<Record<string, unknown>>;
58
64
  scheduleRecovery(operationId: string, key: string, authorizationId: string, now: string): Promise<Record<string, unknown>>;
@@ -34,6 +34,17 @@ export function createPostgresRetryStore(executor) {
34
34
  async applyFailure(operationId, key, input) {
35
35
  return row(await invoke("subscription_retry_apply_failure", [operationId, key, input]));
36
36
  },
37
+ /** Read the immutable rung receipt against the current case. An interrupted
38
+ * apply still needs propagation; an already advanced case must not be rewritten. */
39
+ async failureProgress(operationId, key) {
40
+ const result = await executor.query(`SELECT true AS replayed,
41
+ (c.retry_attempt >= (r.result->>'retry_attempt')::integer OR o.state='recovered') AS case_advanced
42
+ FROM public.subscription_retry_obligations o
43
+ JOIN public.subscription_retry_receipts r ON r.obligation_id=o.id AND r.kind='failure' AND r.receipt_key=$2::text
44
+ LEFT JOIN public.subscription_dunning_cases c ON c.id=o.case_id
45
+ WHERE o.renewal_operation_id=$1::uuid`, [operationId, key]);
46
+ return { replayed: result.rows.length === 1, caseAdvanced: result.rows[0]?.case_advanced === true };
47
+ },
37
48
  async openCase(operationId, template, recoveryPath) {
38
49
  return subscriptionRecord(await invoke("subscription_retry_open_case", [operationId, template, recoveryPath]));
39
50
  },
@@ -0,0 +1,62 @@
1
+ import type { StockWaitCase, StockWaitDeficit, StockWaitFrozenCase, StockWaitRecoveryBinding } from "./contracts/stockWait.js";
2
+ import type { RenewalSchedule } from "./contracts/renewal.js";
3
+ import { type NativeRenewalCodec, type SubscriptionQueryExecutor } from "./postgresRenewalStore.js";
4
+ export interface NativeStockWaitBinding {
5
+ executor: SubscriptionQueryExecutor;
6
+ withTransaction<T>(work: (executor: SubscriptionQueryExecutor) => Promise<T>): Promise<T>;
7
+ codec: NativeRenewalCodec;
8
+ workerId: string;
9
+ }
10
+ export interface NativeStockWaitAdmission {
11
+ waiting: boolean;
12
+ caseId: string | null;
13
+ response: Record<string, unknown>;
14
+ }
15
+ /** Each multi-statement mutation uses the host transaction. Payment execution is
16
+ * deliberately outside this store. SQL owns stock locks and subtransactions. */
17
+ export declare function createPostgresStockWaitStore(options: NativeStockWaitBinding): {
18
+ readFrozen(input: RenewalSchedule): Promise<StockWaitFrozenCase | null>;
19
+ listNormalDue(input: {
20
+ limit: number;
21
+ asOf: string;
22
+ }): Promise<import("./contracts/renewal.js").RenewalDue[]>;
23
+ deficits(input: {
24
+ snapshot: import("./contracts/renewal.js").RenewalFrozenSnapshot;
25
+ operationId: string;
26
+ now: string;
27
+ }): Promise<StockWaitDeficit[]>;
28
+ admit(input: {
29
+ operationId: string;
30
+ claimToken: string;
31
+ snapshot: import("./contracts/renewal.js").RenewalFrozenSnapshot;
32
+ recovery?: StockWaitRecoveryBinding;
33
+ now: string;
34
+ }): Promise<NativeStockWaitAdmission>;
35
+ enqueue(caseId: string, kind: "started" | "resumed"): Promise<void>;
36
+ markResumed(orderId: string): Promise<StockWaitCase | null>;
37
+ listCandidates(input: {
38
+ limit: number;
39
+ asOf: string;
40
+ }): Promise<StockWaitFrozenCase[]>;
41
+ readFrozenCase(input: StockWaitRecoveryBinding): Promise<StockWaitCase | null>;
42
+ reserveAndTransition(input: {
43
+ caseId: string;
44
+ frozenFingerprint: string;
45
+ now: string;
46
+ }): Promise<StockWaitCase>;
47
+ recoverRefusedSchedule(input: {
48
+ operationId: string;
49
+ caseId: string;
50
+ claimGeneration: number;
51
+ frozenFingerprint: string;
52
+ scheduledAt: string;
53
+ now: string;
54
+ }): Promise<{
55
+ outcome: "recovered";
56
+ operation: import("./contracts/renewal.js").RenewalReadback;
57
+ replayed: boolean;
58
+ } | {
59
+ outcome: "refused";
60
+ reason: "not_stock_only" | "external_ownership" | "stale_snapshot" | "lease_active" | "inventory_unavailable";
61
+ }>;
62
+ };