Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 66 additions & 4 deletions apps/api/openapi/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -7240,7 +7240,7 @@
"operationId": "checkoutHoldPayment",
"tags": ["avl"],
"summary": "État du paiement du hold du checkout (US-223b ; 16 PAY-034 ; écran S06, 10b UX-27)",
"description": "Route de réservation : SessionGuard puis TermsGuard. État dérivé de l'état du hold et du trip né de la conversion : CONFIRMED seulement si le hold est CONVERTED et qu'un trip existe (preuve par webhook signé, ADR-139). Le statut de l'opération chez le PSP n'est jamais rendu. Aucun montant ni référence du PSP.",
"description": "Route de réservation : SessionGuard puis TermsGuard. État dérivé de l'état du hold et du trip né de la conversion : CONFIRMED seulement si le hold est CONVERTED et qu'un trip existe (preuve par webhook signé, ADR-139). Le statut de l'opération chez le PSP n'est jamais rendu. Aucun montant ni référence du PSP. US-701 : payment.deposit porte la vue de la caution (décision figée, ou évaluée sans écriture tant qu'un paiement est possible ; montant de la caution seulement) ; absent sinon.",
"parameters": [
{
"name": "holdId",
Expand Down Expand Up @@ -7316,7 +7316,7 @@
"operationId": "checkoutPayHold",
"tags": ["avl"],
"summary": "Paiement du hold du checkout (US-223b ; 17 §2.5 étapes 3a à 3c ; 16 PAY-006, PAY-019 ; 08 E7 règle 1) : intention de paiement (T1), ordre chez le PSP avec le montant explicite de chaque jambe, enregistrement de l'ordre (T2)",
"description": "Route de réservation : SessionGuard puis TermsGuard. Le corps ne porte que le moyen de paiement (défaut CARD) : aucun montant ni jambe n'est reçu, tout champ inconnu est refusé. Montant et jambes viennent du devis engagé au checkout, rejoués par la base. Idempotent par la base : un seul ordre vivant par hold ; pendant un ordre actif, aucun nouvel ordre (200 avec l'état). 201 : ordre créé, redirectUrl = page hébergée du PSP. Aucun connecteur servi (production jusqu'au lot C) : 503 PAYMENT_UNAVAILABLE sans toucher au hold.",
"description": "Route de réservation : SessionGuard puis TermsGuard. Le corps ne porte que le moyen de paiement (défaut CARD) : aucun montant ni jambe n'est reçu, tout champ inconnu est refusé. Montant et jambes viennent du devis engagé au checkout, rejoués par la base. Idempotent par la base : un seul ordre vivant par hold ; pendant un ordre actif, aucun nouvel ordre (200 avec l'état). 201 : ordre créé, redirectUrl = page hébergée du PSP. Aucun connecteur servi (production jusqu'au lot C) : 503 PAYMENT_UNAVAILABLE sans toucher au hold. US-701 : la caution est décidée avant T1 (08 BR-PAY-06) ; refus 409 DEPOSIT_RAIL_UNAVAILABLE ou DEPOSIT_PARAM_MISSING sans écriture ; sinon la décision est figée une fois (deposit_hold) et la vue du voyageur est rendue dans payment.deposit.",
"parameters": [
{
"name": "holdId",
Expand Down Expand Up @@ -7438,7 +7438,7 @@
}
},
"409": {
"description": "Hold échu ou déjà payé, réservation en revue avant tout débit (BOOKING_UNDER_REVIEW), début du trip dépassé, tentatives épuisées (PAY-017), capacité bloquante du PSP non validée (HOST_PAYOUT_RAIL_UNAVAILABLE, inconnue = non)",
"description": "Hold échu ou déjà payé, réservation en revue avant tout débit (BOOKING_UNDER_REVIEW), début du trip dépassé, tentatives épuisées (PAY-017), capacité bloquante du PSP non validée (HOST_PAYOUT_RAIL_UNAVAILABLE, inconnue = non) ; caution exigée sans rail possible pour ces dates (DEPOSIT_RAIL_UNAVAILABLE) ou sans montant fixé (DEPOSIT_PARAM_MISSING), avant tout ordre et sans écriture (US-701)",
"headers": {
"Cache-Control": {
"$ref": "#/components/headers/NoStore"
Expand All @@ -7456,7 +7456,9 @@
"BOOKING_UNDER_REVIEW",
"START_PASSED",
"PAYMENT_ATTEMPTS_EXCEEDED",
"HOST_PAYOUT_RAIL_UNAVAILABLE"
"HOST_PAYOUT_RAIL_UNAVAILABLE",
"DEPOSIT_RAIL_UNAVAILABLE",
"DEPOSIT_PARAM_MISSING"
]
}
}
Expand Down Expand Up @@ -19268,9 +19270,66 @@
},
"request": {
"$ref": "#/components/schemas/CheckoutRequestState"
},
"deposit": {
"$ref": "#/components/schemas/CheckoutDeposit"
}
}
},
"CheckoutDeposit": {
"description": "Caution vue par le voyageur (US-701, ADR-169 ; 08 BR-PAY-06) : NONE (aucune caution), REQUIRED (montant en unités mineures, devise, HOLD = blocage sur la carte ou CHARGE = débit puis remboursement, libération au plus tard) ou UNAVAILABLE (réservation impossible avant le paiement ; maxBookableDays = jours entiers possibles, null ou 0 : aucun). Jamais les déclencheurs, l'âge, le signal de risque ni l'instantané des paramètres [C2].",
"oneOf": [
{
"type": "object",
"required": ["status"],
"additionalProperties": false,
"properties": {
"status": {
"const": "NONE"
}
}
},
{
"type": "object",
"required": ["status", "amountMinor", "currency", "kind", "releaseAt"],
"additionalProperties": false,
"properties": {
"status": {
"const": "REQUIRED"
},
"amountMinor": {
"type": "string",
"pattern": "^[1-9][0-9]{0,17}$"
},
"currency": {
"type": "string",
"pattern": "^[A-Z]{3}$"
},
"kind": {
"type": "string",
"enum": ["HOLD", "CHARGE"]
},
"releaseAt": {
"$ref": "#/components/schemas/DateTime"
}
}
},
{
"type": "object",
"required": ["status", "maxBookableDays"],
"additionalProperties": false,
"properties": {
"status": {
"const": "UNAVAILABLE"
},
"maxBookableDays": {
"type": ["integer", "null"],
"minimum": 0
}
}
}
]
},
"CheckoutPaymentStart": {
"type": "object",
"required": [
Expand Down Expand Up @@ -19328,6 +19387,9 @@
"request": {
"$ref": "#/components/schemas/CheckoutRequestState"
},
"deposit": {
"$ref": "#/components/schemas/CheckoutDeposit"
},
"redirectUrl": {
"type": ["string", "null"],
"description": "Page hébergée du PSP (https), seulement si un ordre vient d'être créé"
Expand Down
28 changes: 26 additions & 2 deletions apps/api/src/modules/avl/internal/checkout/avl-checkout.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@
*/
import { Module } from '@nestjs/common';
import type { DynamicModule } from '@nestjs/common';
import {
DepositCheckoutGate,
PgDepositCheckoutStore,
PgDepositRailConfigReader,
} from '../../../pay/index.js';
import { PgQuoteStore, UnavailableQuoteStore } from '../../../prc/index.js';
import type { QuoteParamsOf, QuoteStore } from '../../../prc/index.js';
import { CheckoutController } from './checkout.controller.js';
Expand All @@ -36,7 +41,7 @@ import { PgCheckoutStore, UnavailableCheckoutStore } from './store.js';
import type { CheckoutStore, SqlExecutor } from './store.js';
import { CheckoutPaymentController } from './payment.controller.js';
import { CheckoutPaymentService, LOG_PAYMENT_FAILURE } from './payment.service.js';
import type { HostedPaymentProvider } from './payment.service.js';
import type { DepositGatePort, HostedPaymentProvider } from './payment.service.js';
import { PgCheckoutPaymentStore, UnavailableCheckoutPaymentStore } from './payment-store.js';
import type { CheckoutPaymentStore } from './payment-store.js';
import { HostRequestsController } from './host-requests.controller.js';
Expand Down Expand Up @@ -74,8 +79,16 @@ export interface AvlCheckoutPaymentOptions {
readonly store: CheckoutPaymentStore;
/** Connecteurs par fournisseur (`payment_psp_account.provider`) ; vide : aucun paiement. */
readonly providers: ReadonlyMap<string, HostedPaymentProvider>;
/** Porte de la caution (US-701, ADR-169) : décidée et figée AVANT le paiement. */
readonly deposits: DepositGatePort;
}

/** Porte de la caution sans base : 503 (jamais un paiement sans décision de caution). */
export const UNAVAILABLE_DEPOSIT_GATE: DepositGatePort = {
view: () => Promise.reject(new Error('porte de la caution indisponible')),
enforce: () => Promise.reject(new Error('porte de la caution indisponible')),
};

/** Demandes de réservation de l'hôte (US-223c) : commandes de 0126 et connecteurs de capture. */
export interface AvlHostRequestOptions {
readonly store: HostRequestStore;
Expand All @@ -93,6 +106,7 @@ export const UNAVAILABLE_HOST_REQUESTS: AvlHostRequestOptions = {
export const UNAVAILABLE_CHECKOUT_PAYMENTS: AvlCheckoutPaymentOptions = {
store: new UnavailableCheckoutPaymentStore(),
providers: new Map(),
deposits: UNAVAILABLE_DEPOSIT_GATE,
};

export interface AvlCheckoutOptions {
Expand Down Expand Up @@ -141,7 +155,16 @@ export function postgresCheckoutAdapters(
store: new PgCheckoutStore(db),
...(cancellationParamsOf === undefined ? {} : { cancellationParamsOf }),
// aucun connecteur de PSP en production avant le lot C (PRODUCTION_PROVIDERS vide)
payments: { store: new PgCheckoutPaymentStore(db), providers: new Map() },
// US-701 : caution décidée et figée avant le paiement (0144), configuration du pays lue sous
// app_api
payments: {
store: new PgCheckoutPaymentStore(db),
providers: new Map(),
deposits: new DepositCheckoutGate(
new PgDepositCheckoutStore(db),
new PgDepositRailConfigReader(db),
),
},
// US-223c : refus et lecture des demandes ; aucune capture avant le lot C
hostRequests: { store: new PgHostRequestStore(db), providers: new Map() },
// US-224d : lecture du remboursement par la partie du trip (aucune écriture)
Expand Down Expand Up @@ -184,6 +207,7 @@ export class AvlCheckoutModule {
useValue: new CheckoutPaymentService(
(options.payments ?? UNAVAILABLE_CHECKOUT_PAYMENTS).store,
(options.payments ?? UNAVAILABLE_CHECKOUT_PAYMENTS).providers,
(options.payments ?? UNAVAILABLE_CHECKOUT_PAYMENTS).deposits,
LOG_PAYMENT_FAILURE,
),
},
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/modules/avl/internal/checkout/payment-errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ export const PAYMENT_MESSAGES = {
KYC_BIOMETRIC_CONSENT_MISSING: CHECKOUT_MESSAGES.KYC_BIOMETRIC_CONSENT_MISSING,
KYC_LICENSE_EXPIRED: CHECKOUT_MESSAGES.KYC_LICENSE_EXPIRED,
AGE_CLASS_MISMATCH: CHECKOUT_MESSAGES.AGE_CLASS_MISMATCH,
// US-701 (ADR-169 ; 08 BR-PAY-06) : caution exigée sans rail possible pour ces dates, ou sans
// montant fixé (`deposit_amount` absent) ; refus AVANT le paiement, aucune écriture
DEPOSIT_RAIL_UNAVAILABLE: { status: 409, messageKey: 'common.payment.depositUnavailable' },
DEPOSIT_PARAM_MISSING: { status: 409, messageKey: 'common.payment.depositUnavailable' },
PAYMENT_UNAVAILABLE: { status: 503, messageKey: 'common.payment.unavailable' },
BOOKING_UNAVAILABLE: CHECKOUT_MESSAGES.BOOKING_UNAVAILABLE,
} as const;
Expand Down
112 changes: 107 additions & 5 deletions apps/api/src/modules/avl/internal/checkout/payment.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,21 @@
* signé, ADR-139) ; le statut brut de l'opération n'est jamais rendu ni lu pour confirmer : il ne
* sert qu'à distinguer un refus (« payer de nouveau ») d'un paiement non prouvé (« ne paie pas de
* nouveau, support »).
*
* US-701 (ADR-169 ; 08 BR-PAY-06 « Moment de l'évaluation ») : la caution est décidée AVANT le
* paiement. `payment` rend la vue du voyageur (`deposit` : aucune caution, montant et libération,
* ou réservation impossible et jours possibles ; jamais les déclencheurs ni l'instantané des
* paramètres, S-7) ; `pay` applique la porte avant T1 : refus ⇒ `DEPOSIT_RAIL_UNAVAILABLE` ou
* `DEPOSIT_PARAM_MISSING` sans écriture ni ordre ; sinon la décision est figée (`deposit_hold`),
* puis le paiement suit.
*/
import { assertMovingLegs, isPaymentError, PAYMENT_METHODS } from '../../../pay/index.js';
import type { PaymentMethod, PaymentProvider } from '../../../pay/index.js';
import type {
DepositEnforcement,
DepositGuestView,
PaymentMethod,
PaymentProvider,
} from '../../../pay/index.js';
import { failureFields } from './checkout.service.js';
import { isUuid } from './model.js';
import { PaymentHttpError } from './payment-errors.js';
Expand All @@ -38,6 +50,50 @@ import type {
/** Ce que l'API demande au connecteur d'un PSP pour le paiement du checkout. */
export type HostedPaymentProvider = Pick<PaymentProvider, 'createHostedPayment' | 'getOperation'>;

/** Porte de la caution du checkout (PAY, `DepositCheckoutGate`). */
export interface DepositGatePort {
view(
proof: Buffer,
holdId: string,
evaluate: boolean,
): Promise<DepositGuestView | null | 'AUTH_REQUIRED' | 'HOLD_NOT_FOUND'>;
enforce(proof: Buffer, holdId: string): Promise<DepositEnforcement>;
}

/**
* Caution vue par le voyageur (S05) : statut, montant (texte d'unités mineures), devise, nature
* (`HOLD` blocage sur la carte, `CHARGE` débit puis remboursement) et libération au plus tard ; ou
* réservation impossible et jours entiers possibles (`null` : aucun). Aucun champ [C2].
*/
export type CheckoutDepositView =
| { readonly status: 'NONE' }
| {
readonly status: 'REQUIRED';
readonly amountMinor: string;
readonly currency: string;
readonly kind: 'HOLD' | 'CHARGE';
readonly releaseAt: string;
}
| { readonly status: 'UNAVAILABLE'; readonly maxBookableDays: number | null };

/** Sérialisation de la vue (liste blanche des champs : rien d'autre ne sort). */
export function depositViewOf(v: DepositGuestView): CheckoutDepositView {
switch (v.status) {
case 'NONE':
return { status: 'NONE' };
case 'REQUIRED':
return {
status: 'REQUIRED',
amountMinor: v.amountMinor.toString(),
currency: v.currency,
kind: v.kind,
releaseAt: v.releaseAt.toISOString(),
};
case 'UNAVAILABLE':
return { status: 'UNAVAILABLE', maxBookableDays: v.maxBookableDays };
}
}

/**
* États du paiement rendus au site (PROPOSÉS, ADR-142) :
* - `PAYABLE` : hold vivant, aucun ordre ; `DECLINED` : hold vivant, dernier ordre refusé ;
Expand Down Expand Up @@ -79,6 +135,11 @@ export interface CheckoutPayment {
* 223c-écrans.
*/
readonly request?: { readonly status: RequestStatus; readonly respondBy: string | null };
/**
* Caution (US-701) : champ absent tant qu'elle n'est ni figée ni évaluable (paiement terminé sans
* décision, devis indisponible).
*/
readonly deposit?: CheckoutDepositView;
}

/**
Expand Down Expand Up @@ -127,6 +188,13 @@ export function paymentStateOf(row: CheckoutPaymentRow): PaymentState {
}
}

/** États où un paiement est possible : la caution y est évaluée (sans écriture) pour S05. */
const PAYABLE_STATES: ReadonlySet<PaymentState> = new Set<PaymentState>([
'PAYABLE',
'DECLINED',
'INTERRUPTED',
]);

const viewOf = (holdId: string, row: CheckoutPaymentRow): CheckoutPayment => ({
holdId,
state: paymentStateOf(row),
Expand All @@ -150,7 +218,8 @@ export function parsePaymentDemand(body: unknown): PaymentMethod | null {
: null;
}

export type PaymentOperation = 'read' | 'start' | 'provider' | 'lookup' | 'psp' | 'record';
export type PaymentOperation =
'read' | 'start' | 'provider' | 'lookup' | 'psp' | 'record' | 'deposit';

/** Journal d'exploitation : opération, nom de l'erreur, SQLSTATE et code PSP ; aucune valeur. */
export type PaymentFailureLog = (operation: PaymentOperation, error: unknown) => void;
Expand All @@ -175,14 +244,31 @@ export class CheckoutPaymentService {
private readonly store: CheckoutPaymentStore,
/** Connecteurs servis par cette image, par fournisseur ; vide en production (lot C). */
private readonly providers: ReadonlyMap<string, HostedPaymentProvider>,
/** Porte de la caution (US-701) ; sans base, elle échoue (503), jamais un paiement sans elle. */
private readonly deposits: DepositGatePort,
private readonly logFailure: PaymentFailureLog = LOG_PAYMENT_FAILURE,
) {}

/** État du paiement du hold du voyageur de la session ; inconnu ou d'un autre ⇒ 404. */
async payment(proof: Buffer, holdId: string): Promise<CheckoutPayment> {
if (!isUuid(holdId)) throw new PaymentHttpError('HOLD_NOT_FOUND');
const id = holdId.toLowerCase();
return viewOf(id, await this.#read(proof, id));
return this.#withDeposit(proof, viewOf(id, await this.#read(proof, id)));
}

/**
* Vue de la caution ajoutée à l'état : décision figée, ou évaluée SANS écriture tant qu'un
* paiement est possible (S05 l'affiche avant le paiement, 08 BR-PAY-06).
*/
async #withDeposit<T extends CheckoutPayment>(proof: Buffer, view: T): Promise<T> {
const evaluate = PAYABLE_STATES.has(view.state);
const deposit = await this.#guard('deposit', () =>
this.deposits.view(proof, view.holdId, evaluate),
);
if (deposit === 'AUTH_REQUIRED' || deposit === 'HOLD_NOT_FOUND') {
throw new PaymentHttpError(deposit);
}
return deposit === null ? view : { ...view, deposit: depositViewOf(deposit) };
}

/**
Expand All @@ -205,7 +291,23 @@ export class CheckoutPaymentService {
before.state !== 'DECLINED' &&
before.state !== 'INTERRUPTED'
) {
return { created: false, payment: { ...before, redirectUrl: null } };
const view = await this.#withDeposit(proof, before);
return { created: false, payment: { ...view, redirectUrl: null } };
}
// US-701 : caution décidée AVANT le paiement ; refus sans écriture ni ordre (08 BR-PAY-06)
const gate = await this.#guard('deposit', () => this.deposits.enforce(proof, id));
switch (gate.kind) {
case 'ACCEPTED':
break;
case 'REFUSED':
throw new PaymentHttpError(
gate.view.code === 'PARAM_MISSING' ? 'DEPOSIT_PARAM_MISSING' : 'DEPOSIT_RAIL_UNAVAILABLE',
);
case 'HOLD_NOT_PAYABLE':
// hold devenu terminal entre la lecture et la décision : l'état fait foi
return this.#current(proof, id, null);
default:
throw new PaymentHttpError(gate.kind);
}
// aucun connecteur dans cette image : refus AVANT T1 (le hold n'est pas mis en vol)
if (this.providers.size === 0) throw new PaymentHttpError('PAYMENT_UNAVAILABLE');
Expand Down Expand Up @@ -297,7 +399,7 @@ export class CheckoutPaymentService {
holdId: string,
redirectUrl: string | null,
): Promise<{ readonly created: boolean; readonly payment: CheckoutPaymentStarted }> {
const view = viewOf(holdId, await this.#read(proof, holdId));
const view = await this.#withDeposit(proof, viewOf(holdId, await this.#read(proof, holdId)));
// une redirection n'a de sens que tant que le paiement est en cours
const url = view.state === 'VERIFYING' || view.state === 'INTERRUPTED' ? redirectUrl : null;
return { created: url !== null, payment: { ...view, redirectUrl: url } };
Expand Down
Loading
Loading