chore: import initial du projet MonTPE (TapTP)

Backend NestJS/Prisma, application mobile Expo (Tap to Pay Stripe),
tableau de bord web Vite et documentation (cadrage en brouillon,
décisions d'architecture). Secrets et fichiers locaux exclus par .gitignore.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Tony AVERTY 2026-10-15 18:26:14 +02:00
commit 061f76a527
213 changed files with 36110 additions and 0 deletions

43
.gitignore vendored Normal file
View file

@ -0,0 +1,43 @@
# Secrets et configuration locale : ne jamais committer
.env
.env.*
!.env.example
backend/.local/
*.local
certs/
*.pem
*.key
*.p8
*.p12
*.pfx
*.jks
*.keystore
*.mobileprovision
google-services.json
GoogleService-Info.plist
*secret*
*credential*
test-account*
# Dépendances et builds
node_modules/
dist/
build/
coverage/
.expo/
web-build/
.metro-health-check*
# Outils et éditeurs
.claude/
.vscode/*
!.vscode/extensions.json
.idea/
.DS_Store
Thumbs.db
# Journaux
*.log
npm-debug.*
yarn-debug.*
yarn-error.*

35
LOCAL_DEV.md Normal file
View file

@ -0,0 +1,35 @@
# TapTP — tests en local
| Élément | Adresse | Démarrage |
|---|---|---|
| Base MariaDB 12.3 | `127.0.0.1:3306`, base `taptp` | Service Windows « MariaDB » (démarre tout seul) |
| API | `http://localhost:3001` (téléphone : `http://<IP Wi-Fi du PC>:3001`) | `npm --prefix backend run start:dev` |
| Webhooks Stripe | — | Stripe CLI (commande ci-dessous), à laisser ouverte |
| Tableau de bord web | `http://localhost:5173` | `npm --prefix web run dev` |
| App mobile | téléphone Android (version de test) | `cd mobile` puis `npx expo start --dev-client` |
Le port 3000 est pris par Grafana : l'API tourne sur **3001**.
## Webhooks Stripe (à lancer à chaque session de test)
```bash
stripe listen --forward-to localhost:3001/api/v1/webhooks/stripe --events payment_intent.succeeded,payment_intent.payment_failed,payment_intent.canceled,refund.updated,refund.failed,charge.dispute.created,payout.created,payout.updated,payout.paid,payout.failed,payout.canceled,transfer.created,transfer.reversed --forward-thin-to localhost:3001/api/v1/webhooks/stripe --thin-events "v2.core.account.updated,v2.core.account[requirements].updated,v2.core.account[configuration.merchant].capability_status_updated,v2.core.account[configuration.recipient].capability_status_updated"
```
Si le secret `whsec_…` affiché change, le reporter dans `backend/.env` (`STRIPE_WEBHOOK_SECRET`) puis relancer l'API.
## Base de données
- Identifiants de l'utilisateur local : `backend/.env` (créés par `backend/.local/setup-db.sql`).
- Après une modification du schéma : `npx prisma migrate dev --name <nom>` (dans `backend`).
- Repartir de zéro : `npx prisma migrate reset` (efface toutes les données locales), puis `npm run prisma:seed`.
## Compte de test
`backend/.local/test-account.txt` (créé par `node backend/.local/smoke.mjs`, qui teste aussi toute l'API).
## Téléphone
- Le téléphone et le PC doivent être sur le **même Wi-Fi**. Si l'IP du PC change, mettre à jour `EXPO_PUBLIC_API_URL` dans `mobile/.env`.
- `EXPO_PUBLIC_TERMINAL_SIMULATED=true` : Tap to Pay simulé par Stripe (aucune carte réelle nécessaire).
- Version de test à installer une fois (compte Expo requis) : `npx eas-cli@latest build --profile development --platform android`.

16
backend/.env.example Normal file
View file

@ -0,0 +1,16 @@
NODE_ENV=development
PORT=3001
DATABASE_URL="mysql://taptp:CHANGE_ME@127.0.0.1:3306/taptp"
# Développement : base temporaire de « prisma migrate dev »
SHADOW_DATABASE_URL="mysql://taptp:CHANGE_ME@127.0.0.1:3306/taptp_shadow"
JWT_ACCESS_SECRET=
JWT_ACCESS_TTL_SECONDS=900
REFRESH_TOKEN_TTL_DAYS=30
PASSWORD_RESET_URL=taptp://reset-password
CORS_ORIGINS=http://localhost:5173
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
STRIPE_CONNECT_WEBHOOK_SECRET=

5
backend/.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
node_modules/
dist/
.env
coverage/
.local/

57
backend/README.md Normal file
View file

@ -0,0 +1,57 @@
# TapTP API
NestJS + Prisma + MySQL.
## Installation
```bash
npm install
cp .env.example .env # puis renseigner DATABASE_URL, JWT_ACCESS_SECRET…
npx prisma migrate dev --name init
npm run prisma:seed
npm run start:dev
```
Base : MySQL 8, créer une base `taptp` (utf8mb4) et un utilisateur dédié limité à cette base.
## Endpoints (préfixe `/api/v1`)
| Méthode | Route | Auth |
|---|---|---|
| GET | `/health` | — |
| POST | `/auth/register` | — |
| POST | `/auth/login` | — |
| POST | `/auth/refresh` | — |
| POST | `/auth/logout` | Bearer |
| POST | `/auth/forgot-password` | — |
| POST | `/auth/reset-password` | — |
| POST | `/auth/web/login`, `/auth/web/refresh`, `/auth/web/logout` (web : cookie HttpOnly, en-tête `X-TapTP-Client: web`) | — |
| GET / PATCH | `/auth/me` (profil : prénom, nom, téléphone) | Bearer |
| PUT | `/auth/password` (`currentPassword`, `newPassword`) | Bearer |
| GET / PUT | `/business` | Bearer |
| GET | `/payment-account` (statut KYC) | Bearer |
| POST | `/payment-account` (crée le compte Stripe) | Bearer |
| POST | `/payment-account/onboarding-session` (secret pour l'onboarding Stripe intégré) | Bearer |
| POST | `/terminal/connection-token` (SDK Terminal : secret, locationId, onBehalfOf) | Bearer |
| POST | `/payments` (`amountCents`, `idempotencyKey` UUID, `note?`) | Bearer |
| POST | `/payments/:id/cancel` | Bearer |
| GET | `/transactions` (`status`, `from`, `to`, `search`, `sort`, `method`, `page` ou `cursor`, `limit`) | Bearer |
| GET | `/transactions/export` (mêmes filtres) : CSV | Bearer |
| GET | `/transactions/:id` | Bearer |
| POST | `/transactions/:id/receipt` (`email`) : reçu Stripe par e-mail | Bearer |
| POST | `/transactions/:id/refunds` (`amountCents?`, `reason?`, `idempotencyKey`, `password`) | Bearer |
| GET | `/transactions/:id/refunds` | Bearer |
| GET | `/stats?period=day\|week\|month` (fuseau Europe/Paris) | Bearer |
| GET | `/payouts`, `/payouts/:id` | Bearer |
| GET | `/payouts/balance` (disponible, en attente, prochain versement) | Bearer |
| GET / POST / DELETE | `/subscription` (TapTP Pro, 10 €/mois) | Bearer |
| POST | `/webhooks/stripe` | Signature Stripe |
## Sécurité en place
- Mots de passe : argon2id ; politique 12+ caractères.
- Access token JWT court (15 min) + refresh token opaque, stocké hashé, rotation et détection de réutilisation.
- Toutes les routes protégées par défaut (`@Public()` pour les exceptions).
- Rate limiting global + limites strictes sur login / register / mot de passe oublié.
- Validation stricte des entrées (champs inconnus rejetés), Helmet, CORS par liste blanche.
- Journal d'audit (sans secrets ni données bancaires).

6
backend/nest-cli.json Normal file
View file

@ -0,0 +1,6 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": { "deleteOutDir": true }
}

8531
backend/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

73
backend/package.json Normal file
View file

@ -0,0 +1,73 @@
{
"name": "taptp-backend",
"version": "1.0.0",
"description": "TapTP API",
"scripts": {
"build": "nest build",
"start": "node dist/main.js",
"start:dev": "nest start --watch",
"typecheck": "tsc --noEmit",
"test": "jest",
"prisma:generate": "prisma generate",
"prisma:migrate": "prisma migrate dev",
"prisma:deploy": "prisma migrate deploy",
"prisma:seed": "ts-node prisma/seed.ts"
},
"author": "",
"license": "ISC",
"type": "commonjs",
"dependencies": {
"@nestjs/common": "^11.2.7",
"@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.2.7",
"@nestjs/jwt": "^11.0.2",
"@nestjs/platform-express": "^11.2.7",
"@nestjs/schedule": "^6.1.3",
"@nestjs/throttler": "^6.7.1",
"@prisma/client": "^6.19.3",
"argon2": "^0.45.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"cookie-parser": "^1.4.7",
"helmet": "^8.3.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2",
"stripe": "^23.0.0",
"zod": "^4.6.5"
},
"devDependencies": {
"@nestjs/cli": "^11.0.24",
"@nestjs/testing": "^11.2.7",
"@types/cookie-parser": "^1.4.10",
"@types/express": "^5.0.6",
"@types/jest": "^29.5.14",
"@types/multer": "^2.3.0",
"@types/node": "^24.19.1",
"@types/react": "~19.2.4",
"jest": "^29.7.0",
"prisma": "^6.19.3",
"ts-jest": "^29.4.14",
"ts-node": "^10.9.2",
"typescript": "^5.9.3"
},
"allowScripts": {
"@prisma/client@6.19.3": true,
"@prisma/engines@6.19.3": true,
"prisma@6.19.3": true,
"argon2@0.45.1": true
},
"private": true,
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*.spec.ts$",
"transform": {
"^.+.ts$": "ts-jest"
},
"testEnvironment": "node"
}
}

View file

@ -0,0 +1,303 @@
-- CreateTable
CREATE TABLE `users` (
`id` CHAR(36) NOT NULL,
`email` VARCHAR(191) NOT NULL,
`password_hash` VARCHAR(255) NOT NULL,
`first_name` VARCHAR(100) NOT NULL,
`last_name` VARCHAR(100) NOT NULL,
`phone` VARCHAR(30) NULL,
`email_verified_at` DATETIME(3) NULL,
`terms_accepted_at` DATETIME(3) NOT NULL,
`terms_version` VARCHAR(20) NOT NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` DATETIME(3) NOT NULL,
UNIQUE INDEX `users_email_key`(`email`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `sessions` (
`id` CHAR(36) NOT NULL,
`user_id` CHAR(36) NOT NULL,
`token_hash` CHAR(64) NOT NULL,
`user_agent` VARCHAR(255) NULL,
`ip` VARCHAR(45) NULL,
`expires_at` DATETIME(3) NOT NULL,
`revoked_at` DATETIME(3) NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
UNIQUE INDEX `sessions_token_hash_key`(`token_hash`),
INDEX `sessions_user_id_idx`(`user_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `password_resets` (
`id` CHAR(36) NOT NULL,
`user_id` CHAR(36) NOT NULL,
`token_hash` CHAR(64) NOT NULL,
`expires_at` DATETIME(3) NOT NULL,
`used_at` DATETIME(3) NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
UNIQUE INDEX `password_resets_token_hash_key`(`token_hash`),
INDEX `password_resets_user_id_idx`(`user_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `businesses` (
`id` CHAR(36) NOT NULL,
`user_id` CHAR(36) NOT NULL,
`legal_name` VARCHAR(191) NOT NULL,
`trade_name` VARCHAR(191) NULL,
`siret` CHAR(14) NULL,
`legal_form` VARCHAR(30) NOT NULL,
`mcc` CHAR(4) NULL,
`description` VARCHAR(500) NULL,
`address_line1` VARCHAR(191) NOT NULL,
`address_line2` VARCHAR(191) NULL,
`postal_code` VARCHAR(10) NOT NULL,
`city` VARCHAR(100) NOT NULL,
`country` CHAR(2) NOT NULL DEFAULT 'FR',
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` DATETIME(3) NOT NULL,
UNIQUE INDEX `businesses_user_id_key`(`user_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `payment_accounts` (
`id` CHAR(36) NOT NULL,
`business_id` CHAR(36) NOT NULL,
`provider` VARCHAR(20) NOT NULL DEFAULT 'stripe',
`provider_account_id` VARCHAR(64) NOT NULL,
`charges_enabled` BOOLEAN NOT NULL DEFAULT false,
`payouts_enabled` BOOLEAN NOT NULL DEFAULT false,
`requirements` JSON NULL,
`bank_last4` CHAR(4) NULL,
`bank_name` VARCHAR(100) NULL,
`terminal_location_id` VARCHAR(64) NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` DATETIME(3) NOT NULL,
UNIQUE INDEX `payment_accounts_business_id_key`(`business_id`),
UNIQUE INDEX `payment_accounts_provider_account_id_key`(`provider_account_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `fee_plans` (
`id` CHAR(36) NOT NULL,
`code` VARCHAR(50) NOT NULL,
`per_transaction_cents` INTEGER NOT NULL,
`monthly_price_cents` INTEGER NOT NULL DEFAULT 0,
`tap_to_pay_fee_cents` INTEGER NOT NULL DEFAULT 10,
`pass_through_stripe_fees` BOOLEAN NOT NULL DEFAULT true,
`active` BOOLEAN NOT NULL DEFAULT true,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` DATETIME(3) NOT NULL,
UNIQUE INDEX `fee_plans_code_key`(`code`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `subscriptions` (
`id` CHAR(36) NOT NULL,
`business_id` CHAR(36) NOT NULL,
`price_cents` INTEGER NOT NULL,
`status` VARCHAR(20) NOT NULL,
`current_period_start` DATETIME(3) NOT NULL,
`current_period_end` DATETIME(3) NOT NULL,
`cancel_at_period_end` BOOLEAN NOT NULL DEFAULT false,
`canceled_at` DATETIME(3) NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` DATETIME(3) NOT NULL,
INDEX `subscriptions_business_id_status_idx`(`business_id`, `status`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `transactions` (
`id` CHAR(36) NOT NULL,
`business_id` CHAR(36) NOT NULL,
`idempotency_key` VARCHAR(64) NOT NULL,
`provider_payment_intent_id` VARCHAR(64) NULL,
`provider_charge_id` VARCHAR(64) NULL,
`provider_transfer_id` VARCHAR(64) NULL,
`amount_cents` INTEGER NOT NULL,
`currency` CHAR(3) NOT NULL DEFAULT 'eur',
`provider_fee_cents` INTEGER NULL,
`platform_fee_cents` INTEGER NULL,
`net_cents` INTEGER NULL,
`refunded_cents` INTEGER NOT NULL DEFAULT 0,
`fee_plan_code` VARCHAR(50) NULL,
`debt_deducted_cents` INTEGER NOT NULL DEFAULT 0,
`note` VARCHAR(255) NULL,
`status` VARCHAR(30) NOT NULL,
`failure_reason` VARCHAR(255) NULL,
`card_brand` VARCHAR(20) NULL,
`card_last4` CHAR(4) NULL,
`wallet_type` VARCHAR(20) NULL,
`receipt_email` VARCHAR(191) NULL,
`succeeded_at` DATETIME(3) NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` DATETIME(3) NOT NULL,
UNIQUE INDEX `transactions_idempotency_key_key`(`idempotency_key`),
UNIQUE INDEX `transactions_provider_payment_intent_id_key`(`provider_payment_intent_id`),
UNIQUE INDEX `transactions_provider_charge_id_key`(`provider_charge_id`),
UNIQUE INDEX `transactions_provider_transfer_id_key`(`provider_transfer_id`),
INDEX `transactions_business_id_created_at_idx`(`business_id`, `created_at`),
INDEX `transactions_business_id_status_idx`(`business_id`, `status`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `refunds` (
`id` CHAR(36) NOT NULL,
`transaction_id` CHAR(36) NOT NULL,
`idempotency_key` VARCHAR(64) NOT NULL,
`provider_refund_id` VARCHAR(64) NULL,
`amount_cents` INTEGER NOT NULL,
`reason` VARCHAR(50) NULL,
`status` VARCHAR(20) NOT NULL,
`requested_by` CHAR(36) NOT NULL,
`provider_reversal_id` VARCHAR(64) NULL,
`reversed_cents` INTEGER NOT NULL DEFAULT 0,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` DATETIME(3) NOT NULL,
UNIQUE INDEX `refunds_idempotency_key_key`(`idempotency_key`),
UNIQUE INDEX `refunds_provider_refund_id_key`(`provider_refund_id`),
UNIQUE INDEX `refunds_provider_reversal_id_key`(`provider_reversal_id`),
INDEX `refunds_transaction_id_idx`(`transaction_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `merchant_debts` (
`id` CHAR(36) NOT NULL,
`business_id` CHAR(36) NOT NULL,
`kind` VARCHAR(30) NOT NULL,
`amount_cents` INTEGER NOT NULL,
`settled_cents` INTEGER NOT NULL DEFAULT 0,
`status` VARCHAR(20) NOT NULL DEFAULT 'open',
`subscription_id` CHAR(36) NULL,
`period_start` DATETIME(3) NULL,
`refund_id` CHAR(36) NULL,
`settled_at` DATETIME(3) NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` DATETIME(3) NOT NULL,
UNIQUE INDEX `merchant_debts_refund_id_key`(`refund_id`),
INDEX `merchant_debts_business_id_status_created_at_idx`(`business_id`, `status`, `created_at`),
UNIQUE INDEX `merchant_debts_subscription_id_period_start_key`(`subscription_id`, `period_start`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `debt_allocations` (
`id` CHAR(36) NOT NULL,
`debt_id` CHAR(36) NOT NULL,
`transaction_id` CHAR(36) NOT NULL,
`amount_cents` INTEGER NOT NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
INDEX `debt_allocations_transaction_id_idx`(`transaction_id`),
UNIQUE INDEX `debt_allocations_debt_id_transaction_id_key`(`debt_id`, `transaction_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `payouts` (
`id` CHAR(36) NOT NULL,
`payment_account_id` CHAR(36) NOT NULL,
`provider_payout_id` VARCHAR(64) NOT NULL,
`amount_cents` INTEGER NOT NULL,
`currency` CHAR(3) NOT NULL DEFAULT 'eur',
`arrival_date` DATETIME(3) NOT NULL,
`status` VARCHAR(20) NOT NULL,
`bank_last4` CHAR(4) NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` DATETIME(3) NOT NULL,
UNIQUE INDEX `payouts_provider_payout_id_key`(`provider_payout_id`),
INDEX `payouts_payment_account_id_arrival_date_idx`(`payment_account_id`, `arrival_date`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `webhook_events` (
`id` CHAR(36) NOT NULL,
`provider_event_id` VARCHAR(64) NOT NULL,
`type` VARCHAR(100) NOT NULL,
`payload` JSON NOT NULL,
`processed_at` DATETIME(3) NULL,
`error` TEXT NULL,
`attempts` INTEGER NOT NULL DEFAULT 0,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
UNIQUE INDEX `webhook_events_provider_event_id_key`(`provider_event_id`),
INDEX `webhook_events_type_idx`(`type`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `audit_logs` (
`id` CHAR(36) NOT NULL,
`user_id` CHAR(36) NULL,
`action` VARCHAR(100) NOT NULL,
`ip` VARCHAR(45) NULL,
`metadata` JSON NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
INDEX `audit_logs_user_id_created_at_idx`(`user_id`, `created_at`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- AddForeignKey
ALTER TABLE `sessions` ADD CONSTRAINT `sessions_user_id_fkey` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `password_resets` ADD CONSTRAINT `password_resets_user_id_fkey` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `businesses` ADD CONSTRAINT `businesses_user_id_fkey` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `payment_accounts` ADD CONSTRAINT `payment_accounts_business_id_fkey` FOREIGN KEY (`business_id`) REFERENCES `businesses`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `subscriptions` ADD CONSTRAINT `subscriptions_business_id_fkey` FOREIGN KEY (`business_id`) REFERENCES `businesses`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `transactions` ADD CONSTRAINT `transactions_business_id_fkey` FOREIGN KEY (`business_id`) REFERENCES `businesses`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `refunds` ADD CONSTRAINT `refunds_transaction_id_fkey` FOREIGN KEY (`transaction_id`) REFERENCES `transactions`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `merchant_debts` ADD CONSTRAINT `merchant_debts_business_id_fkey` FOREIGN KEY (`business_id`) REFERENCES `businesses`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `merchant_debts` ADD CONSTRAINT `merchant_debts_subscription_id_fkey` FOREIGN KEY (`subscription_id`) REFERENCES `subscriptions`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `merchant_debts` ADD CONSTRAINT `merchant_debts_refund_id_fkey` FOREIGN KEY (`refund_id`) REFERENCES `refunds`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `debt_allocations` ADD CONSTRAINT `debt_allocations_debt_id_fkey` FOREIGN KEY (`debt_id`) REFERENCES `merchant_debts`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `debt_allocations` ADD CONSTRAINT `debt_allocations_transaction_id_fkey` FOREIGN KEY (`transaction_id`) REFERENCES `transactions`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `payouts` ADD CONSTRAINT `payouts_payment_account_id_fkey` FOREIGN KEY (`payment_account_id`) REFERENCES `payment_accounts`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `audit_logs` ADD CONSTRAINT `audit_logs_user_id_fkey` FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;

View file

@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "mysql"

View file

@ -0,0 +1,292 @@
// TapTP — schéma MySQL.
// Règles : montants en centimes (Int), aucune donnée carte/IBAN complète,
// uniquement les identifiants fournis par Stripe.
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
// Développement uniquement (prisma migrate dev) ; inutile en production (prisma migrate deploy).
shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
}
model User {
id String @id @default(uuid()) @db.Char(36)
email String @unique @db.VarChar(191)
passwordHash String @map("password_hash") @db.VarChar(255)
firstName String @map("first_name") @db.VarChar(100)
lastName String @map("last_name") @db.VarChar(100)
phone String? @db.VarChar(30)
emailVerifiedAt DateTime? @map("email_verified_at")
termsAcceptedAt DateTime @map("terms_accepted_at")
termsVersion String @map("terms_version") @db.VarChar(20)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
business Business?
sessions Session[]
passwordResets PasswordReset[]
auditLogs AuditLog[]
@@map("users")
}
// Refresh tokens (hashés) : permet déconnexion et révocation.
model Session {
id String @id @default(uuid()) @db.Char(36)
userId String @map("user_id") @db.Char(36)
tokenHash String @unique @map("token_hash") @db.Char(64)
userAgent String? @map("user_agent") @db.VarChar(255)
ip String? @db.VarChar(45)
expiresAt DateTime @map("expires_at")
revokedAt DateTime? @map("revoked_at")
createdAt DateTime @default(now()) @map("created_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
@@map("sessions")
}
model PasswordReset {
id String @id @default(uuid()) @db.Char(36)
userId String @map("user_id") @db.Char(36)
tokenHash String @unique @map("token_hash") @db.Char(64)
expiresAt DateTime @map("expires_at")
usedAt DateTime? @map("used_at")
createdAt DateTime @default(now()) @map("created_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
@@map("password_resets")
}
model Business {
id String @id @default(uuid()) @db.Char(36)
userId String @unique @map("user_id") @db.Char(36)
legalName String @map("legal_name") @db.VarChar(191)
tradeName String? @map("trade_name") @db.VarChar(191)
siret String? @db.Char(14)
legalForm String @map("legal_form") @db.VarChar(30) // individual | company
mcc String? @db.Char(4)
description String? @db.VarChar(500) // activité, exigée par Stripe (business_profile.product_description)
addressLine1 String @map("address_line1") @db.VarChar(191)
addressLine2 String? @map("address_line2") @db.VarChar(191)
postalCode String @map("postal_code") @db.VarChar(10)
city String @db.VarChar(100)
country String @default("FR") @db.Char(2)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
paymentAccount PaymentAccount?
transactions Transaction[]
subscriptions Subscription[]
debts MerchantDebt[]
@@map("businesses")
}
model PaymentAccount {
id String @id @default(uuid()) @db.Char(36)
businessId String @unique @map("business_id") @db.Char(36)
provider String @default("stripe") @db.VarChar(20)
providerAccountId String @unique @map("provider_account_id") @db.VarChar(64)
chargesEnabled Boolean @default(false) @map("charges_enabled")
payoutsEnabled Boolean @default(false) @map("payouts_enabled")
// KYC, IBAN et acceptation des CGU Stripe sont collectés par Stripe (onboarding intégré).
requirements Json? // exigences restantes renvoyées par Stripe (sans données personnelles)
bankLast4 String? @map("bank_last4") @db.Char(4)
bankName String? @map("bank_name") @db.VarChar(100)
terminalLocationId String? @map("terminal_location_id") @db.VarChar(64)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
business Business @relation(fields: [businessId], references: [id], onDelete: Restrict)
payouts Payout[]
@@map("payment_accounts")
}
// Frais TapTP configurables (frais Stripe réels refacturés + fixe par transaction).
model FeePlan {
id String @id @default(uuid()) @db.Char(36)
code String @unique @db.VarChar(50) // default | subscriber
perTransactionCents Int @map("per_transaction_cents")
monthlyPriceCents Int @default(0) @map("monthly_price_cents") // abonnement (0 = sans abonnement)
// Frais Tap to Pay Stripe par autorisation (tarif public 0,10 €) s'ils ne figurent pas dans la balance transaction.
tapToPayFeeCents Int @default(10) @map("tap_to_pay_fee_cents")
passThroughStripeFees Boolean @default(true) @map("pass_through_stripe_fees")
active Boolean @default(true)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("fee_plans")
}
model Subscription {
id String @id @default(uuid()) @db.Char(36)
businessId String @map("business_id") @db.Char(36)
priceCents Int @map("price_cents")
status String @db.VarChar(20) // active | past_due | canceled
currentPeriodStart DateTime @map("current_period_start")
currentPeriodEnd DateTime @map("current_period_end")
cancelAtPeriodEnd Boolean @default(false) @map("cancel_at_period_end")
canceledAt DateTime? @map("canceled_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
business Business @relation(fields: [businessId], references: [id], onDelete: Restrict)
debts MerchantDebt[]
@@index([businessId, status])
@@map("subscriptions")
}
model Transaction {
id String @id @default(uuid()) @db.Char(36)
businessId String @map("business_id") @db.Char(36)
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(64)
providerPaymentIntentId String? @unique @map("provider_payment_intent_id") @db.VarChar(64)
providerChargeId String? @unique @map("provider_charge_id") @db.VarChar(64)
providerTransferId String? @unique @map("provider_transfer_id") @db.VarChar(64)
amountCents Int @map("amount_cents")
currency String @default("eur") @db.Char(3)
providerFeeCents Int? @map("provider_fee_cents") // coût Stripe réel
platformFeeCents Int? @map("platform_fee_cents") // part fixe TapTP
netCents Int? @map("net_cents") // reversé au pro
refundedCents Int @default(0) @map("refunded_cents")
feePlanCode String? @map("fee_plan_code") @db.VarChar(50) // plan appliqué (default | subscriber)
debtDeductedCents Int @default(0) @map("debt_deducted_cents") // sommes dues retenues sur cette vente
note String? @db.VarChar(255)
status String @db.VarChar(30) // pending | succeeded | failed | canceled | refunded | partially_refunded
failureReason String? @map("failure_reason") @db.VarChar(255)
cardBrand String? @map("card_brand") @db.VarChar(20)
cardLast4 String? @map("card_last4") @db.Char(4)
walletType String? @map("wallet_type") @db.VarChar(20)
receiptEmail String? @map("receipt_email") @db.VarChar(191)
succeededAt DateTime? @map("succeeded_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
business Business @relation(fields: [businessId], references: [id], onDelete: Restrict)
refunds Refund[]
debtAllocations DebtAllocation[]
@@index([businessId, createdAt])
@@index([businessId, status])
@@map("transactions")
}
model Refund {
id String @id @default(uuid()) @db.Char(36)
transactionId String @map("transaction_id") @db.Char(36)
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(64)
providerRefundId String? @unique @map("provider_refund_id") @db.VarChar(64)
amountCents Int @map("amount_cents")
reason String? @db.VarChar(50)
status String @db.VarChar(20) // pending | succeeded | failed | canceled
requestedBy String @map("requested_by") @db.Char(36)
// Part reprise au pro sur le reversement de la vente ; le reste devient une dette (frais à sa charge).
providerReversalId String? @unique @map("provider_reversal_id") @db.VarChar(64)
reversedCents Int @default(0) @map("reversed_cents")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
transaction Transaction @relation(fields: [transactionId], references: [id], onDelete: Restrict)
debt MerchantDebt?
@@index([transactionId])
@@map("refunds")
}
// Sommes dues par le pro à TapTP (abonnement, frais d'un remboursement non couverts),
// retenues automatiquement sur les reversements des ventes suivantes.
model MerchantDebt {
id String @id @default(uuid()) @db.Char(36)
businessId String @map("business_id") @db.Char(36)
kind String @db.VarChar(30) // subscription | refund_shortfall
amountCents Int @map("amount_cents")
settledCents Int @default(0) @map("settled_cents")
status String @default("open") @db.VarChar(20) // open | settled | canceled
subscriptionId String? @map("subscription_id") @db.Char(36)
periodStart DateTime? @map("period_start") // abonnement : une dette par période
refundId String? @unique @map("refund_id") @db.Char(36)
settledAt DateTime? @map("settled_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
business Business @relation(fields: [businessId], references: [id], onDelete: Restrict)
subscription Subscription? @relation(fields: [subscriptionId], references: [id], onDelete: Restrict)
refund Refund? @relation(fields: [refundId], references: [id], onDelete: Restrict)
allocations DebtAllocation[]
@@unique([subscriptionId, periodStart])
@@index([businessId, status, createdAt])
@@map("merchant_debts")
}
model DebtAllocation {
id String @id @default(uuid()) @db.Char(36)
debtId String @map("debt_id") @db.Char(36)
transactionId String @map("transaction_id") @db.Char(36)
amountCents Int @map("amount_cents")
createdAt DateTime @default(now()) @map("created_at")
debt MerchantDebt @relation(fields: [debtId], references: [id], onDelete: Restrict)
transaction Transaction @relation(fields: [transactionId], references: [id], onDelete: Restrict)
@@unique([debtId, transactionId])
@@index([transactionId])
@@map("debt_allocations")
}
model Payout {
id String @id @default(uuid()) @db.Char(36)
paymentAccountId String @map("payment_account_id") @db.Char(36)
providerPayoutId String @unique @map("provider_payout_id") @db.VarChar(64)
amountCents Int @map("amount_cents")
currency String @default("eur") @db.Char(3)
arrivalDate DateTime @map("arrival_date")
status String @db.VarChar(20) // pending | in_transit | paid | failed | canceled
bankLast4 String? @map("bank_last4") @db.Char(4)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
paymentAccount PaymentAccount @relation(fields: [paymentAccountId], references: [id], onDelete: Restrict)
@@index([paymentAccountId, arrivalDate])
@@map("payouts")
}
model WebhookEvent {
id String @id @default(uuid()) @db.Char(36)
providerEventId String @unique @map("provider_event_id") @db.VarChar(64)
type String @db.VarChar(100)
payload Json
processedAt DateTime? @map("processed_at")
error String? @db.Text
attempts Int @default(0)
createdAt DateTime @default(now()) @map("created_at")
@@index([type])
@@map("webhook_events")
}
model AuditLog {
id String @id @default(uuid()) @db.Char(36)
userId String? @map("user_id") @db.Char(36)
action String @db.VarChar(100)
ip String? @db.VarChar(45)
metadata Json?
createdAt DateTime @default(now()) @map("created_at")
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
@@index([userId, createdAt])
@@map("audit_logs")
}

25
backend/prisma/seed.ts Normal file
View file

@ -0,0 +1,25 @@
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
// Plans de frais par défaut (modifiables ensuite en base sans redéploiement).
async function main() {
await prisma.feePlan.upsert({
where: { code: 'default' },
create: { code: 'default', perTransactionCents: 200, passThroughStripeFees: true },
update: {},
});
await prisma.feePlan.upsert({
where: { code: 'subscriber' },
// Abonnement 10 €/mois : supprime les 2 € par transaction (frais Stripe toujours refacturés).
create: { code: 'subscriber', perTransactionCents: 0, monthlyPriceCents: 1000, passThroughStripeFees: true },
update: {},
});
}
main()
.catch((err) => {
console.error(err);
process.exit(1);
})
.finally(() => prisma.$disconnect());

47
backend/src/app.module.ts Normal file
View file

@ -0,0 +1,47 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_GUARD } from '@nestjs/core';
import { ScheduleModule } from '@nestjs/schedule';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { AuditModule } from './audit/audit.module';
import { AuthModule } from './auth/auth.module';
import { BusinessModule } from './business/business.module';
import { validateEnv } from './config/env';
import { HealthController } from './health.controller';
import { LedgerModule } from './ledger/ledger.module';
import { MailModule } from './mail/mail.module';
import { PaymentAccountModule } from './payment-account/payment-account.module';
import { PaymentsModule } from './payments/payments.module';
import { PayoutsModule } from './payouts/payouts.module';
import { PrismaModule } from './prisma/prisma.module';
import { RefundsModule } from './refunds/refunds.module';
import { StatsModule } from './stats/stats.module';
import { SubscriptionsModule } from './subscriptions/subscriptions.module';
import { StripeModule } from './stripe/stripe.module';
import { WebhooksModule } from './webhooks/webhooks.module';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true, validate: validateEnv }),
// Limite globale par IP ; les routes sensibles ont leurs propres limites plus strictes.
ThrottlerModule.forRoot([{ name: 'default', ttl: 60_000, limit: 120 }]),
ScheduleModule.forRoot(),
PrismaModule,
AuditModule,
MailModule,
AuthModule,
BusinessModule,
StripeModule,
PaymentAccountModule,
PaymentsModule,
LedgerModule,
RefundsModule,
SubscriptionsModule,
PayoutsModule,
StatsModule,
WebhooksModule,
],
controllers: [HealthController],
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],
})
export class AppModule {}

View file

@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { AuditService } from './audit.service';
@Global()
@Module({
providers: [AuditService],
exports: [AuditService],
})
export class AuditModule {}

View file

@ -0,0 +1,34 @@
import { Injectable, Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
export interface AuditEntry {
userId?: string | null;
action: string;
ip?: string | null;
/** Ne jamais y mettre de secret, mot de passe, token ou donnée bancaire. */
metadata?: Prisma.InputJsonValue;
}
@Injectable()
export class AuditService {
private readonly logger = new Logger(AuditService.name);
constructor(private readonly prisma: PrismaService) {}
async log(entry: AuditEntry): Promise<void> {
try {
await this.prisma.auditLog.create({
data: {
userId: entry.userId ?? null,
action: entry.action,
ip: entry.ip ?? null,
metadata: entry.metadata,
},
});
} catch (err) {
// L'audit ne doit jamais faire échouer l'opération métier.
this.logger.error(`Échec écriture audit "${entry.action}"`, err as Error);
}
}
}

