rubis/apps/api/commands/banking_simulate_payment.ts
ordinarthur 51217175ad
All checks were successful
Build & Deploy Web / build-and-deploy (push) Successful in 38s
Build & Deploy API / build-and-deploy (push) Successful in 1m36s
feat(banking): intégration Powens AISP + auto-réconciliation factures
Module banking complet en lecture seule via Powens (ex-Budget Insight)
pour détecter automatiquement les paiements clients et arrêter les
relances dès qu'une facture est payée. Réservé plans Pro / Business,
kill switch global BANKING_ENABLED désactivé en prod tant que le KYC
Powens n'est pas validé (cf. .claude/deploy-memory.md).

Backend (apps/api)
- PowensClient bas niveau : init user, code temporaire 30s, build
  webview URL, list/get/delete connections, accounts, transactions,
  vérif HMAC SHA-256 timing-safe pour webhook.
- BankingService : ensurePowensUser (chiffrement token via Adonis
  encryption / APP_KEY), createWebviewUrl avec state HMAC anti-CSRF
  (TTL 10 min), handleCallback (upsert connection + accounts +
  fire-and-forget mail + sync 90j + reconcile), disconnect (DELETE
  Powens + soft-revoke en DB), setReconciliationMode.
- Réconciliation : match transactions ↔ factures sur montant exact
  + label normalisé (numero ou nom client, NFD strip + alphanum).
  Confiance HIGH (label matche) vs LOW (montant seul). Mode auto +
  HIGH → invoice.status=paid + bonus rubis + cancel relances +
  enqueuePaymentThanks (client) + sendInvoiceAutoPaidNotification
  (user). Mode manual ou LOW → match_status='suggested' (UI V2).
- Webhook /webhooks/powens : vérif HMAC, lookup org par
  powens_user_id, dispatch CONNECTION_SYNCED / NEW_TRANSACTIONS /
  USER_SYNC_ENDED → sync incrémental 7j + reconcile, CONNECTION_ERROR
  / SCA_REQUIRED → update state + last_error. Réponse 200 immédiate
  puis processing fire-and-forget pour ne pas timeout côté Powens.
- 4 migrations : bank_connections, bank_accounts, bank_transactions
  + colonnes powens_user_id (chiffré APP_KEY) et reconciliation_mode
  sur organizations.
- 2 templates React Email : BankConnectedEmail (post-connection,
  récap comptes + lien settings) et InvoiceAutoPaidNotificationEmail
  (notif user après match auto, lien direct facture + libellé
  bancaire détecté). Toujours en branding Rubis (notif Rubis → user,
  jamais marque blanche).
- 2 commandes ace : banking:reconcile (rejoue le reconcile sans
  reconnecter la banque) et banking:simulate-payment (injecte une
  bank_transaction synthétique qui matche une facture, pour test E2E
  sans devoir attendre un vrai virement sandbox).
- Kill switch isBankingEnabled() : flag BANKING_ENABLED + check des
  credentials Powens. Endpoint public GET /banking/status renvoie
  { enabled }, /banking/powens/init throw 503 banking_disabled si OFF.
- Fix handler exceptions : UNIQUE violation composite (org, X)
  rapporte désormais la vraie colonne en faute (numero/slug/…) avec
  message lisible « Le numéro de facture "F2026-0013" existe déjà »,
  au lieu d'un message ambigu sur organization_id.

Frontend (apps/web)
- /parametres : nouvelle SettingsSection "Banque" gated par kill
  switch + plan Pro/Business. Si Free → upsell card avec CTA vers
  /parametres/abonnement. Si Pro/Business sans banque → CTA "Connecter
  une banque". Si banque connectée → carte avec accounts (IBAN
  masqué FR76 **** **** **** 1234), solde, last sync, bouton
  Déconnecter. Toggle Manuel/Auto pour reconciliation_mode.
- /parametres/banque/success : nouvelle route dédiée post-callback
  avec badge ✓ animé + halo glow rubis, récap des comptes
  synchronisés, 2 CTAs ("Voir mes paramètres" / "Retour dashboard"),
  note sécurité "lecture seule, aucun déplacement de fonds".
- Hooks : useBankingStatus, useBankConnections (avec opt-out via
  { enabled }), useInitBanking, useDisconnectBank, useBankingSettings,
  useUpdateBankingSettings.

Infrastructure (k3s)
- ConfigMap rubis-api-config : BANKING_ENABLED='false' par défaut,
  BANKING_PROVIDER='powens', POWENS_DOMAIN='rubis',
  POWENS_API_BASE_URL='https://rubis.biapi.pro/2.0/',
  POWENS_REDIRECT_URI='https://app.rubis.pro/api/v1/banking/powens/callback'.
- Secret rubis-app-secrets : 3 nouvelles clés POWENS_CLIENT_ID,
  POWENS_CLIENT_SECRET, POWENS_WEBHOOK_SECRET (valeurs sandbox posées
  via kubectl patch, à remplacer post-KYC).

Sécurité
- Token Powens chiffré au repos via Adonis encryption (AES-256-GCM,
  clé APP_KEY).
