@openlup/platform 0.20.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +62 -231
- package/README.md +172 -6
- package/dist/composition/composeBundle.d.ts +6 -0
- package/dist/composition/composeBundle.js +2 -0
- package/dist/composition/index.js +1 -0
- package/dist/payments/adapterConformance.d.ts +8 -0
- package/dist/payments/adapterConformance.js +109 -0
- package/dist/payments/bindings.d.ts +3 -0
- package/dist/payments/bindings.js +17 -0
- package/dist/payments/checkoutActivePaymentActionResolver.d.ts +7 -0
- package/dist/payments/checkoutActivePaymentActionResolver.js +77 -0
- package/dist/payments/checkoutRecoveryPaymentResolver.d.ts +8 -0
- package/dist/payments/checkoutRecoveryPaymentResolver.js +87 -0
- package/dist/payments/contracts/adapter.d.ts +113 -0
- package/dist/payments/contracts/adapter.js +1 -0
- package/dist/payments/contracts/conformance.d.ts +155 -0
- package/dist/payments/contracts/conformance.js +1 -0
- package/dist/payments/contracts/evidence.d.ts +157 -0
- package/dist/payments/contracts/evidence.js +1 -0
- package/dist/payments/contracts/index.d.ts +10 -0
- package/dist/payments/contracts/index.js +1 -0
- package/dist/payments/contracts/preparedAttempt.d.ts +69 -0
- package/dist/payments/contracts/preparedAttempt.js +1 -0
- package/dist/payments/contracts/reconciliation.d.ts +303 -0
- package/dist/payments/contracts/reconciliation.js +1 -0
- package/dist/payments/contracts/repair.d.ts +92 -0
- package/dist/payments/contracts/repair.js +1 -0
- package/dist/payments/contracts/truth.d.ts +92 -0
- package/dist/payments/contracts/truth.js +1 -0
- package/dist/payments/eventConformanceRunner.d.ts +12 -0
- package/dist/payments/eventConformanceRunner.js +125 -0
- package/dist/payments/index.d.ts +16 -0
- package/dist/payments/index.js +16 -0
- package/dist/payments/paymentAttemptSilenceWindow.d.ts +10 -0
- package/dist/payments/paymentAttemptSilenceWindow.js +19 -0
- package/dist/payments/paymentMethodLifecycle.d.ts +11 -0
- package/dist/payments/paymentMethodLifecycle.js +37 -0
- package/dist/payments/paymentProviderReconciliationAbsenceReopen.d.ts +7 -0
- package/dist/payments/paymentProviderReconciliationAbsenceReopen.js +100 -0
- package/dist/payments/paymentProviderReconciliationEvidence.d.ts +36 -0
- package/dist/payments/paymentProviderReconciliationEvidence.js +91 -0
- package/dist/payments/paymentProviderReconciliationWorker.d.ts +4 -0
- package/dist/payments/paymentProviderReconciliationWorker.js +245 -0
- package/dist/payments/paymentTruth.d.ts +8 -0
- package/dist/payments/paymentTruth.js +125 -0
- package/dist/payments/paymentVerifyNowHandler.d.ts +27 -0
- package/dist/payments/paymentVerifyNowHandler.js +70 -0
- package/dist/payments/paymentVerifyNowService.d.ts +23 -0
- package/dist/payments/paymentVerifyNowService.js +93 -0
- package/dist/payments/paymentWebhookPostProcessing.d.ts +22 -0
- package/dist/payments/paymentWebhookPostProcessing.js +15 -0
- package/dist/payments/postgresPaymentTruth.d.ts +10 -0
- package/dist/payments/postgresPaymentTruth.js +126 -0
- package/dist/payments/preparedAttempt.d.ts +6 -0
- package/dist/payments/preparedAttempt.js +70 -0
- package/dist/payments/preparedAttemptFinalization.d.ts +5 -0
- package/dist/payments/preparedAttemptFinalization.js +12 -0
- package/dist/payments/schemaCapabilities.d.ts +10 -0
- package/dist/payments/schemaCapabilities.js +10 -0
- package/dist/payments/sql.d.ts +20 -0
- package/dist/payments/sql.js +6 -0
- package/dist/payments/stripe/classifyDecline.d.ts +46 -0
- package/dist/payments/stripe/classifyDecline.js +58 -0
- package/dist/payments/stripe/declineFailureHints.d.ts +46 -0
- package/dist/payments/stripe/declineFailureHints.js +87 -0
- package/dist/payments/stripe/donorContracts.d.ts +120 -0
- package/dist/payments/stripe/donorContracts.js +1 -0
- package/dist/payments/stripe/executionDecline.d.ts +53 -0
- package/dist/payments/stripe/executionDecline.js +107 -0
- package/dist/payments/stripe/index.d.ts +16 -0
- package/dist/payments/stripe/index.js +239 -0
- package/dist/payments/stripe/intentMapper.d.ts +26 -0
- package/dist/payments/stripe/intentMapper.js +51 -0
- package/dist/payments/stripe/methodFacts.d.ts +10 -0
- package/dist/payments/stripe/methodFacts.js +12 -0
- package/dist/payments/stripe/paymentFailureEvidence.d.ts +26 -0
- package/dist/payments/stripe/paymentFailureEvidence.js +33 -0
- package/dist/payments/stripe/stripeFailureEvidence.d.ts +41 -0
- package/dist/payments/stripe/stripeFailureEvidence.js +82 -0
- package/dist/payments/stripe/stripeIntentConfirmationEvidence.d.ts +28 -0
- package/dist/payments/stripe/stripeIntentConfirmationEvidence.js +32 -0
- package/dist/payments/stripe/stripePaymentReconciliationProvider.d.ts +35 -0
- package/dist/payments/stripe/stripePaymentReconciliationProvider.js +222 -0
- package/dist/payments/stripe/stripeRefundEvidence.d.ts +8 -0
- package/dist/payments/stripe/stripeRefundEvidence.js +17 -0
- package/dist/payments/stripe/stripeSandboxPaymentExecutionAdapter.d.ts +45 -0
- package/dist/payments/stripe/stripeSandboxPaymentExecutionAdapter.js +220 -0
- package/dist/payments/stripe/stripeWebhookNormalizer.d.ts +14 -0
- package/dist/payments/stripe/stripeWebhookNormalizer.js +243 -0
- package/dist/payments/stripe/webhookSignature.d.ts +14 -0
- package/dist/payments/stripe/webhookSignature.js +43 -0
- package/dist/payments/tpay/blikRecurringMapper.d.ts +37 -0
- package/dist/payments/tpay/blikRecurringMapper.js +24 -0
- package/dist/payments/tpay/capabilities.d.ts +3 -0
- package/dist/payments/tpay/capabilities.js +18 -0
- package/dist/payments/tpay/classifyDecline.d.ts +46 -0
- package/dist/payments/tpay/classifyDecline.js +58 -0
- package/dist/payments/tpay/declineFailureHints.d.ts +72 -0
- package/dist/payments/tpay/declineFailureHints.js +37 -0
- package/dist/payments/tpay/donorContracts.d.ts +140 -0
- package/dist/payments/tpay/donorContracts.js +1 -0
- package/dist/payments/tpay/index.d.ts +43 -0
- package/dist/payments/tpay/index.js +264 -0
- package/dist/payments/tpay/paymentFailureEvidence.d.ts +26 -0
- package/dist/payments/tpay/paymentFailureEvidence.js +33 -0
- package/dist/payments/tpay/preparedProviderAttempt.d.ts +22 -0
- package/dist/payments/tpay/preparedProviderAttempt.js +24 -0
- package/dist/payments/tpay/providerAttemptFailureDiagnostic.d.ts +3 -0
- package/dist/payments/tpay/providerAttemptFailureDiagnostic.js +95 -0
- package/dist/payments/tpay/tpayCreateTransactionInput.d.ts +25 -0
- package/dist/payments/tpay/tpayCreateTransactionInput.js +128 -0
- package/dist/payments/tpay/tpayDeclineEvidence.d.ts +126 -0
- package/dist/payments/tpay/tpayDeclineEvidence.js +177 -0
- package/dist/payments/tpay/tpayDispatchFailure.d.ts +60 -0
- package/dist/payments/tpay/tpayDispatchFailure.js +121 -0
- package/dist/payments/tpay/tpayFailureEvidence.d.ts +20 -0
- package/dist/payments/tpay/tpayFailureEvidence.js +61 -0
- package/dist/payments/tpay/tpayHttpClient.d.ts +52 -0
- package/dist/payments/tpay/tpayHttpClient.js +185 -0
- package/dist/payments/tpay/tpayHttpFailure.d.ts +57 -0
- package/dist/payments/tpay/tpayHttpFailure.js +143 -0
- package/dist/payments/tpay/tpayPaymentExecutionAdapter.d.ts +20 -0
- package/dist/payments/tpay/tpayPaymentExecutionAdapter.js +249 -0
- package/dist/payments/tpay/tpayPaymentReconciliationProvider.d.ts +5 -0
- package/dist/payments/tpay/tpayPaymentReconciliationProvider.js +244 -0
- package/dist/payments/tpay/tpayTransactionPayload.d.ts +120 -0
- package/dist/payments/tpay/tpayTransactionPayload.js +96 -0
- package/dist/payments/tpay/wallClockTime.d.ts +31 -0
- package/dist/payments/tpay/wallClockTime.js +57 -0
- package/dist/payments/tpay/webhookJwsVerifier.d.ts +17 -0
- package/dist/payments/tpay/webhookJwsVerifier.js +51 -0
- package/dist/payments/tpay/webhookNormalizer.d.ts +54 -0
- package/dist/payments/tpay/webhookNormalizer.js +200 -0
- package/dist/payments/verifiedEvidenceProjection.d.ts +12 -0
- package/dist/payments/verifiedEvidenceProjection.js +166 -0
- package/dist/payments/verifiedIngress.d.ts +119 -0
- package/dist/payments/verifiedIngress.js +220 -0
- package/package.json +22 -2
- package/release-gates.json +64 -3
- package/sql/20260810180000_payment_settlement_rail.sql +574 -0
- package/sql/20260815150000_payment_truth_reconciliation.sql +479 -0
- package/sql/20260826100000_late_payment_shifts_the_subscription_cycle.sql +215 -0
- package/src/composition/composeBundle.ts +9 -0
- package/src/composition/index.ts +1 -0
- package/src/payments/adapterConformance.ts +118 -0
- package/src/payments/bindings.ts +17 -0
- package/src/payments/checkoutActivePaymentActionResolver.ts +97 -0
- package/src/payments/checkoutRecoveryPaymentResolver.ts +108 -0
- package/src/payments/contracts/adapter.ts +96 -0
- package/src/payments/contracts/conformance.ts +171 -0
- package/src/payments/contracts/evidence.ts +142 -0
- package/src/payments/contracts/index.ts +54 -0
- package/src/payments/contracts/preparedAttempt.ts +86 -0
- package/src/payments/contracts/reconciliation.ts +296 -0
- package/src/payments/contracts/repair.ts +95 -0
- package/src/payments/contracts/truth.ts +108 -0
- package/src/payments/eventConformanceRunner.ts +149 -0
- package/src/payments/index.ts +21 -0
- package/src/payments/paymentAttemptSilenceWindow.ts +26 -0
- package/src/payments/paymentMethodLifecycle.ts +50 -0
- package/src/payments/paymentProviderReconciliationAbsenceReopen.ts +130 -0
- package/src/payments/paymentProviderReconciliationEvidence.ts +117 -0
- package/src/payments/paymentProviderReconciliationWorker.ts +291 -0
- package/src/payments/paymentTruth.ts +131 -0
- package/src/payments/paymentVerifyNowHandler.ts +94 -0
- package/src/payments/paymentVerifyNowService.ts +125 -0
- package/src/payments/paymentWebhookPostProcessing.ts +36 -0
- package/src/payments/postgresPaymentTruth.ts +149 -0
- package/src/payments/preparedAttempt.ts +90 -0
- package/src/payments/preparedAttemptFinalization.ts +13 -0
- package/src/payments/schemaCapabilities.ts +10 -0
- package/src/payments/sql.ts +6 -0
- package/src/payments/stripe/classifyDecline.ts +62 -0
- package/src/payments/stripe/declineFailureHints.ts +89 -0
- package/src/payments/stripe/donorContracts.ts +87 -0
- package/src/payments/stripe/executionDecline.ts +126 -0
- package/src/payments/stripe/index.ts +235 -0
- package/src/payments/stripe/intentMapper.ts +58 -0
- package/src/payments/stripe/methodFacts.ts +21 -0
- package/src/payments/stripe/paymentFailureEvidence.ts +58 -0
- package/src/payments/stripe/stripeFailureEvidence.ts +115 -0
- package/src/payments/stripe/stripeIntentConfirmationEvidence.ts +34 -0
- package/src/payments/stripe/stripePaymentReconciliationProvider.ts +263 -0
- package/src/payments/stripe/stripeRefundEvidence.ts +19 -0
- package/src/payments/stripe/stripeSandboxPaymentExecutionAdapter.ts +283 -0
- package/src/payments/stripe/stripeWebhookNormalizer.ts +277 -0
- package/src/payments/stripe/webhookSignature.ts +55 -0
- package/src/payments/tpay/blikRecurringMapper.ts +42 -0
- package/src/payments/tpay/capabilities.ts +21 -0
- package/src/payments/tpay/classifyDecline.ts +62 -0
- package/src/payments/tpay/declineFailureHints.ts +90 -0
- package/src/payments/tpay/donorContracts.ts +104 -0
- package/src/payments/tpay/index.ts +257 -0
- package/src/payments/tpay/paymentFailureEvidence.ts +58 -0
- package/src/payments/tpay/preparedProviderAttempt.ts +38 -0
- package/src/payments/tpay/providerAttemptFailureDiagnostic.ts +99 -0
- package/src/payments/tpay/tpayCreateTransactionInput.ts +158 -0
- package/src/payments/tpay/tpayDeclineEvidence.ts +233 -0
- package/src/payments/tpay/tpayDispatchFailure.ts +186 -0
- package/src/payments/tpay/tpayFailureEvidence.ts +75 -0
- package/src/payments/tpay/tpayHttpClient.ts +290 -0
- package/src/payments/tpay/tpayHttpFailure.ts +186 -0
- package/src/payments/tpay/tpayPaymentExecutionAdapter.ts +297 -0
- package/src/payments/tpay/tpayPaymentReconciliationProvider.ts +285 -0
- package/src/payments/tpay/tpayTransactionPayload.ts +207 -0
- package/src/payments/tpay/wallClockTime.ts +57 -0
- package/src/payments/tpay/webhookJwsVerifier.ts +82 -0
- package/src/payments/tpay/webhookNormalizer.ts +279 -0
- package/src/payments/verifiedEvidenceProjection.ts +179 -0
- package/src/payments/verifiedIngress.ts +317 -0
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
-- Provider-neutral payment-event truth and reconciliation over the published
|
|
2
|
+
-- settlement, dunning and accounting rails.
|
|
3
|
+
--
|
|
4
|
+
-- WHAT THIS FORWARD SHIPS. One event ledger, one reconciliation-evidence
|
|
5
|
+
-- ledger and four entry points: ingest, reconcile, sweep-open and readback.
|
|
6
|
+
-- Event identity plus a canonical fingerprint is the replay boundary. A
|
|
7
|
+
-- captured event delegates to `commerce_record_settlement` and
|
|
8
|
+
-- `accounting_document_request_from_paid_order`; a refused event delegates to
|
|
9
|
+
-- the same settlement result and `dunning_lifecycle_open_case`. Indeterminate
|
|
10
|
+
-- and failed reconciliation evidence remain open. The event row records only
|
|
11
|
+
-- references to effects owned by those existing rails.
|
|
12
|
+
--
|
|
13
|
+
-- DELIBERATE BOUNDARIES. There is no provider enum, signature, attempt,
|
|
14
|
+
-- mandate, browser callback, retry cadence, payment state machine or accounting
|
|
15
|
+
-- document lifecycle here. Source references are opaque, external payment
|
|
16
|
+
-- references are never invented, currency is a required three-character datum,
|
|
17
|
+
-- and all amounts are minor units. Dunning notification templates and recovery
|
|
18
|
+
-- paths are composition inputs. A capture can close an existing case through
|
|
19
|
+
-- the existing recovery verb, but this forward owns neither the case nor its
|
|
20
|
+
-- ladder. All routines are invoker-rights with fixed search paths, matching the
|
|
21
|
+
-- public platform catalogue.
|
|
22
|
+
|
|
23
|
+
CREATE TABLE public.payment_truth_events (
|
|
24
|
+
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
25
|
+
source_event_id text NOT NULL,
|
|
26
|
+
event_fingerprint text NOT NULL,
|
|
27
|
+
ingest_idempotency_key text NOT NULL,
|
|
28
|
+
settlement_intent_id uuid NOT NULL REFERENCES public.commerce_settlement_intents(id) ON DELETE RESTRICT,
|
|
29
|
+
state text NOT NULL DEFAULT 'open',
|
|
30
|
+
outcome text NOT NULL,
|
|
31
|
+
amount_minor bigint NOT NULL,
|
|
32
|
+
currency_code text NOT NULL,
|
|
33
|
+
failure_class text,
|
|
34
|
+
failure_reason text,
|
|
35
|
+
source_evidence jsonb NOT NULL,
|
|
36
|
+
settlement_transition_id uuid REFERENCES public.commerce_settlement_transitions(id) ON DELETE RESTRICT,
|
|
37
|
+
dunning_case_id uuid REFERENCES public.subscription_dunning_cases(id) ON DELETE SET NULL,
|
|
38
|
+
accounting_document_id uuid REFERENCES public.accounting_documents(id) ON DELETE SET NULL,
|
|
39
|
+
occurred_at timestamptz NOT NULL,
|
|
40
|
+
settled_at timestamptz,
|
|
41
|
+
last_reconciled_at timestamptz,
|
|
42
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
43
|
+
updated_at timestamptz NOT NULL DEFAULT now(),
|
|
44
|
+
CONSTRAINT payment_truth_events_source_event_id_key UNIQUE (source_event_id),
|
|
45
|
+
CONSTRAINT payment_truth_events_ingest_idempotency_key_key UNIQUE (ingest_idempotency_key),
|
|
46
|
+
CONSTRAINT payment_truth_events_source_event_id_check CHECK (btrim(source_event_id) <> ''),
|
|
47
|
+
CONSTRAINT payment_truth_events_event_fingerprint_check CHECK (event_fingerprint ~ '^[0-9a-f]{64}$'),
|
|
48
|
+
CONSTRAINT payment_truth_events_state_check CHECK (state IN ('open', 'settled')),
|
|
49
|
+
CONSTRAINT payment_truth_events_outcome_check CHECK (outcome IN ('captured', 'refused', 'indeterminate')),
|
|
50
|
+
CONSTRAINT payment_truth_events_amount_check CHECK (amount_minor > 0),
|
|
51
|
+
CONSTRAINT payment_truth_events_currency_check CHECK (currency_code ~ '^[A-Z]{3}$'),
|
|
52
|
+
CONSTRAINT payment_truth_events_evidence_check CHECK (jsonb_typeof(source_evidence) = 'object'),
|
|
53
|
+
CONSTRAINT payment_truth_events_failure_class_check CHECK (
|
|
54
|
+
failure_class IS NULL OR failure_class IN (
|
|
55
|
+
'authorization_refused', 'insufficient_funds', 'method_unavailable',
|
|
56
|
+
'risk_refused', 'unknown_refusal'
|
|
57
|
+
)
|
|
58
|
+
),
|
|
59
|
+
CONSTRAINT payment_truth_events_refusal_check CHECK (
|
|
60
|
+
(outcome = 'refused' AND failure_class IS NOT NULL)
|
|
61
|
+
OR (outcome <> 'refused' AND failure_class IS NULL AND failure_reason IS NULL)
|
|
62
|
+
),
|
|
63
|
+
CONSTRAINT payment_truth_events_settled_at_check CHECK ((state = 'settled') = (settled_at IS NOT NULL)),
|
|
64
|
+
CONSTRAINT payment_truth_events_transition_check CHECK (
|
|
65
|
+
(state = 'settled') = (settlement_transition_id IS NOT NULL)
|
|
66
|
+
),
|
|
67
|
+
CONSTRAINT payment_truth_events_accounting_check CHECK (
|
|
68
|
+
accounting_document_id IS NULL OR (state = 'settled' AND outcome = 'captured')
|
|
69
|
+
),
|
|
70
|
+
CONSTRAINT payment_truth_events_dunning_check CHECK (
|
|
71
|
+
dunning_case_id IS NULL OR (state = 'settled' AND outcome = 'refused')
|
|
72
|
+
)
|
|
73
|
+
);
|
|
74
|
+
|
|
75
|
+
CREATE INDEX idx_payment_truth_events_open
|
|
76
|
+
ON public.payment_truth_events (occurred_at, id)
|
|
77
|
+
WHERE state = 'open';
|
|
78
|
+
|
|
79
|
+
CREATE TABLE public.payment_truth_reconciliation_evidence (
|
|
80
|
+
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
81
|
+
event_id uuid NOT NULL REFERENCES public.payment_truth_events(id) ON DELETE CASCADE,
|
|
82
|
+
idempotency_key text NOT NULL,
|
|
83
|
+
evidence_fingerprint text NOT NULL,
|
|
84
|
+
evidence_status text NOT NULL,
|
|
85
|
+
outcome text NOT NULL,
|
|
86
|
+
failure_class text,
|
|
87
|
+
failure_reason text,
|
|
88
|
+
source_evidence jsonb NOT NULL,
|
|
89
|
+
occurred_at timestamptz NOT NULL,
|
|
90
|
+
applied_at timestamptz,
|
|
91
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
92
|
+
CONSTRAINT payment_truth_reconciliation_idempotency_key_key UNIQUE (idempotency_key),
|
|
93
|
+
CONSTRAINT payment_truth_reconciliation_fingerprint_check CHECK (evidence_fingerprint ~ '^[0-9a-f]{64}$'),
|
|
94
|
+
CONSTRAINT payment_truth_reconciliation_status_check CHECK (evidence_status IN ('observed', 'failed')),
|
|
95
|
+
CONSTRAINT payment_truth_reconciliation_outcome_check CHECK (outcome IN ('captured', 'refused', 'indeterminate')),
|
|
96
|
+
CONSTRAINT payment_truth_reconciliation_evidence_check CHECK (jsonb_typeof(source_evidence) = 'object'),
|
|
97
|
+
CONSTRAINT payment_truth_reconciliation_failure_class_check CHECK (
|
|
98
|
+
failure_class IS NULL OR failure_class IN (
|
|
99
|
+
'authorization_refused', 'insufficient_funds', 'method_unavailable',
|
|
100
|
+
'risk_refused', 'unknown_refusal'
|
|
101
|
+
)
|
|
102
|
+
),
|
|
103
|
+
CONSTRAINT payment_truth_reconciliation_failed_open_check CHECK (
|
|
104
|
+
evidence_status <> 'failed' OR outcome = 'indeterminate'
|
|
105
|
+
),
|
|
106
|
+
CONSTRAINT payment_truth_reconciliation_refusal_check CHECK (
|
|
107
|
+
(outcome = 'refused' AND failure_class IS NOT NULL)
|
|
108
|
+
OR (outcome <> 'refused' AND failure_class IS NULL AND failure_reason IS NULL)
|
|
109
|
+
)
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
CREATE INDEX idx_payment_truth_reconciliation_event
|
|
113
|
+
ON public.payment_truth_reconciliation_evidence (event_id, occurred_at DESC);
|
|
114
|
+
|
|
115
|
+
CREATE FUNCTION public.payment_truth_readback(
|
|
116
|
+
p_event_id uuid,
|
|
117
|
+
p_replayed boolean DEFAULT false
|
|
118
|
+
)
|
|
119
|
+
RETURNS jsonb
|
|
120
|
+
LANGUAGE sql
|
|
121
|
+
STABLE
|
|
122
|
+
SET search_path = public, pg_catalog
|
|
123
|
+
AS $$
|
|
124
|
+
SELECT jsonb_build_object(
|
|
125
|
+
'event', jsonb_build_object(
|
|
126
|
+
'id', event.id,
|
|
127
|
+
'sourceEventId', event.source_event_id,
|
|
128
|
+
'fingerprint', event.event_fingerprint,
|
|
129
|
+
'state', event.state,
|
|
130
|
+
'outcome', event.outcome,
|
|
131
|
+
'replayed', p_replayed
|
|
132
|
+
),
|
|
133
|
+
'effects', jsonb_build_object(
|
|
134
|
+
'paymentResultRecorded', event.settlement_transition_id IS NOT NULL,
|
|
135
|
+
'dunningOpened', event.dunning_case_id IS NOT NULL,
|
|
136
|
+
'accountingRequested', event.accounting_document_id IS NOT NULL
|
|
137
|
+
),
|
|
138
|
+
'financial', jsonb_build_object(
|
|
139
|
+
'settlementStatus', settlement.status,
|
|
140
|
+
'orderStatus', order_row.status,
|
|
141
|
+
'subscriptionStatus', subscription.status,
|
|
142
|
+
'accountingStatus', document.status,
|
|
143
|
+
'amountMinor', event.amount_minor,
|
|
144
|
+
'currency', event.currency_code
|
|
145
|
+
)
|
|
146
|
+
)
|
|
147
|
+
FROM public.payment_truth_events event
|
|
148
|
+
JOIN public.commerce_settlement_intents settlement ON settlement.id = event.settlement_intent_id
|
|
149
|
+
JOIN public.commerce_orders order_row ON order_row.id = settlement.order_id
|
|
150
|
+
LEFT JOIN public.subscription_cycles cycle ON cycle.id = order_row.subscription_cycle_id
|
|
151
|
+
LEFT JOIN public.subscriptions subscription ON subscription.id = cycle.subscription_id
|
|
152
|
+
LEFT JOIN public.accounting_documents document ON document.id = event.accounting_document_id
|
|
153
|
+
WHERE event.id = p_event_id;
|
|
154
|
+
$$;
|
|
155
|
+
|
|
156
|
+
CREATE FUNCTION public.payment_truth_apply_terminal(
|
|
157
|
+
p_event_id uuid,
|
|
158
|
+
p_idempotency_key text,
|
|
159
|
+
p_outcome text,
|
|
160
|
+
p_occurred_at timestamptz,
|
|
161
|
+
p_failure_class text,
|
|
162
|
+
p_failure_reason text,
|
|
163
|
+
p_source_evidence jsonb,
|
|
164
|
+
p_dunning_template_slug text,
|
|
165
|
+
p_recovery_url_path text,
|
|
166
|
+
p_recovery_template_slug text
|
|
167
|
+
)
|
|
168
|
+
RETURNS void
|
|
169
|
+
LANGUAGE plpgsql
|
|
170
|
+
SET search_path = public, pg_catalog
|
|
171
|
+
AS $$
|
|
172
|
+
DECLARE
|
|
173
|
+
v_event public.payment_truth_events%ROWTYPE;
|
|
174
|
+
v_intent public.commerce_settlement_intents%ROWTYPE;
|
|
175
|
+
v_order public.commerce_orders%ROWTYPE;
|
|
176
|
+
v_cycle public.subscription_cycles%ROWTYPE;
|
|
177
|
+
v_subscription public.subscriptions%ROWTYPE;
|
|
178
|
+
v_settlement jsonb;
|
|
179
|
+
v_dunning jsonb;
|
|
180
|
+
v_accounting jsonb;
|
|
181
|
+
v_positions jsonb;
|
|
182
|
+
v_open_case_id uuid;
|
|
183
|
+
v_transition_id uuid;
|
|
184
|
+
v_dunning_case_id uuid;
|
|
185
|
+
v_accounting_document_id uuid;
|
|
186
|
+
BEGIN
|
|
187
|
+
SELECT * INTO v_event FROM public.payment_truth_events WHERE id = p_event_id FOR UPDATE;
|
|
188
|
+
IF NOT FOUND THEN RAISE EXCEPTION 'payment_truth_event_not_found' USING ERRCODE = '22023'; END IF;
|
|
189
|
+
IF v_event.state = 'settled' THEN RETURN; END IF;
|
|
190
|
+
IF p_outcome NOT IN ('captured', 'refused') THEN
|
|
191
|
+
RAISE EXCEPTION 'payment_truth_terminal_outcome_invalid' USING ERRCODE = '22023';
|
|
192
|
+
END IF;
|
|
193
|
+
IF p_outcome = 'refused' AND p_failure_class IS NULL THEN
|
|
194
|
+
RAISE EXCEPTION 'payment_truth_refusal_classification_required' USING ERRCODE = '22023';
|
|
195
|
+
END IF;
|
|
196
|
+
IF p_failure_class IS NOT NULL AND p_failure_class NOT IN (
|
|
197
|
+
'authorization_refused', 'insufficient_funds', 'method_unavailable',
|
|
198
|
+
'risk_refused', 'unknown_refusal'
|
|
199
|
+
) THEN
|
|
200
|
+
RAISE EXCEPTION 'payment_truth_failure_class_invalid' USING ERRCODE = '22023';
|
|
201
|
+
END IF;
|
|
202
|
+
|
|
203
|
+
SELECT * INTO v_intent
|
|
204
|
+
FROM public.commerce_settlement_intents WHERE id = v_event.settlement_intent_id;
|
|
205
|
+
SELECT * INTO v_order FROM public.commerce_orders WHERE id = v_intent.order_id;
|
|
206
|
+
IF v_intent.amount_minor IS DISTINCT FROM v_event.amount_minor
|
|
207
|
+
OR v_intent.currency_code IS DISTINCT FROM v_event.currency_code
|
|
208
|
+
THEN
|
|
209
|
+
RAISE EXCEPTION 'payment_truth_settlement_money_mismatch' USING ERRCODE = '22023';
|
|
210
|
+
END IF;
|
|
211
|
+
|
|
212
|
+
v_settlement := public.commerce_record_settlement(
|
|
213
|
+
p_idempotency_key || ':settlement',
|
|
214
|
+
v_event.settlement_intent_id,
|
|
215
|
+
CASE WHEN p_outcome = 'captured' THEN 'succeeded' ELSE 'failed' END,
|
|
216
|
+
NULL,
|
|
217
|
+
jsonb_build_object(
|
|
218
|
+
'paymentTruthEventId', v_event.id,
|
|
219
|
+
'sourceEvidence', COALESCE(p_source_evidence, '{}'::jsonb),
|
|
220
|
+
'reason', p_failure_reason,
|
|
221
|
+
'failureClass', p_failure_class
|
|
222
|
+
),
|
|
223
|
+
p_occurred_at
|
|
224
|
+
);
|
|
225
|
+
v_transition_id := (v_settlement->>'transitionId')::uuid;
|
|
226
|
+
|
|
227
|
+
IF p_outcome = 'captured' THEN
|
|
228
|
+
SELECT COALESCE(jsonb_agg(jsonb_build_object(
|
|
229
|
+
'description', 'order position ' || item.line_ordinal::text,
|
|
230
|
+
'quantity', item.quantity,
|
|
231
|
+
'unitGrossMinor', item.unit_amount_minor,
|
|
232
|
+
'totalGrossMinor', item.line_amount_minor,
|
|
233
|
+
'taxRateBps', 0
|
|
234
|
+
) ORDER BY item.line_ordinal), '[]'::jsonb)
|
|
235
|
+
INTO v_positions
|
|
236
|
+
FROM public.commerce_order_items item
|
|
237
|
+
WHERE item.order_id = v_order.id;
|
|
238
|
+
|
|
239
|
+
v_accounting := public.accounting_document_request_from_paid_order(
|
|
240
|
+
p_idempotency_key || ':accounting',
|
|
241
|
+
v_order.id,
|
|
242
|
+
v_positions,
|
|
243
|
+
v_event.amount_minor,
|
|
244
|
+
jsonb_build_object(
|
|
245
|
+
'paymentTruthEventId', v_event.id,
|
|
246
|
+
'currency', v_event.currency_code,
|
|
247
|
+
'sourceEvidence', COALESCE(p_source_evidence, '{}'::jsonb)
|
|
248
|
+
),
|
|
249
|
+
p_occurred_at
|
|
250
|
+
);
|
|
251
|
+
v_accounting_document_id := (v_accounting->'document'->>'id')::uuid;
|
|
252
|
+
|
|
253
|
+
IF v_order.subscription_cycle_id IS NOT NULL THEN
|
|
254
|
+
SELECT id INTO v_open_case_id
|
|
255
|
+
FROM public.subscription_dunning_cases
|
|
256
|
+
WHERE cycle_id = v_order.subscription_cycle_id AND status = 'open'
|
|
257
|
+
FOR UPDATE;
|
|
258
|
+
IF v_open_case_id IS NOT NULL THEN
|
|
259
|
+
PERFORM public.dunning_lifecycle_record_recovery(
|
|
260
|
+
v_open_case_id, p_occurred_at, p_recovery_template_slug
|
|
261
|
+
);
|
|
262
|
+
END IF;
|
|
263
|
+
END IF;
|
|
264
|
+
ELSE
|
|
265
|
+
IF v_order.subscription_cycle_id IS NOT NULL THEN
|
|
266
|
+
SELECT * INTO v_cycle
|
|
267
|
+
FROM public.subscription_cycles WHERE id = v_order.subscription_cycle_id;
|
|
268
|
+
SELECT * INTO v_subscription
|
|
269
|
+
FROM public.subscriptions WHERE id = v_cycle.subscription_id;
|
|
270
|
+
v_dunning := public.dunning_lifecycle_open_case(
|
|
271
|
+
'payment-truth:dunning:' || v_cycle.id::text,
|
|
272
|
+
v_subscription.id,
|
|
273
|
+
v_cycle.id,
|
|
274
|
+
v_subscription.client_id,
|
|
275
|
+
1,
|
|
276
|
+
NULL,
|
|
277
|
+
p_failure_class,
|
|
278
|
+
p_failure_reason,
|
|
279
|
+
p_occurred_at,
|
|
280
|
+
v_event.amount_minor,
|
|
281
|
+
v_event.currency_code,
|
|
282
|
+
p_dunning_template_slug,
|
|
283
|
+
p_recovery_url_path
|
|
284
|
+
);
|
|
285
|
+
v_dunning_case_id := (v_dunning->>'caseId')::uuid;
|
|
286
|
+
END IF;
|
|
287
|
+
END IF;
|
|
288
|
+
|
|
289
|
+
UPDATE public.payment_truth_events
|
|
290
|
+
SET state = 'settled',
|
|
291
|
+
outcome = p_outcome,
|
|
292
|
+
failure_class = CASE WHEN p_outcome = 'refused' THEN p_failure_class ELSE NULL END,
|
|
293
|
+
failure_reason = CASE WHEN p_outcome = 'refused' THEN p_failure_reason ELSE NULL END,
|
|
294
|
+
settlement_transition_id = v_transition_id,
|
|
295
|
+
dunning_case_id = v_dunning_case_id,
|
|
296
|
+
accounting_document_id = v_accounting_document_id,
|
|
297
|
+
settled_at = p_occurred_at,
|
|
298
|
+
updated_at = p_occurred_at
|
|
299
|
+
WHERE id = v_event.id;
|
|
300
|
+
END;
|
|
301
|
+
$$;
|
|
302
|
+
|
|
303
|
+
CREATE FUNCTION public.payment_truth_ingest_event(
|
|
304
|
+
p_source_event_id text,
|
|
305
|
+
p_event_fingerprint text,
|
|
306
|
+
p_idempotency_key text,
|
|
307
|
+
p_settlement_intent_id uuid,
|
|
308
|
+
p_outcome text,
|
|
309
|
+
p_amount_minor bigint,
|
|
310
|
+
p_currency_code text,
|
|
311
|
+
p_occurred_at timestamptz,
|
|
312
|
+
p_failure_class text,
|
|
313
|
+
p_failure_reason text,
|
|
314
|
+
p_source_evidence jsonb,
|
|
315
|
+
p_dunning_template_slug text,
|
|
316
|
+
p_recovery_url_path text,
|
|
317
|
+
p_recovery_template_slug text
|
|
318
|
+
)
|
|
319
|
+
RETURNS jsonb
|
|
320
|
+
LANGUAGE plpgsql
|
|
321
|
+
SET search_path = public, pg_catalog
|
|
322
|
+
AS $$
|
|
323
|
+
DECLARE
|
|
324
|
+
v_event public.payment_truth_events%ROWTYPE;
|
|
325
|
+
BEGIN
|
|
326
|
+
IF p_source_event_id IS NULL OR btrim(p_source_event_id) = ''
|
|
327
|
+
OR p_event_fingerprint !~ '^[0-9a-f]{64}$'
|
|
328
|
+
OR p_idempotency_key IS NULL OR char_length(btrim(p_idempotency_key)) < 8
|
|
329
|
+
OR p_outcome NOT IN ('captured', 'refused', 'indeterminate')
|
|
330
|
+
OR p_amount_minor IS NULL OR p_amount_minor < 1
|
|
331
|
+
OR p_currency_code !~ '^[A-Z]{3}$'
|
|
332
|
+
OR p_source_evidence IS NULL OR jsonb_typeof(p_source_evidence) <> 'object'
|
|
333
|
+
OR (p_outcome = 'refused') IS DISTINCT FROM (p_failure_class IS NOT NULL)
|
|
334
|
+
OR (p_failure_class IS NOT NULL AND p_failure_class NOT IN (
|
|
335
|
+
'authorization_refused', 'insufficient_funds', 'method_unavailable',
|
|
336
|
+
'risk_refused', 'unknown_refusal'
|
|
337
|
+
))
|
|
338
|
+
THEN
|
|
339
|
+
RAISE EXCEPTION 'payment_truth_event_invalid' USING ERRCODE = '22023';
|
|
340
|
+
END IF;
|
|
341
|
+
|
|
342
|
+
INSERT INTO public.payment_truth_events (
|
|
343
|
+
source_event_id, event_fingerprint, ingest_idempotency_key,
|
|
344
|
+
settlement_intent_id, state, outcome, amount_minor, currency_code,
|
|
345
|
+
failure_class, failure_reason, source_evidence, occurred_at, updated_at
|
|
346
|
+
) VALUES (
|
|
347
|
+
p_source_event_id, p_event_fingerprint, p_idempotency_key,
|
|
348
|
+
p_settlement_intent_id, 'open', p_outcome, p_amount_minor, p_currency_code,
|
|
349
|
+
p_failure_class, p_failure_reason, p_source_evidence, p_occurred_at, p_occurred_at
|
|
350
|
+
)
|
|
351
|
+
ON CONFLICT ON CONSTRAINT payment_truth_events_source_event_id_key DO NOTHING
|
|
352
|
+
RETURNING * INTO v_event;
|
|
353
|
+
|
|
354
|
+
IF NOT FOUND THEN
|
|
355
|
+
SELECT * INTO v_event
|
|
356
|
+
FROM public.payment_truth_events
|
|
357
|
+
WHERE source_event_id = p_source_event_id
|
|
358
|
+
FOR UPDATE;
|
|
359
|
+
IF v_event.event_fingerprint IS DISTINCT FROM p_event_fingerprint THEN
|
|
360
|
+
RAISE EXCEPTION 'payment_truth_event_fingerprint_conflict' USING ERRCODE = '23505';
|
|
361
|
+
END IF;
|
|
362
|
+
RETURN public.payment_truth_readback(v_event.id, true);
|
|
363
|
+
END IF;
|
|
364
|
+
|
|
365
|
+
IF p_outcome IN ('captured', 'refused') THEN
|
|
366
|
+
PERFORM public.payment_truth_apply_terminal(
|
|
367
|
+
v_event.id, p_idempotency_key, p_outcome, p_occurred_at,
|
|
368
|
+
p_failure_class, p_failure_reason, p_source_evidence,
|
|
369
|
+
p_dunning_template_slug, p_recovery_url_path, p_recovery_template_slug
|
|
370
|
+
);
|
|
371
|
+
END IF;
|
|
372
|
+
RETURN public.payment_truth_readback(v_event.id, false);
|
|
373
|
+
END;
|
|
374
|
+
$$;
|
|
375
|
+
|
|
376
|
+
CREATE FUNCTION public.payment_truth_record_reconciliation(
|
|
377
|
+
p_event_id uuid,
|
|
378
|
+
p_idempotency_key text,
|
|
379
|
+
p_evidence_fingerprint text,
|
|
380
|
+
p_evidence_status text,
|
|
381
|
+
p_outcome text,
|
|
382
|
+
p_occurred_at timestamptz,
|
|
383
|
+
p_failure_class text,
|
|
384
|
+
p_failure_reason text,
|
|
385
|
+
p_source_evidence jsonb,
|
|
386
|
+
p_dunning_template_slug text,
|
|
387
|
+
p_recovery_url_path text,
|
|
388
|
+
p_recovery_template_slug text
|
|
389
|
+
)
|
|
390
|
+
RETURNS jsonb
|
|
391
|
+
LANGUAGE plpgsql
|
|
392
|
+
SET search_path = public, pg_catalog
|
|
393
|
+
AS $$
|
|
394
|
+
DECLARE
|
|
395
|
+
v_event public.payment_truth_events%ROWTYPE;
|
|
396
|
+
v_evidence public.payment_truth_reconciliation_evidence%ROWTYPE;
|
|
397
|
+
BEGIN
|
|
398
|
+
IF p_idempotency_key IS NULL OR char_length(btrim(p_idempotency_key)) < 8
|
|
399
|
+
OR p_evidence_fingerprint !~ '^[0-9a-f]{64}$'
|
|
400
|
+
OR p_evidence_status NOT IN ('observed', 'failed')
|
|
401
|
+
OR p_outcome NOT IN ('captured', 'refused', 'indeterminate')
|
|
402
|
+
OR (p_evidence_status = 'failed' AND p_outcome <> 'indeterminate')
|
|
403
|
+
OR (p_outcome = 'refused') IS DISTINCT FROM (p_failure_class IS NOT NULL)
|
|
404
|
+
OR (p_failure_class IS NOT NULL AND p_failure_class NOT IN (
|
|
405
|
+
'authorization_refused', 'insufficient_funds', 'method_unavailable',
|
|
406
|
+
'risk_refused', 'unknown_refusal'
|
|
407
|
+
))
|
|
408
|
+
OR p_source_evidence IS NULL OR jsonb_typeof(p_source_evidence) <> 'object'
|
|
409
|
+
THEN
|
|
410
|
+
RAISE EXCEPTION 'payment_truth_reconciliation_invalid' USING ERRCODE = '22023';
|
|
411
|
+
END IF;
|
|
412
|
+
|
|
413
|
+
SELECT * INTO v_event FROM public.payment_truth_events WHERE id = p_event_id FOR UPDATE;
|
|
414
|
+
IF NOT FOUND THEN RAISE EXCEPTION 'payment_truth_event_not_found' USING ERRCODE = '22023'; END IF;
|
|
415
|
+
|
|
416
|
+
INSERT INTO public.payment_truth_reconciliation_evidence (
|
|
417
|
+
event_id, idempotency_key, evidence_fingerprint, evidence_status,
|
|
418
|
+
outcome, failure_class, failure_reason, source_evidence, occurred_at
|
|
419
|
+
) VALUES (
|
|
420
|
+
p_event_id, p_idempotency_key, p_evidence_fingerprint, p_evidence_status,
|
|
421
|
+
p_outcome, p_failure_class, p_failure_reason, p_source_evidence, p_occurred_at
|
|
422
|
+
)
|
|
423
|
+
ON CONFLICT ON CONSTRAINT payment_truth_reconciliation_idempotency_key_key DO NOTHING
|
|
424
|
+
RETURNING * INTO v_evidence;
|
|
425
|
+
|
|
426
|
+
IF NOT FOUND THEN
|
|
427
|
+
SELECT * INTO v_evidence
|
|
428
|
+
FROM public.payment_truth_reconciliation_evidence
|
|
429
|
+
WHERE idempotency_key = p_idempotency_key;
|
|
430
|
+
IF v_evidence.event_id IS DISTINCT FROM p_event_id
|
|
431
|
+
OR v_evidence.evidence_fingerprint IS DISTINCT FROM p_evidence_fingerprint
|
|
432
|
+
THEN
|
|
433
|
+
RAISE EXCEPTION 'payment_truth_reconciliation_fingerprint_conflict' USING ERRCODE = '23505';
|
|
434
|
+
END IF;
|
|
435
|
+
RETURN public.payment_truth_readback(v_event.id, true);
|
|
436
|
+
END IF;
|
|
437
|
+
|
|
438
|
+
UPDATE public.payment_truth_events
|
|
439
|
+
SET last_reconciled_at = p_occurred_at, updated_at = p_occurred_at
|
|
440
|
+
WHERE id = v_event.id;
|
|
441
|
+
|
|
442
|
+
IF v_event.state = 'open'
|
|
443
|
+
AND p_evidence_status = 'observed'
|
|
444
|
+
AND p_outcome IN ('captured', 'refused')
|
|
445
|
+
THEN
|
|
446
|
+
PERFORM public.payment_truth_apply_terminal(
|
|
447
|
+
v_event.id, p_idempotency_key, p_outcome, p_occurred_at,
|
|
448
|
+
p_failure_class, p_failure_reason, p_source_evidence,
|
|
449
|
+
p_dunning_template_slug, p_recovery_url_path, p_recovery_template_slug
|
|
450
|
+
);
|
|
451
|
+
UPDATE public.payment_truth_reconciliation_evidence
|
|
452
|
+
SET applied_at = p_occurred_at WHERE id = v_evidence.id;
|
|
453
|
+
END IF;
|
|
454
|
+
|
|
455
|
+
RETURN public.payment_truth_readback(v_event.id, false);
|
|
456
|
+
END;
|
|
457
|
+
$$;
|
|
458
|
+
|
|
459
|
+
CREATE FUNCTION public.payment_truth_sweep_open_events(
|
|
460
|
+
p_now timestamptz,
|
|
461
|
+
p_limit integer
|
|
462
|
+
)
|
|
463
|
+
RETURNS jsonb
|
|
464
|
+
LANGUAGE sql
|
|
465
|
+
SET search_path = public, pg_catalog
|
|
466
|
+
AS $$
|
|
467
|
+
WITH open_events AS (
|
|
468
|
+
SELECT id FROM public.payment_truth_events
|
|
469
|
+
WHERE state = 'open' AND occurred_at <= p_now
|
|
470
|
+
ORDER BY occurred_at, id
|
|
471
|
+
LIMIT GREATEST(COALESCE(p_limit, 1), 1)
|
|
472
|
+
FOR UPDATE SKIP LOCKED
|
|
473
|
+
)
|
|
474
|
+
SELECT jsonb_build_object(
|
|
475
|
+
'claimed', count(*)::integer,
|
|
476
|
+
'settledIgnored', (SELECT count(*)::integer FROM public.payment_truth_events WHERE state = 'settled'),
|
|
477
|
+
'eventIds', COALESCE(jsonb_agg(id ORDER BY id), '[]'::jsonb)
|
|
478
|
+
) FROM open_events;
|
|
479
|
+
$$;
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
-- A late settlement moves the subscription's next date out, and never pulls it in.
|
|
2
|
+
--
|
|
3
|
+
-- THIS FORWARD REPLACES public.commerce_record_settlement so that the schedule
|
|
4
|
+
-- advance it delegates -- "Departure 8", introduced by
|
|
5
|
+
-- 20260810180000_payment_settlement_rail.sql -- measures the whole days the
|
|
6
|
+
-- payment was LATE in addition to the cadence, and so that the write can only ever
|
|
7
|
+
-- move the date later.
|
|
8
|
+
--
|
|
9
|
+
-- WHAT WAS THERE, and why one cadence measured from the cycle is not enough:
|
|
10
|
+
--
|
|
11
|
+
-- next_cycle_at = v_cycle.scheduled_at + (cadence_days || ' days')::interval
|
|
12
|
+
--
|
|
13
|
+
-- Departure 8 chose the cycle rather than the instant the money arrived, and that
|
|
14
|
+
-- half of the ruling is CORRECT and is kept: an on-time settlement must land on
|
|
15
|
+
-- the original grid, to the second, not on whatever second a channel happened to
|
|
16
|
+
-- answer. What it did not account for is a settlement that arrives DAYS after the
|
|
17
|
+
-- cycle it pays for. A retry ladder above this kernel can carry a cycle a week and
|
|
18
|
+
-- a half past its scheduled date; the anchor did not move with it, so the interval
|
|
19
|
+
-- between the delivery just paid for and the next one shrank by exactly the delay.
|
|
20
|
+
-- On a 28-day cadence an eleven-day recovery leaves sixteen days between parcels,
|
|
21
|
+
-- which is the shape of a subscription that stacks goods on a customer who has not
|
|
22
|
+
-- consumed the previous ones yet.
|
|
23
|
+
--
|
|
24
|
+
-- The second defect was that the write was UNCONDITIONAL. Any rail above this one
|
|
25
|
+
-- that had already moved a subscription's date FURTHER out -- because a delivery
|
|
26
|
+
-- was delayed, replaced or re-sent -- had that later date silently overwritten by
|
|
27
|
+
-- this statement with an earlier one.
|
|
28
|
+
--
|
|
29
|
+
-- WHAT REPLACES IT:
|
|
30
|
+
--
|
|
31
|
+
-- next_cycle_at = GREATEST(next_cycle_at,
|
|
32
|
+
-- v_cycle.scheduled_at + make_interval(days =>
|
|
33
|
+
-- GREATEST(0, floor(extract(epoch FROM
|
|
34
|
+
-- (LEAST(p_occurred_at, now()) - v_cycle.scheduled_at)) / 86400.0)::int)
|
|
35
|
+
-- + cadence_days))
|
|
36
|
+
--
|
|
37
|
+
-- Read outward: whole days late (never a fraction of one, so an on-time or
|
|
38
|
+
-- minutes-late settlement truncates to zero and the anchor is byte-identical to
|
|
39
|
+
-- what this forward replaces); never negative, so paying early does not pull the
|
|
40
|
+
-- next delivery closer; LEAST bounds a channel that reports an instant in the
|
|
41
|
+
-- future, which is caller-supplied data this kernel does not trust; and the outer
|
|
42
|
+
-- GREATEST states the invariant directly -- this date extends or it stays, and
|
|
43
|
+
-- nothing here may move it earlier. GREATEST ignores NULL operands, so a
|
|
44
|
+
-- subscription with no date yet still receives the computed one. Lateness is
|
|
45
|
+
-- derived from p_occurred_at and never from a bare now(), so a replayed settlement
|
|
46
|
+
-- computes the same date it computed the first time.
|
|
47
|
+
--
|
|
48
|
+
-- PRESERVED, unchanged, from the definition this replaces: the validate-then-LOCK
|
|
49
|
+
-- ordering and the order-first lock sequence that keeps an opening caller and a
|
|
50
|
+
-- settling caller from deadlocking; the ledger-replay answer; Departure 3, the
|
|
51
|
+
-- outright refusal of a second settlement of a settled intent; the write-once
|
|
52
|
+
-- external reference; the cycle payability refusal; the `AND status = 'active'`
|
|
53
|
+
-- predicate that leaves a cancelled subscription's schedule alone; the declined
|
|
54
|
+
-- arm that leaves the order payable; and the transition row that ends the body.
|
|
55
|
+
-- The function keeps its argument list, its invoker rights, and its pinned
|
|
56
|
+
-- search_path, so this forward creates no table, index, trigger, role or grant.
|
|
57
|
+
--
|
|
58
|
+
-- WHY A NEW FORWARD RATHER THAN AN EDIT to 20260810180000: this catalogue's
|
|
59
|
+
-- migration runner asserts that the applied ledger is the EXACT manifest prefix,
|
|
60
|
+
-- sha256 included (server/adapters/postgres/migrationRunner.ts, readAppliedPrefix).
|
|
61
|
+
-- Rewriting a forward an adopter has already applied is therefore a hard boot
|
|
62
|
+
-- failure for that adopter, not a silent upgrade. Superseding it with a new
|
|
63
|
+
-- forward is what every previous replacement in this catalogue has done.
|
|
64
|
+
|
|
65
|
+
CREATE OR REPLACE FUNCTION public.commerce_record_settlement(
|
|
66
|
+
p_idempotency_key text,
|
|
67
|
+
p_intent_id uuid,
|
|
68
|
+
p_outcome text,
|
|
69
|
+
p_external_ref text DEFAULT NULL,
|
|
70
|
+
p_metadata jsonb DEFAULT '{}'::jsonb,
|
|
71
|
+
p_occurred_at timestamptz DEFAULT now()
|
|
72
|
+
)
|
|
73
|
+
RETURNS jsonb
|
|
74
|
+
LANGUAGE plpgsql
|
|
75
|
+
SET search_path = public, pg_catalog
|
|
76
|
+
AS $$
|
|
77
|
+
DECLARE
|
|
78
|
+
v_intent public.commerce_settlement_intents%ROWTYPE;
|
|
79
|
+
v_from text;
|
|
80
|
+
v_transition public.commerce_settlement_transitions%ROWTYPE;
|
|
81
|
+
v_order public.commerce_orders%ROWTYPE;
|
|
82
|
+
v_cycle public.subscription_cycles%ROWTYPE;
|
|
83
|
+
v_subscription public.subscriptions%ROWTYPE;
|
|
84
|
+
BEGIN
|
|
85
|
+
IF p_idempotency_key IS NULL OR char_length(btrim(p_idempotency_key)) < 8
|
|
86
|
+
OR p_intent_id IS NULL
|
|
87
|
+
OR p_outcome IS NULL OR p_outcome NOT IN ('succeeded', 'failed')
|
|
88
|
+
THEN
|
|
89
|
+
RAISE EXCEPTION 'commerce_settlement_record_invalid_input' USING ERRCODE = '22023';
|
|
90
|
+
END IF;
|
|
91
|
+
|
|
92
|
+
SELECT * INTO v_intent
|
|
93
|
+
FROM public.commerce_settlement_intents WHERE id = p_intent_id;
|
|
94
|
+
IF NOT FOUND THEN
|
|
95
|
+
RAISE EXCEPTION 'commerce_settlement_record_intent_not_found' USING ERRCODE = '22023';
|
|
96
|
+
END IF;
|
|
97
|
+
|
|
98
|
+
SELECT * INTO v_order
|
|
99
|
+
FROM public.commerce_orders WHERE id = v_intent.order_id FOR UPDATE;
|
|
100
|
+
|
|
101
|
+
SELECT * INTO v_intent
|
|
102
|
+
FROM public.commerce_settlement_intents WHERE id = p_intent_id FOR UPDATE;
|
|
103
|
+
|
|
104
|
+
SELECT * INTO v_transition
|
|
105
|
+
FROM public.commerce_settlement_transitions
|
|
106
|
+
WHERE intent_id = p_intent_id AND idempotency_key = p_idempotency_key;
|
|
107
|
+
IF FOUND THEN
|
|
108
|
+
RETURN public.commerce_settlement_response(v_intent, v_transition.id, v_transition.outcome, true);
|
|
109
|
+
END IF;
|
|
110
|
+
|
|
111
|
+
IF v_intent.status = 'settled' THEN
|
|
112
|
+
RAISE EXCEPTION 'commerce_settlement_record_intent_already_settled' USING ERRCODE = '22023';
|
|
113
|
+
END IF;
|
|
114
|
+
|
|
115
|
+
-- Write-once, and compared rather than overwritten: a channel that hands back a different handle
|
|
116
|
+
-- for the same intent is describing a different payment.
|
|
117
|
+
IF v_intent.external_ref IS NOT NULL AND p_external_ref IS NOT NULL
|
|
118
|
+
AND v_intent.external_ref IS DISTINCT FROM p_external_ref
|
|
119
|
+
THEN
|
|
120
|
+
RAISE EXCEPTION 'commerce_settlement_record_external_reference_immutable' USING ERRCODE = '22023';
|
|
121
|
+
END IF;
|
|
122
|
+
|
|
123
|
+
v_from := v_intent.status;
|
|
124
|
+
|
|
125
|
+
IF p_outcome = 'succeeded' THEN
|
|
126
|
+
-- An order somebody took off the table between the ask and the answer is not paid into. The
|
|
127
|
+
-- money question then belongs to whoever cancelled it, and this kernel has no refund verb.
|
|
128
|
+
IF v_order.status <> 'pending_payment' THEN
|
|
129
|
+
RAISE EXCEPTION 'commerce_settlement_record_order_not_payable' USING ERRCODE = '22023';
|
|
130
|
+
END IF;
|
|
131
|
+
|
|
132
|
+
UPDATE public.commerce_settlement_intents
|
|
133
|
+
SET status = 'settled',
|
|
134
|
+
settled_at = p_occurred_at,
|
|
135
|
+
external_ref = COALESCE(external_ref, p_external_ref),
|
|
136
|
+
failure_reason = NULL,
|
|
137
|
+
updated_at = p_occurred_at
|
|
138
|
+
WHERE id = p_intent_id
|
|
139
|
+
RETURNING * INTO v_intent;
|
|
140
|
+
|
|
141
|
+
-- The order transition is the delegation onto the order rail: that rail owns `paid`, owns the
|
|
142
|
+
-- notification it produces, and its emitter fires from this statement without this forward
|
|
143
|
+
-- restating a single line of it.
|
|
144
|
+
UPDATE public.commerce_orders
|
|
145
|
+
SET status = 'paid', paid_at = p_occurred_at, updated_at = p_occurred_at
|
|
146
|
+
WHERE id = v_intent.order_id
|
|
147
|
+
RETURNING * INTO v_order;
|
|
148
|
+
|
|
149
|
+
IF v_order.subscription_cycle_id IS NOT NULL THEN
|
|
150
|
+
SELECT * INTO v_cycle
|
|
151
|
+
FROM public.subscription_cycles WHERE id = v_order.subscription_cycle_id FOR UPDATE;
|
|
152
|
+
IF NOT FOUND THEN
|
|
153
|
+
RAISE EXCEPTION 'commerce_settlement_record_cycle_not_found' USING ERRCODE = '22023';
|
|
154
|
+
END IF;
|
|
155
|
+
IF v_cycle.status NOT IN ('planned', 'payment_pending') THEN
|
|
156
|
+
RAISE EXCEPTION 'commerce_settlement_record_cycle_not_payable' USING ERRCODE = '22023';
|
|
157
|
+
END IF;
|
|
158
|
+
|
|
159
|
+
SELECT * INTO v_subscription
|
|
160
|
+
FROM public.subscriptions WHERE id = v_cycle.subscription_id FOR UPDATE;
|
|
161
|
+
|
|
162
|
+
UPDATE public.subscription_cycles
|
|
163
|
+
SET status = 'paid', updated_at = p_occurred_at
|
|
164
|
+
WHERE id = v_cycle.id;
|
|
165
|
+
|
|
166
|
+
-- Departure 8, revised: one cadence past the cycle that was just paid for PLUS the whole
|
|
167
|
+
-- days the payment itself was late -- so a recovery that took eleven days moves the next
|
|
168
|
+
-- delivery out by eleven days instead of stacking it on top of the parcel just shipped.
|
|
169
|
+
-- Whole days only, so an on-time settlement still lands on the original grid, to the
|
|
170
|
+
-- second. The inner GREATEST refuses a negative shift for an early payment; LEAST bounds a
|
|
171
|
+
-- channel that reports a future instant; the outer GREATEST is the invariant itself -- this
|
|
172
|
+
-- date may extend and may never move earlier, whoever set the value it is replacing. A
|
|
173
|
+
-- subscription nobody is running any more is not slid: settlement truth still applies to a
|
|
174
|
+
-- cancelled subscription, but its schedule is not this function's to revive.
|
|
175
|
+
UPDATE public.subscriptions
|
|
176
|
+
SET next_cycle_at = GREATEST(
|
|
177
|
+
next_cycle_at,
|
|
178
|
+
v_cycle.scheduled_at + make_interval(days =>
|
|
179
|
+
GREATEST(0, floor(extract(epoch FROM
|
|
180
|
+
(LEAST(p_occurred_at, now()) - v_cycle.scheduled_at)) / 86400.0)::int)
|
|
181
|
+
+ cadence_days)),
|
|
182
|
+
updated_at = p_occurred_at
|
|
183
|
+
WHERE id = v_subscription.id
|
|
184
|
+
AND status = 'active';
|
|
185
|
+
|
|
186
|
+
INSERT INTO public.subscription_events
|
|
187
|
+
(subscription_id, event_type, idempotency_key, payload, occurred_at)
|
|
188
|
+
VALUES (v_subscription.id, 'subscription.cycle_settled',
|
|
189
|
+
p_idempotency_key || ':subscription',
|
|
190
|
+
jsonb_build_object('cycleId', v_cycle.id, 'orderId', v_order.id,
|
|
191
|
+
'settlementId', v_intent.id),
|
|
192
|
+
p_occurred_at)
|
|
193
|
+
ON CONFLICT (subscription_id, idempotency_key) DO NOTHING;
|
|
194
|
+
END IF;
|
|
195
|
+
ELSE
|
|
196
|
+
-- Departure 4: the order is untouched, so it stays `pending_payment` and can be settled again.
|
|
197
|
+
UPDATE public.commerce_settlement_intents
|
|
198
|
+
SET status = 'failed',
|
|
199
|
+
external_ref = COALESCE(external_ref, p_external_ref),
|
|
200
|
+
failure_reason = COALESCE(NULLIF(btrim(COALESCE(p_metadata, '{}'::jsonb)->>'reason'), ''),
|
|
201
|
+
'declined'),
|
|
202
|
+
updated_at = p_occurred_at
|
|
203
|
+
WHERE id = p_intent_id
|
|
204
|
+
RETURNING * INTO v_intent;
|
|
205
|
+
END IF;
|
|
206
|
+
|
|
207
|
+
INSERT INTO public.commerce_settlement_transitions
|
|
208
|
+
(intent_id, from_status, to_status, outcome, idempotency_key, payload, occurred_at)
|
|
209
|
+
VALUES (p_intent_id, v_from, v_intent.status, p_outcome, p_idempotency_key,
|
|
210
|
+
COALESCE(p_metadata, '{}'::jsonb), p_occurred_at)
|
|
211
|
+
RETURNING * INTO v_transition;
|
|
212
|
+
|
|
213
|
+
RETURN public.commerce_settlement_response(v_intent, v_transition.id, p_outcome, false);
|
|
214
|
+
END;
|
|
215
|
+
$$;
|