View file

@ -0,0 +1,87 @@
import { Body, Controller, Get, HttpCode, HttpStatus, Patch, Post, Put, Req } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import type { Request } from 'express';
import { AuthUser, CurrentUser } from '../common/current-user.decorator';
import { Public } from '../common/public.decorator';
import { AuthService, ClientContext } from './auth.service';
import { ChangePasswordDto } from './dto/change-password.dto';
import { ForgotPasswordDto } from './dto/forgot-password.dto';
import { UpdateProfileDto } from './dto/update-profile.dto';
import { LoginDto } from './dto/login.dto';
import { RefreshDto } from './dto/refresh.dto';
import { RegisterDto } from './dto/register.dto';
import { ResetPasswordDto } from './dto/reset-password.dto';
const clientContext = (req: Request): ClientContext => ({
ip: req.ip,
userAgent: req.get('user-agent'),
});
// Limites strictes (par IP) sur les routes exposées au brute-force.
const STRICT = { default: { limit: 5, ttl: 60_000 } };
@Controller('auth')
export class AuthController {
constructor(private readonly auth: AuthService) {}
@Public()
@Throttle(STRICT)
@Post('register')
register(@Body() dto: RegisterDto, @Req() req: Request) {
return this.auth.register(dto, clientContext(req));
}
@Public()
@Throttle(STRICT)
@Post('login')
@HttpCode(HttpStatus.OK)
login(@Body() dto: LoginDto, @Req() req: Request) {
return this.auth.login(dto, clientContext(req));
}
@Public()
@Throttle({ default: { limit: 20, ttl: 60_000 } })
@Post('refresh')
@HttpCode(HttpStatus.OK)
refresh(@Body() dto: RefreshDto, @Req() req: Request) {
return this.auth.refresh(dto.refreshToken, clientContext(req));
}
@Post('logout')
@HttpCode(HttpStatus.NO_CONTENT)
logout(@Body() dto: RefreshDto, @CurrentUser() user: AuthUser) {
return this.auth.logout(dto.refreshToken, user.id);
}
@Public()
@Throttle({ default: { limit: 3, ttl: 60_000 } })
@Post('forgot-password')
@HttpCode(HttpStatus.NO_CONTENT)
forgotPassword(@Body() dto: ForgotPasswordDto, @Req() req: Request) {
return this.auth.forgotPassword(dto.email, clientContext(req));
}
@Public()
@Throttle(STRICT)
@Post('reset-password')
@HttpCode(HttpStatus.NO_CONTENT)
resetPassword(@Body() dto: ResetPasswordDto, @Req() req: Request) {
return this.auth.resetPassword(dto.token, dto.password, clientContext(req));
}
@Patch('me')
updateProfile(@CurrentUser() user: AuthUser, @Body() dto: UpdateProfileDto, @Req() req: Request) {
return this.auth.updateProfile(user.id, dto, req.ip);
}
@Put('password')
@Throttle(STRICT)
changePassword(@CurrentUser() user: AuthUser, @Body() dto: ChangePasswordDto, @Req() req: Request) {
return this.auth.changePassword(user.id, dto.currentPassword, dto.newPassword, clientContext(req));
}
@Get('me')
me(@CurrentUser() user: AuthUser) {
return this.auth.me(user.id);
}
}

View file

@ -0,0 +1,24 @@
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { APP_GUARD } from '@nestjs/core';
import { JwtModule } from '@nestjs/jwt';
import { Env } from '../config/env';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtAuthGuard } from './jwt-auth.guard';
import { WebAuthController } from './web-auth.controller';
@Module({
imports: [
JwtModule.registerAsync({
inject: [ConfigService],
useFactory: (config: ConfigService<Env, true>) => ({
secret: config.get('JWT_ACCESS_SECRET', { infer: true }),
}),
}),
],
controllers: [AuthController, WebAuthController],
providers: [AuthService, { provide: APP_GUARD, useClass: JwtAuthGuard }],
exports: [AuthService],
})
export class AuthModule {}

View file

@ -0,0 +1,256 @@
import { BadRequestException, ConflictException, Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { Prisma, User } from '@prisma/client';
import * as argon2 from 'argon2';
import { AuditService } from '../audit/audit.service';
import { generateToken, hashToken } from '../common/crypto';
import { Env } from '../config/env';
import { MailService } from '../mail/mail.service';
import { PrismaService } from '../prisma/prisma.service';
import { LoginDto } from './dto/login.dto';
import { RegisterDto } from './dto/register.dto';
import { UpdateProfileDto } from './dto/update-profile.dto';
export interface ClientContext {
ip?: string;
userAgent?: string;
}
export interface AuthTokens {
accessToken: string;
accessTokenExpiresIn: number;
refreshToken: string;
}
const PASSWORD_RESET_TTL_MS = 30 * 60 * 1000; // 30 min (annoncé dans l'app)
/** Version des CGU en vigueur : à incrémenter à chaque modification des conditions. */
export const TERMS_VERSION = '2026-10';
const ARGON2_OPTIONS = { type: argon2.argon2id } as const;
@Injectable()
export class AuthService {
/** Hash factice : temps de réponse constant quand l'email n'existe pas. */
private dummyHash?: Promise<string>;
constructor(
private readonly prisma: PrismaService,
private readonly jwt: JwtService,
private readonly config: ConfigService<Env, true>,
private readonly mail: MailService,
private readonly audit: AuditService,
) {}
async register(dto: RegisterDto, ctx: ClientContext): Promise<AuthTokens> {
const passwordHash = await argon2.hash(dto.password, ARGON2_OPTIONS);
let user: User;
try {
user = await this.prisma.user.create({
data: {
email: dto.email,
passwordHash,
firstName: dto.firstName,
lastName: dto.lastName,
phone: dto.phone,
// Preuve de l'acceptation des CGU et de la politique de confidentialité.
termsAcceptedAt: new Date(),
termsVersion: TERMS_VERSION,
},
});
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
throw new ConflictException('Un compte existe déjà avec cet email.');
}
throw err;
}
await this.audit.log({ userId: user.id, action: 'auth.register', ip: ctx.ip });
return this.issueTokens(user, ctx);
}
async login(dto: LoginDto, ctx: ClientContext): Promise<AuthTokens> {
const user = await this.prisma.user.findUnique({ where: { email: dto.email } });
const hash = user?.passwordHash ?? (await this.getDummyHash());
const valid = await argon2.verify(hash, dto.password);
if (!user || !valid) {
await this.audit.log({ userId: user?.id, action: 'auth.login_failed', ip: ctx.ip });
throw new UnauthorizedException('Email ou mot de passe incorrect.');
}
await this.audit.log({ userId: user.id, action: 'auth.login', ip: ctx.ip });
return this.issueTokens(user, ctx);
}
/** Rotation : l'ancien refresh token est révoqué, un nouveau est émis. */
async refresh(refreshToken: string, ctx: ClientContext): Promise<AuthTokens> {
const session = await this.prisma.session.findUnique({
where: { tokenHash: hashToken(refreshToken) },
include: { user: true },
});
if (!session || session.expiresAt < new Date()) throw new UnauthorizedException();
if (session.revokedAt) {
// Réutilisation d'un token déjà tourné : vol probable, on coupe toutes les sessions.
await this.revokeAllSessions(session.userId);
await this.audit.log({ userId: session.userId, action: 'auth.refresh_reuse_detected', ip: ctx.ip });
throw new UnauthorizedException();
}
// Mise à jour conditionnelle : deux refresh concurrents ne peuvent pas réussir tous les deux.
const { count } = await this.prisma.session.updateMany({
where: { id: session.id, revokedAt: null },
data: { revokedAt: new Date() },
});
if (count !== 1) throw new UnauthorizedException();
return this.issueTokens(session.user, ctx);
}
/** Déconnexion web : révocation par le seul jeton du cookie (pas d'access token requis). */
async revokeRefreshToken(refreshToken: string): Promise<void> {
await this.prisma.session.updateMany({
where: { tokenHash: hashToken(refreshToken), revokedAt: null },
data: { revokedAt: new Date() },
});
}
async logout(refreshToken: string, userId: string): Promise<void> {
await this.prisma.session.updateMany({
where: { tokenHash: hashToken(refreshToken), userId, revokedAt: null },
data: { revokedAt: new Date() },
});
await this.audit.log({ userId, action: 'auth.logout' });
}
/** Réponse identique que l'email existe ou non (pas d'énumération de comptes). */
async forgotPassword(email: string, ctx: ClientContext): Promise<void> {
const user = await this.prisma.user.findUnique({ where: { email } });
if (!user) return;
const token = generateToken();
await this.prisma.$transaction([
this.prisma.passwordReset.updateMany({
where: { userId: user.id, usedAt: null },
data: { usedAt: new Date() },
}),
this.prisma.passwordReset.create({
data: {
userId: user.id,
tokenHash: hashToken(token),
expiresAt: new Date(Date.now() + PASSWORD_RESET_TTL_MS),
},
}),
]);
await this.audit.log({ userId: user.id, action: 'auth.password_reset_requested', ip: ctx.ip });
await this.mail.sendPasswordReset(user.email, token);
}
async resetPassword(token: string, password: string, ctx: ClientContext): Promise<void> {
const reset = await this.prisma.passwordReset.findUnique({ where: { tokenHash: hashToken(token) } });
if (!reset || reset.usedAt || reset.expiresAt < new Date()) {
throw new BadRequestException('Lien invalide ou expiré.');
}
const passwordHash = await argon2.hash(password, ARGON2_OPTIONS);
await this.prisma.$transaction(async (tx) => {
const { count } = await tx.passwordReset.updateMany({
where: { id: reset.id, usedAt: null },
data: { usedAt: new Date() },
});
if (count !== 1) throw new BadRequestException('Lien invalide ou expiré.');
await tx.user.update({ where: { id: reset.userId }, data: { passwordHash } });
// Toutes les sessions existantes sont coupées après un changement de mot de passe.
await tx.session.updateMany({
where: { userId: reset.userId, revokedAt: null },
data: { revokedAt: new Date() },
});
});
await this.audit.log({ userId: reset.userId, action: 'auth.password_reset', ip: ctx.ip });
}
/** Re-vérifie le mot de passe avant une action sensible (ex. remboursement). */
async confirmPassword(userId: string, password: string, action: string, ip?: string): Promise<void> {
const user = await this.prisma.user.findUnique({ where: { id: userId } });
const valid = user ? await argon2.verify(user.passwordHash, password) : false;
if (!valid) {
await this.audit.log({ userId, action: `${action}.password_rejected`, ip });
throw new UnauthorizedException('Mot de passe incorrect.');
}
}
async updateProfile(userId: string, dto: UpdateProfileDto, ip?: string) {
await this.prisma.user.update({
where: { id: userId },
data: { firstName: dto.firstName, lastName: dto.lastName, phone: dto.phone },
});
await this.audit.log({ userId, action: 'auth.profile_updated', ip });
return this.me(userId);
}
/**
* Changement de mot de passe : l'ancien est exigé ; toutes les autres sessions sont coupées.
* Une nouvelle session est renvoyée pour cet appareil.
*/
async changePassword(userId: string, currentPassword: string, newPassword: string, ctx: ClientContext): Promise<AuthTokens> {
await this.confirmPassword(userId, currentPassword, 'auth.change_password', ctx.ip);
const passwordHash = await argon2.hash(newPassword, ARGON2_OPTIONS);
const user = await this.prisma.$transaction(async (tx) => {
const u = await tx.user.update({ where: { id: userId }, data: { passwordHash } });
await tx.session.updateMany({ where: { userId, revokedAt: null }, data: { revokedAt: new Date() } });
return u;
});
await this.audit.log({ userId, action: 'auth.password_changed', ip: ctx.ip });
return this.issueTokens(user, ctx);
}
async me(userId: string) {
const user = await this.prisma.user.findUnique({
where: { id: userId },
select: {
id: true,
email: true,
firstName: true,
lastName: true,
phone: true,
emailVerifiedAt: true,
createdAt: true,
business: { select: { id: true, legalName: true, tradeName: true } },
},
});
if (!user) throw new UnauthorizedException();
return user;
}
private async issueTokens(user: User, ctx: ClientContext): Promise<AuthTokens> {
const ttl = this.config.get('JWT_ACCESS_TTL_SECONDS', { infer: true });
const accessToken = await this.jwt.signAsync(
{ sub: user.id, email: user.email, typ: 'access' },
{ expiresIn: ttl, algorithm: 'HS256' },
);
const refreshToken = generateToken();
const days = this.config.get('REFRESH_TOKEN_TTL_DAYS', { infer: true });
await this.prisma.session.create({
data: {
userId: user.id,
tokenHash: hashToken(refreshToken),
ip: ctx.ip?.slice(0, 45),
userAgent: ctx.userAgent?.slice(0, 255),
expiresAt: new Date(Date.now() + days * 24 * 60 * 60 * 1000),
},
});
return { accessToken, accessTokenExpiresIn: ttl, refreshToken };
}
private async revokeAllSessions(userId: string): Promise<void> {
await this.prisma.session.updateMany({
where: { userId, revokedAt: null },
data: { revokedAt: new Date() },
});
}
private getDummyHash(): Promise<string> {
this.dummyHash ??= argon2.hash(generateToken(), ARGON2_OPTIONS);
return this.dummyHash;
}
}

View file

@ -0,0 +1,13 @@
import { IsString, Length, Matches, MaxLength } from 'class-validator';
import { PASSWORD_POLICY, PASSWORD_POLICY_MESSAGE } from './password-policy';
export class ChangePasswordDto {
@IsString()
@MaxLength(128)
currentPassword: string;
@IsString()
@Length(12, 128, { message: 'Le mot de passe doit contenir entre 12 et 128 caractères.' })
@Matches(PASSWORD_POLICY, { message: PASSWORD_POLICY_MESSAGE })
newPassword: string;
}

View file

@ -0,0 +1,9 @@
import { Transform } from 'class-transformer';
import { IsEmail, MaxLength } from 'class-validator';
export class ForgotPasswordDto {
@Transform(({ value }) => (typeof value === 'string' ? value.trim().toLowerCase() : value))
@IsEmail()
@MaxLength(191)
email: string;
}

View file

@ -0,0 +1,13 @@
import { Transform } from 'class-transformer';
import { IsEmail, IsString, MaxLength } from 'class-validator';
export class LoginDto {
@Transform(({ value }) => (typeof value === 'string' ? value.trim().toLowerCase() : value))
@IsEmail()
@MaxLength(191)
email: string;
@IsString()
@MaxLength(128)
password: string;
}

View file

@ -0,0 +1,4 @@
// Mêmes règles que l'app (maquette) : 12 caractères, une majuscule, une minuscule, un chiffre.
// Les lettres accentuées comptent (É majuscule, é minuscule).
export const PASSWORD_POLICY = /(?=.*\p{Ll})(?=.*\p{Lu})(?=.*\d)/u;
export const PASSWORD_POLICY_MESSAGE = 'Le mot de passe doit contenir une minuscule, une majuscule et un chiffre.';

View file

@ -0,0 +1,7 @@
import { IsString, Length } from 'class-validator';
export class RefreshDto {
@IsString()
@Length(20, 200)
refreshToken: string;
}

View file

@ -0,0 +1,33 @@
import { Transform } from 'class-transformer';
import { Equals, IsEmail, IsOptional, IsString, Length, Matches, MaxLength } from 'class-validator';
import { PASSWORD_POLICY, PASSWORD_POLICY_MESSAGE } from './password-policy';
export class RegisterDto {
@Transform(({ value }) => (typeof value === 'string' ? value.trim().toLowerCase() : value))
@IsEmail()
@MaxLength(191)
email: string;
@IsString()
@Length(12, 128, { message: 'Le mot de passe doit contenir entre 12 et 128 caractères.' })
@Matches(PASSWORD_POLICY, { message: PASSWORD_POLICY_MESSAGE })
password: string;
@Transform(({ value }) => (typeof value === 'string' ? value.trim() : value))
@IsString()
@Length(1, 100)
firstName: string;
@Transform(({ value }) => (typeof value === 'string' ? value.trim() : value))
@IsString()
@Length(1, 100)
lastName: string;
@IsOptional()
@Matches(/^\+?[0-9 ]{8,20}$/, { message: 'Numéro de téléphone invalide.' })
phone?: string;
/** Case « J'accepte les CGU et la politique de confidentialité » : doit être cochée. */
@Equals(true, { message: 'Acceptez les conditions pour créer votre compte.' })
acceptTerms: boolean;
}

View file

@ -0,0 +1,13 @@
import { IsString, Length, Matches } from 'class-validator';
import { PASSWORD_POLICY, PASSWORD_POLICY_MESSAGE } from './password-policy';
export class ResetPasswordDto {
@IsString()
@Length(20, 200)
token: string;
@IsString()
@Length(12, 128, { message: 'Le mot de passe doit contenir entre 12 et 128 caractères.' })
@Matches(PASSWORD_POLICY, { message: PASSWORD_POLICY_MESSAGE })
password: string;
}

View file

