Skip to content
Draft
4 changes: 4 additions & 0 deletions apps/api/src/modules/bus/internal/alert-channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ export const ALERT_CODES = [
// caution (US-701, ADR-169) : ré-autorisation refusée, trip signalé à l'ops, AUCUN débit
// (19 US-225 critère 3) ; une fois par caution (la transition retire la minuterie)
'DEPOSIT_REAUTH_FAILED',
// décision de la caution (US-702, ADR-172) : annulation refusée (autorisation laissée expirer) ou
// autre échec de la décision (P1) ; frais annexes non recouvrés, caution libérée quand même (P2)
'DEPOSIT_DECISION_FAILED',
'DEPOSIT_FEES_UNCOLLECTED',
// files de revue (US-106, ADR-106) : élément en retard (16 ADM-002, P2) ; dossier KYC en revue
// qui ne peut pas être mis en file (P1 : personne ne le verrait)
'OPS_REVIEW_SLA_BREACH',
Expand Down
56 changes: 56 additions & 0 deletions apps/api/src/modules/ntf/internal/catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ export const TEMPLATE_KEYS = [
'EVT_BOOKING_REQUEST_EXPIRED',
'EVT_BOOKING_REQUEST_FAILED',
'EVT_BOOKING_REQUEST_FAILED_HOST',
// décision de la caution (US-702, ADR-172) : libération entière, ou frais annoncés capturés
'EVT_DEPOSIT_RELEASED',
'EVT_DEPOSIT_PARTIALLY_CAPTURED',
] as const;
export type TemplateKey = (typeof TEMPLATE_KEYS)[number];

Expand All @@ -148,6 +151,13 @@ const BOOKING_REF: VariableSource = { from: 'payload', type: 'ref', field: 'trip
const REQUEST_REF: VariableSource = { from: 'payload', type: 'ref', field: 'hold_id' };
const START_AT: VariableSource = { from: 'payload', type: 'instant', field: 'scheduled_start' };
const END_AT: VariableSource = { from: 'payload', type: 'instant', field: 'scheduled_end' };
/** Part de la caution libérée (VOID, expiration ou remboursement), US-702. */
const RELEASED: VariableSource = {
from: 'payload',
type: 'money',
field: 'released_minor',
currencyField: 'currency',
};

/** Documents et confirmations : e-mail d'abord (preuve écrite), SMS en repli (16 A.8 « Notifications »). */
const EMAIL_THEN_SMS: readonly ChannelSpec[] = [{ channel: 'EMAIL', fallback: 'SMS' }];
Expand Down Expand Up @@ -308,6 +318,33 @@ export const TEMPLATES: Readonly<Record<TemplateKey, TemplateSpec>> = {
channels: EMAIL_THEN_SMS,
critical: true,
},
// `deposit.decision.executed` (0149 : deposit_id, trip_id, status, captured_minor,
// released_minor, currency) ; 16 PAY-011 `EVT_DEPOSIT_RELEASED` (PROPOSÉ, ADR-172)
EVT_DEPOSIT_RELEASED: {
key: 'EVT_DEPOSIT_RELEASED',
slug: 'depositReleased',
variables: { first_name: FIRST_NAME, brand: BRAND, booking_ref: BOOKING_REF, amount: RELEASED },
channels: EMAIL_THEN_SMS,
critical: false,
},
EVT_DEPOSIT_PARTIALLY_CAPTURED: {
key: 'EVT_DEPOSIT_PARTIALLY_CAPTURED',
slug: 'depositPartiallyCaptured',
variables: {
first_name: FIRST_NAME,
brand: BRAND,
booking_ref: BOOKING_REF,
amount: RELEASED,
captured: {
from: 'payload',
type: 'money',
field: 'captured_minor',
currencyField: 'currency',
},
},
channels: EMAIL_THEN_SMS,
critical: false,
},
};

const GUEST: RecipientSpec = { role: 'GUEST', field: 'guest_user_id' };
Expand Down Expand Up @@ -457,6 +494,25 @@ export const RULES: readonly RuleSpec[] = [
recipients: [HOST],
parties: CAPTURE_DECLINED_PARTIES,
},
// décision de la caution exécutée (0149, US-702, ADR-172 ; 16 PAY-011 « Notifications ») :
// voyageur du trip (parties lues en base) ; libération entière ou frais annoncés capturés
{
eventType: 'deposit.decision.executed',
template: 'EVT_DEPOSIT_RELEASED',
condition: {
field: 'status',
matches: (v) => v === 'VOIDED' || v === 'EXPIRED' || v === 'REFUNDED',
},
recipients: [GUEST],
parties: TRIP_PARTIES,
},
{
eventType: 'deposit.decision.executed',
template: 'EVT_DEPOSIT_PARTIALLY_CAPTURED',
condition: fieldIs('status', 'PARTIALLY_CAPTURED'),
recipients: [GUEST],
parties: TRIP_PARTIES,
},
];