- State HMAC SHA-256 signé sur APP_KEY pour le flow webview
  (anti-CSRF + porte l'org_id à travers le redirect).
- Webhook HMAC SHA-256 sur header BI-Signature avec
  POWENS_WEBHOOK_SECRET, comparaison timing-safe.
- IBAN masqué côté API (transformer).
- Scope par org sur tous les endpoints (anti-IDOR).
- Rate limiting via le middleware Adonis existant.
- Idempotence DB : UNIQUE (org, powens_connection_id), (connection,
  powens_account_id), (account, powens_id) → rejouer un event ou un
  callback ne pose pas de problème.

Documentation
- /docs/tech/banking-setup.md : procédure complète setup dev avec
  Cloudflare Quick Tunnel, compte sandbox Powens, whitelist URLs.
- /.claude/deploy-memory.md : section "Banking (Powens) — activation
  prod" avec procédure en 6 étapes (KYC → secrets → ConfigMap →
  flip flag → smoke test), snippet kubectl patch pour rotation
  ciblée de secrets.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-12 14:03:32 +02:00

113 lines
4.1 KiB
TypeScript

import { BaseCommand, args, flags } from '@adonisjs/core/ace'
import type { CommandOptions } from '@adonisjs/core/types/ace'
import { DateTime } from 'luxon'
import Invoice from '#models/invoice'
import BankAccount from '#models/bank_account'
import BankConnection from '#models/bank_connection'
import BankTransaction from '#models/bank_transaction'
import { reconcileTransactionsForOrg } from '#services/banking/reconcile_transactions'
/**
* Simule un virement bancaire entrant qui matche une facture donnée.
*
* Pourquoi : le sandbox Powens ne permet pas de "faire" de vrais virements
* (les comptes sont des fixtures avec des transactions pré-générées qui
* ne matchent pas les factures qu'on crée dans Rubis). Cette commande
* injecte directement une bank_transaction synthétique avec montant + label
* forgés pour matcher la facture, puis relance le reconcile.
*
* Réservé dev/test — ne pas exposer en prod.
*
* Usage :
* node ace banking:simulate-payment <invoiceId>
* node ace banking:simulate-payment <invoiceId> --no-reconcile # juste insérer
*/
export default class BankingSimulatePayment extends BaseCommand {
static commandName = 'banking:simulate-payment'
static description = 'Injecte une transaction synthétique qui matche une facture (dev)'
static options: CommandOptions = {
startApp: true,
}
@args.string({ description: 'Facture id (UUID) à simuler payée' })
declare invoiceId: string
@flags.boolean({
description: 'Lance reconcile après injection (default true)',
default: true,
})
declare reconcile: boolean
async run() {
const invoice = await Invoice.query()
.where('id', this.invoiceId)
.preload('client')
.first()
if (!invoice) {
this.logger.error(`Facture ${this.invoiceId} introuvable`)
return
}
this.logger.info(
`Facture trouvée : ${invoice.numero} · ${invoice.client.name} · ${(invoice.amountTtcCents / 100).toFixed(2)}`
)
// Récupère le 1er compte courant de la 1re connection active de l'org.
const connection = await BankConnection.query()
.where('organizationId', invoice.organizationId)
.where('state', 'active')
.orderBy('createdAt', 'desc')
.first()
if (!connection) {
this.logger.error('Aucune connection bancaire active sur cette org. Connecte une banque d\'abord.')
return
}
const account = await BankAccount.query()
.where('bankConnectionId', connection.id)
.where('type', 'checking')
.first()
if (!account) {
this.logger.error('Aucun compte de type "checking" sur la connexion. Aucun compte à matcher.')
return
}
// Label "réaliste" : style VIR SEPA + nom client + numéro de facture
// pour que le matching HIGH-confidence trigger (label contient numero
// ou nom client).
const label = `VIR SEPA ${invoice.client.name.toUpperCase()} REF ${invoice.numero}`
const tx = await BankTransaction.create({
bankAccountId: account.id,
powensId: BigInt(Date.now()) as any, // pseudo-id unique
amountCents: invoice.amountTtcCents, // crédit, montant exact
label,
wording: 'Virement reçu',
valueDate: DateTime.now(),
bookedAt: DateTime.now(),
raw: {
synthetic: true,
sourceCommand: 'banking:simulate-payment',
invoiceId: invoice.id,
},
matchStatus: 'unmatched',
})
this.logger.success(`Transaction synthétique créée : ${tx.id}`)
this.logger.info(` Compte : ${account.name}`)
this.logger.info(` Montant : ${(tx.amountCents / 100).toFixed(2)}`)
this.logger.info(` Label : ${tx.label}`)
if (this.reconcile) {
this.logger.info('---')
this.logger.info('Lancement du reconcile…')
const result = await reconcileTransactionsForOrg(invoice.organizationId)
this.logger.success(
`Scanné : ${result.scanned} · Auto-confirmé : ${result.autoConfirmed} · Suggéré : ${result.suggested}`
)
} else {
this.logger.info('Reconcile sauté (--no-reconcile). Lance `node ace banking:reconcile` quand prêt.')
}
}
}