@ -0,0 +1,25 @@
import { Transform } from 'class-transformer';
import { IsOptional, IsString, Length, Matches, ValidateIf } from 'class-validator';
const trim = ({ value }: { value: unknown }) => (typeof value === 'string' ? value.trim() : value);
export class UpdateProfileDto {
@IsOptional()
@Transform(trim)
@IsString()
@Length(1, 100)
firstName?: string;
@IsOptional()
@Transform(trim)
@IsString()
@Length(1, 100)
lastName?: string;
/** null ou chaîne vide pour retirer le numéro. */
@IsOptional()
@Transform(({ value }) => (value === '' ? null : value))
@ValidateIf((o: UpdateProfileDto) => o.phone !== null)
@Matches(/^\+?[0-9 ]{8,20}$/, { message: 'Numéro de téléphone invalide.' })
phone?: string | null;
}

View file

@ -0,0 +1,37 @@
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { IS_PUBLIC_KEY } from '../common/public.decorator';
interface AccessPayload {
sub: string;
email: string;
typ: string;
}
/** Guard global : toute route est protégée sauf celles marquées @Public(). */
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(
private readonly jwt: JwtService,
private readonly reflector: Reflector,
) {}
async canActivate(ctx: ExecutionContext): Promise<boolean> {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [ctx.getHandler(), ctx.getClass()]);
if (isPublic) return true;
const req = ctx.switchToHttp().getRequest();
const [scheme, token] = (req.headers.authorization ?? '').split(' ');
if (scheme !== 'Bearer' || !token) throw new UnauthorizedException();
try {
const payload = await this.jwt.verifyAsync<AccessPayload>(token, { algorithms: ['HS256'] });
if (payload.typ !== 'access') throw new Error('wrong token type');
req.user = { id: payload.sub, email: payload.email };
return true;
} catch {
throw new UnauthorizedException();
}
}
}

View file

@ -0,0 +1,81 @@
import { Body, Controller, ForbiddenException, HttpCode, HttpStatus, Post, Req, Res, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Throttle } from '@nestjs/throttler';
import type { CookieOptions, Request, Response } from 'express';
import { Public } from '../common/public.decorator';
import { Env } from '../config/env';
import { AuthService, AuthTokens, ClientContext } from './auth.service';
import { LoginDto } from './dto/login.dto';
export const REFRESH_COOKIE = 'taptp_rt';
/** En-tête exigé sur ces routes : un formulaire d'un autre site ne peut pas l'envoyer (protection CSRF). */
const CLIENT_HEADER = 'x-taptp-client';
/**
* Authentification du tableau de bord web.
* Le refresh token vit dans un cookie HttpOnly, SameSite=Strict, limité à ce chemin :
* le JavaScript de la page ne peut jamais le lire (protection contre le vol de session par XSS).
* L'access token (15 min) reste en mémoire dans la page.
*/
@Controller('auth/web')
@Public()
export class WebAuthController {
constructor(
private readonly auth: AuthService,
private readonly config: ConfigService<Env, true>,
) {}
@Post('login')
@HttpCode(HttpStatus.OK)
@Throttle({ default: { limit: 5, ttl: 60_000 } })
async login(@Body() dto: LoginDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
this.assertClient(req);
return this.withCookie(res, await this.auth.login(dto, ctx(req)));
}
@Post('refresh')
@HttpCode(HttpStatus.OK)
@Throttle({ default: { limit: 30, ttl: 60_000 } })
async refresh(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
this.assertClient(req);
const token = req.cookies?.[REFRESH_COOKIE] as string | undefined;
if (!token) throw new UnauthorizedException();
try {
return this.withCookie(res, await this.auth.refresh(token, ctx(req)));
} catch (err) {
res.clearCookie(REFRESH_COOKIE, this.cookieOptions());
throw err;
}
}
@Post('logout')
@HttpCode(HttpStatus.NO_CONTENT)
async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
this.assertClient(req);
const token = req.cookies?.[REFRESH_COOKIE] as string | undefined;
if (token) await this.auth.revokeRefreshToken(token);
res.clearCookie(REFRESH_COOKIE, this.cookieOptions());
}
private withCookie(res: Response, tokens: AuthTokens) {
const days = this.config.get('REFRESH_TOKEN_TTL_DAYS', { infer: true });
res.cookie(REFRESH_COOKIE, tokens.refreshToken, { ...this.cookieOptions(), maxAge: days * 86_400_000 });
// Le refresh token n'est jamais renvoyé dans le corps de la réponse.
return { accessToken: tokens.accessToken, accessTokenExpiresIn: tokens.accessTokenExpiresIn };
}
private cookieOptions(): CookieOptions {
return {
httpOnly: true,
secure: this.config.get('NODE_ENV', { infer: true }) === 'production',
sameSite: 'strict',
path: '/api/v1/auth/web',
};
}
private assertClient(req: Request) {
if (req.get(CLIENT_HEADER) !== 'web') throw new ForbiddenException();
}
}
const ctx = (req: Request): ClientContext => ({ ip: req.ip, userAgent: req.get('user-agent') });

View file

@ -0,0 +1,22 @@
import { Body, Controller, Get, Put, Req } from '@nestjs/common';
import type { Request } from 'express';
import { AuthUser, CurrentUser } from '../common/current-user.decorator';
import { BusinessService } from './business.service';
import { UpsertBusinessDto } from './dto/upsert-business.dto';
// L'entreprise est toujours résolue depuis l'utilisateur authentifié : aucun id dans l'URL,
// donc impossible d'accéder à l'entreprise d'un autre professionnel.
@Controller('business')
export class BusinessController {
constructor(private readonly business: BusinessService) {}
@Get()
get(@CurrentUser() user: AuthUser) {
return this.business.get(user.id);
}
@Put()
upsert(@CurrentUser() user: AuthUser, @Body() dto: UpsertBusinessDto, @Req() req: Request) {
return this.business.upsert(user.id, dto, req.ip);
}
}

View file

@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { BusinessController } from './business.controller';
import { BusinessService } from './business.service';
@Module({
controllers: [BusinessController],
providers: [BusinessService],
exports: [BusinessService],
})
export class BusinessModule {}

View file

@ -0,0 +1,42 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { AuditService } from '../audit/audit.service';
import { PrismaService } from '../prisma/prisma.service';
import { UpsertBusinessDto } from './dto/upsert-business.dto';
@Injectable()
export class BusinessService {
constructor(
private readonly prisma: PrismaService,
private readonly audit: AuditService,
) {}
async get(userId: string) {
const business = await this.prisma.business.findUnique({ where: { userId } });
if (!business) throw new NotFoundException('Aucune entreprise renseignée.');
return business;
}
async upsert(userId: string, dto: UpsertBusinessDto, ip?: string) {
const data = {
legalName: dto.legalName,
tradeName: dto.tradeName ?? null,
legalForm: dto.legalForm,
siret: dto.siret ?? null,
mcc: dto.mcc ?? null,
description: dto.description,
addressLine1: dto.addressLine1,
addressLine2: dto.addressLine2 ?? null,
postalCode: dto.postalCode,
city: dto.city,
};
// TODO (étape KYC) : une fois le compte Stripe créé, répercuter ces changements
// sur le compte connecté et bloquer les champs que Stripe a déjà vérifiés.
const business = await this.prisma.business.upsert({
where: { userId },
create: { userId, ...data },
update: data,
});
await this.audit.log({ userId, action: 'business.upsert', ip, metadata: { businessId: business.id } });
return business;
}
}

View file

@ -0,0 +1,17 @@
import { isValidSiret } from './is-siret.validator';
describe('isValidSiret', () => {
it('accepte un SIRET valide', () => {
expect(isValidSiret('73282932000074')).toBe(true);
});
it('refuse une clé de Luhn invalide', () => {
expect(isValidSiret('73282932000075')).toBe(false);
});
it('refuse un format incorrect', () => {
expect(isValidSiret('1234')).toBe(false);
expect(isValidSiret('7328293200007A')).toBe(false);
expect(isValidSiret(undefined)).toBe(false);
});
});

View file

@ -0,0 +1,31 @@
import { registerDecorator, ValidationOptions } from 'class-validator';
/** SIRET : 14 chiffres + clé de Luhn (exception : établissements de La Poste, SIREN 356000000). */
export function isValidSiret(value: unknown): boolean {
if (typeof value !== 'string' || !/^\d{14}$/.test(value)) return false;
if (value.startsWith('356000000')) {
const sum = [...value].reduce((acc, d) => acc + Number(d), 0);
return sum % 5 === 0;
}
let sum = 0;
for (let i = 0; i < 14; i++) {
let digit = Number(value[13 - i]);
if (i % 2 === 1) {
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
}
return sum % 10 === 0;
}
export function IsSiret(options?: ValidationOptions) {
return (object: object, propertyName: string) =>
registerDecorator({
name: 'isSiret',
target: object.constructor,
propertyName,
options: { message: 'SIRET invalide.', ...options },
validator: { validate: isValidSiret },
});
}

View file

@ -0,0 +1,59 @@
import { Transform } from 'class-transformer';
import { IsIn, IsOptional, IsString, Length, Matches, ValidateIf } from 'class-validator';
import { IsSiret } from './is-siret.validator';
const trim = ({ value }: { value: unknown }) => (typeof value === 'string' ? value.trim() : value);
export const LEGAL_FORMS = ['individual', 'company'] as const;
export type LegalForm = (typeof LEGAL_FORMS)[number];
export class UpsertBusinessDto {
@Transform(trim)
@IsString()
@Length(1, 191)
legalName: string;
@IsOptional()
@Transform(trim)
@IsString()
@Length(1, 191)
tradeName?: string;
@IsIn(LEGAL_FORMS)
legalForm: LegalForm;
// Obligatoire pour une société ; facultatif pour un particulier/micro en cours d'immatriculation.
@ValidateIf((o: UpsertBusinessDto) => o.legalForm === 'company' || o.siret !== undefined)
@Transform(({ value }) => (typeof value === 'string' ? value.replace(/\s/g, '') : value))
@IsSiret()
siret?: string;
@IsOptional()
@Matches(/^\d{4}$/, { message: 'Code MCC invalide (4 chiffres).' })
mcc?: string;
/** Description de l'activité (ce que vend le pro), demandée par Stripe. */
@Transform(trim)
@IsString()
@Length(10, 500)
description: string;
@Transform(trim)
@IsString()
@Length(1, 191)
addressLine1: string;
@IsOptional()
@Transform(trim)
@IsString()
@Length(1, 191)
addressLine2?: string;
@Matches(/^\d{5}$/, { message: 'Code postal invalide.' })
postalCode: string;
@Transform(trim)
@IsString()
@Length(1, 100)
city: string;
}

View file

@ -0,0 +1,11 @@
import { createHash, randomBytes } from 'crypto';
/** Token opaque à transmettre au client (jamais stocké en clair). */
export function generateToken(bytes = 32): string {
return randomBytes(bytes).toString('base64url');
}
/** Empreinte stockée en base. SHA-256 suffit : le token est déjà aléatoire et long. */
export function hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
}

View file

@ -0,0 +1,10 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
export interface AuthUser {
id: string;
email: string;
}
export const CurrentUser = createParamDecorator((_: unknown, ctx: ExecutionContext): AuthUser => {
return ctx.switchToHttp().getRequest().user;
});

View file

@ -0,0 +1,5 @@
import { SetMetadata } from '@nestjs/common';
export const IS_PUBLIC_KEY = 'isPublic';
/** Route accessible sans authentification (toutes les autres sont protégées par défaut). */
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);

33
backend/src/config/env.ts Normal file
View file

@ -0,0 +1,33 @@
import { z } from 'zod';
const envSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().positive().default(3000),
DATABASE_URL: z.string().startsWith('mysql://'),
JWT_ACCESS_SECRET: z.string().min(32, 'JWT_ACCESS_SECRET doit faire au moins 32 caractères'),
JWT_ACCESS_TTL_SECONDS: z.coerce.number().int().positive().default(900),
REFRESH_TOKEN_TTL_DAYS: z.coerce.number().int().positive().default(30),
PASSWORD_RESET_URL: z.string().url(),
CORS_ORIGINS: z.string().default(''),
STRIPE_SECRET_KEY: z.string().regex(/^(sk|rk)_(test|live)_/, 'Clé Stripe secrète invalide'),
STRIPE_WEBHOOK_SECRET: z.string().startsWith('whsec_').optional().or(z.literal('')),
// Bornes d'un encaissement (centimes). Le minimum doit couvrir les frais.
PAYMENT_MIN_CENTS: z.coerce.number().int().positive().default(100),
PAYMENT_MAX_CENTS: z.coerce.number().int().positive().default(300_000),
STRIPE_CONNECT_WEBHOOK_SECRET: z.string().startsWith('whsec_').optional().or(z.literal('')),
}).refine((env) => env.NODE_ENV === 'production' || !env.STRIPE_SECRET_KEY.includes('_live_'), {
message: 'Clé Stripe LIVE interdite hors production',
path: ['STRIPE_SECRET_KEY'],
});
export type Env = z.infer<typeof envSchema>;
/** Validation au démarrage : l'API refuse de démarrer avec une config invalide. */
export function validateEnv(raw: Record<string, unknown>): Env {
const parsed = envSchema.safeParse(raw);
if (!parsed.success) {
const issues = parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('\n');
throw new Error(`Configuration invalide :\n${issues}`);
}
return parsed.data;
}

View file

@ -0,0 +1,17 @@
import { Controller, Get } from '@nestjs/common';
import { SkipThrottle } from '@nestjs/throttler';
import { Public } from './common/public.decorator';
import { PrismaService } from './prisma/prisma.service';
@Controller('health')
export class HealthController {
constructor(private readonly prisma: PrismaService) {}
@Public()
@SkipThrottle()
@Get()
async check() {
await this.prisma.$queryRaw`SELECT 1`;
return { status: 'ok' };
}
}

View file

@ -0,0 +1,30 @@
import { allocate } from './allocate';
describe('allocate', () => {
const debts = [
{ id: 'abonnement', amountCents: 1000, settledCents: 400 }, // reste 6 €
{ id: 'remboursement', amountCents: 290, settledCents: 0 },
];
it('solde la dette la plus ancienne en premier', () => {
expect(allocate(debts, 500)).toEqual([{ debtId: 'abonnement', amountCents: 500 }]);
});
it('enchaîne sur la dette suivante', () => {
expect(allocate(debts, 700)).toEqual([
{ debtId: 'abonnement', amountCents: 600 },
{ debtId: 'remboursement', amountCents: 100 },
]);
});
it('ne prend jamais plus que ce qui est dû', () => {
expect(allocate(debts, 10_000)).toEqual([
{ debtId: 'abonnement', amountCents: 600 },
{ debtId: 'remboursement', amountCents: 290 },
]);
});
it('rien à retenir sans montant disponible', () => {
expect(allocate(debts, 0)).toEqual([]);
});
});

View file

@ -0,0 +1,26 @@
export interface OpenDebt {
id: string;
amountCents: number;
settledCents: number;
}
export interface Allocation {
debtId: string;
amountCents: number;
}
/** Répartit au plus `availableCents` sur les dettes, la plus ancienne d'abord (ordre fourni). */
export function allocate(debts: OpenDebt[], availableCents: number): Allocation[] {
if (!Number.isInteger(availableCents) || availableCents < 0) throw new Error('Montant disponible invalide.');
const result: Allocation[] = [];
let remaining = availableCents;
for (const debt of debts) {
if (remaining === 0) break;
const due = debt.amountCents - debt.settledCents;
if (due <= 0) continue;
const take = Math.min(due, remaining);
result.push({ debtId: debt.id, amountCents: take });
remaining -= take;
}
return result;
}

View file

@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { LedgerService } from './ledger.service';
@Global()
@Module({
providers: [LedgerService],
exports: [LedgerService],
})
export class LedgerModule {}

View file

@ -0,0 +1,110 @@
import { Injectable, Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { allocate, OpenDebt } from './allocate';
type Tx = Prisma.TransactionClient;
/**
* Registre des sommes dues par le pro (abonnement, frais d'un remboursement),
* retenues sur les reversements de ses ventes suivantes.
*/
@Injectable()
export class LedgerService {
private readonly logger = new Logger(LedgerService.name);
constructor(private readonly prisma: PrismaService) {}
async addDebt(data: {
businessId: string;
kind: 'subscription' | 'refund_shortfall';
amountCents: number;
subscriptionId?: string;
periodStart?: Date;
refundId?: string;
}, client: Tx | PrismaService = this.prisma) {
if (!Number.isInteger(data.amountCents) || data.amountCents <= 0) throw new Error('Montant de dette invalide.');
return client.merchantDebt.create({ data });
}
/** Total restant dû (affiché au pro). */
async outstanding(businessId: string): Promise<number> {
const debts = await this.prisma.merchantDebt.findMany({
where: { businessId, status: 'open' },
select: { amountCents: true, settledCents: true },
});
return debts.reduce((sum, d) => sum + d.amountCents - d.settledCents, 0);
}
/**
* Retient sur une vente au plus `maxCents` de dettes ouvertes. Idempotent : si la vente a déjà
* fait l'objet d'une retenue (webhook rejoué), renvoie la même retenue sans en refaire une.
* Les dettes sont verrouillées (FOR UPDATE) : deux ventes simultanées ne peuvent pas solder deux fois la même dette.
*/
async allocateForTransaction(transactionId: string, businessId: string, maxCents: number): Promise<number> {
return this.prisma.$transaction(async (tx) => {
// Verrou sur la vente : sérialise les traitements concurrents d'un même webhook.
await tx.$queryRaw`SELECT id FROM transactions WHERE id = ${transactionId} FOR UPDATE`;
const previous = await tx.debtAllocation.aggregate({
where: { transactionId },
_sum: { amountCents: true },
_count: true,
});
if (previous._count > 0) return previous._sum.amountCents ?? 0;
if (maxCents <= 0) return 0;
const debts = await tx.$queryRaw<OpenDebt[]>`
SELECT id, amount_cents AS amountCents, settled_cents AS settledCents
FROM merchant_debts
WHERE business_id = ${businessId} AND status = 'open'
ORDER BY created_at ASC, id ASC
FOR UPDATE`;
const allocations = allocate(
debts.map((d) => ({ id: d.id, amountCents: Number(d.amountCents), settledCents: Number(d.settledCents) })),
maxCents,
);
let total = 0;
for (const a of allocations) {
await tx.debtAllocation.create({ data: { debtId: a.debtId, transactionId, amountCents: a.amountCents } });
const debt = await tx.merchantDebt.update({
where: { id: a.debtId },
data: { settledCents: { increment: a.amountCents } },
});
if (debt.settledCents >= debt.amountCents) {
await tx.merchantDebt.update({ where: { id: debt.id }, data: { status: 'settled', settledAt: new Date() } });
await this.reactivateSubscriptionIfPaid(tx, debt.subscriptionId);
}
total += a.amountCents;
}
await tx.transaction.update({ where: { id: transactionId }, data: { debtDeductedCents: total } });
return total;
});
}
/** Annule la part non encore payée d'une dette (ex. remboursement finalement échoué). */
async cancelUnsettled(debtId: string): Promise<void> {
const debt = await this.prisma.merchantDebt.findUnique({ where: { id: debtId } });
if (!debt || debt.status !== 'open') return;
if (debt.settledCents > 0) {
// Déjà partiellement retenue : on la clôt au montant payé ; le trop-perçu est loggé pour régularisation.
this.logger.warn(`Dette ${debt.id} annulée après ${debt.settledCents} c déjà retenus : régularisation manuelle.`);
}
await this.prisma.merchantDebt.update({
where: { id: debt.id },
data: { status: 'canceled', amountCents: debt.settledCents },
});
}
/** Abonnement impayé redevenu à jour : il est réactivé s'il n'est pas expiré. */
private async reactivateSubscriptionIfPaid(tx: Tx, subscriptionId: string | null): Promise<void> {
if (!subscriptionId) return;
const stillOpen = await tx.merchantDebt.count({ where: { subscriptionId, status: 'open' } });
if (stillOpen > 0) return;
await tx.subscription.updateMany({
where: { id: subscriptionId, status: 'past_due', currentPeriodEnd: { gt: new Date() } },
data: { status: 'active' },
});
}
}

View file

@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { MailService } from './mail.service';
@Global()
@Module({
providers: [MailService],
exports: [MailService],
})
export class MailModule {}

View file

@ -0,0 +1,24 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Env } from '../config/env';
/**
* Envoi d'emails transactionnels.
* TODO: brancher un fournisseur (Brevo, Postmark…) avant la production.
* En développement, le lien est affiché dans les logs ; jamais en production.
*/
@Injectable()
export class MailService {
private readonly logger = new Logger(MailService.name);
constructor(private readonly config: ConfigService<Env, true>) {}
async sendPasswordReset(to: string, token: string): Promise<void> {
const url = `${this.config.get('PASSWORD_RESET_URL', { infer: true })}?token=${encodeURIComponent(token)}`;
if (this.config.get('NODE_ENV', { infer: true }) === 'development') {
this.logger.debug(`[DEV] Lien de réinitialisation pour ${to} : ${url}`);
return;
}
this.logger.warn('Aucun fournisseur email configuré : email de réinitialisation non envoyé.');
}
}

44
backend/src/main.ts Normal file
View file

@ -0,0 +1,44 @@
import { Logger, ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import cookieParser from 'cookie-parser';
import helmet from 'helmet';
import { AppModule } from './app.module';
import { Env } from './config/env';
async function bootstrap() {
// rawBody : nécessaire pour vérifier la signature des webhooks Stripe.
const app = await NestFactory.create<NestExpressApplication>(AppModule, { rawBody: true });
const config = app.get(ConfigService<Env, true>);
app.use(helmet());
app.use(cookieParser());
// Derrière un reverse proxy (Nginx) : req.ip doit refléter l'IP client réelle pour le rate limiting.
app.set('trust proxy', 1);
app.useBodyParser('json', { limit: '100kb' });
const origins = config
.get('CORS_ORIGINS', { infer: true })
.split(',')
.map((o) => o.trim())
.filter(Boolean);
// Credentials : le tableau de bord web envoie le cookie de session (origines en liste blanche uniquement).
app.enableCors({ origin: origins, credentials: true, allowedHeaders: ['Content-Type', 'Authorization', 'X-TapTP-Client'] });
app.setGlobalPrefix('api/v1');
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, // supprime les champs non déclarés
forbidNonWhitelisted: true, // et rejette la requête s'il y en a
transform: true,
}),
);
app.enableShutdownHooks();
const port = config.get('PORT', { infer: true });
await app.listen(port);
Logger.log(`TapTP API démarrée sur le port ${port}`, 'Bootstrap');
}
void bootstrap();

View file

@ -0,0 +1,86 @@
import type Stripe from 'stripe';
import { computeKycStatus, extractAccountState, StoredRequirements } from './kyc-status';
const req = (over: Partial<StoredRequirements> = {}): StoredRequirements => ({
currentlyDue: [],
pastDue: [],
eventuallyDue: [],
pendingVerification: [],
errors: [],
...over,
});
describe('computeKycStatus', () => {
it('sans compte : not_started', () => {
expect(computeKycStatus(null)).toBe('not_started');
});
it('informations manquantes : action_required', () => {
expect(
computeKycStatus({ chargesEnabled: false, payoutsEnabled: false, requirements: req({ currentlyDue: ['identity.individual.date_of_birth.day'] }) }),
).toBe('action_required');
});
it('en attente de Stripe : pending_verification', () => {
expect(
computeKycStatus({ chargesEnabled: false, payoutsEnabled: false, requirements: req({ pendingVerification: ['identity.individual.verification'] }) }),
).toBe('pending_verification');
});
it('paiements et versements autorisés : active', () => {
expect(computeKycStatus({ chargesEnabled: true, payoutsEnabled: true, requirements: req() })).toBe('active');
});
it('actif mais nouvelle exigence en retard : action_required', () => {
expect(computeKycStatus({ chargesEnabled: true, payoutsEnabled: true, requirements: req({ pastDue: ['external_account'] }) })).toBe(
'action_required',
);
});
it('refusé : rejected', () => {
expect(computeKycStatus({ chargesEnabled: false, payoutsEnabled: false, rejected: true, requirements: req() })).toBe('rejected');
});
});
describe('extractAccountState', () => {
it('classe les exigences et lit les capacités (forme réelle renvoyée par Stripe en test)', () => {
const account = {
configuration: {
merchant: {
capabilities: {
card_payments: { status: 'restricted', status_details: [] },
stripe_balance: { payouts: { status: 'restricted', status_details: [] } },
},
},
},
requirements: {
entries: [
{
awaiting_action_from: 'user',
description: 'configuration.merchant.support.phone',
errors: [],
impact: {},
minimum_deadline: { status: 'past_due' },
requested_reasons: [],
},
{
awaiting_action_from: 'stripe',
description: 'identity.individual.verification.document',
errors: [{ code: 'verification_document_expired', description: 'Document expiré' }],
impact: {},
minimum_deadline: { status: 'currently_due' },
requested_reasons: [],
},
],
},
} as unknown as Stripe.V2.Core.Account;
const state = extractAccountState(account);
expect(state.chargesEnabled).toBe(false);
expect(state.payoutsEnabled).toBe(false);
expect(state.requirements.pastDue).toEqual(['configuration.merchant.support.phone']);
expect(state.requirements.pendingVerification).toEqual(['identity.individual.verification.document']);
expect(state.requirements.errors).toHaveLength(1);
expect(computeKycStatus(state)).toBe('action_required');
});
});

View file