/** Types d'événements consommés par NTF (abonnement du travailleur `ntf_dispatcher`). */
Expand Down
41 changes: 41 additions & 0 deletions apps/api/src/modules/ntf/internal/dispatcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ describe('abonnement', () => {
'booking.trip.host_restricted',
'booking.trip.host_restriction_lifted',
'catalog.addition_request.resolved',
'deposit.decision.executed',
'kyc.verification.status_changed',
'payout.batch.status_changed',
'trip.overdue.detected',
Expand Down Expand Up @@ -112,6 +113,46 @@ describe.each(COUNTRY_CASES)('planDispatches — $country ($currency)', (c) => {
expect(() => planDispatches(real)).toThrow(NotificationContractError);
});

it('US-702 : décision de la caution exécutée ⇒ le voyageur du trip (base) ; libérée en entier ou frais annoncés capturés ; montants dans la devise du pays', () => {
// 0149 : deposit_id, trip_id, status, captured_minor, released_minor, currency, decided_at
const decided = (status: string, captured: string, released: string) =>
event(
'deposit.decision.executed',
{
deposit_id: randomUUID(),
trip_id: tripId,
status,
captured_minor: captured,
released_minor: released,
currency: c.currency,
decided_at: '2031-07-16T08:00:00+00:00',
},
c.country,
);
for (const status of ['VOIDED', 'EXPIRED', 'REFUNDED']) {
const plan = planDispatches(decided(status, '0', '1500000'), RULES, tripMap());
expect(who(plan)).toEqual([['GUEST', guest, 'EMAIL', 'EVT_DEPOSIT_RELEASED']]);
expect(plan[0]?.variables).toEqual({
booking_ref: '0190F5A2',
amount: { amount_minor: '1500000', currency: c.currency },
});
}
const partial = planDispatches(
decided('PARTIALLY_CAPTURED', '1200', '28800'),
RULES,
tripMap(),
);
expect(who(partial)).toEqual([['GUEST', guest, 'EMAIL', 'EVT_DEPOSIT_PARTIALLY_CAPTURED']]);
expect(partial[0]?.variables).toEqual({
booking_ref: '0190F5A2',
amount: { amount_minor: '28800', currency: c.currency },
captured: { amount_minor: '1200', currency: c.currency },
});
// statut absent : erreur de contrat (jamais un avis deviné)
const bad = event('deposit.decision.executed', { trip_id: tripId }, c.country);
expect(() => planDispatches(bad, RULES, tripMap())).toThrow(NotificationContractError);
});

it('US-213 : charge utile et base en désaccord sur une personne ⇒ erreur de contrat (jamais un mélange)', () => {
const other = randomUUID();
expect(() => planDispatches(booked(), RULES, tripMap(tripFacts(other, host)))).toThrow(
Expand Down
50 changes: 28 additions & 22 deletions apps/api/src/modules/pay/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,27 +19,27 @@ Détail fichier par fichier, FAKE et mode hostile : [`internal/README.md`](inter

Entités de 17 §3.2.7 :

| Entité | État en base |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `payment_operation` | table `core.payment_payment_operation` (migration 0005 ; `psp_account_id` 0028, `NOT NULL` 0038) |
| `webhook_inbox` | table `core.payment_webhook_inbox` (migration 0005 ; clé étrangère du compte 0038) |
| `psp_account` | table `core.payment_psp_account` (migration 0028) |
| `psp_capability` | table `core.payment_psp_capability` (migration 0028) |
| `payment_operation_leg` | table `core.payment_payment_operation_leg` (migration 0028) |
| `payment_operation_event` | table `core.payment_payment_operation_event` (migration 0028) |
| `psp_submerchant` | table `core.payment_psp_submerchant` (migration 0039) |
| `payment_command` | table `core.payment_payment_command` (migration 0040, réduite à `CANCEL_ORDER`) |
| `payment_operation_link` | cible 17, pas encore créée |
| `payment_instrument` | cible 17, pas encore créée |
| `mit_consent` | cible 17, pas encore créée |
| `tender` | cible 17, pas encore créée |
| `refund_instance` | cible 17, pas encore créée |
| `deposit_hold` | `core.payment_deposit_hold` (0146, US-701) : décision figée par hold avant le paiement, lue et écrite par les seules fonctions de cmd_hold_owner |
| `chargeback` | cible 17, pas encore créée |
| `debt_balance` | cible 17, pas encore créée |
| `payment_plan` | cible 17, pas encore créée |
| `payment_plan_installment` | cible 17, pas encore créée |
| `credit_lot` | cible 17, pas encore créée |
| Entité | État en base |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `payment_operation` | table `core.payment_payment_operation` (migration 0005 ; `psp_account_id` 0028, `NOT NULL` 0038) |
| `webhook_inbox` | table `core.payment_webhook_inbox` (migration 0005 ; clé étrangère du compte 0038) |
| `psp_account` | table `core.payment_psp_account` (migration 0028) |
| `psp_capability` | table `core.payment_psp_capability` (migration 0028) |
| `payment_operation_leg` | table `core.payment_payment_operation_leg` (migration 0028) |
| `payment_operation_event` | table `core.payment_payment_operation_event` (migration 0028) |
| `psp_submerchant` | table `core.payment_psp_submerchant` (migration 0039) |
| `payment_command` | table `core.payment_payment_command` (migration 0040, réduite à `CANCEL_ORDER`) |
| `payment_operation_link` | cible 17, pas encore créée |
| `payment_instrument` | cible 17, pas encore créée |
| `mit_consent` | cible 17, pas encore créée |
| `tender` | cible 17, pas encore créée |
| `refund_instance` | cible 17, pas encore créée |
| `deposit_hold` | `core.payment_deposit_hold` (0146, US-701 ; 0149, US-702) : décision figée par hold avant le paiement, décision exécutée (capturé, libéré), lue et écrite par les seules fonctions de cmd_hold_owner |
| `chargeback` | cible 17, pas encore créée |
| `debt_balance` | cible 17, pas encore créée |
| `payment_plan` | cible 17, pas encore créée |
| `payment_plan_installment` | cible 17, pas encore créée |
| `credit_lot` | cible 17, pas encore créée |

Hors entités de 17 : `core.payment_psp_capability_catalog` (catalogue des capacités, migration 0039 ; `SUPPORTS_PAYOUT_WITHOUT_HOST_TAX_ID` ajoutée par 0087, non bloquante, lue par le KYC de l'hôte : inconnue ⇒ numéro fiscal exigé avant l'activation, ADR-115). Commandes `SECURITY DEFINER` (famille `cmd_money`) : `core.payment_cmd_record_operation`, `payment_cmd_apply_operation_status`, `payment_cmd_receive_webhook` (0028), `payment_cmd_register_submerchant`, `payment_cmd_record_submerchant_status` (0039). Détail : `packages/db/README.md`, sections « Port PaymentProvider » et « Port de place de marché ».

Expand All @@ -55,9 +55,15 @@ Hors entités de 17 : `core.payment_psp_capability_catalog` (catalogue des capac
- `DepositRailExecutor.reauthorize` : `SUCCEEDED` seul ⇒ `REAUTHORIZED` ; `PENDING` / `SUBMITTED` / `UNKNOWN` / `UNKNOWN_OUTCOME` ⇒ `REAUTH_PENDING` (`needsLookup`).
- Clés d'idempotence (S-6, 08 E4) : `{trip}:{segment}:v0-DEPOSIT-{caution}:{opération}:{moyen}:i{n}:a{m}` (`depositOperationKey`) ; remboursement du rail (b) = `offSettlementRefundKey` d'origine `DEPOSIT`.

### Décision de la caution à l'heure de décision (US-702 ; ADR-172)

- **Échéancier recalculé par la base** : `core.payment_cmd_record_deposit_decision` (0149) ignore `provider`, `authAt`, `releaseAt`, `decisionAt`, `reauthDueAt` de la décision envoyée et les recalcule (compte marchand du pays, durées `auth_lead_h`, `release_delay_h`, `deposit_safety_h`, `deposit_reauth_lead_h` lues en base) ; `V` reste l'instantané, borné. Le site lit toujours la libération figée en base.
- `DepositDecisionTimer` / `PgDepositDecisionStore` (`internal/deposit-decision.ts`), dans la tâche `deposit_timer` après les ré-autorisations : file `core.payment_deposit_decision_due` (décision échue ou autorisation expirée ; rien ne la suspend), plan `planDepositDecision`, exécution `DepositRailExecutor.execute` hors transaction, transition finale `core.payment_cmd_deposit_decide` (rang attendu, Σ capturé + libéré = montant) qui écrit `deposit.decision.executed`. Autorisation expirée ⇒ `EXPIRED` sans appel ; issue inconnue ⇒ même clé au passage suivant ; VOID refusé ⇒ laissée expirer, `DEPOSIT_DECISION_FAILED` ; MIT impossible ⇒ libérée quand même, `DEPOSIT_FEES_UNCOLLECTED`.
- `DepositFeeSource` : frais annexes et carte du consentement MIT ; en production `NO_DEPOSIT_FEES` (aucun registre des frais annexes encore : caution libérée en entier, frais ensuite par MIT, PROPOSÉ).

## Événements

Aucun événement de domaine n'est émis ni consommé par le code de PAY aujourd'hui. Chaque statut reçu est écrit dans `core.payment_payment_operation_event` (pas un événement d'outbox). La commande `CANCEL_ORDER` est écrite dans `core.payment_payment_command` par les commandes du hold (AVL, migration 0040), pas par un événement.
Émis par une fonction de la base appelée par PAY : `deposit.decision.executed` (0149, US-702 ; `deposit_id`, `trip_id`, `status`, `captured_minor`, `released_minor`, `currency`, `decided_at`), consommé par NTF (avis au voyageur). Aucun autre événement de domaine n'est émis ni consommé par le code de PAY aujourd'hui. Chaque statut reçu est écrit dans `core.payment_payment_operation_event` (pas un événement d'outbox). La commande `CANCEL_ORDER` est écrite dans `core.payment_payment_command` par les commandes du hold (AVL, migration 0040), pas par un événement.

Cible (17 §2.2, §4.5) :

Expand Down
16 changes: 16 additions & 0 deletions apps/api/src/modules/pay/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,22 @@ export type {
DepositTimerStep,
DueDepositReauth,
} from './internal/deposit-timer.js';
// décision de la caution à l'heure de décision (US-702, ADR-172)
export {
DEPOSIT_DECISION_BATCH,
DepositDecisionTimer,
NO_DEPOSIT_FEES,
PgDepositDecisionStore,
postgresDepositDecisionDeps,
withoutMit,
} from './internal/deposit-decision.js';
export type {
DepositDecisionDeps,
DepositDecisionStep,
DepositFeeSource,
DepositOutcome,
DueDepositDecision,
} from './internal/deposit-decision.js';

// Webhooks (17 §4.4)
export {
Expand Down
Loading
Loading