@ -0,0 +1,73 @@
import type Stripe from 'stripe';
type V2Account = Stripe.V2.Core.Account;
export type KycStatus =
| 'not_started' // aucun compte Stripe
| 'action_required' // le pro doit fournir des informations dans l'onboarding
| 'pending_verification' // tout est fourni, Stripe vérifie
| 'active' // paiements et versements autorisés
| 'rejected';
/** Exigences restantes, conservées en base et renvoyées à l'app (aucune donnée personnelle). */
export interface StoredRequirements {
currentlyDue: string[];
pastDue: string[];
eventuallyDue: string[];
pendingVerification: string[]; // en attente d'une action de Stripe
errors: { requirement: string; code: string; description: string }[];
}
export interface AccountState {
chargesEnabled: boolean;
payoutsEnabled: boolean;
rejected: boolean;
requirements: StoredRequirements;
}
/** Extrait l'état utile d'un compte Stripe v2 (récupéré avec include configuration.merchant + requirements). */
export function extractAccountState(account: V2Account): AccountState {
const caps = account.configuration?.merchant?.capabilities;
const cardStatus = caps?.card_payments?.status;
const payoutStatus = caps?.stripe_balance?.payouts?.status;
const requirements: StoredRequirements = {
currentlyDue: [],
pastDue: [],
eventuallyDue: [],
pendingVerification: [],
errors: [],
};
for (const entry of account.requirements?.entries ?? []) {
if (entry.awaiting_action_from === 'stripe') {
requirements.pendingVerification.push(entry.description);
} else if (entry.minimum_deadline.status === 'past_due') {
requirements.pastDue.push(entry.description);
} else if (entry.minimum_deadline.status === 'currently_due') {
requirements.currentlyDue.push(entry.description);
} else {
requirements.eventuallyDue.push(entry.description);
}
for (const err of entry.errors) {
requirements.errors.push({ requirement: entry.description, code: err.code, description: err.description });
}
}
return {
chargesEnabled: cardStatus === 'active',
payoutsEnabled: payoutStatus === 'active',
rejected: cardStatus === 'rejected',
requirements,
};
}
export function computeKycStatus(
account: { chargesEnabled: boolean; payoutsEnabled: boolean; rejected?: boolean; requirements: StoredRequirements | null } | null,
): KycStatus {
if (!account) return 'not_started';
if (account.rejected) return 'rejected';
const req = account.requirements;
if (req && (req.currentlyDue.length > 0 || req.pastDue.length > 0)) return 'action_required';
if (account.chargesEnabled && account.payoutsEnabled) return 'active';
return 'pending_verification';
}

View file

@ -0,0 +1,31 @@
import { Controller, Get, HttpCode, HttpStatus, Post, Req } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import type { Request } from 'express';
import { AuthUser, CurrentUser } from '../common/current-user.decorator';
import { PaymentAccountService, RequestContext } from './payment-account.service';
const ctxOf = (req: Request): RequestContext => ({ ip: req.ip, userAgent: req.get('user-agent') });
/** Compte de paiement du pro connecté. Le KYC lui-même se fait dans l'onboarding Stripe intégré. */
@Controller('payment-account')
@Throttle({ default: { limit: 20, ttl: 60_000 } }) // chaque appel interroge Stripe
export class PaymentAccountController {
constructor(private readonly accounts: PaymentAccountService) {}
@Get()
status(@CurrentUser() user: AuthUser) {
return this.accounts.getStatus(user.id);
}
@Post()
@HttpCode(HttpStatus.OK)
create(@CurrentUser() user: AuthUser, @Req() req: Request) {
return this.accounts.createAccount(user.id, ctxOf(req));
}
@Post('onboarding-session')
@HttpCode(HttpStatus.OK)
onboardingSession(@CurrentUser() user: AuthUser, @Req() req: Request) {
return this.accounts.createOnboardingSession(user.id, ctxOf(req));
}
}

View file

@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { PaymentAccountController } from './payment-account.controller';
import { PaymentAccountService } from './payment-account.service';
@Module({
controllers: [PaymentAccountController],
providers: [PaymentAccountService],
exports: [PaymentAccountService],
})
export class PaymentAccountModule {}

View file

@ -0,0 +1,211 @@
import { Inject, Injectable, Logger, NotFoundException, UnprocessableEntityException } from '@nestjs/common';
import { Business, PaymentAccount, Prisma } from '@prisma/client';
import Stripe from 'stripe';
import { AuditService } from '../audit/audit.service';
import { PrismaService } from '../prisma/prisma.service';
import { STRIPE } from '../stripe/stripe.module';
import { computeKycStatus, extractAccountState, KycStatus, StoredRequirements } from './kyc-status';
export interface RequestContext {
ip?: string;
userAgent?: string;
}
export interface PaymentAccountView {
status: KycStatus;
chargesEnabled: boolean;
payoutsEnabled: boolean;
bankAccount: { last4: string; bankName: string | null } | null;
requirements: StoredRequirements | null;
}
export interface OnboardingSession {
/** À passer aux composants Stripe Connect intégrés de l'app. Courte durée, usage unique. */
clientSecret: string;
expiresAt: number;
}
type AccountInclude = NonNullable<NonNullable<Parameters<Stripe['v2']['core']['accounts']['retrieve']>[1]>['include']>;
const ACCOUNT_INCLUDE: AccountInclude = ['configuration.merchant', 'requirements'];
/**
* Comptes connectés Stripe (Accounts v2).
* Contraintes Stripe pour une plateforme française (vérifiées en mode test) :
* - Stripe porte les pertes et collecte le KYC → onboarding via les composants Stripe intégrés ;
* - TapTP paie les frais Stripe (fees_collector = application) ;
* - les informations d'identité ne passent que par des « account tokens ».
* Conséquence : aucune donnée d'identité, aucun document ni IBAN ne transite par TapTP.
*/
@Injectable()
export class PaymentAccountService {
private readonly logger = new Logger(PaymentAccountService.name);
constructor(
private readonly prisma: PrismaService,
private readonly audit: AuditService,
@Inject(STRIPE) private readonly stripe: Stripe,
) {}
/** Statut à jour : relit le compte chez Stripe (source de vérité) puis synchronise la base. */
async getStatus(userId: string): Promise<PaymentAccountView> {
// Entreprise pas encore renseignée : le compte est simplement « à activer » (pas une erreur).
const business = await this.prisma.business.findUnique({ where: { userId } });
if (!business) return this.toView(null);
const account = await this.prisma.paymentAccount.findUnique({ where: { businessId: business.id } });
if (!account) return this.toView(null);
return this.toView(await this.refreshByProviderId(account.providerAccountId));
}
/** Crée le compte connecté (idempotent : renvoie l'existant s'il y en a un). */
async createAccount(userId: string, ctx: RequestContext): Promise<PaymentAccountView> {
const business = await this.getBusiness(userId);
const existing = await this.prisma.paymentAccount.findUnique({ where: { businessId: business.id } });
if (existing) return this.toView(existing);
if (!business.description) {
throw new UnprocessableEntityException('Décrivez votre activité avant de créer votre compte de paiement.');
}
const user = await this.prisma.user.findUniqueOrThrow({ where: { id: userId } });
const idempotencyBase = `taptp-account-${business.id}`;
// Seules des informations non sensibles sont mises dans le jeton ; le reste est saisi dans l'onboarding Stripe.
const token = await this.stripe.v2.core.accountTokens.create(
{
contact_email: user.email,
display_name: business.tradeName ?? business.legalName,
identity: { entity_type: business.legalForm === 'company' ? 'company' : 'individual' },
},
{ idempotencyKey: `${idempotencyBase}-token` },
);
const stripeAccount = await this.stripe.v2.core.accounts.create(
{
account_token: token.id,
dashboard: 'none',
identity: { country: 'fr' },
configuration: {
merchant: {
mcc: business.mcc ?? undefined,
capabilities: { card_payments: { requested: true } },
},
// Nécessaire pour reverser au pro (transfert) le net de chaque vente.
recipient: { capabilities: { stripe_balance: { stripe_transfers: { requested: true } } } },
},
defaults: {
currency: 'eur',
locales: ['fr-FR'],
profile: { product_description: business.description },
responsibilities: { fees_collector: 'application', losses_collector: 'stripe' },
},
include: ACCOUNT_INCLUDE,
metadata: { taptp_business_id: business.id },
},
// Même clé pour un même pro : un double appel ne crée pas deux comptes chez Stripe.
{ idempotencyKey: idempotencyBase },
);
try {
await this.prisma.paymentAccount.create({
data: { businessId: business.id, providerAccountId: stripeAccount.id },
});
} catch (err) {
// Création concurrente : l'autre requête a déjà enregistré le compte.
if (!(err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002')) throw err;
}
await this.audit.log({
userId,
action: 'payment_account.created',
ip: ctx.ip,
metadata: { providerAccountId: stripeAccount.id },
});
return this.toView(await this.syncFromStripe(stripeAccount));
}
/** Session pour l'onboarding Stripe intégré dans l'app (identité, documents, IBAN, CGU Stripe). */
async createOnboardingSession(userId: string, ctx: RequestContext): Promise<OnboardingSession> {
const account = await this.getAccountOrThrow(userId);
const session = await this.stripe.accountSessions.create({
account: account.providerAccountId,
components: {
account_onboarding: { enabled: true, features: { external_account_collection: true } },
account_management: { enabled: true, features: { external_account_collection: true } },
// Écran « Compte bancaire » de l'app : changement d'IBAN (versements automatiques gérés par Stripe).
payouts: {
enabled: true,
features: { external_account_collection: true, edit_payout_schedule: false, instant_payouts: false, standard_payouts: false },
},
notification_banner: { enabled: true, features: { external_account_collection: true } },
},
});
await this.audit.log({ userId, action: 'payment_account.onboarding_session', ip: ctx.ip });
return { clientSecret: session.client_secret, expiresAt: session.expires_at };
}
// ---------------------------------------------------------------------------
// Synchronisation (appelée aussi par les webhooks)
// ---------------------------------------------------------------------------
/** Relit le compte chez Stripe : évite d'appliquer un événement arrivé dans le désordre. */
async refreshByProviderId(providerAccountId: string): Promise<PaymentAccount | null> {
const stripeAccount = await this.stripe.v2.core.accounts.retrieve(providerAccountId, { include: ACCOUNT_INCLUDE });
return this.syncFromStripe(stripeAccount);
}
private async syncFromStripe(stripeAccount: Stripe.V2.Core.Account): Promise<PaymentAccount | null> {
const state = extractAccountState(stripeAccount);
const bank = await this.getDefaultBankAccount(stripeAccount.id);
const { count } = await this.prisma.paymentAccount.updateMany({
where: { providerAccountId: stripeAccount.id },
data: {
chargesEnabled: state.chargesEnabled,
payoutsEnabled: state.payoutsEnabled,
requirements: { ...state.requirements, rejected: state.rejected } as unknown as Prisma.InputJsonValue,
bankLast4: bank?.last4 ?? null,
bankName: bank?.bank_name ?? null,
},
});
if (count === 0) {
this.logger.warn(`Compte Stripe ${stripeAccount.id} inconnu de TapTP : synchronisation ignorée.`);
return null;
}
return this.prisma.paymentAccount.findUnique({ where: { providerAccountId: stripeAccount.id } });
}
/** Seuls les 4 derniers chiffres et le nom de la banque sont conservés. */
private async getDefaultBankAccount(providerAccountId: string): Promise<Stripe.BankAccount | null> {
const list = await this.stripe.accounts.listExternalAccounts(providerAccountId, { object: 'bank_account', limit: 10 });
const banks = list.data.filter((e): e is Stripe.BankAccount => e.object === 'bank_account');
return banks.find((b) => b.default_for_currency) ?? banks[0] ?? null;
}
// ---------------------------------------------------------------------------
// Outils internes
// ---------------------------------------------------------------------------
private async getBusiness(userId: string): Promise<Business> {
const business = await this.prisma.business.findUnique({ where: { userId } });
if (!business) throw new NotFoundException("Renseignez d'abord les informations de votre entreprise.");
return business;
}
private async getAccountOrThrow(userId: string): Promise<PaymentAccount> {
const business = await this.getBusiness(userId);
const account = await this.prisma.paymentAccount.findUnique({ where: { businessId: business.id } });
if (!account) throw new UnprocessableEntityException("Créez d'abord votre compte de paiement.");
return account;
}
private toView(account: PaymentAccount | null): PaymentAccountView {
const stored = (account?.requirements as unknown as (StoredRequirements & { rejected?: boolean }) | null) ?? null;
const { rejected = false, ...requirements } = stored ?? ({} as StoredRequirements & { rejected?: boolean });
return {
status: computeKycStatus(account ? { ...account, rejected, requirements: stored ? requirements : null } : null),
chargesEnabled: account?.chargesEnabled ?? false,
payoutsEnabled: account?.payoutsEnabled ?? false,
bankAccount: account?.bankLast4 ? { last4: account.bankLast4, bankName: account.bankName } : null,
requirements: stored ? requirements : null,
};
}
}

View file

@ -0,0 +1,42 @@
import { transactionsToCsv } from './csv';
import type { TransactionView } from './payments.service';
const base: TransactionView = {
id: 't1',
amountCents: 5000,
currency: 'eur',
status: 'succeeded',
feeCents: 290,
netCents: 4710,
refundedCents: 0,
debtDeductedCents: 0,
cardBrand: 'visa',
cardLast4: '4242',
walletType: null,
note: null,
failureReason: null,
createdAt: new Date('2026-10-02T07:58:00Z'),
succeededAt: new Date('2026-10-02T07:58:00Z'),
reference: 'pi_123',
receiptEmail: null,
};
describe('transactionsToCsv', () => {
it('format français : séparateur ;, virgule décimale, heure de Paris, BOM', () => {
const csv = transactionsToCsv([base]);
expect(csv.startsWith('')).toBe(true);
const [header, line] = csv.slice(1).split('\r\n');
expect(header).toBe('Date;Heure;Montant;Moyen de paiement;Statut;Frais;Remboursé;Net;Note;Identifiant');
expect(line).toBe('02/10/2026;09:58;50,00;Visa 4242;Réussi;2,90;;47,10;;pi_123');
});
it('net après remboursement partiel', () => {
const line = transactionsToCsv([{ ...base, status: 'partially_refunded', refundedCents: 2000 }]).split('\r\n')[1];
expect(line).toContain(';Partiellement remboursé;2,90;20,00;27,10;');
});
it('neutralise les formules et échappe les ; dans une note', () => {
const line = transactionsToCsv([{ ...base, note: '=HYPERLINK("x");2 tartes' }]).split('\r\n')[1];
expect(line).toContain(`"'=HYPERLINK(""x"");2 tartes"`);
});
});

View file

@ -0,0 +1,55 @@
import type { TransactionView } from './payments.service';
const STATUS_LABELS: Record<string, string> = {
succeeded: 'Réussi',
refunded: 'Remboursé',
partially_refunded: 'Partiellement remboursé',
failed: 'Échoué',
pending: 'En attente',
canceled: 'Annulé',
};
const BRAND_LABELS: Record<string, string> = { visa: 'Visa', mastercard: 'Mastercard', amex: 'American Express', cartes_bancaires: 'CB' };
const WALLET_LABELS: Record<string, string> = { apple_pay: 'Apple Pay', google_pay: 'Google Pay', samsung_pay: 'Samsung Pay' };
const dateFmt = new Intl.DateTimeFormat('fr-FR', { timeZone: 'Europe/Paris', day: '2-digit', month: '2-digit', year: 'numeric' });
const timeFmt = new Intl.DateTimeFormat('fr-FR', { timeZone: 'Europe/Paris', hour: '2-digit', minute: '2-digit' });
/** Montant au format des tableurs français : 1234,50 (sans symbole ni séparateur de milliers). */
const amount = (cents: number | null) => (cents === null ? '' : (cents / 100).toFixed(2).replace('.', ','));
/**
* Champ texte sûr : neutralise les formules (=, +, -, @ en tête → injection dans Excel)
* et entoure de guillemets si nécessaire.
*/
function text(value: string): string {
const safe = /^[=+\-@\t\r]/.test(value) ? `'${value}` : value;
return /[;"\r\n]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe;
}
function paymentMethod(t: TransactionView): string {
if (t.walletType) return WALLET_LABELS[t.walletType] ?? 'Téléphone';
if (!t.cardBrand) return '';
return `${BRAND_LABELS[t.cardBrand] ?? t.cardBrand}${t.cardLast4 ? ` ${t.cardLast4}` : ''}`;
}
/** Export des transactions (séparateur « ; », BOM UTF-8 : s'ouvre directement dans Excel en français). */
export function transactionsToCsv(rows: TransactionView[]): string {
const header = ['Date', 'Heure', 'Montant', 'Moyen de paiement', 'Statut', 'Frais', 'Remboursé', 'Net', 'Note', 'Identifiant'];
const lines = rows.map((t) => {
const at = t.succeededAt ?? t.createdAt;
const net = t.netCents === null ? null : t.netCents - t.refundedCents;
return [
dateFmt.format(at),
timeFmt.format(at),
amount(t.amountCents),
text(paymentMethod(t)),
STATUS_LABELS[t.status] ?? t.status,
amount(t.feeCents),
amount(t.refundedCents || null),
amount(net),
text(t.note ?? ''),
text(t.reference ?? ''),
].join(';');
});
return '' + [header.join(';'), ...lines].join('\r\n');
}

View file

@ -0,0 +1,22 @@
import { Transform } from 'class-transformer';
import { IsInt, IsOptional, IsString, IsUUID, MaxLength, Min } from 'class-validator';
export class CreatePaymentDto {
/** Montant en centimes (1500 = 15,00 €). Les bornes sont vérifiées côté service (configurables). */
@IsInt()
@Min(1)
amountCents: number;
/**
* Généré par l'app (UUID v4) une fois par vente, avant le premier appui sur ENCAISSER.
* Un renvoi avec la même clé (réseau coupé, double appui) renvoie le même paiement : jamais deux.
*/
@IsUUID('4')
idempotencyKey: string;
@IsOptional()
@Transform(({ value }) => (typeof value === 'string' ? value.trim() : value))
@IsString()
@MaxLength(255)
note?: string;
}

View file

@ -0,0 +1,63 @@
import { Transform, Type } from 'class-transformer';
import { ArrayMaxSize, IsArray, IsIn, IsInt, IsISO8601, IsOptional, IsUUID, Matches, Max, Min } from 'class-validator';
export const TRANSACTION_STATUSES = ['pending', 'succeeded', 'failed', 'canceled', 'refunded', 'partially_refunded'] as const;
export type TransactionStatus = (typeof TRANSACTION_STATUSES)[number];
export const TRANSACTION_SORTS = ['date_desc', 'date_asc', 'amount_desc', 'amount_asc'] as const;
export type TransactionSort = (typeof TRANSACTION_SORTS)[number];
/** Statuts listés par défaut : les ventes annulées par le pro (jamais présentées au client) sont masquées. */
export const DEFAULT_LIST_STATUSES: TransactionStatus[] = ['pending', 'succeeded', 'failed', 'refunded', 'partially_refunded'];
export class ListTransactionsDto {
/** Un ou plusieurs statuts séparés par des virgules : `refunded,partially_refunded`. */
@IsOptional()
@Transform(({ value }) => (typeof value === 'string' ? value.split(',').filter(Boolean) : value))
@IsArray()
@ArrayMaxSize(TRANSACTION_STATUSES.length)
@IsIn(TRANSACTION_STATUSES, { each: true })
status?: TransactionStatus[];
@IsOptional()
@IsISO8601()
from?: string;
@IsOptional()
@IsISO8601()
to?: string;
/** Recherche : montant tel qu'affiché (15, 15,50), 4 derniers chiffres de la carte ou identifiant (pi_…). */
@IsOptional()
@Matches(/^[\w.,]{1,64}$/, { message: 'Recherche invalide.' })
search?: string;
@IsOptional()
@IsIn(TRANSACTION_SORTS)
sort: TransactionSort = 'date_desc';
/** card = carte présentée ; wallet = téléphone ou montre (Apple Pay, Google Pay…). */
@IsOptional()
@IsIn(['card', 'wallet'])
method?: 'card' | 'wallet';
/** Pagination par pages (tableau de bord web) ; sans `page`, pagination par curseur (app). */
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(10_000)
page?: number;
/** Identifiant de la dernière transaction de la page précédente. */
@IsOptional()
@IsUUID()
cursor?: string;
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(100)
limit: number = 30;
}

View file

@ -0,0 +1,9 @@
import { Transform } from 'class-transformer';
import { IsEmail, MaxLength } from 'class-validator';
export class SendReceiptDto {
@Transform(({ value }) => (typeof value === 'string' ? value.trim().toLowerCase() : value))
@IsEmail()
@MaxLength(191)
email: string;
}

View file

@ -0,0 +1,31 @@
import { computeFees } from './fees';
describe('computeFees', () => {
it('vente de 50 € sans abonnement : frais Stripe + 2 €', () => {
// 1,4 % + 0,10 € + 0,10 € Tap to Pay = 0,90 €
expect(computeFees({ amountCents: 5000, providerFeeCents: 90, platformFeeCents: 200 })).toEqual({
providerFeeCents: 90,
platformFeeCents: 200,
totalFeeCents: 290,
netCents: 4710,
});
});
it('abonné : seuls les frais Stripe sont déduits', () => {
expect(computeFees({ amountCents: 5000, providerFeeCents: 90, platformFeeCents: 0 }).netCents).toBe(4910);
});
it('petite vente : le net ne devient jamais négatif (part TapTP réduite)', () => {
expect(computeFees({ amountCents: 150, providerFeeCents: 22, platformFeeCents: 200 })).toEqual({
providerFeeCents: 22,
platformFeeCents: 128,
totalFeeCents: 150,
netCents: 0,
});
});
it('refuse des montants non entiers ou négatifs', () => {
expect(() => computeFees({ amountCents: 10.5, providerFeeCents: 0, platformFeeCents: 0 })).toThrow();
expect(() => computeFees({ amountCents: 100, providerFeeCents: -1, platformFeeCents: 0 })).toThrow();
});
});

View file

@ -0,0 +1,34 @@
export interface FeeInput {
amountCents: number;
/** Frais Stripe réels du paiement (balance transaction + Tap to Pay). */
providerFeeCents: number;
/** Part fixe TapTP selon le plan (200 = 2 €, 0 si abonné). */
platformFeeCents: number;
}
export interface FeeBreakdown {
providerFeeCents: number;
platformFeeCents: number;
/** « Frais de gestion TapTP » affichés au pro = frais Stripe + part TapTP. */
totalFeeCents: number;
/** Montant reversé au pro. */
netCents: number;
}
/**
* Calcule la répartition d'une vente. Le pro ne peut jamais recevoir un montant négatif :
* sur une très petite vente, la part TapTP est réduite d'abord, puis les frais Stripe restent à la charge de TapTP.
*/
export function computeFees({ amountCents, providerFeeCents, platformFeeCents }: FeeInput): FeeBreakdown {
if (![amountCents, providerFeeCents, platformFeeCents].every((n) => Number.isInteger(n) && n >= 0)) {
throw new Error('Montants invalides pour le calcul des frais.');
}
const provider = Math.min(providerFeeCents, amountCents);
const platform = Math.min(platformFeeCents, amountCents - provider);
return {
providerFeeCents: provider,
platformFeeCents: platform,
totalFeeCents: provider + platform,
netCents: amountCents - provider - platform,
};
}

View file

@ -0,0 +1,68 @@
import { Body, Controller, Get, HttpCode, HttpStatus, Param, ParseUUIDPipe, Post, Query, Req, Res } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import type { Request, Response } from 'express';
import { AuthUser, CurrentUser } from '../common/current-user.decorator';
import { transactionsToCsv } from './csv';
import { CreatePaymentDto } from './dto/create-payment.dto';
import { ListTransactionsDto } from './dto/list-transactions.dto';
import { SendReceiptDto } from './dto/send-receipt.dto';
import { PaymentsService } from './payments.service';
@Controller()
export class PaymentsController {
constructor(private readonly payments: PaymentsService) {}
@Post('terminal/connection-token')
@HttpCode(HttpStatus.OK)
@Throttle({ default: { limit: 30, ttl: 60_000 } })
connectionToken(@CurrentUser() user: AuthUser) {
return this.payments.createConnectionToken(user.id);
}
@Post('payments')
@HttpCode(HttpStatus.OK)
@Throttle({ default: { limit: 30, ttl: 60_000 } })
create(@CurrentUser() user: AuthUser, @Body() dto: CreatePaymentDto, @Req() req: Request) {
return this.payments.createPayment(user.id, dto, req.ip);
}
@Post('payments/:id/cancel')
@HttpCode(HttpStatus.OK)
cancel(@CurrentUser() user: AuthUser, @Param('id', new ParseUUIDPipe()) id: string, @Req() req: Request) {
return this.payments.cancelPayment(user.id, id, req.ip);
}
@Get('transactions')
list(@CurrentUser() user: AuthUser, @Query() query: ListTransactionsDto) {
return this.payments.listTransactions(user.id, query);
}
// Déclarée avant 'transactions/:id' pour ne pas être prise pour un identifiant.
@Get('transactions/export')
@Throttle({ default: { limit: 10, ttl: 60_000 } })
async export(@CurrentUser() user: AuthUser, @Query() query: ListTransactionsDto, @Res({ passthrough: true }) res: Response) {
const rows = await this.payments.exportTransactions(user.id, query);
const date = new Intl.DateTimeFormat('sv-SE', { timeZone: 'Europe/Paris' }).format(new Date()); // AAAA-MM-JJ
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="taptp-transactions-${date}.csv"`);
res.setHeader('Cache-Control', 'no-store');
return transactionsToCsv(rows);
}
@Post('transactions/:id/receipt')
@HttpCode(HttpStatus.OK)
@Throttle({ default: { limit: 10, ttl: 60_000 } })
receipt(
@CurrentUser() user: AuthUser,
@Param('id', new ParseUUIDPipe()) id: string,
@Body() dto: SendReceiptDto,
@Req() req: Request,
) {
return this.payments.sendReceipt(user.id, id, dto.email, req.ip);
}
@Get('transactions/:id')
get(@CurrentUser() user: AuthUser, @Param('id', new ParseUUIDPipe()) id: string) {
return this.payments.getTransaction(user.id, id);
}
}

View file

@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { PaymentsController } from './payments.controller';
import { PaymentsService } from './payments.service';
@Module({
controllers: [PaymentsController],
providers: [PaymentsService],
exports: [PaymentsService],
})
export class PaymentsModule {}

View file

@ -0,0 +1,524 @@
import {
BadRequestException,
ConflictException,
ForbiddenException,
Inject,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Business, PaymentAccount, Prisma, Transaction } from '@prisma/client';
import Stripe from 'stripe';
import { AuditService } from '../audit/audit.service';
import { Env } from '../config/env';
import { LedgerService } from '../ledger/ledger.service';
import { PrismaService } from '../prisma/prisma.service';
import { STRIPE } from '../stripe/stripe.module';
import { CreatePaymentDto } from './dto/create-payment.dto';
import { DEFAULT_LIST_STATUSES, ListTransactionsDto, TransactionSort } from './dto/list-transactions.dto';
import { computeFees } from './fees';
/** Statuts Stripe à partir desquels un PaymentIntent peut encore être présenté au lecteur. */
const REUSABLE_PI_STATUSES: Stripe.PaymentIntent.Status[] = ['requires_payment_method', 'requires_confirmation', 'requires_action'];
const CANCELABLE_PI_STATUSES: Stripe.PaymentIntent.Status[] = [...REUSABLE_PI_STATUSES, 'requires_capture'];
export interface ConnectionTokenView {
secret: string;
locationId: string;
/** À passer à connectReader({ onBehalfOf }) dans le SDK Terminal. */
onBehalfOf: string;
/** Nom affiché par l'écran Tap to Pay du système (Apple / Google). */
merchantDisplayName: string;
}
export interface PaymentView {
transactionId: string;
paymentIntentId: string;
clientSecret: string;
amountCents: number;
currency: string;
}
export interface TransactionView {
id: string;
amountCents: number;
currency: string;
status: string;
/** Frais de gestion TapTP (frais Stripe + part TapTP). Null tant que le paiement n'est pas confirmé. */
feeCents: number | null;
netCents: number | null;
refundedCents: number;
/** Sommes dues (abonnement, frais de remboursement) retenues sur cette vente. */
debtDeductedCents: number;
cardBrand: string | null;
cardLast4: string | null;
walletType: string | null;
note: string | null;
failureReason: string | null;
createdAt: Date;
succeededAt: Date | null;
/** Identifiant Stripe du paiement (affiché et copiable dans le détail). */
reference: string | null;
receiptEmail: string | null;
}
@Injectable()
export class PaymentsService {
private readonly logger = new Logger(PaymentsService.name);
constructor(
private readonly prisma: PrismaService,
private readonly audit: AuditService,
private readonly config: ConfigService<Env, true>,
private readonly ledger: LedgerService,
@Inject(STRIPE) private readonly stripe: Stripe,
) {}
// ---------------------------------------------------------------------------
// Terminal (Tap to Pay)
// ---------------------------------------------------------------------------
/** Jeton de connexion du SDK Terminal, lié à l'emplacement du pro (créé à la première demande). */
async createConnectionToken(userId: string): Promise<ConnectionTokenView> {
const { business, account } = await this.getActiveAccount(userId);
const locationId = account.terminalLocationId ?? (await this.createLocation(business, account));
const token = await this.stripe.terminal.connectionTokens.create({ location: locationId });
return {
secret: token.secret,
locationId,
onBehalfOf: account.providerAccountId,
merchantDisplayName: (business.tradeName ?? business.legalName).slice(0, 100),
};
}
private async createLocation(business: Business, account: PaymentAccount): Promise<string> {
const location = await this.stripe.terminal.locations.create(
{
display_name: (business.tradeName ?? business.legalName).slice(0, 100),
address: {
line1: business.addressLine1,
line2: business.addressLine2 ?? undefined,
postal_code: business.postalCode,
city: business.city,
country: business.country,
},
metadata: { taptp_business_id: business.id },
},
{ idempotencyKey: `taptp-location-${business.id}` },
);
// Mise à jour conditionnelle : si une requête concurrente a déjà enregistré un emplacement, on garde le sien.
await this.prisma.paymentAccount.updateMany({
where: { id: account.id, terminalLocationId: null },
data: { terminalLocationId: location.id },
});
const saved = await this.prisma.paymentAccount.findUniqueOrThrow({ where: { id: account.id } });
return saved.terminalLocationId ?? location.id;
}
// ---------------------------------------------------------------------------
// Encaissement
// ---------------------------------------------------------------------------
/**
* Prépare un encaissement. Idempotent sur `idempotencyKey` : un renvoi (double appui, réseau coupé)
* renvoie le même PaymentIntent, jamais un second paiement.
*/
async createPayment(userId: string, dto: CreatePaymentDto, ip?: string): Promise<PaymentView> {
const min = this.config.get('PAYMENT_MIN_CENTS', { infer: true });
const max = this.config.get('PAYMENT_MAX_CENTS', { infer: true });
if (dto.amountCents < min || dto.amountCents > max) {
throw new BadRequestException(`Le montant doit être compris entre ${formatEur(min)} et ${formatEur(max)}.`);
}
const { business, account } = await this.getActiveAccount(userId);
const existing = await this.prisma.transaction.findUnique({ where: { idempotencyKey: dto.idempotencyKey } });
if (existing) return this.resumePayment(existing, business, dto.amountCents);
let tx: Transaction;
try {
tx = await this.prisma.transaction.create({
data: {
businessId: business.id,
idempotencyKey: dto.idempotencyKey,
amountCents: dto.amountCents,
currency: 'eur',
status: 'pending',
note: dto.note,
},
});
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
const concurrent = await this.prisma.transaction.findUniqueOrThrow({ where: { idempotencyKey: dto.idempotencyKey } });
return this.resumePayment(concurrent, business, dto.amountCents);
}
throw err;
}
const pi = await this.createPaymentIntent(tx, business, account);
await this.audit.log({ userId, action: 'payment.created', ip, metadata: { transactionId: tx.id, amountCents: tx.amountCents } });
return this.toPaymentView(tx, pi);
}
private async createPaymentIntent(tx: Transaction, business: Business, account: PaymentAccount): Promise<Stripe.PaymentIntent> {
const pi = await this.stripe.paymentIntents.create(
{
amount: tx.amountCents,
currency: tx.currency,
allowed_payment_method_types: ['card_present'],
capture_method: 'automatic',
// Le pro est le marchand affiché au client ; les fonds lui sont reversés après confirmation (webhook).
on_behalf_of: account.providerAccountId,
transfer_group: `taptp_tx_${tx.id}`,
description: `Vente ${business.tradeName ?? business.legalName}`.slice(0, 1000),
metadata: { taptp_transaction_id: tx.id, taptp_business_id: business.id },
},
{ idempotencyKey: `taptp-pi-${tx.id}` },
);
// Conditionnel : ne jamais écraser un PaymentIntent déjà associé.
await this.prisma.transaction.updateMany({
where: { id: tx.id, providerPaymentIntentId: null },
data: { providerPaymentIntentId: pi.id },
});
return pi;
}
private async resumePayment(tx: Transaction, business: Business, amountCents: number): Promise<PaymentView> {
if (tx.businessId !== business.id) throw new ConflictException('Clé de paiement déjà utilisée.');
if (tx.amountCents !== amountCents) throw new ConflictException('Cette vente a déjà été créée avec un autre montant.');
if (tx.status !== 'pending' && tx.status !== 'failed') {
throw new ConflictException('Cette vente est déjà terminée.');
}
if (!tx.providerPaymentIntentId) {
// La création précédente a échoué entre la base et Stripe : on la reprend (même clé d'idempotence Stripe).
const account = await this.prisma.paymentAccount.findUniqueOrThrow({ where: { businessId: business.id } });
return this.toPaymentView(tx, await this.createPaymentIntent(tx, business, account));
}
const pi = await this.stripe.paymentIntents.retrieve(tx.providerPaymentIntentId);
if (!REUSABLE_PI_STATUSES.includes(pi.status)) throw new ConflictException('Cette vente est déjà terminée.');
return this.toPaymentView(tx, pi);
}
async cancelPayment(userId: string, transactionId: string, ip?: string): Promise<TransactionView> {
const tx = await this.getOwnedTransaction(userId, transactionId);
if (tx.status !== 'pending' && tx.status !== 'failed') throw new ConflictException('Cette vente ne peut plus être annulée.');
if (tx.providerPaymentIntentId) {
const pi = await this.stripe.paymentIntents.retrieve(tx.providerPaymentIntentId);
if (pi.status === 'succeeded') throw new ConflictException('Paiement déjà accepté : utilisez un remboursement.');
if (CANCELABLE_PI_STATUSES.includes(pi.status)) {
await this.stripe.paymentIntents.cancel(pi.id, {}, { idempotencyKey: `taptp-pi-cancel-${tx.id}` });
}
}
const updated = await this.markIfOpen(tx.id, { status: 'canceled' });
await this.audit.log({ userId, action: 'payment.canceled', ip, metadata: { transactionId: tx.id } });
return this.toTransactionView(updated ?? tx);
}
// ---------------------------------------------------------------------------
// Confirmation par webhook (seule source de vérité du statut)
// ---------------------------------------------------------------------------
/** Paiement accepté : calcule les frais réels puis reverse le net au pro. Rejouable sans risque. */
async handlePaymentSucceeded(paymentIntentId: string): Promise<void> {
const pi = await this.stripe.paymentIntents.retrieve(paymentIntentId, {
expand: ['latest_charge.balance_transaction'],
});
const tx = await this.findTransactionForIntent(pi);
if (!tx) return;
// Le passage à « succeeded » est la dernière étape : une vente déjà finalisée n'est jamais retraitée.
if (tx.status !== 'pending' && tx.status !== 'failed') return;
const charge = pi.latest_charge as Stripe.Charge | null;
const balanceTx = charge?.balance_transaction as Stripe.BalanceTransaction | null | undefined;
if (!charge || !balanceTx || typeof balanceTx === 'string') {
throw new Error(`Charge ou balance transaction indisponible pour ${pi.id} : nouvel essai via webhook.`);
}
if (pi.amount_received !== tx.amountCents) {
throw new Error(`Montant reçu (${pi.amount_received}) différent de la vente ${tx.id} (${tx.amountCents}).`);
}
const plan = await this.resolveFeePlan(tx.businessId);
const fees = computeFees({
amountCents: tx.amountCents,
providerFeeCents: balanceTx.fee + plan.tapToPayFeeCents,
platformFeeCents: plan.perTransactionCents,
});
// Sommes dues (abonnement, frais de remboursements) retenues avant reversement.
const deducted = await this.ledger.allocateForTransaction(tx.id, tx.businessId, fees.netCents);
const transferCents = fees.netCents - deducted;
const account = await this.prisma.paymentAccount.findUniqueOrThrow({ where: { businessId: tx.businessId } });
const transfer =
transferCents > 0
? await this.stripe.transfers.create(
{
amount: transferCents,
currency: tx.currency,
destination: account.providerAccountId,
source_transaction: charge.id, // le transfert suit la disponibilité des fonds du paiement
transfer_group: `taptp_tx_${tx.id}`,
metadata: { taptp_transaction_id: tx.id },
},
// Une seule fois par vente, même si le webhook est rejoué.
{ idempotencyKey: `taptp-transfer-${tx.id}` },
)
: null;
const card = charge.payment_method_details?.card_present;
await this.prisma.transaction.update({
where: { id: tx.id },
data: {
status: 'succeeded',
providerChargeId: charge.id,
providerTransferId: transfer?.id ?? null,
providerFeeCents: fees.providerFeeCents,
platformFeeCents: fees.platformFeeCents,
netCents: fees.netCents,
feePlanCode: plan.code,
cardBrand: card?.brand ?? null,
cardLast4: card?.last4 ?? null,
walletType: card?.wallet?.type ?? null,
failureReason: null,
succeededAt: new Date(charge.created * 1000),
},
});
this.logger.log(`Vente ${tx.id} confirmée : ${tx.amountCents} c, net ${fees.netCents} c, retenue ${deducted} c.`);
}
async handlePaymentFailed(paymentIntentId: string): Promise<void> {
const pi = await this.stripe.paymentIntents.retrieve(paymentIntentId);
const tx = await this.findTransactionForIntent(pi);
if (!tx) return;
// Un refus n'est pas définitif : le client peut représenter une carte sur le même paiement.
await this.markIfOpen(tx.id, {
status: 'failed',
failureReason: (pi.last_payment_error?.decline_code ?? pi.last_payment_error?.code ?? 'payment_failed').slice(0, 255),
});
}
async handlePaymentCanceled(paymentIntentId: string): Promise<void> {
const pi = await this.stripe.paymentIntents.retrieve(paymentIntentId);
const tx = await this.findTransactionForIntent(pi);
if (tx) await this.markIfOpen(tx.id, { status: 'canceled' });
}
// ---------------------------------------------------------------------------
// Historique
// ---------------------------------------------------------------------------
async listTransactions(userId: string, query: ListTransactionsDto) {
const business = await this.getBusiness(userId);
const where = this.listWhere(business.id, query);
const orderBy = SORT_ORDER[query.sort ?? 'date_desc'];
if (query.search) {
// Recherche « comme affiché » (montant, 4 derniers chiffres, identifiant) : en mémoire sur une fenêtre bornée.
const matches = await this.searchTransactions(where, orderBy, query.search);
if (query.page !== undefined) {
const start = (query.page - 1) * query.limit;
return this.pageResult(matches.slice(start, start + query.limit), matches.length, query.page, query.limit);
}
const startIndex = query.cursor ? matches.findIndex((t) => t.id === query.cursor) + 1 : 0;
const page = matches.slice(startIndex, startIndex + query.limit);
return {
data: page.map((t) => this.toTransactionView(t)),
nextCursor: matches.length > startIndex + query.limit ? page[page.length - 1].id : null,
};
}
// Pagination par pages : tableau de bord web.
if (query.page !== undefined) {
const [rows, total] = await Promise.all([
this.prisma.transaction.findMany({ where, orderBy, skip: (query.page - 1) * query.limit, take: query.limit }),
this.prisma.transaction.count({ where }),
]);
return this.pageResult(rows, total, query.page, query.limit);
}
// Pagination par curseur : défilement infini de l'app.
const rows = await this.prisma.transaction.findMany({
where,
orderBy,
take: query.limit + 1,
...(query.cursor ? { cursor: { id: query.cursor }, skip: 1 } : {}),
});
const hasMore = rows.length > query.limit;
const page = rows.slice(0, query.limit);
return {
data: page.map((t) => this.toTransactionView(t)),
nextCursor: hasMore ? page[page.length - 1].id : null,
};
}
/** Toutes les ventes filtrées (export CSV), dans la limite de EXPORT_MAX. */
async exportTransactions(userId: string, query: ListTransactionsDto): Promise<TransactionView[]> {
const business = await this.getBusiness(userId);
const where = this.listWhere(business.id, query);
const orderBy = SORT_ORDER[query.sort ?? 'date_desc'];
const rows = query.search
? await this.searchTransactions(where, orderBy, query.search)
: await this.prisma.transaction.findMany({ where, orderBy, take: EXPORT_MAX });
return rows.slice(0, EXPORT_MAX).map((t) => this.toTransactionView(t));
}
private listWhere(businessId: string, query: ListTransactionsDto): Prisma.TransactionWhereInput {
return {
businessId,
status: { in: query.status?.length ? query.status : DEFAULT_LIST_STATUSES },
createdAt:
query.from || query.to
? { gte: query.from ? new Date(query.from) : undefined, lt: query.to ? new Date(query.to) : undefined }
: undefined,
walletType: query.method === 'card' ? null : query.method === 'wallet' ? { not: null } : undefined,
};
}
private async searchTransactions(
where: Prisma.TransactionWhereInput,
orderBy: Prisma.TransactionOrderByWithRelationInput[],
search: string,
): Promise<Transaction[]> {
const needle = search.trim().toLowerCase();
const amountNeedle = /^\d+([.,]\d*)?$/.test(needle) ? needle.replace('.', ',') : null;
const candidates = await this.prisma.transaction.findMany({ where, orderBy, take: SEARCH_WINDOW });
return candidates.filter(
(t) =>
(amountNeedle !== null && formatAmountPlain(t.amountCents).includes(amountNeedle)) ||
(/^\d{4}$/.test(needle) && t.cardLast4 === needle) ||
(needle.length >= 3 && !!t.providerPaymentIntentId?.toLowerCase().includes(needle)),
);
}
private pageResult(rows: Transaction[], total: number, page: number, pageSize: number) {
return { data: rows.map((t) => this.toTransactionView(t)), total, page, pageSize };
}
/**
* Reçu par e-mail : Stripe envoie un reçu à chaque mise à jour de l'e-mail d'une charge réussie.
* (En mode test, Stripe n'envoie pas réellement l'e-mail.)
*/
async sendReceipt(userId: string, transactionId: string, email: string, ip?: string): Promise<TransactionView> {
const tx = await this.getOwnedTransaction(userId, transactionId);
if (!['succeeded', 'partially_refunded', 'refunded'].includes(tx.status) || !tx.providerChargeId) {
throw new ConflictException('Le reçu sera disponible dès la confirmation du paiement.');
}
await this.stripe.charges.update(tx.providerChargeId, { receipt_email: email });
const updated = await this.prisma.transaction.update({ where: { id: tx.id }, data: { receiptEmail: email } });
await this.audit.log({ userId, action: 'payment.receipt_sent', ip, metadata: { transactionId: tx.id } });
return this.toTransactionView(updated);
}
async getTransaction(userId: string, transactionId: string): Promise<TransactionView> {
return this.toTransactionView(await this.getOwnedTransaction(userId, transactionId));
}
// ---------------------------------------------------------------------------
// Outils internes
// ---------------------------------------------------------------------------
private async getBusiness(userId: string): Promise<Business> {
const business = await this.prisma.business.findUnique({ where: { userId } });
if (!business) throw new NotFoundException("Renseignez d'abord les informations de votre entreprise.");
return business;
}
/** Encaissement autorisé seulement si Stripe a validé le compte (état synchronisé par webhook). */
private async getActiveAccount(userId: string): Promise<{ business: Business; account: PaymentAccount }> {
const business = await this.getBusiness(userId);
const account = await this.prisma.paymentAccount.findUnique({ where: { businessId: business.id } });
if (!account?.chargesEnabled) {
throw new ForbiddenException("Votre compte n'est pas encore activé pour encaisser.");
}
return { business, account };
}
private async getOwnedTransaction(userId: string, transactionId: string): Promise<Transaction> {
const business = await this.getBusiness(userId);
const tx = await this.prisma.transaction.findFirst({ where: { id: transactionId, businessId: business.id } });
if (!tx) throw new NotFoundException('Transaction introuvable.');
return tx;
}
private async findTransactionForIntent(pi: Stripe.PaymentIntent): Promise<Transaction | null> {
const tx =
(await this.prisma.transaction.findUnique({ where: { providerPaymentIntentId: pi.id } })) ??
(pi.metadata?.taptp_transaction_id
? await this.prisma.transaction.findUnique({ where: { id: pi.metadata.taptp_transaction_id } })
: null);
if (!tx) {
this.logger.warn(`PaymentIntent ${pi.id} sans transaction TapTP : ignoré.`);
return null;
}
return tx;
}
/** Met à jour uniquement une vente encore ouverte : un succès n'est jamais écrasé par un échec tardif. */
private async markIfOpen(id: string, data: Prisma.TransactionUpdateManyMutationInput): Promise<Transaction | null> {
await this.prisma.transaction.updateMany({ where: { id, status: { in: ['pending', 'failed'] } }, data });
return this.prisma.transaction.findUnique({ where: { id } });
}
/** Plan « subscriber » si un abonnement est actif, sinon « default ». */
private async resolveFeePlan(businessId: string) {
const subscribed = await this.prisma.subscription.findFirst({
where: { businessId, status: 'active', currentPeriodEnd: { gt: new Date() } },
select: { id: true },
});
const code = subscribed ? 'subscriber' : 'default';
const plan = await this.prisma.feePlan.findFirst({ where: { code, active: true } });
if (!plan) throw new Error(`Plan de frais « ${code} » absent : lancer le seed.`);
return plan;
}
private toPaymentView(tx: Transaction, pi: Stripe.PaymentIntent): PaymentView {
if (!pi.client_secret) throw new Error(`PaymentIntent ${pi.id} sans client_secret.`);
return { transactionId: tx.id, paymentIntentId: pi.id, clientSecret: pi.client_secret, amountCents: tx.amountCents, currency: tx.currency };
}
toTransactionView(t: Transaction): TransactionView {
const fee = t.providerFeeCents !== null && t.platformFeeCents !== null ? t.providerFeeCents + t.platformFeeCents : null;
return {
id: t.id,
amountCents: t.amountCents,
currency: t.currency,
status: t.status,
feeCents: fee,
netCents: t.netCents,
refundedCents: t.refundedCents,
debtDeductedCents: t.debtDeductedCents,
cardBrand: t.cardBrand,
cardLast4: t.cardLast4,
walletType: t.walletType,
note: t.note,
failureReason: t.failureReason,
createdAt: t.createdAt,
succeededAt: t.succeededAt,
reference: t.providerPaymentIntentId,
receiptEmail: t.receiptEmail,
};
}
}
/** Nombre maximal de ventes parcourues par une recherche. */
const SEARCH_WINDOW = 5000;
/** Nombre maximal de lignes d'un export CSV. */
const EXPORT_MAX = 10_000;
const SORT_ORDER: Record<TransactionSort, Prisma.TransactionOrderByWithRelationInput[]> = {
date_desc: [{ createdAt: 'desc' }, { id: 'desc' }],
date_asc: [{ createdAt: 'asc' }, { id: 'asc' }],
amount_desc: [{ amountCents: 'desc' }, { createdAt: 'desc' }],
amount_asc: [{ amountCents: 'asc' }, { createdAt: 'desc' }],
};
/** 1500 → « 15,00 » (format affiché dans l'app, sans espace ni symbole). */
export function formatAmountPlain(cents: number): string {
return (cents / 100).toFixed(2).replace('.', ',');
}
function formatEur(cents: number): string {
return new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(cents / 100);
}

View file

@ -0,0 +1,38 @@
import { Controller, Get, Param, ParseUUIDPipe, Query } from '@nestjs/common';
import { Type } from 'class-transformer';
import { IsInt, IsOptional, IsUUID, Max, Min } from 'class-validator';
import { AuthUser, CurrentUser } from '../common/current-user.decorator';
import { PayoutsService } from './payouts.service';
class ListPayoutsDto {
@IsOptional()
@IsUUID()
cursor?: string;
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(100)
limit: number = 30;
}
@Controller('payouts')
export class PayoutsController {
constructor(private readonly payouts: PayoutsService) {}
@Get()
list(@CurrentUser() user: AuthUser, @Query() query: ListPayoutsDto) {
return this.payouts.list(user.id, query.cursor, query.limit);
}
@Get('balance')
balance(@CurrentUser() user: AuthUser) {
return this.payouts.balance(user.id);
}
@Get(':id')
get(@CurrentUser() user: AuthUser, @Param('id', new ParseUUIDPipe()) id: string) {
return this.payouts.get(user.id, id);
}
}

View file

@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { PayoutsController } from './payouts.controller';
import { PayoutsService } from './payouts.service';
@Module({
controllers: [PayoutsController],
providers: [PayoutsService],
exports: [PayoutsService],
})
export class PayoutsModule {}

View file

@ -0,0 +1,160 @@
import { Inject, Injectable, Logger, NotFoundException } from '@nestjs/common';
import { PaymentAccount, Payout, Transaction } from '@prisma/client';
import Stripe from 'stripe';
import { PrismaService } from '../prisma/prisma.service';
import { STRIPE } from '../stripe/stripe.module';
export interface PayoutView {
id: string;
amountCents: number;
currency: string;
arrivalDate: Date;
status: string;
bankLast4: string | null;
}
export interface PayoutDetailView extends PayoutView {
reference: string;
/** Calcul reconstitué à partir des ventes TapTP incluses (ventes, remboursements, frais, retenues). */
salesCount: number;
salesCents: number;
refundedCents: number;
feesCents: number;
deductedCents: number;
/** Période couverte par les ventes incluses. */
firstSaleAt: Date | null;
lastSaleAt: Date | null;
/** Aperçu des ventes incluses (les plus récentes). */
transactions: Pick<Transaction, 'id' | 'amountCents' | 'status' | 'cardBrand' | 'cardLast4' | 'walletType' | 'createdAt'>[];
}
const MAX_BALANCE_TX = 1000;
export interface BalanceView {
/** Disponible pour le prochain versement. */
availableCents: number;
/** En attente (fonds des ventes récentes pas encore disponibles). */
pendingCents: number;
/** Versement en cours (en attente ou en transit), s'il y en a un. */
nextPayout: PayoutView | null;
}
/** Versements Stripe du compte du pro vers son IBAN (automatiques, gérés par Stripe). */
@Injectable()
export class PayoutsService {
private readonly logger = new Logger(PayoutsService.name);
constructor(
private readonly prisma: PrismaService,
@Inject(STRIPE) private readonly stripe: Stripe,
) {}
async list(userId: string, cursor?: string, limit = 30) {
const account = await this.getAccount(userId);
const rows = await this.prisma.payout.findMany({
where: { paymentAccountId: account.id },
orderBy: [{ arrivalDate: 'desc' }, { id: 'desc' }],
take: limit + 1,
...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
});
const page = rows.slice(0, limit);
return { data: page.map(toView), nextCursor: rows.length > limit ? page[page.length - 1].id : null };
}
/**
* Détail d'un versement : mouvements Stripe du compte du pro inclus dans ce versement, rapprochés des ventes TapTP
* (chaque vente est reversée par un transfert dont l'identifiant est enregistré sur la transaction).
*/
async get(userId: string, payoutId: string): Promise<PayoutDetailView> {
const account = await this.getAccount(userId);
const payout = await this.prisma.payout.findFirst({ where: { id: payoutId, paymentAccountId: account.id } });
if (!payout) throw new NotFoundException('Versement introuvable.');
const transferIds = new Set<string>();
const movements = await this.stripe.balanceTransactions
.list({ payout: payout.providerPayoutId, limit: 100, expand: ['data.source'] }, { stripeAccount: account.providerAccountId })
.autoPagingToArray({ limit: MAX_BALANCE_TX });
for (const bt of movements) {
const source = bt.source as { source_transfer?: string | { id: string } | null } | string | null;
const transfer = source && typeof source !== 'string' ? source.source_transfer : null;
if (transfer) transferIds.add(typeof transfer === 'string' ? transfer : transfer.id);
}
const txs = transferIds.size
? await this.prisma.transaction.findMany({
where: { providerTransferId: { in: [...transferIds] }, business: { userId } },
orderBy: { createdAt: 'desc' },
})
: [];
return {
...toView(payout),
reference: payout.providerPayoutId,
salesCount: txs.length,
salesCents: txs.reduce((s, t) => s + t.amountCents, 0),
refundedCents: txs.reduce((s, t) => s + t.refundedCents, 0),
feesCents: txs.reduce((s, t) => s + (t.providerFeeCents ?? 0) + (t.platformFeeCents ?? 0), 0),
deductedCents: txs.reduce((s, t) => s + t.debtDeductedCents, 0),
firstSaleAt: txs.length ? txs[txs.length - 1].createdAt : null,
lastSaleAt: txs.length ? txs[0].createdAt : null,
transactions: txs.slice(0, 20).map((t) => ({
id: t.id,
amountCents: t.amountCents,
status: t.status,
cardBrand: t.cardBrand,
cardLast4: t.cardLast4,
walletType: t.walletType,
createdAt: t.createdAt,
})),
};
}
/** Solde en euros du compte du pro, lu chez Stripe. */
async balance(userId: string): Promise<BalanceView> {
const account = await this.getAccount(userId);
const balance = await this.stripe.balance.retrieve({}, { stripeAccount: account.providerAccountId });
const sum = (items: { amount: number; currency: string }[]) =>
items.filter((i) => i.currency === 'eur').reduce((s, i) => s + i.amount, 0);
const next = await this.prisma.payout.findFirst({
where: { paymentAccountId: account.id, status: { in: ['pending', 'in_transit'] } },
orderBy: { arrivalDate: 'asc' },
});
return { availableCents: sum(balance.available), pendingCents: sum(balance.pending), nextPayout: next ? toView(next) : null };
}
/** Webhook payout.* (événement d'un compte connecté) : relit le versement chez Stripe et l'enregistre. */
async syncFromStripe(payoutId: string, providerAccountId: string | null): Promise<void> {
if (!providerAccountId) return; // versement du compte TapTP lui-même : hors périmètre
const account = await this.prisma.paymentAccount.findUnique({ where: { providerAccountId } });
if (!account) {
this.logger.warn(`Versement ${payoutId} d'un compte inconnu (${providerAccountId}) : ignoré.`);
return;
}
const payout = await this.stripe.payouts.retrieve(payoutId, { expand: ['destination'] }, { stripeAccount: providerAccountId });
const destination = payout.destination as Stripe.BankAccount | Stripe.Card | string | null;
const bankLast4 = destination && typeof destination !== 'string' ? destination.last4 : account.bankLast4;
const data = {
amountCents: payout.amount,
currency: payout.currency,
arrivalDate: new Date(payout.arrival_date * 1000),
status: payout.status,
bankLast4,
};
await this.prisma.payout.upsert({
where: { providerPayoutId: payout.id },
create: { paymentAccountId: account.id, providerPayoutId: payout.id, ...data },
update: data,
});
}
private async getAccount(userId: string): Promise<PaymentAccount> {
const account = await this.prisma.paymentAccount.findFirst({ where: { business: { userId } } });
if (!account) throw new NotFoundException("Aucun compte de paiement : terminez d'abord l'activation.");
return account;
}
}
function toView(p: Payout): PayoutView {
return { id: p.id, amountCents: p.amountCents, currency: p.currency, arrivalDate: p.arrivalDate, status: p.status, bankLast4: p.bankLast4 };
}

View file

@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';
@Global()
@Module({
providers: [PrismaService],
exports: [PrismaService],
})
export class PrismaModule {}

View file

@ -0,0 +1,13 @@
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
async onModuleInit(): Promise<void> {
await this.$connect();
}
async onModuleDestroy(): Promise<void> {
await this.$disconnect();
}
}

View file

@ -0,0 +1,25 @@
import { IsIn, IsInt, IsOptional, IsString, IsUUID, MaxLength, Min } from 'class-validator';
/** Motifs de la maquette (visibles uniquement par le pro). */
export const REFUND_REASONS = ['amount_error', 'returned', 'goodwill', 'other'] as const;
export class CreateRefundDto {
/** Absent = remboursement total du montant encore remboursable. */
@IsOptional()
@IsInt()
@Min(1)
amountCents?: number;
@IsOptional()
@IsIn(REFUND_REASONS)
reason?: (typeof REFUND_REASONS)[number];
/** UUID v4 généré par l'app pour ce remboursement : un renvoi ne rembourse jamais deux fois. */
@IsUUID('4')
idempotencyKey: string;
/** Confirmation obligatoire : protège si le téléphone est prêté ou volé. */
@IsString()
@MaxLength(128)
password: string;
}

View file

@ -0,0 +1,28 @@
import { Body, Controller, Get, Param, ParseUUIDPipe, Post, Req } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import type { Request } from 'express';
import { AuthUser, CurrentUser } from '../common/current-user.decorator';
import { CreateRefundDto } from './dto/create-refund.dto';
import { RefundsService } from './refunds.service';
@Controller('transactions/:transactionId/refunds')
export class RefundsController {
constructor(private readonly refunds: RefundsService) {}
// Mot de passe exigé : limite stricte contre le brute-force.
@Post()
@Throttle({ default: { limit: 5, ttl: 60_000 } })
create(
@CurrentUser() user: AuthUser,
@Param('transactionId', new ParseUUIDPipe()) transactionId: string,
@Body() dto: CreateRefundDto,
@Req() req: Request,
) {
return this.refunds.create(user.id, transactionId, dto, req.ip);
}
@Get()
list(@CurrentUser() user: AuthUser, @Param('transactionId', new ParseUUIDPipe()) transactionId: string) {
return this.refunds.list(user.id, transactionId);
}
}

View file

@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { RefundsController } from './refunds.controller';
import { RefundsService } from './refunds.service';
@Module({
imports: [AuthModule],
controllers: [RefundsController],
providers: [RefundsService],
exports: [RefundsService],
})
export class RefundsModule {}

View file

@ -0,0 +1,238 @@
import { BadRequestException, ConflictException, Inject, Injectable, Logger, NotFoundException } from '@nestjs/common';
import { Refund, Transaction } from '@prisma/client';
import Stripe from 'stripe';
import { AuditService } from '../audit/audit.service';
import { AuthService } from '../auth/auth.service';
import { LedgerService } from '../ledger/ledger.service';
import { PrismaService } from '../prisma/prisma.service';
import { STRIPE } from '../stripe/stripe.module';
import { CreateRefundDto } from './dto/create-refund.dto';
const REFUNDABLE_STATUSES = ['succeeded', 'partially_refunded'];
/** Remboursements qui comptent dans le montant déjà remboursé. */
const ACTIVE_REFUND_STATUSES = ['processing', 'pending', 'succeeded'];
export interface RefundView {
id: string;
transactionId: string;
amountCents: number;
reason: string | null;
status: string;
createdAt: Date;
}
/**
* Remboursements. Règle TapTP : le pro supporte le remboursement ET les frais de la vente d'origine.
* Le montant est repris sur le reversement de la vente ; ce qui ne peut pas l'être devient une dette
* retenue sur ses ventes suivantes.
*/
@Injectable()
export class RefundsService {
private readonly logger = new Logger(RefundsService.name);
constructor(
private readonly prisma: PrismaService,
private readonly auth: AuthService,
private readonly ledger: LedgerService,
private readonly audit: AuditService,
@Inject(STRIPE) private readonly stripe: Stripe,
) {}
async create(userId: string, transactionId: string, dto: CreateRefundDto, ip?: string): Promise<RefundView> {
await this.auth.confirmPassword(userId, dto.password, 'refund', ip);
const tx = await this.getOwnedTransaction(userId, transactionId);
const existing = await this.prisma.refund.findUnique({ where: { idempotencyKey: dto.idempotencyKey } });
if (existing) {
if (existing.transactionId !== tx.id) throw new ConflictException('Clé de remboursement déjà utilisée.');
return this.toView(existing.status === 'processing' ? await this.process(existing.id) : existing);
}
if (!REFUNDABLE_STATUSES.includes(tx.status)) throw new ConflictException("Cette vente ne peut pas être remboursée.");
// Verrou sur la vente : deux remboursements simultanés ne peuvent pas dépasser le montant encaissé.
const refund = await this.prisma.$transaction(async (db) => {
await db.$queryRaw`SELECT id FROM transactions WHERE id = ${tx.id} FOR UPDATE`;
const already = await db.refund.aggregate({
where: { transactionId: tx.id, status: { in: ACTIVE_REFUND_STATUSES } },
_sum: { amountCents: true },
});
const refundable = tx.amountCents - (already._sum.amountCents ?? 0);
const amount = dto.amountCents ?? refundable;
if (refundable <= 0) throw new ConflictException('Cette vente a déjà été entièrement remboursée.');
if (amount > refundable) {
throw new BadRequestException(`Montant maximum remboursable : ${(refundable / 100).toFixed(2).replace('.', ',')} €.`);
}
return db.refund.create({
data: {
transactionId: tx.id,
idempotencyKey: dto.idempotencyKey,
amountCents: amount,
reason: dto.reason,
status: 'processing',
requestedBy: userId,
},
});
});
await this.audit.log({ userId, action: 'refund.requested', ip, metadata: { transactionId: tx.id, refundId: refund.id, amountCents: refund.amountCents } });
return this.toView(await this.process(refund.id));
}
/**
* Étapes du remboursement, rejouables (clés d'idempotence Stripe) si le processus est interrompu :
* 1. remboursement Stripe au client ; 2. reprise sur le reversement du pro ; 3. dette pour le reste ; 4. comptabilisation.
*/
private async process(refundId: string): Promise<Refund> {
const refund = await this.prisma.refund.findUniqueOrThrow({ where: { id: refundId }, include: { transaction: true } });
const tx = refund.transaction;
if (!tx.providerPaymentIntentId) throw new Error(`Vente ${tx.id} sans PaymentIntent.`);
const stripeRefund = await this.stripe.refunds.create(
{
payment_intent: tx.providerPaymentIntentId,
amount: refund.amountCents,
// Les motifs TapTP sont internes ; côté Stripe, c'est une demande du client.
reason: 'requested_by_customer',
metadata: { taptp_refund_id: refund.id, taptp_transaction_id: tx.id },
},
{ idempotencyKey: `taptp-refund-${refund.id}` },
);
const reversal = await this.reverseFromMerchant(refund, tx);
const shortfall = refund.amountCents - reversal.amountCents;
return this.prisma.$transaction(async (db) => {
// Comptabilisation une seule fois : seule la requête qui fait passer le statut de « processing » à final compte.
const { count } = await db.refund.updateMany({
where: { id: refund.id, status: 'processing' },
data: {
status: mapRefundStatus(stripeRefund.status),
providerRefundId: stripeRefund.id,
providerReversalId: reversal.id,
reversedCents: reversal.amountCents,
},
});
if (count === 1) {
if (shortfall > 0) {
await this.ledger.addDebt({ businessId: tx.businessId, kind: 'refund_shortfall', amountCents: shortfall, refundId: refund.id }, db);
}
const updated = await db.transaction.update({
where: { id: tx.id },
data: { refundedCents: { increment: refund.amountCents } },
});
await db.transaction.update({
where: { id: tx.id },
data: { status: updated.refundedCents >= updated.amountCents ? 'refunded' : 'partially_refunded' },
});
}
return db.refund.findUniqueOrThrow({ where: { id: refund.id } });
});
}
/** Reprend au pro, sur le reversement de la vente, au plus le montant remboursé. */
private async reverseFromMerchant(refund: Refund, tx: Transaction): Promise<{ id: string | null; amountCents: number }> {
if (!tx.providerTransferId) return { id: null, amountCents: 0 };
const transfer = await this.stripe.transfers.retrieve(tx.providerTransferId);
const reversible = transfer.amount - transfer.amount_reversed;
const amount = Math.min(refund.amountCents, reversible);
if (amount <= 0) return { id: null, amountCents: 0 };
try {
const reversal = await this.stripe.transfers.createReversal(
transfer.id,
{ amount, metadata: { taptp_refund_id: refund.id } },
{ idempotencyKey: `taptp-reversal-${refund.id}` },
);
return { id: reversal.id, amountCents: reversal.amount };
} catch (err) {
// Solde du pro insuffisant (déjà versé sur son IBAN) : tout passe en dette.
this.logger.warn(`Reprise impossible pour le remboursement ${refund.id} : ${(err as Error).message}`);
return { id: null, amountCents: 0 };
}
}
/** Webhook refund.updated / refund.failed : met à jour le statut et compense un remboursement échoué. */
async syncFromStripe(providerRefundId: string): Promise<void> {
const stripeRefund = await this.stripe.refunds.retrieve(providerRefundId);
const refundId = stripeRefund.metadata?.taptp_refund_id;
const refund = refundId
? await this.prisma.refund.findUnique({ where: { id: refundId }, include: { transaction: true, debt: true } })
: null;
if (!refund || refund.status === 'processing') return; // inconnu, ou comptabilisation en cours (elle lira le statut)
const status = mapRefundStatus(stripeRefund.status);
if (status === refund.status) return;
if (status === 'failed' || status === 'canceled') {
await this.compensateFailedRefund(refund.id, status);
return;
}
await this.prisma.refund.update({ where: { id: refund.id }, data: { status } });
}
/** Le client n'a pas été remboursé : on rend au pro ce qui lui a été repris et on annule la dette. */
private async compensateFailedRefund(refundId: string, status: 'failed' | 'canceled'): Promise<void> {
const refund = await this.prisma.$transaction(async (db) => {
const { count } = await db.refund.updateMany({
where: { id: refundId, status: { in: ['pending', 'succeeded'] } },
data: { status },
});
if (count !== 1) return null;
const r = await db.refund.findUniqueOrThrow({ where: { id: refundId }, include: { transaction: true, debt: true } });
const t = await db.transaction.update({
where: { id: r.transactionId },
data: { refundedCents: { decrement: r.amountCents } },
});
await db.transaction.update({
where: { id: t.id },
data: { status: t.refundedCents <= 0 ? 'succeeded' : 'partially_refunded' },
});
return r;
});
if (!refund) return;
if (refund.reversedCents > 0) {
const account = await this.prisma.paymentAccount.findUniqueOrThrow({ where: { businessId: refund.transaction.businessId } });
await this.stripe.transfers.create(
{
amount: refund.reversedCents,
currency: refund.transaction.currency,
destination: account.providerAccountId,
metadata: { taptp_refund_id: refund.id, reason: 'refund_failed' },
},
{ idempotencyKey: `taptp-refund-failed-${refund.id}` },
);
}
if (refund.debt) await this.ledger.cancelUnsettled(refund.debt.id);
await this.audit.log({ action: 'refund.failed_compensated', metadata: { refundId: refund.id } });
}
async list(userId: string, transactionId: string): Promise<RefundView[]> {
const tx = await this.getOwnedTransaction(userId, transactionId);
const refunds = await this.prisma.refund.findMany({ where: { transactionId: tx.id }, orderBy: { createdAt: 'desc' } });
return refunds.map((r) => this.toView(r));
}
private async getOwnedTransaction(userId: string, transactionId: string): Promise<Transaction> {
const tx = await this.prisma.transaction.findFirst({ where: { id: transactionId, business: { userId } } });
if (!tx) throw new NotFoundException('Transaction introuvable.');
return tx;
}
private toView(r: Refund): RefundView {
return { id: r.id, transactionId: r.transactionId, amountCents: r.amountCents, reason: r.reason, status: r.status, createdAt: r.createdAt };
}
}
function mapRefundStatus(status: string | null): 'pending' | 'succeeded' | 'failed' | 'canceled' {
switch (status) {
case 'succeeded':
return 'succeeded';
case 'failed':
return 'failed';
case 'canceled':
return 'canceled';
default:
return 'pending'; // pending, requires_action
}
}

View file

@ -0,0 +1,62 @@
import { bucketIndex, currentPeriod, localMidnightToUtc, periodAt } from './periods';
describe('périodes (Europe/Paris)', () => {
it('minuit à Paris en heure d’été = 22h UTC la veille', () => {
expect(localMidnightToUtc(2026, 10, 2).toISOString()).toBe('2026-10-01T22:00:00.000Z');
});
it('minuit à Paris en heure d’hiver = 23h UTC la veille', () => {
expect(localMidnightToUtc(2026, 12, 15).toISOString()).toBe('2026-12-14T23:00:00.000Z');
});
it('jour du changement d’heure (25 octobre 2026) : 25 heures', () => {
const r = currentPeriod('day', new Date('2026-10-25T12:00:00Z'));
expect(r.from.toISOString()).toBe('2026-10-24T22:00:00.000Z');
expect(r.to.toISOString()).toBe('2026-10-25T23:00:00.000Z');
});
it('semaine du lundi au lundi', () => {
// vendredi 2 octobre 2026 → lundi 28 septembre
const r = currentPeriod('week', new Date('2026-10-02T10:00:00Z'));
expect(r.from.toISOString()).toBe('2026-09-27T22:00:00.000Z');
expect(r.to.toISOString()).toBe('2026-10-04T22:00:00.000Z');
expect(r.buckets).toBe(7);
});
it('mois calendaire', () => {
const r = currentPeriod('month', new Date('2026-10-02T10:00:00Z'));
expect(r.from.toISOString()).toBe('2026-09-30T22:00:00.000Z');
expect(r.to.toISOString()).toBe('2026-10-31T23:00:00.000Z');
expect(r.buckets).toBe(31);
});
it('une vente à 23h30 heure de Paris tombe dans la tranche 23 du jour', () => {
expect(bucketIndex('day', new Date('2026-10-02T21:30:00Z'))).toBe(23);
});
it('le dimanche est la 7e tranche de la semaine', () => {
expect(bucketIndex('week', new Date('2026-10-04T10:00:00Z'))).toBe(6);
});
it('période précédente : hier, semaine dernière, mois dernier', () => {
const now = new Date('2026-10-02T10:00:00Z');
expect(periodAt('day', now, -1).from.toISOString()).toBe('2026-09-30T22:00:00.000Z');
expect(periodAt('week', now, -1).from.toISOString()).toBe('2026-09-20T22:00:00.000Z');
const prevMonth = periodAt('month', now, -1);
expect(prevMonth.from.toISOString()).toBe('2026-08-31T22:00:00.000Z');
expect(prevMonth.buckets).toBe(30);
});
it('passage de janvier à décembre de l’année précédente', () => {
expect(periodAt('month', new Date('2027-01-15T10:00:00Z'), -1).from.toISOString()).toBe('2026-11-30T23:00:00.000Z');
});
it('30 derniers jours : fenêtre glissante qui finit ce soir, tranches par jour', () => {
const now = new Date('2026-10-02T10:00:00Z');
const r = periodAt('last30', now, 0);
expect(r.from.toISOString()).toBe('2026-09-02T22:00:00.000Z');
expect(r.to.toISOString()).toBe('2026-10-02T22:00:00.000Z');
expect(bucketIndex('last30', new Date('2026-10-02T08:00:00Z'), undefined, r.from)).toBe(29);
expect(periodAt('last30', now, -1).to.toISOString()).toBe(r.from.toISOString());
});
});

View file

@ -0,0 +1,132 @@
/** Calendaires (jour, semaine du lundi, mois) ou glissantes (7 / 30 derniers jours, aujourd'hui inclus). */
export type StatsPeriod = 'day' | 'week' | 'month' | 'last7' | 'last30';
const ROLLING_DAYS: Partial<Record<StatsPeriod, number>> = { last7: 7, last30: 30 };
export const TIMEZONE = 'Europe/Paris';
interface LocalParts {
year: number;
month: number; // 1-12
day: number;
hour: number;
weekday: number; // 1 = lundi … 7 = dimanche
}
const WEEKDAYS: Record<string, number> = { Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6, Sun: 7 };
/** Date/heure locale (fuseau donné) d'un instant. */
export function localParts(date: Date, timeZone = TIMEZONE): LocalParts {
const parts = new Intl.DateTimeFormat('en-US', {
timeZone,
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
hourCycle: 'h23',
weekday: 'short',
}).formatToParts(date);
const get = (type: string) => parts.find((p) => p.type === type)!.value;
return {
year: Number(get('year')),
month: Number(get('month')),
day: Number(get('day')),
hour: Number(get('hour')),
weekday: WEEKDAYS[get('weekday')],
};
}
/** Instant UTC correspondant à minuit local du jour donné (gère l'heure d'été/hiver). */
export function localMidnightToUtc(year: number, month: number, day: number, timeZone = TIMEZONE): Date {
const guess = Date.UTC(year, month - 1, day);
// Décalage du fuseau à cet instant, puis correction (deux passes suffisent autour des changements d'heure).
let utc = guess - offsetMs(new Date(guess), timeZone);
utc = guess - offsetMs(new Date(utc), timeZone);
return new Date(utc);
}
function offsetMs(date: Date, timeZone: string): number {
const p = new Intl.DateTimeFormat('en-US', {
timeZone,
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hourCycle: 'h23',
}).formatToParts(date);
const get = (type: string) => Number(p.find((x) => x.type === type)!.value);
const asUtc = Date.UTC(get('year'), get('month') - 1, get('day'), get('hour'), get('minute'), get('second'));
return asUtc - Math.floor(date.getTime() / 1000) * 1000;
}
export interface PeriodRange {
from: Date;
to: Date;
/** Nombre de tranches du graphique : 24 heures (jour), 7 jours (semaine), N jours (mois). */
buckets: number;
}
/** Période en cours à Paris : aujourd'hui, semaine du lundi, mois calendaire. */
export function currentPeriod(period: StatsPeriod, now: Date, timeZone = TIMEZONE): PeriodRange {
const t = localParts(now, timeZone);
if (period === 'day') {
const from = localMidnightToUtc(t.year, t.month, t.day, timeZone);
const next = new Date(Date.UTC(t.year, t.month - 1, t.day + 1));
return { from, to: localMidnightToUtc(next.getUTCFullYear(), next.getUTCMonth() + 1, next.getUTCDate(), timeZone), buckets: 24 };
}
if (period === 'week') {
const monday = new Date(Date.UTC(t.year, t.month - 1, t.day - (t.weekday - 1)));
const nextMonday = new Date(monday.getTime() + 7 * 86_400_000);
return {
from: localMidnightToUtc(monday.getUTCFullYear(), monday.getUTCMonth() + 1, monday.getUTCDate(), timeZone),
to: localMidnightToUtc(nextMonday.getUTCFullYear(), nextMonday.getUTCMonth() + 1, nextMonday.getUTCDate(), timeZone),
buckets: 7,
};
}
const daysInMonth = new Date(Date.UTC(t.year, t.month, 0)).getUTCDate();
const nextMonth = new Date(Date.UTC(t.year, t.month, 1));
return {
from: localMidnightToUtc(t.year, t.month, 1, timeZone),
to: localMidnightToUtc(nextMonth.getUTCFullYear(), nextMonth.getUTCMonth() + 1, 1, timeZone),
buckets: daysInMonth,
};
}
/**
* Période décalée de `offset` unités (0 = en cours, -1 = précédente…), à l'heure de Paris.
* On part de midi UTC du jour local : aucun changement d'heure ne fait basculer de jour.
*/
export function periodAt(period: StatsPeriod, now: Date, offset: number, timeZone = TIMEZONE): PeriodRange {
const t = localParts(now, timeZone);
const rolling = ROLLING_DAYS[period];
if (rolling) {
// Fenêtre de N jours se terminant aujourd'hui (décalée de N jours par unité d'offset).
const end = new Date(Date.UTC(t.year, t.month - 1, t.day + 1 + offset * rolling));
const start = new Date(Date.UTC(t.year, t.month - 1, t.day + 1 + offset * rolling - rolling));
return {
from: localMidnightToUtc(start.getUTCFullYear(), start.getUTCMonth() + 1, start.getUTCDate(), timeZone),
to: localMidnightToUtc(end.getUTCFullYear(), end.getUTCMonth() + 1, end.getUTCDate(), timeZone),
buckets: rolling,
};
}
const ref =
period === 'month'
? new Date(Date.UTC(t.year, t.month - 1 + offset, 1, 12))
: new Date(Date.UTC(t.year, t.month - 1, t.day + offset * (period === 'week' ? 7 : 1), 12));
return currentPeriod(period, ref, timeZone);
}
/** Index de tranche (0-based) d'une vente dans la période. */
export function bucketIndex(period: StatsPeriod, date: Date, timeZone = TIMEZONE, from?: Date): number {
const p = localParts(date, timeZone);
if (period === 'day') return p.hour;
if (ROLLING_DAYS[period]) {
// Nombre de jours (calendaires, heure de Paris) depuis le début de la fenêtre.
const f = localParts(from!, timeZone);
return Math.round((Date.UTC(p.year, p.month - 1, p.day) - Date.UTC(f.year, f.month - 1, f.day)) / 86_400_000);
}
if (period === 'week') return p.weekday - 1;
return p.day - 1;
}

View file

@ -0,0 +1,28 @@
import { Controller, Get, Query } from '@nestjs/common';
import { Type } from 'class-transformer';
import { IsIn, IsInt, Max, Min } from 'class-validator';
import { AuthUser, CurrentUser } from '../common/current-user.decorator';
import { StatsPeriod } from './periods';
import { StatsService } from './stats.service';
class StatsQueryDto {
@IsIn(['day', 'week', 'month', 'last7', 'last30'])
period: StatsPeriod = 'day';
/** 0 = période en cours, -1 = précédente… (pas de période future). */
@Type(() => Number)
@IsInt()
@Min(-36)
@Max(0)
offset: number = 0;
}
@Controller('stats')
export class StatsController {
constructor(private readonly stats: StatsService) {}
@Get()
get(@CurrentUser() user: AuthUser, @Query() query: StatsQueryDto) {
return this.stats.get(user.id, query.period, query.offset);
}
}

View file

@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { StatsController } from './stats.controller';
import { StatsService } from './stats.service';
@Module({
controllers: [StatsController],
providers: [StatsService],
})
export class StatsModule {}

View file

@ -0,0 +1,100 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { bucketIndex, periodAt, StatsPeriod, TIMEZONE } from './periods';
/** Ventes encaissées (y compris celles remboursées ensuite). */
const COLLECTED_STATUSES = ['succeeded', 'partially_refunded', 'refunded'];
export interface StatsView {
period: StatsPeriod;
/** 0 = période en cours, -1 = précédente… */
offset: number;
timezone: string;
from: Date;
to: Date;
/** Chiffre d'affaires encaissé. */
grossCents: number;
refundedCents: number;
/** Frais de gestion TapTP (frais Stripe + part TapTP). */
feesCents: number;
/** Détail des frais : part TapTP et frais du partenaire de paiement (Stripe). */
platformFeeCents: number;
providerFeeCents: number;
/** Montant net pour le pro : ventes − frais − remboursements. */
netCents: number;
transactionCount: number;
averageCents: number;
/** CA de la période précédente (pour « +12 % vs hier »). */
previousGrossCents: number;
/** Évolution en %, arrondie ; null si la période précédente est vide. */
deltaPercent: number | null;
/** CA par heure (jour), par jour (semaine, mois). */
series: { index: number; grossCents: number; count: number }[];
}
@Injectable()
export class StatsService {
constructor(private readonly prisma: PrismaService) {}
async get(userId: string, period: StatsPeriod, offset = 0, now = new Date()): Promise<StatsView> {
// Sans entreprise renseignée, il n'y a encore aucune vente : statistiques à zéro (pas une erreur).
const business = await this.prisma.business.findUnique({ where: { userId }, select: { id: true } });
const businessId = business?.id ?? '__aucune_entreprise__';
const range = periodAt(period, now, offset);
const previous = periodAt(period, now, offset - 1);
// Volume d'un pro sur un mois : quelques milliers de lignes au plus, agrégées en mémoire.
const [rows, prev] = await Promise.all([
this.prisma.transaction.findMany({
where: { businessId, status: { in: COLLECTED_STATUSES }, succeededAt: { gte: range.from, lt: range.to } },
select: { amountCents: true, refundedCents: true, providerFeeCents: true, platformFeeCents: true, netCents: true, succeededAt: true },
}),
this.prisma.transaction.aggregate({
where: { businessId, status: { in: COLLECTED_STATUSES }, succeededAt: { gte: previous.from, lt: previous.to } },
_sum: { amountCents: true },
}),
]);
const series = Array.from({ length: range.buckets }, (_, index) => ({ index, grossCents: 0, count: 0 }));
let gross = 0;
let refunded = 0;
let fees = 0;
let platformFees = 0;
let providerFees = 0;
let net = 0;
for (const r of rows) {
gross += r.amountCents;
refunded += r.refundedCents;
fees += (r.providerFeeCents ?? 0) + (r.platformFeeCents ?? 0);
platformFees += r.platformFeeCents ?? 0;
providerFees += r.providerFeeCents ?? 0;
net += (r.netCents ?? 0) - r.refundedCents;
const bucket = series[bucketIndex(period, r.succeededAt!, TIMEZONE, range.from)];
if (bucket) {
bucket.grossCents += r.amountCents;
bucket.count += 1;
}
}
const previousGross = prev._sum.amountCents ?? 0;
return {
period,
offset,
timezone: TIMEZONE,
from: range.from,
to: range.to,
grossCents: gross,
refundedCents: refunded,
feesCents: fees,
platformFeeCents: platformFees,
providerFeeCents: providerFees,
netCents: net,
transactionCount: rows.length,
averageCents: rows.length ? Math.round(gross / rows.length) : 0,
previousGrossCents: previousGross,
deltaPercent: previousGross > 0 ? Math.round(((gross - previousGross) / previousGross) * 100) : null,
series,
};
}
}

View file

@ -0,0 +1,24 @@
import { Global, Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Stripe from 'stripe';
import { Env } from '../config/env';
export const STRIPE = Symbol('STRIPE');
@Global()
@Module({
providers: [
{
provide: STRIPE,
inject: [ConfigService],
useFactory: (config: ConfigService<Env, true>) =>
new Stripe(config.get('STRIPE_SECRET_KEY', { infer: true }), {
maxNetworkRetries: 2, // sûr : les écritures passent une clé d'idempotence
timeout: 20_000,
appInfo: { name: 'TapTP' },
}),
},
],
exports: [STRIPE],
})
export class StripeModule {}

View file

@ -0,0 +1,19 @@
import { addOneMonth } from './period';
describe('addOneMonth', () => {
it('mois standard', () => {
expect(addOneMonth(new Date('2026-10-02T09:00:00Z')).toISOString()).toBe('2026-11-02T09:00:00.000Z');
});
it('31 janvier → fin février (année non bissextile)', () => {
expect(addOneMonth(new Date('2027-01-31T12:00:00Z')).toISOString()).toBe('2027-02-28T12:00:00.000Z');
});
it('31 janvier → 29 février (année bissextile)', () => {
expect(addOneMonth(new Date('2028-01-31T12:00:00Z')).toISOString()).toBe('2028-02-29T12:00:00.000Z');
});
it('décembre → janvier de l’année suivante', () => {
expect(addOneMonth(new Date('2026-12-15T00:00:00Z')).toISOString()).toBe('2027-01-15T00:00:00.000Z');
});
});

View file

@ -0,0 +1,10 @@
/** Ajoute un mois calendaire (UTC). Le 31 janvier donne le 28/29 février, jamais le 3 mars. */
export function addOneMonth(date: Date): Date {
const y = date.getUTCFullYear();
const m = date.getUTCMonth();
const lastDayOfNextMonth = new Date(Date.UTC(y, m + 2, 0)).getUTCDate();
const day = Math.min(date.getUTCDate(), lastDayOfNextMonth);
return new Date(
Date.UTC(y, m + 1, day, date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()),
);
}

View file

@ -0,0 +1,25 @@
import { Controller, Delete, Get, HttpCode, HttpStatus, Post, Req } from '@nestjs/common';
import type { Request } from 'express';
import { AuthUser, CurrentUser } from '../common/current-user.decorator';
import { SubscriptionsService } from './subscriptions.service';
@Controller('subscription')
export class SubscriptionsController {
constructor(private readonly subscriptions: SubscriptionsService) {}
@Get()
get(@CurrentUser() user: AuthUser) {
return this.subscriptions.get(user.id);
}
@Post()
@HttpCode(HttpStatus.OK)
subscribe(@CurrentUser() user: AuthUser, @Req() req: Request) {
return this.subscriptions.subscribe(user.id, req.ip);
}
@Delete()
cancel(@CurrentUser() user: AuthUser, @Req() req: Request) {
return this.subscriptions.cancel(user.id, req.ip);
}
}

View file

@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { SubscriptionsController } from './subscriptions.controller';
import { SubscriptionsService } from './subscriptions.service';
@Module({
controllers: [SubscriptionsController],
providers: [SubscriptionsService],
})
export class SubscriptionsModule {}

View file

@ -0,0 +1,203 @@
import { ConflictException, Injectable, Logger, NotFoundException } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { Subscription } from '@prisma/client';
import { AuditService } from '../audit/audit.service';
import { LedgerService } from '../ledger/ledger.service';
import { PrismaService } from '../prisma/prisma.service';
import { addOneMonth } from './period';
const LIVE_STATUSES = ['active', 'past_due'];
export interface SubscriptionView {
/** Prix mensuel de TapTP Pro (configurable dans fee_plans). */
priceCents: number;
subscription: {
status: string;
currentPeriodStart: Date;
currentPeriodEnd: Date;
cancelAtPeriodEnd: boolean;
} | null;
/** Total encore dû (abonnement + frais de remboursements), retenu sur les prochaines ventes. */
outstandingCents: number;
/** Frais TapTP par vente sans abonnement (pour le comparatif et le simulateur). */
perSaleFeeCents: number;
/** Période en cours : ventes réalisées sous TapTP Pro et économie nette (ventes × frais évités − abonnement). */
periodSalesCount: number;
periodSavingsCents: number;
/** Prélèvements mensuels, du plus récent au plus ancien. */
charges: { periodStart: Date; amountCents: number; settledCents: number; status: string; settledAt: Date | null }[];
}
/**
* Abonnement TapTP Pro (10 €/mois) : supprime la part fixe de 2 € par vente.
* Il n'est pas payé par carte : chaque mois crée une dette retenue sur les reversements des ventes suivantes.
*/
@Injectable()
export class SubscriptionsService {
private readonly logger = new Logger(SubscriptionsService.name);
constructor(
private readonly prisma: PrismaService,
private readonly ledger: LedgerService,
private readonly audit: AuditService,
) {}
async get(userId: string): Promise<SubscriptionView> {
const businessId = await this.getBusinessId(userId);
const [sub, priceCents, outstandingCents, defaultPlan, charges] = await Promise.all([
this.findLiveOrRecent(businessId),
this.getPriceCents(),
this.ledger.outstanding(businessId),
this.prisma.feePlan.findFirst({ where: { code: 'default', active: true } }),
this.prisma.merchantDebt.findMany({
where: { businessId, kind: 'subscription' },
orderBy: { periodStart: 'desc' },
take: 12,
select: { periodStart: true, amountCents: true, settledCents: true, status: true, settledAt: true },
}),
]);
const perSaleFeeCents = defaultPlan?.perTransactionCents ?? 0;
const periodSalesCount = sub
? await this.prisma.transaction.count({
where: { businessId, feePlanCode: 'subscriber', succeededAt: { gte: sub.currentPeriodStart, lt: sub.currentPeriodEnd } },
})
: 0;
return {
...this.toView(sub, priceCents, outstandingCents),
perSaleFeeCents,
periodSalesCount,
periodSavingsCents: sub ? periodSalesCount * perSaleFeeCents - sub.priceCents : 0,
charges: charges.map((c) => ({ ...c, periodStart: c.periodStart! })),
};
}
async subscribe(userId: string, ip?: string): Promise<SubscriptionView> {
const businessId = await this.getBusinessId(userId);
const priceCents = await this.getPriceCents();
await this.prisma.$transaction(async (db) => {
// Verrou sur l'entreprise : un double appui ne crée pas deux abonnements.
await db.$queryRaw`SELECT id FROM businesses WHERE id = ${businessId} FOR UPDATE`;
const live = await db.subscription.findFirst({ where: { businessId, status: { in: LIVE_STATUSES } } });
if (live?.status === 'active') {
if (live.cancelAtPeriodEnd) await db.subscription.update({ where: { id: live.id }, data: { cancelAtPeriodEnd: false } });
return;
}
if (live?.status === 'past_due') throw new ConflictException("Réglez d'abord le mois impayé : il sera retenu sur vos prochaines ventes.");
const start = new Date();
const sub = await db.subscription.create({
data: { businessId, priceCents, status: 'active', currentPeriodStart: start, currentPeriodEnd: addOneMonth(start) },
});
await this.ledger.addDebt({ businessId, kind: 'subscription', amountCents: priceCents, subscriptionId: sub.id, periodStart: start }, db);
});
await this.audit.log({ userId, action: 'subscription.subscribed', ip });
return this.get(userId);
}
/** Résiliation en fin de période : les avantages restent actifs jusqu'à l'échéance. */
async cancel(userId: string, ip?: string): Promise<SubscriptionView> {
const businessId = await this.getBusinessId(userId);
const sub = await this.findLive(businessId);
if (!sub) throw new NotFoundException('Aucun abonnement en cours.');
await this.prisma.subscription.update({ where: { id: sub.id }, data: { cancelAtPeriodEnd: true } });
await this.audit.log({ userId, action: 'subscription.cancel_requested', ip });
return this.get(userId);
}
/**
* Échéances (toutes les heures). Sûr en cas de plusieurs instances : mises à jour conditionnelles
* et dette unique par (abonnement, période).
*/
@Cron(CronExpression.EVERY_HOUR)
async processRenewals(now = new Date()): Promise<void> {
const due = await this.prisma.subscription.findMany({
where: { status: { in: LIVE_STATUSES }, currentPeriodEnd: { lte: now } },
take: 500,
});
for (const sub of due) {
try {
await this.renewOne(sub, now);
} catch (err) {
this.logger.error(`Échéance de l'abonnement ${sub.id} en échec : ${(err as Error).message}`);
}
}
}
private async renewOne(sub: Subscription, now: Date): Promise<void> {
if (sub.cancelAtPeriodEnd) {
await this.prisma.subscription.updateMany({
where: { id: sub.id, currentPeriodEnd: sub.currentPeriodEnd },
data: { status: 'canceled', canceledAt: now },
});
return;
}
const unpaid = await this.prisma.merchantDebt.count({ where: { subscriptionId: sub.id, status: 'open' } });
if (unpaid > 0) {
// Mois précédent pas encore retenu : plus d'avantages, pas de nouveau mois facturé.
await this.prisma.subscription.updateMany({
where: { id: sub.id, currentPeriodEnd: sub.currentPeriodEnd },
data: { status: 'past_due' },
});
return;
}
const priceCents = await this.getPriceCents();
await this.prisma.$transaction(async (db) => {
const start = sub.currentPeriodEnd;
const { count } = await db.subscription.updateMany({
where: { id: sub.id, currentPeriodEnd: sub.currentPeriodEnd },
data: { status: 'active', priceCents, currentPeriodStart: start, currentPeriodEnd: addOneMonth(start) },
});
if (count !== 1) return; // déjà renouvelé par une autre instance
await this.ledger.addDebt(
{ businessId: sub.businessId, kind: 'subscription', amountCents: priceCents, subscriptionId: sub.id, periodStart: start },
db,
);
});
}
/** Abonnement en cours, ou résilié dont la période n'est pas finie (pour afficher « actif jusqu'au… »). */
private findLiveOrRecent(businessId: string) {
return this.prisma.subscription.findFirst({
where: { businessId, status: { in: LIVE_STATUSES } },
orderBy: { createdAt: 'desc' },
});
}
private findLive(businessId: string) {
return this.prisma.subscription.findFirst({
where: { businessId, status: { in: LIVE_STATUSES } },
orderBy: { createdAt: 'desc' },
});
}
private async getPriceCents(): Promise<number> {
const plan = await this.prisma.feePlan.findFirst({ where: { code: 'subscriber', active: true } });
if (!plan || plan.monthlyPriceCents <= 0) throw new Error('Plan « subscriber » absent ou sans prix : lancer le seed.');
return plan.monthlyPriceCents;
}
private async getBusinessId(userId: string): Promise<string> {
const business = await this.prisma.business.findUnique({ where: { userId }, select: { id: true } });
if (!business) throw new NotFoundException("Renseignez d'abord les informations de votre entreprise.");
return business.id;
}
private toView(sub: Subscription | null, priceCents: number, outstandingCents: number) {
return {
priceCents,
subscription: sub
? {
status: sub.status,
currentPeriodStart: sub.currentPeriodStart,
currentPeriodEnd: sub.currentPeriodEnd,
cancelAtPeriodEnd: sub.cancelAtPeriodEnd,
}
: null,
outstandingCents,
};
}
}

View file

@ -0,0 +1,22 @@
import { Controller, Headers, HttpCode, HttpStatus, Post, Req } from '@nestjs/common';
import type { RawBodyRequest } from '@nestjs/common';
import { SkipThrottle } from '@nestjs/throttler';
import type { Request } from 'express';
import { Public } from '../common/public.decorator';
import { WebhooksService } from './webhooks.service';
/** Pas d'authentification par jeton : l'authenticité est garantie par la signature Stripe. */
@Controller('webhooks')
export class WebhooksController {
constructor(private readonly webhooks: WebhooksService) {}
@Public()
@SkipThrottle()
@Post('stripe')
@HttpCode(HttpStatus.OK)
async stripe(@Req() req: RawBodyRequest<Request>, @Headers('stripe-signature') signature?: string) {
const event = this.webhooks.verify(req.rawBody, signature);
await this.webhooks.handle(event);
return { received: true };
}
}

View file

@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { PaymentAccountModule } from '../payment-account/payment-account.module';
import { PaymentsModule } from '../payments/payments.module';
import { PayoutsModule } from '../payouts/payouts.module';
import { RefundsModule } from '../refunds/refunds.module';
import { WebhooksController } from './webhooks.controller';
import { WebhooksService } from './webhooks.service';
@Module({
imports: [PaymentAccountModule, PaymentsModule, RefundsModule, PayoutsModule],
controllers: [WebhooksController],
providers: [WebhooksService],
})
export class WebhooksModule {}

View file

@ -0,0 +1,167 @@
import { BadRequestException, Inject, Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Prisma } from '@prisma/client';
import Stripe from 'stripe';
import { Env } from '../config/env';
import { PaymentAccountService } from '../payment-account/payment-account.service';
import { PaymentsService } from '../payments/payments.service';
import { PayoutsService } from '../payouts/payouts.service';
import { PrismaService } from '../prisma/prisma.service';
import { RefundsService } from '../refunds/refunds.service';
import { STRIPE } from '../stripe/stripe.module';
/** Forme commune, après vérification, aux événements v1 (complets) et v2 (légers). */
interface VerifiedEvent {
id: string;
type: string;
/** Objet concerné : complet pour un événement v1, simple référence pour un événement v2. */
object: { id: string } | null;
/** Compte connecté à l'origine de l'événement (événements Connect v1), sinon null. */
account: string | null;
payload: Prisma.InputJsonValue;
}
type Handler = (event: VerifiedEvent) => Promise<void>;
@Injectable()
export class WebhooksService {
private readonly logger = new Logger(WebhooksService.name);
private readonly secrets: string[];
private readonly handlers: Record<string, Handler>;
constructor(
private readonly prisma: PrismaService,
private readonly paymentAccounts: PaymentAccountService,
private readonly payments: PaymentsService,
private readonly refunds: RefundsService,
private readonly payouts: PayoutsService,
@Inject(STRIPE) private readonly stripe: Stripe,
config: ConfigService<Env, true>,
) {
// Plusieurs destinations possibles en production ; une seule avec la Stripe CLI.
this.secrets = [config.get('STRIPE_WEBHOOK_SECRET', { infer: true }), config.get('STRIPE_CONNECT_WEBHOOK_SECRET', { infer: true })]
.filter((s): s is string => !!s);
const refreshAccount: Handler = async (event) => {
if (event.object) await this.paymentAccounts.refreshByProviderId(event.object.id);
};
this.handlers = {
// Comptes connectés v2 : on relit toujours le compte chez Stripe (ordre des événements non garanti).
'v2.core.account.updated': refreshAccount,
'v2.core.account[requirements].updated': refreshAccount,
'v2.core.account[configuration.merchant].capability_status_updated': refreshAccount,
'v2.core.account[configuration.recipient].capability_status_updated': refreshAccount,
// Paiements : le statut est toujours relu chez Stripe dans le service.
'payment_intent.succeeded': async (event) => {
if (event.object) await this.payments.handlePaymentSucceeded(event.object.id);
},
'payment_intent.payment_failed': async (event) => {
if (event.object) await this.payments.handlePaymentFailed(event.object.id);
},
'payment_intent.canceled': async (event) => {
if (event.object) await this.payments.handlePaymentCanceled(event.object.id);
},
// Remboursements : statut relu chez Stripe ; un échec est compensé (reprise rendue au pro).
'refund.updated': async (event) => {
if (event.object) await this.refunds.syncFromStripe(event.object.id);
},
'refund.failed': async (event) => {
if (event.object) await this.refunds.syncFromStripe(event.object.id);
},
// Versements vers l'IBAN du pro (événements de ses comptes connectés).
...Object.fromEntries(
['payout.created', 'payout.updated', 'payout.paid', 'payout.failed', 'payout.canceled'].map((type) => [
type,
async (event: VerifiedEvent) => {
if (event.object) await this.payouts.syncFromStripe(event.object.id, event.account);
},
]),
),
};
}
/** Vérifie la signature (avec chacun des secrets) et normalise l'événement. */
verify(rawBody: Buffer | undefined, signature: string | undefined): VerifiedEvent {
if (!rawBody || !signature) throw new BadRequestException('Signature manquante.');
if (this.secrets.length === 0) {
this.logger.error('Aucun secret webhook configuré : événement rejeté.');
throw new BadRequestException('Webhook non configuré.');
}
const isThin = this.peekObjectType(rawBody) === 'v2.core.event';
for (const secret of this.secrets) {
try {
if (isThin) {
const n = this.stripe.parseEventNotification(rawBody, signature, secret);
const related = 'related_object' in n ? n.related_object : null;
const relatedId = related && 'id' in related && typeof related.id === 'string' ? related.id : null;
return {
id: n.id,
type: n.type,
object: relatedId ? { id: relatedId } : null,
account: null,
payload: { id: n.id, type: n.type, created: n.created, livemode: n.livemode, related_object_id: relatedId },
};
}
const e = this.stripe.webhooks.constructEvent(rawBody, signature, secret);
return {
id: e.id,
type: e.type,
object: e.data.object as { id: string },
account: e.account ?? null,
payload: e as unknown as Prisma.InputJsonValue,
};
} catch {
// essai du secret suivant
}
}
throw new BadRequestException('Signature invalide.');
}
/**
* Enregistre puis traite l'événement une seule fois.
* En cas d'erreur, l'exception remonte : Stripe renverra l'événement plus tard.
*/
async handle(event: VerifiedEvent): Promise<void> {
const stored = await this.store(event);
if (stored.processedAt) return; // déjà traité (Stripe peut renvoyer un événement)
const handler = this.handlers[event.type];
try {
if (handler) await handler(event);
await this.prisma.webhookEvent.update({
where: { id: stored.id },
data: { processedAt: new Date(), error: null, attempts: { increment: 1 } },
});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
this.logger.error(`Échec du traitement de ${event.type} (${event.id}) : ${message}`);
await this.prisma.webhookEvent.update({
where: { id: stored.id },
data: { error: message.slice(0, 5000), attempts: { increment: 1 } },
});
throw err;
}
}
private peekObjectType(rawBody: Buffer): string | undefined {
try {
return (JSON.parse(rawBody.toString('utf8')) as { object?: string }).object;
} catch {
throw new BadRequestException('Corps de requête invalide.');
}
}
private async store(event: VerifiedEvent) {
try {
return await this.prisma.webhookEvent.create({
data: { providerEventId: event.id, type: event.type, payload: event.payload },
});
} catch (err) {
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
return this.prisma.webhookEvent.findUniqueOrThrow({ where: { providerEventId: event.id } });
}
throw err;
}
}
}

24
backend/tsconfig.json Normal file
View file

@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "ES2022",
"lib": [
"ES2022"
],
"declaration": false,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"esModuleInterop": true,
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"strict": true,
"strictPropertyInitialization": false,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"src/**/*.ts"
]
}

55
docs/CADRAGE.md Normal file
View file

@ -0,0 +1,55 @@
Statut : brouillon
# Cadrage MonTPE (nom produit : TapTP)
> Brouillon rédigé à partir de LOCAL_DEV.md et de docs/DECISIONS.md. Tout ce qui est marqué « à confirmer » n'a pas pu être vérifié. Ce dossier n'est pas un dépôt git (aucun historique disponible). Pour valider : relire, corriger, puis remplacer la première ligne par « Statut : validé (AAAA-MM-JJ) ».
## 1. Contexte et objectif
- Produit propre à Tony : encaissement par carte sur téléphone (Tap to Pay iOS/Android) pour des professionnels, avec Stripe Terminal et Stripe Connect.
- Objectif : permettre à un commerçant ou une TPE d'encaisser sans terminal dédié, avec reversement des fonds et frais transparents.
- Objectif commercial et calendrier : à confirmer.
## 2. Utilisateurs / cibles
- Professionnels (commerçants, TPE, indépendants) qui encaissent sur mobile.
- Clients payeurs par carte sans contact.
- Tony (plateforme) : tableau de bord web.
## 3. Périmètre
Inclus (constaté dans les documents) :
- API Node.js/NestJS + Prisma + MySQL (`backend/`), application mobile React Native/Expo (`mobile/`), tableau de bord web (`web/`).
- Comptes connectés Stripe Accounts v2 avec onboarding intégré (KYC chez Stripe, aucune donnée d'identité stockée).
- Paiement `card_present` avec `on_behalf_of`, statut confirmé uniquement par webhook, transfert du net au professionnel.
- Modèle de frais : frais Stripe réels + 2,00 € par transaction ; abonnement à 10 €/mois qui supprime les 2 €.
- Remboursements supportés par le professionnel, registre de dettes retenues sur les ventes suivantes.
Hors périmètre (à confirmer) :
- Autres moyens de paiement que la carte présente.
- Fonctions de caisse (catalogue, stock, facturation).
## 4. Contraintes
- Stripe impose Accounts v2 et `losses_collector = stripe` pour une plateforme française.
- Tap to Pay : prérequis Apple et Google, version de test Android via EAS.
- Juridique et réglementaire : CGU, absence d'agrément (risque d'activité d'intermédiaire de paiement), TVA sur les frais : à valider avant la mise en production.
- RGPD : voir skill rgpd-legal. Secrets Stripe et `.env` hors dépôt.
## 5. Livrables et critères d'acceptation (à confirmer)
- Premier vrai paiement Tap to Pay validé de bout en bout (frais réels vérifiés).
- Webhooks Stripe fiables (succès, échec, litige, remboursement, payout) et tests d'API (`smoke.mjs`) au vert.
- Onboarding professionnel complet, remboursement avec mot de passe, abonnement mensuel et dettes testés.
- Documents légaux validés par un professionnel.
## 6. Risques et hypothèses
- Qualification juridique de l'activité (agrément, responsabilité en cas de litige ou de dette impayée).
- Dépendance à Stripe (changements d'API, frais de gestion du risque non encore vérifiés).
- Équilibre économique du modèle de frais (2 € par transaction, abonnement 10 €).
## 7. Jalons et estimation (à définir)
1. Validation du flux de fonds en mode test : fait le 02/10/2026 avec un lecteur simulé.
2. Premier paiement réel Tap to Pay : date à confirmer.
3. Validation juridique et TVA, puis mise en production : date à confirmer.
## 8. À faire valider par Tony
- Modèle de frais et tarif de l'abonnement.
- Stratégie juridique (agrément, CGU).
- Objectifs, dates cibles et public prioritaire.
- Initialiser un dépôt git sur Forgejo pour ce projet.

47
docs/DECISIONS.md Normal file
View file

@ -0,0 +1,47 @@
# TapTP — Décisions d'architecture
## Stack
- Backend : Node.js 24 + TypeScript, NestJS, Prisma, MySQL (hébergé sur le serveur, pas de Docker).
- Mobile : React Native + TypeScript.
## PSP
- Stripe Terminal (Tap to Pay iOS/Android) + Stripe Connect.
- SDK mobile : `@stripe/stripe-terminal-react-native`.
## Comptes connectés — Stripe Accounts v2 (imposé par Stripe, vérifié en mode test le 2026-10-02)
- API v1 refusée pour les nouvelles plateformes ; plateforme française → comptes v2 uniquement.
- `dashboard = none`, `fees_collector = application` (TapTP paie Stripe),
`losses_collector = stripe` (Stripe porte litiges et soldes négatifs — imposé).
- Conséquence : `requirements_collector = stripe` → KYC, documents, IBAN et CGU Stripe sont collectés
par l'**onboarding Stripe intégré** dans l'app (Connect embedded components, `POST /payment-account/onboarding-session`).
- TapTP ne reçoit ni ne stocke aucune donnée d'identité, document ou IBAN (seulement les 4 derniers chiffres).
- Identité FR uniquement via « account tokens » ; le serveur n'y met que email, nom affiché et type d'entité.
- Configurations : `merchant` (card_payments, payouts) + `recipient` (stripe_transfers, pour reverser le net).
- Événements v2 légers `v2.core.account*` → le backend relit le compte chez Stripe.
## Modèle de frais
- Frais de gestion TapTP = frais Stripe réels + 2,00 € par transaction (montant fixe configurable).
- Abonnement mensuel à 10 €/mois (configurable, `fee_plans.monthly_price_cents`) : supprime les 2 € par transaction.
Les frais Stripe réels restent refacturés. Rentable pour le pro dès 5 transactions/mois.
- Abonnement prélevé sur les ventes du commerçant (pas d'achat in-app).
## Flux de fonds (validé en mode test le 2026-10-02 avec un lecteur simulé)
- Paiement créé sur la plateforme avec `on_behalf_of = compte connecté` (le commerçant est le marchand affiché),
`allowed_payment_method_types: ['card_present']` (`payment_method_types` n'existe plus dans l'API 2026-09-30).
- Statut confirmé uniquement par webhook ; l'app n'est jamais crue sur parole.
- Frais Stripe lus dans la balance transaction (ils varient selon la carte : 1,55 € sur 50 € avec une carte test hors EEE)
+ frais Tap to Pay configurables (`fee_plans.tap_to_pay_fee_cents`, 0,10 € par défaut) : à vérifier sur le premier vrai paiement Tap to Pay.
- Après `payment_intent.succeeded` : lecture du coût Stripe réel (balance transaction), puis transfert vers le compte connecté de :
montant − frais Stripe − 2 € (ou 0 € si abonné), lié à la charge via `source_transaction`.
- Remboursements (décision 2026-10-02) : le pro supporte le remboursement ET les frais de la vente.
Le montant est repris sur le transfert de la vente (transfer reversal) ; le reste (frais) devient une dette.
Mot de passe exigé pour chaque remboursement. Remboursement échoué → reprise rendue au pro, dette annulée.
- Registre `merchant_debts` : abonnement + frais de remboursements, retenus automatiquement (dette la plus ancienne
d'abord, verrous SQL) sur le reversement des ventes suivantes.
- Abonnement TapTP Pro : une dette de 10 € par mois (tâche horaire de renouvellement). Mois précédent non réglé à
l'échéance → `past_due` (plus de réduction, pas de nouveau mois) ; résiliation en fin de période.
## Points ouverts
- Validation juridique (CGU, absence d'agrément) et TVA sur les frais : avant mise en production.
- Valider en mode test (étape paiements) : Tap to Pay + `on_behalf_of` + transfert vers un compte v2.
- Vérifier s'il existe des frais Stripe liés à la gestion du risque par Stripe (losses_collector = stripe).

57
docs/DEMANDE_STRIPE.md Normal file
View file

@ -0,0 +1,57 @@
# Demande à Stripe — plateforme TapTP en marque blanche
À envoyer depuis le Dashboard : **Aide (?) → Contacter le support → Connect**, ou à l'équipe commerciale : https://stripe.com/fr/contact/sales
Compléter les éléments entre [crochets] avant l'envoi.
---
**Objet :** TapTP (acct_1TS3Fq3wLGO2e0bc) — activation des comptes connectés gérés par la plateforme (collecte des informations par la plateforme, sans dashboard Stripe)
Bonjour,
Je développe **TapTP**, une application qui transforme le smartphone d'un professionnel (artisans, commerçants, marchés, food trucks, VTC…) en terminal de paiement grâce à **Tap to Pay sur iPhone et Android**, via **Stripe Terminal** et **Stripe Connect**. La plateforme est basée en **France** et s'adresse à des professionnels établis en France.
**Compte plateforme :** acct_1TS3Fq3wLGO2e0bc
**Société :** [raison sociale, SIREN, adresse]
**Site :** https://taptp.fr
### Ma demande
TapTP est conçue comme une solution **en marque blanche** : le professionnel ne doit interagir qu'avec l'application TapTP, sans redirection ni connexion à un compte Stripe. Je souhaiterais donc que ma plateforme puisse créer des comptes connectés avec la configuration suivante :
- `requirement_collection: application` : TapTP collecte elle-même les informations KYC/KYB dans son application (identité, pièce d'identité, justificatifs, IBAN), les transmet via l'API et assure le suivi des exigences mises à jour ;
- `stripe_dashboard.type: none` : aucun accès au Dashboard Stripe pour les comptes connectés ;
- `fees.payer: application` : TapTP paie les frais Stripe et facture ses propres frais de gestion au professionnel ;
- `losses.payments: application` : **TapTP accepte d'assumer la responsabilité des soldes négatifs** de ses comptes connectés.
Lors de mes essais en mode test, la création de tels comptes a été refusée : la configuration actuelle de ma plateforme impose une inscription hébergée par Stripe et `losses_collector: stripe`. Pourriez-vous m'indiquer si ma plateforme peut être éligible à ce mode et, le cas échéant, les étapes ou l'examen nécessaires pour l'activer (en test puis en production) ? Je suis ouvert à l'utilisation des Accounts v2 si c'est la voie recommandée.
### Fonctionnement des paiements
- Encaissement sur place uniquement, par **Tap to Pay** (cartes sans contact, Apple Pay, Google Pay).
- Paiements créés par la plateforme avec `on_behalf_of` (le professionnel est le commerçant affiché), puis reversement au compte connecté par transfert du montant net (frais Stripe et frais TapTP déduits).
- Remboursements initiés depuis l'application, avec reprise du montant sur le compte connecté.
- Statuts confirmés uniquement par webhooks ; aucune donnée de carte ni IBAN complet stockés par TapTP.
### Gestion des risques mise en place par TapTP
- Vérification de l'entreprise (SIRET contrôlé) et de l'identité du dirigeant avant toute activation des paiements.
- Plafond par paiement ([3 000] € actuellement, ajustable) et montant minimum.
- Confirmation par mot de passe avant chaque remboursement ; journal d'audit des actions sensibles.
- Mécanisme de compensation interne : les sommes dues par un professionnel (abonnement, frais de remboursements, soldes) sont retenues automatiquement sur ses reversements suivants.
- [Réserve financière prévue pour couvrir les soldes négatifs : montant]
- [Procédure de suivi des litiges et de suspension d'un compte en cas d'activité anormale]
### Volumes prévus
- Nombre de professionnels visés à 12 mois : [nombre]
- Panier moyen estimé : [montant] €
- Volume mensuel estimé à 12 mois : [montant] €
Je reste disponible pour un échange ou pour fournir tout document complémentaire.
Merci par avance,
[Prénom Nom]
[Fonction] — TapTP
[Téléphone] · contact@taptp.fr

132
docs/DESIGN_PROMPTS.md Normal file
View file

@ -0,0 +1,132 @@
# TapTP — Prompts pour Claude Design
Utilisation : colle d'abord le **Prompt 0** (identité + design system), valide-le,
puis enchaîne les prompts écran par écran dans le même projet pour garder la cohérence.
---
## Prompt 0 — Identité & design system
```
Je conçois TapTP, une application mobile (iOS + Android, React Native) qui transforme le smartphone d'un professionnel en terminal de paiement grâce au Tap to Pay : le pro saisit un montant, le client approche sa carte ou son téléphone, le paiement est accepté.
Slogan : « TapTP — Votre TPE. Dans votre poche. »
Cibles : artisans, commerçants, food trucks, marchés, coiffeurs, VTC, indépendants. Utilisation debout, devant un client, souvent dehors, parfois d'une seule main.
Crée le design system de l'app :
- Logo / wordmark « TapTP » simple, évoquant le sans contact (ondes NFC) sans copier les logos Apple Pay, Visa ou Mastercard.
- Palette : une couleur de marque forte et rassurante (confiance, argent, rapidité), un vert de succès, un rouge d'erreur, un orange d'attente, neutres. Thème clair ET thème sombre. Contrastes WCAG AA minimum, lisibles en plein soleil.
- Typographie : une police sans-serif moderne ; chiffres tabulaires pour les montants ; montant principal très grand (≥ 56 pt).
- Composants : bouton principal plein largeur (hauteur ≥ 64 pt), boutons secondaires, pavé numérique géant, cartes de statistiques, ligne de transaction, badges de statut (Réussi, Remboursé, Partiellement remboursé, Échoué, En attente), champs de formulaire, barre d'onglets, états vides, toasts.
- Zones tactiles ≥ 48 pt, espacement généreux, coins arrondis, animations sobres.
- Ton : professionnel, clair, rassurant. Textes en français, montants au format français (15,00 €).
Montre une planche du design system (couleurs, typo, composants) en clair et en sombre.
```
---
## Prompt 1 — Accueil, inscription, connexion
```
Avec le design system TapTP, crée les écrans d'authentification (mobile, iPhone 15) :
1. Écran de bienvenue : logo, slogan « Votre TPE. Dans votre poche. », 3 bénéfices courts (Pas de terminal à acheter, Paiement sans contact en 2 secondes, Argent versé sur votre compte), boutons « Créer mon compte » et « Se connecter ».
2. Inscription : prénom, nom, email, téléphone (facultatif), mot de passe (règles affichées : 12 caractères, majuscule, minuscule, chiffre, avec indicateur de validation en direct), case CGU, bouton « Créer mon compte ».
3. Connexion : email, mot de passe (afficher/masquer), lien « Mot de passe oublié ? », bouton « Se connecter ».
4. Mot de passe oublié : champ email + écran de confirmation neutre « Si un compte existe, un email vous a été envoyé ».
5. Nouveau mot de passe (ouvert depuis le lien email).
Inclure les états d'erreur (champ invalide, identifiants incorrects) et de chargement.
```
---
## Prompt 2 — Onboarding professionnel & KYC
```
Crée le parcours d'activation du compte TapTP, sous forme d'étapes avec barre de progression (« Étape 2 sur 5 ») :
1. Votre activité : type (Entreprise individuelle / Société), raison sociale, nom commercial, SIRET (14 chiffres, validé), secteur d'activité (liste), adresse.
2. Votre identité : date de naissance, adresse personnelle, nationalité.
3. Pièce d'identité : choix carte d'identité / passeport, photo recto + verso (cadre de capture caméra avec conseils : bonne lumière, pas de reflet), aperçu et bouton « Reprendre ».
4. Compte bancaire : saisie de l'IBAN et du titulaire, mention « Vos coordonnées sont transmises de façon sécurisée à notre partenaire de paiement Stripe et ne sont pas stockées par TapTP ».
5. Conditions : récapitulatif + case d'acceptation des conditions TapTP et de l'accord de compte connecté Stripe, bouton « Valider ».
Puis :
6. Écran « Vérification en cours » (attente, explication, délai indicatif, notification à venir).
7. Écran « Document supplémentaire requis » (liste des éléments demandés, bouton pour les fournir).
8. Écran « Compte activé 🎉 » avec bouton « Faire mon premier encaissement ».
Ton rassurant, sans jargon bancaire.
```
---
## Prompt 3 — Encaissement (écran le plus important)
```
Crée le flux d'encaissement TapTP. C'est l'écran le plus utilisé : il doit être ultra-simple, utilisable debout, d'une main, devant un client.
1. Écran principal « Nouvelle vente » :
- montant géant centré (0,00 € → 15,00 €), saisie en centimes (taper 1-5-0-0 donne 15,00 €)
- pavé numérique géant (1-9, 00, 0, effacer), touches ≥ 72 pt
- champ optionnel discret « Ajouter une note »
- gros bouton « ENCAISSER » plein largeur, désactivé tant que le montant est à 0
- en bas, résumé du jour : « Aujourd'hui · 12 transactions · 347,50 € » + accès Transactions / Stats
2. Écran « Approchez la carte ou le téléphone » : montant en grand, animation d'ondes sans contact, indication de l'endroit où approcher la carte (haut du téléphone), bouton « Annuler ». Aucune autre information.
3. Écran « Traitement… » bref.
4. Écran « Paiement accepté » : grande coche verte animée, montant, moyen de paiement (ex. Visa •••• 4242 ou Apple Pay), boutons « Envoyer un reçu » et « Terminé » (gros).
5. Écran « Paiement refusé » : icône rouge, raison simple (Carte refusée, Délai dépassé…), boutons « Réessayer » et « Annuler ».
6. Écran « Code PIN demandé » si la banque l'exige (au-delà de 50 €), selon l'interface fournie par le SDK.
7. Feuille « Envoyer un reçu » : email ou SMS du client.
Prévois aussi l'état « Compte non activé » (bouton ENCAISSER remplacé par « Terminer l'activation ») et « Téléphone incompatible avec Tap to Pay ».
Montre les écrans du flux enchaînés, en clair et en sombre.
```
---
## Prompt 4 — Transactions & remboursements
```
Crée les écrans de transactions TapTP :
1. Liste : regroupée par jour (Aujourd'hui, Hier, date), chaque ligne = heure, montant, moyen de paiement (logo + 4 derniers chiffres), badge de statut. Recherche par montant, filtres (statut, période). États vide et chargement.
2. Détail d'une transaction :
- montant encaissé en grand + statut
- décomposition claire :
Vente 50,00 €
Frais de gestion TapTP -2,90 €
Montant reversé 47,10 €
- date et heure, moyen de paiement, identifiant, note
- historique (Payé, Remboursé partiellement…)
- actions : « Envoyer le reçu », « Rembourser »
3. Remboursement : choix « Total » ou « Partiel » (pavé numérique, montant max affiché), motif facultatif, confirmation par Face ID / code (écran de confirmation explicite « Rembourser 20,00 € au client ? »), puis écran de succès.
```
---
## Prompt 5 — Statistiques & versements
```
Crée les écrans Statistiques et Versements TapTP :
1. Statistiques : sélecteur Jour / Semaine / Mois, chiffre d'affaires en grand, cartes : nombre de transactions, panier moyen, frais de gestion TapTP, montant net. Graphique en barres simple du CA par jour/heure. Lisible en un coup d'œil, pas de surcharge.
2. Versements : prochain versement mis en avant (montant, date prévue, compte •••• 1234), puis liste des versements passés avec statut (En attente, En cours, Versé, Échoué). Détail d'un versement : montant, date, compte bancaire, transactions incluses.
```
---
## Prompt 6 — Abonnement & compte
```
Crée les écrans Compte et Abonnement TapTP :
1. Abonnement « TapTP Pro » à 10 €/mois : supprime les 2 € de frais TapTP par transaction (les frais du partenaire de paiement restent appliqués).
- comparatif clair Sans abonnement / Avec TapTP Pro
- simulateur : « Avec 40 ventes ce mois-ci, vous économisez 70 € »
- mention : l'abonnement est prélevé sur vos ventes, résiliable à tout moment
- états : non abonné, abonné (prochaine échéance), résilié (actif jusqu'au…)
2. Mon compte : infos personnelles, entreprise, compte bancaire (masqué •••• 1234, modification via vérification), statut de vérification, sécurité (mot de passe, Face ID pour rembourser), notifications, aide et contact, mentions légales, déconnexion.
```
---
## Prompt 7 (optionnel) — Dashboard web
```
Crée un dashboard web responsive pour TapTP (desktop d'abord), dans le même design system :
menu latéral (Vue d'ensemble, Transactions, Remboursements, Versements, Statistiques, Compte), vue d'ensemble avec KPIs (CA du jour/semaine/mois, transactions, frais, net), graphique d'évolution, dernières transactions, prochain versement. Tableau des transactions avec filtres, recherche et export CSV.
```

17
mobile/.env.example Normal file
View file

@ -0,0 +1,17 @@
# URL de l API TapTP (sur téléphone physique : IP locale du PC, ex. http://192.168.1.20:3000)
EXPO_PUBLIC_API_URL=http://192.168.1.20:3001
# Pages légales (CGU, confidentialité) ouvertes depuis l inscription
EXPO_PUBLIC_TERMS_URL=
EXPO_PUBLIC_PRIVACY_URL=
# Clé PUBLIABLE Stripe (pk_test_… en développement) pour l onboarding intégré
EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY=
# true = lecteur Tap to Pay simulé (mode test Stripe), pour tester sans carte réelle
EXPO_PUBLIC_TERMINAL_SIMULATED=true
# Aide et mentions légales (écran Mon compte)
EXPO_PUBLIC_LEGAL_NOTICE_URL=
EXPO_PUBLIC_HELP_URL=
EXPO_PUBLIC_SUPPORT_EMAIL=

43
mobile/.gitignore vendored Normal file
View file

@ -0,0 +1,43 @@
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
# dependencies
node_modules/
# Expo
.expo/
dist/
web-build/
expo-env.d.ts
# Native
.kotlin/
*.orig.*
*.jks
*.p8
*.p12
*.key
*.mobileprovision
# Metro
.metro-health-check*
# debug
npm-debug.*
yarn-debug.*
yarn-error.*
# macOS
.DS_Store
*.pem
# local env files
.env*.local
# typescript
*.tsbuildinfo
# generated native folders
/ios
/android
.env

1
mobile/.npmrc Normal file
View file

@ -0,0 +1 @@
legacy-peer-deps=true

41
mobile/AGENTS.md Normal file
View file

@ -0,0 +1,41 @@
This is an Expo/React Native mobile application. Prioritize mobile-first patterns, performance, and cross-platform compatibility.
## Expo has changed — do not trust your training data
Expo ships breaking changes every SDK release. APIs you remember are likely renamed, moved, or removed. Before writing any code that touches an Expo, EAS, or React Native API:
1. Read the major version of the `expo` package in `package.json`.
2. Fetch the matching versioned docs: `https://docs.expo.dev/versions/v<major>.0.0/`
3. For anything else, fetch https://docs.expo.dev/llms.txt — an index of all Expo docs with corrections to common LLM misconceptions. Follow its links to the specific page you need; never answer from memory.
## Commands
Use `bunx` instead of `npx` if the project uses bun (`bun.lock` present).
```bash
npx expo install <package> # ALWAYS use instead of npm/yarn/pnpm/bun add — resolves SDK-compatible versions
npx expo start # start the dev server
npx expo lint # lint
npx tsc --noEmit # typecheck
npx expo-doctor # diagnose dependency and config issues
npx expo install --fix # fix incompatible package versions
```
Run lint and typecheck before declaring any task done.
## Navigation & Routing
- Use **Expo Router** for all navigation. Routes live in `src/app/` — every file there is a screen, `_layout.tsx` files define navigators. Keep non-route code (components, hooks, utils) outside `src/app/`.
- Import `Link`, `router`, and `useLocalSearchParams` from `expo-router`.
- Docs: https://docs.expo.dev/router/introduction.md
## Building with EAS
Use EAS to build, sign, and submit the app in the cloud (`eas build`, `eas submit`) and to ship over-the-air updates (`eas update`) — no local Xcode or Android Studio required. Run EAS CLI as `bunx eas-cli <command>` in Bun projects, or `npx eas-cli@latest <command>` otherwise; substitute that for bare `eas` in docs examples.
Docs: https://docs.expo.dev/eas/index.md
## Rules
- If `ios/` and `android/` directories do not exist, they are generated (Continuous Native Generation). Never create or edit them by hand — configure native behavior in `app.json` and config plugins.
- Expo Go only includes its bundled native modules. After adding a library with native code, the app needs a development build: `npx expo run:ios|android` locally, or `eas build --profile development`.
- Prefer recommended Expo modules over third-party libraries, and check your available skills before adding dependencies. Docs: https://docs.expo.dev/versions/latest/index.md

21
mobile/LICENSE Normal file
View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

33
mobile/README.md Normal file
View file

@ -0,0 +1,33 @@
# TapTP — application mobile
Expo (SDK 57) + React Native + TypeScript + Expo Router.
Le design reproduit la maquette Claude Design : https://claude.ai/artifact/Rb8cPro75bgTADHywuBPKA
## Lancer
```bash
npm install
cp .env.example .env # EXPO_PUBLIC_API_URL = URL de l'API (IP locale du PC sur un vrai téléphone)
npx expo start
```
Tant que Stripe Terminal n'est pas intégré, l'app tourne dans **Expo Go**.
Ensuite, Tap to Pay exige un **development build** sur un vrai téléphone
(`npx eas-cli@latest build --profile development`), le simulateur ne gère pas le NFC.
## Structure
- `src/app/` — écrans (Expo Router). Routes protégées selon la session (`Stack.Protected`).
- `src/components/ui/` — composants de la maquette (Button, TextField, Icon, Logo, Text, Screen).
`designAssets.ts` est généré depuis la maquette (icônes, logo).
- `src/theme/` — tokens de la maquette (couleurs clair/sombre, typo Manrope, espacements, rayons).
- `src/api/` — client HTTP : jeton d'accès en mémoire, refresh token dans le Keychain/Keystore,
renouvellement automatique et unique en cas de 401.
- `src/auth/` — état de session.
## Vérifications
```bash
npx tsc --noEmit
npx expo-doctor
```

26
mobile/app.config.js Normal file
View file

@ -0,0 +1,26 @@
/**
* Configuration Expo dynamique (complète app.json).
*
* Tap to Pay sur iPhone exige une autorisation Apple (entitlement « proximity-reader.payment.acceptance »).
* Tant qu'Apple ne l'a pas accordée au compte développeur, un build qui la réclame échoue à la signature.
* Elle n'est donc ajoutée que si TAP_TO_PAY_ENTITLEMENT=true (profil EAS « production » une fois l'accord obtenu).
*/
const TAP_TO_PAY_ENTITLEMENT = 'com.apple.developer.proximity-reader.payment.acceptance';
module.exports = ({ config }) => {
const entitlements = { ...(config.ios?.entitlements ?? {}) };
if (process.env.TAP_TO_PAY_ENTITLEMENT === 'true') entitlements[TAP_TO_PAY_ENTITLEMENT] = true;
else delete entitlements[TAP_TO_PAY_ENTITLEMENT];
return {
...config,
ios: {
...config.ios,
entitlements,
// Autorise l'appel HTTP vers l'API locale (http://IP:3001) dans les builds de développement uniquement.
...(process.env.EAS_BUILD_PROFILE === 'development'
? { infoPlist: { ...(config.ios?.infoPlist ?? {}), NSAppTransportSecurity: { NSAllowsLocalNetworking: true, NSAllowsArbitraryLoads: true } } }
: {}),
},
};
};

86
mobile/app.json Normal file
View file

@ -0,0 +1,86 @@
{
"expo": {
"name": "TapTP",
"slug": "taptp",
"scheme": "taptp",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"userInterfaceStyle": "automatic",
"backgroundColor": "#F3F5F9",
"ios": {
"supportsTablet": false,
"bundleIdentifier": "fr.taptp.app",
"infoPlist": {
"NSLocalNetworkUsageDescription": "TapTP se connecte à votre serveur de test sur le réseau local.",
"ITSAppUsesNonExemptEncryption": false
},
"entitlements": {}
},
"android": {
"package": "fr.taptp.app",
"adaptiveIcon": {
"backgroundColor": "#1747D6",
"foregroundImage": "./assets/android-icon-foreground.png",
"backgroundImage": "./assets/android-icon-background.png",
"monochromeImage": "./assets/android-icon-monochrome.png"
},
"predictiveBackGestureEnabled": false
},
"web": {
"favicon": "./assets/favicon.png"
},
"plugins": [
"expo-router",
"expo-secure-store",
"expo-font",
[
"expo-splash-screen",
{
"image": "./assets/splash-icon.png",
"imageWidth": 120,
"backgroundColor": "#1747D6",
"dark": {
"backgroundColor": "#080C17"
}
}
],
[
"@stripe/stripe-react-native",
{
"merchantIdentifier": "",
"enableGooglePay": false
}
],
[
"@stripe/stripe-terminal-react-native",
{
"tapToPayCheck": true,
"appDelegate": true,
"locationWhenInUsePermission": "TapTP utilise votre position pour sécuriser les paiements par carte, comme l’exige notre partenaire Stripe.",
"bluetoothPeripheralPermission": "TapTP n’utilise le Bluetooth que si vous connectez un lecteur de carte.",
"bluetoothAlwaysUsagePermission": "TapTP n’utilise le Bluetooth que si vous connectez un lecteur de carte.",
"localNetworkUsagePermission": "TapTP n’utilise le réseau local que si vous connectez un lecteur de carte."
}
],
[
"expo-build-properties",
{
"android": {
"minSdkVersion": 26
}
}
]
],
"experiments": {
"typedRoutes": true
},
"extra": {
"router": {},
"eas": {
"projectId": "97eceecb-76db-466a-a179-91c2647b78a6"
}
},
"owner": "hunterlevrai"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4 KiB

Some files were not shown because too many files have changed in this diff Show more