Table des matières
Phase 4-A — Consolidation Finale du Prisma Schema
Objectif
Fusionner l'ensemble des modèles construits durant :
Phase 2-A à Phase 2-N
dans un unique schéma Prisma cohérent :
apps/api/prisma/schema.prisma
Ce schéma deviendra :
Source de vérité de la base PostgreSQL
et servira à générer :
Prisma Client Repositories Services NestJS DTO OpenAPI SDK Frontend
Étape 4-A.1 — Consolidation des Enums
Créer les enums globaux
enum UserStatus enum ReservationStatus enum PaymentStatus enum ContractStatus enum LeadStatus enum OpportunityStatus enum TaskStatus enum TaskPriority enum PropertyStatus enum RiskLevel enum NotificationType enum CampaignStatus enum ChannelType enum SyncStatus enum CurrencyCode enum LanguageCode enum DataClassificationLevel
Exemple
enum UserStatus {
ACTIVE
INACTIVE
BLOCKED
PENDING
}
Étape 4-A.2 — Consolidation Authentification & RBAC
Modèles concernés
User Role Permission UserRole RolePermission Session RefreshToken
Relations attendues
User ↓ UserRole ↓ Role ↓ RolePermission ↓ Permission
Contraintes
@@unique([userId, roleId]) @@unique([roleId, permissionId])
Étape 4-A.3 — Consolidation CRM
Modèles
Lead Opportunity Pipeline PipelineStage Activity Task CustomerNote Tag Segment
Corrections
Ajouter :
assignedUserId String?
sur :
Lead Opportunity Task
Relation
assignedUser User? @relation(fields:[assignedUserId], references:[id])
Étape 4-A.4 — Consolidation Immobilier
Modèles
Owner Property PropertyMedia PropertyFeature PropertyAvailability PropertyRate PropertyDistribution
Champs supplémentaires
slug String @unique reference String @unique publicUrl String?
Index
@@index([slug]) @@index([reference])
Étape 4-A.5 — Consolidation Réservations
Modèles
Reservation ReservationGuest ReservationPricing ReservationEvent ReservationStatusHistory
Champ métier
reservationNumber String @unique
Index
@@index([reservationNumber])
Étape 4-A.6 — Consolidation Finance
Modèles
Payment Refund Invoice AccountingEntry
Contraintes
paymentReference String @unique invoiceNumber String @unique
Index
@@index([paymentReference]) @@index([invoiceNumber])
Étape 4-A.7 — Consolidation Communication
Modèles
Conversation Message Notification Email Sms Template Campaign CampaignRecipient CampaignExecution
Multi-tenant
Ajouter :
tenantId String
sur tous les modèles.
Étape 4-A.8 — Consolidation IA
Modèles
AiConversation AiMessage KnowledgeDocument KnowledgeChunk Recommendation AutomationScenario AutomationExecution
Support Vector Search
Si pgvector est utilisé :
embedding Unsupported("vector")?
Fallback
Sinon :
embedding Json?
Étape 4-A.9 — Consolidation Gouvernance
Modèles
AuditLog EntityHistory FeatureFlag Workflow WorkflowStep WorkflowInstance WorkflowExecution
Multi-tenant
Ajouter :
tenantId String
sur l'ensemble des modèles.
Étape 4-A.10 — Mise en place du Multi-Tenant
Modèle central
model Tenant {
id String @id @default(uuid())
code String @unique
name String
active Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Relation standard
Ajouter sur tous les modèles métier :
tenantId String tenant Tenant @relation(fields:[tenantId], references:[id])
Index
@@index([tenantId])
Étape 4-A.11 — Soft Delete Global
Ajouter sur tous les modèles métier
deletedAt DateTime?
Bénéfices
Suppression logique Restauration possible Audit complet Conformité RGPD
Étape 4-A.12 — Audit Global
Ajouter sur tous les modèles métier
createdAt DateTime @default(now()) updatedAt DateTime @updatedAt createdBy String? updatedBy String?
Objectif
Tracer :
Création Modification Historique utilisateur
sur l'ensemble du système.
Étape 4-A.13 — Indexation Enterprise
Ajouter systématiquement
@@index([createdAt]) @@index([updatedAt]) @@index([deletedAt])
sur tous les modèles volumineux :
Reservation Payment Invoice Lead Activity AuditLog Notification Message CampaignExecution AutomationExecution
Étape 4-A.14 — Validation du schéma
Vérification Prisma
npx prisma validate
Formatage
npx prisma format
Génération Client
npx prisma generate
Résultat attendu
À la fin de la Phase 4-A :
1 schema.prisma consolidé ≈ 110 modèles ≈ 350 relations ≈ 150 enums ≈ 500 index 100 % cohérent Prêt pour migration
Livrable
apps/api/prisma/schema.prisma
Phase 4-B — Migrations Prisma
Objectif
Transformer le schéma Prisma consolidé :
apps/api/prisma/schema.prisma
en une véritable base PostgreSQL opérationnelle.
À l'issue de cette phase :
✓ Base PostgreSQL créée ✓ Tables générées ✓ Index générés ✓ Contraintes générées ✓ Prisma Client généré ✓ Prisma Studio disponible
Prérequis
Vérifier PostgreSQL
docker ps
Vous devez voir :
postgres
en cours d'exécution.
Tester la connexion
psql -h localhost -U postgres
ou
docker exec -it postgres psql -U postgres
Étape 4-B.1 — Création du fichier .env
apps/api/.env
touch apps/api/.env
Contenu
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/rental_platform?schema=public"
Vérification
cat apps/api/.env
Étape 4-B.2 — Validation Prisma
Vérification du schéma
cd apps/api npx prisma validate
Résultat attendu
The schema at prisma/schema.prisma is valid
Si erreur
Corriger :
relations enum index syntaxe Prisma
avant de continuer.
Étape 4-B.3 — Formatage Prisma
Formatage
npx prisma format
Résultat
Prisma schema loaded Formatted prisma/schema.prisma
Étape 4-B.4 — Création de la première migration
Génération
npx prisma migrate dev --name init
Prisma va créer
prisma/
└── migrations/
└── xxxxxxxxx_init/
└── migration.sql
Exemple
CREATE TABLE "User" CREATE TABLE "Role" CREATE TABLE "Property" CREATE TABLE "Reservation" CREATE TABLE "Invoice" CREATE TABLE "Payment"
etc.
Étape 4-B.5 — Vérification des tables
Ouvrir PostgreSQL
docker exec -it postgres psql -U postgres
Sélection base
\c rental_platform
Lister les tables
\dt
Résultat attendu
Tenant User Role Permission Owner Property Customer Reservation Contract Invoice Payment ...
≈ 110 tables.
Étape 4-B.6 — Génération Prisma Client
Générer
npx prisma generate
Résultat
node_modules/.prisma/client
Vérification
ls node_modules/.prisma/client
Étape 4-B.7 — Test Prisma Client
Créer
apps/api/src/test-prisma.ts
Contenu
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function main() {
const tenants = await prisma.tenant.findMany();
console.log(tenants);
}
main();
Exécuter
npx ts-node src/test-prisma.ts
Résultat attendu
[]
ou une liste de tenants.
Étape 4-B.8 — Seed Initial
Créer
prisma/seed.ts
Tenant principal
await prisma.tenant.create({
data: {
code: 'MAIN',
name: 'Main Tenant'
}
});
Rôle Admin
await prisma.role.create({
data: {
code: 'SUPER_ADMIN',
name: 'Super Administrateur'
}
});
Permissions
await prisma.permission.createMany({
data: [
{
code: 'users.read',
name: 'Users Read'
},
{
code: 'users.create',
name: 'Users Create'
}
]
});
Exécuter
npx prisma db seed
Étape 4-B.9 — Prisma Studio
Lancer
npx prisma studio
URL
http://localhost:5555
Vérifications
Tenant User Role Permission Property Reservation Payment Invoice
doivent être visibles.
Étape 4-B.10 — Snapshot SQL
Générer
pg_dump \ -U postgres \ -d rental_platform \ -s \ > schema.sql
Résultat
schema.sql
Ce fichier servira :
Audit Review Backup Documentation
Contrôles qualité
Nombre de tables
SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public';
Nombre d'index
SELECT COUNT(*) FROM pg_indexes WHERE schemaname='public';
Nombre de contraintes
SELECT COUNT(*) FROM information_schema.table_constraints;
Définition de terminé
La Phase 4-B est terminée lorsque :
✓ Migration init exécutée ✓ PostgreSQL fonctionnel ✓ 110+ tables créées ✓ Prisma Client généré ✓ Seed exécuté ✓ Prisma Studio fonctionnel ✓ Snapshot SQL généré
Livrables
prisma/schema.prisma prisma/migrations/* prisma/seed.ts schema.sql
Phase 4-C — DTO & Contrats TypeScript
Objectif
Transformer le modèle Prisma consolidé en contrats applicatifs utilisables par :
NestJS Swagger OpenAPI Zod NextJS React Query SDK TypeScript
À l'issue de cette phase :
✓ DTO générés ✓ Types TypeScript générés ✓ Validation Zod générée ✓ Contrats API stabilisés ✓ Base de génération Swagger
Architecture cible
Structure
libs/
└── contracts/
├── dto/
├── schemas/
├── enums/
├── types/
└── index.ts
Objectif
Séparer :
Base de données ↓ Prisma Models ---------------- API ↓ DTO ---------------- Frontend ↓ Types
Étape 4-C.1 — Création de la librairie Contracts
Nx
nx g @nx/js:library contracts
Résultat
libs/contracts
Étape 4-C.2 — Installation des dépendances
DTO
npm install class-validator npm install class-transformer npm install @nestjs/swagger
Validation Runtime
npm install zod
Génération Zod
npm install prisma-zod-generator
Étape 4-C.3 — Organisation des contrats
Arborescence
libs/contracts ├── dto │ ├── auth │ ├── users │ ├── properties │ ├── reservations │ ├── crm │ ├── finance │ └── security │ ├── schemas │ ├── enums │ └── types
Étape 4-C.4 — DTO Auth
CreateUserDto
export class CreateUserDto {
@IsEmail()
email: string;
@IsString()
firstName: string;
@IsString()
lastName: string;
@MinLength(8)
password: string;
}
LoginDto
export class LoginDto {
@IsEmail()
email: string;
@IsString()
password: string;
}
RefreshTokenDto
export class RefreshTokenDto {
@IsString()
refreshToken: string;
}
Étape 4-C.5 — DTO Users
UpdateUserDto
export class UpdateUserDto {
@IsOptional()
firstName?: string;
@IsOptional()
lastName?: string;
@IsOptional()
phone?: string;
}
UserResponseDto
export class UserResponseDto {
id: string;
email: string;
firstName: string;
lastName: string;
status: UserStatus;
}
Étape 4-C.6 — DTO Properties
CreatePropertyDto
export class CreatePropertyDto {
title: string;
description?: string;
propertyType: string;
maxGuests: number;
bedrooms: number;
bathrooms: number;
}
UpdatePropertyDto
export class UpdatePropertyDto {
title?: string;
description?: string;
published?: boolean;
}
PropertyResponseDto
export class PropertyResponseDto {
id: string;
reference: string;
slug: string;
title: string;
published: boolean;
}
Étape 4-C.7 — DTO Reservations
CreateReservationDto
export class CreateReservationDto {
propertyId: string;
customerId: string;
checkInDate: Date;
checkOutDate: Date;
adults: number;
children?: number;
}
ReservationResponseDto
export class ReservationResponseDto {
id: string;
reservationNumber: string;
status: ReservationStatus;
totalAmount: number;
}
Étape 4-C.8 — DTO CRM
CreateLeadDto
export class CreateLeadDto {
firstName: string;
lastName: string;
email: string;
source?: string;
}
CreateTaskDto
export class CreateTaskDto {
title: string;
description?: string;
assignedUserId?: string;
dueDate?: Date;
}
Étape 4-C.9 — DTO Finance
CreateInvoiceDto
export class CreateInvoiceDto {
reservationId: string;
issueDate: Date;
}
PaymentDto
export class PaymentDto {
reservationId: string;
amount: number;
currencyCode: string;
}
Étape 4-C.10 — DTO Security
EnableMfaDto
export class EnableMfaDto {
method: string;
}
ConsentDto
export class ConsentDto {
consentType: string;
granted: boolean;
}
Étape 4-C.11 — Pagination Contracts
PaginationRequest
export class PaginationRequest {
page?: number;
pageSize?: number;
sort?: string;
search?: string;
}
PaginationResponse
export class PaginationResponse<T> {
data: T[];
total: number;
page: number;
pageSize: number;
totalPages: number;
}
Étape 4-C.12 — API Response Contracts
Success
export interface ApiResponse<T> {
success: true;
data: T;
}
Error
export interface ApiError {
success: false;
code: string;
message: string;
}
Étape 4-C.13 — Génération Zod
Generator Prisma
Dans :
schema.prisma
ajouter :
generator zod {
provider = "prisma-zod-generator"
}
Génération
npx prisma generate
Résultat
libs/contracts/schemas
contenant :
UserSchema PropertySchema ReservationSchema LeadSchema InvoiceSchema PaymentSchema
Étape 4-C.14 — Barrel Exports
enums/index.ts
export * from './user-status.enum'; export * from './reservation-status.enum'; export * from './payment-status.enum';
dto/index.ts
export * from './auth'; export * from './users'; export * from './properties'; export * from './reservations';
index.ts
export * from './dto'; export * from './schemas'; export * from './enums'; export * from './types';
Contrôles qualité
Compilation
nx build contracts
Type Check
npx tsc --noEmit
Lint
nx lint contracts
Livrables
libs/contracts/dto libs/contracts/types libs/contracts/enums libs/contracts/schemas libs/contracts/index.ts
Définition de terminé
La Phase 4-C est terminée lorsque :
✓ DTO créés ✓ Types TypeScript créés ✓ Zod généré ✓ Contrats partagés Backend/Frontend ✓ Validation unifiée ✓ Build vert
Phase 4-D — Structure NestJS Enterprise
Objectif
Construire l'architecture complète du backend NestJS à partir :
Prisma Schema consolidé OpenAPI Enterprise 4.0 Contrats DTO DDD CQRS Hexagonal Architecture
À l'issue de cette phase :
✓ Backend structuré ✓ Modules générés ✓ CQRS en place ✓ Event Bus en place ✓ Repository Pattern ✓ Domain Services ✓ Guards ✓ Interceptors ✓ Filters ✓ Multi-Tenant
Architecture cible
Structure globale
apps/api/src ├── core ├── infrastructure ├── shared ├── modules └── bootstrap
Étape 4-D.1 — Core Layer
Objectif
Contenir les composants techniques communs.
Arborescence
src/core ├── database ├── cqrs ├── events ├── guards ├── interceptors ├── filters ├── decorators ├── exceptions ├── logging └── tenancy
Database
Prisma Service
src/core/database/prisma.service.ts
Prisma Module
src/core/database/prisma.module.ts
CQRS
Installation
npm install @nestjs/cqrs
Module
src/core/cqrs/cqrs.module.ts
Composants
Commands Queries Handlers Events Sagas
Event Bus
Événements globaux
UserCreated ReservationCreated ContractSigned PaymentReceived InvoiceGenerated LeadConverted MfaEnabled
Répertoire
src/core/events
Étape 4-D.2 — Shared Layer
Objectif
Mutualiser les objets transverses.
Structure
src/shared ├── dto ├── enums ├── constants ├── types ├── interfaces └── utils
Étape 4-D.3 — Infrastructure Layer
Objectif
Contenir les adaptateurs techniques.
Structure
Phase 4-D — Structure NestJS Enterprise
Objectif
Construire l'architecture complète du backend NestJS à partir :
Prisma Schema consolidé OpenAPI Enterprise 4.0 Contrats DTO DDD CQRS Hexagonal Architecture
À l'issue de cette phase :
✓ Backend structuré ✓ Modules générés ✓ CQRS en place ✓ Event Bus en place ✓ Repository Pattern ✓ Domain Services ✓ Guards ✓ Interceptors ✓ Filters ✓ Multi-Tenant
Architecture cible
Structure globale
apps/api/src ├── core ├── infrastructure ├── shared ├── modules └── bootstrap
Étape 4-D.1 — Core Layer
Objectif
Contenir les composants techniques communs.
Arborescence
src/core ├── database ├── cqrs ├── events ├── guards ├── interceptors ├── filters ├── decorators ├── exceptions ├── logging └── tenancy
Database
Prisma Service
src/core/database/prisma.service.ts
Prisma Module
src/core/database/prisma.module.ts
CQRS
Installation
npm install @nestjs/cqrs
Module
src/core/cqrs/cqrs.module.ts
Composants
Commands Queries Handlers Events Sagas
Event Bus
Événements globaux
UserCreated ReservationCreated ContractSigned PaymentReceived InvoiceGenerated LeadConverted MfaEnabled
Répertoire
src/core/events
Étape 4-D.2 — Shared Layer
Objectif
Mutualiser les objets transverses.
Structure
src/shared ├── dto ├── enums ├── constants ├── types ├── interfaces └── utils
Phase 4-D.3 — Infrastructure Layer (suite)
Structure
src/infrastructure ├── prisma ├── cache ├── queue ├── mail ├── sms ├── storage ├── payments ├── signatures ├── ota ├── ai └── search
Cache
Redis
src/infrastructure/cache
Installation
npm install @nestjs/cache-manager npm install cache-manager npm install cache-manager-redis-store npm install redis
Services
CacheService CacheKeys CacheInvalidationService
Queue
BullMQ
npm install @nestjs/bullmq npm install bullmq
Files
queue.module.ts jobs/ processors/ workers/
Jobs
SendEmailJob SendSmsJob GenerateInvoiceJob SyncOtaJob GenerateContractJob AiIndexationJob
Provider
SendGrid Mailgun SMTP Amazon SES
Interface
export interface EmailProvider {
send(
payload: SendEmailPayload
): Promise<void>;
}
SMS
Provider
Twilio MessageBird OVH SMS
Interface
export interface SmsProvider {
send(
payload: SendSmsPayload
): Promise<void>;
}
Storage
Providers
S3 MinIO Azure Blob
Services
StorageService FileUploadService ImageOptimizationService
Payments
Providers
Stripe PayPal
Adapters
StripeAdapter PaypalAdapter
Signature
Providers
DocuSign Yousign Universign
Adapters
DocusignAdapter YousignAdapter
OTA
Connecteurs
BookingAdapter AirbnbAdapter VrboAdapter ExpediaAdapter
IA
Providers
OpenAI Azure OpenAI Anthropic
Services
AiAssistantService EmbeddingService RecommendationService KnowledgeSearchService
Étape 4-D.4 — Domain Modules
Structure standard
Chaque domaine métier adopte exactement la même structure.
Exemple
src/modules/properties ├── application ├── domain ├── infrastructure ├── presentation └── properties.module.ts
Application Layer
Structure
application ├── commands ├── queries ├── handlers ├── dto └── mappers
Exemple
commands/ CreatePropertyCommand UpdatePropertyCommand PublishPropertyCommand
Queries
GetPropertyQuery SearchPropertiesQuery GetAvailabilityQuery
Domain Layer
Structure
domain ├── entities ├── repositories ├── services ├── value-objects └── events
Entités
Property Reservation Owner Invoice Lead
Repositories
export interface PropertyRepository {
findById(id: string);
save(property: Property);
delete(id: string);
}
Domain Services
PricingService ReservationService ContractService RevenueManagementService
Infrastructure Layer Domaine
Implémentations
PrismaPropertyRepository PrismaReservationRepository PrismaLeadRepository
Exemple
infrastructure/prisma └── prisma-property.repository.ts
Presentation Layer
Structure
presentation ├── controllers ├── presenters └── swagger
Exemple
properties.controller.ts availability.controller.ts rates.controller.ts
Étape 4-D.5 — Modules Métier
Modules à générer
AuthModule UsersModule OwnersModule PropertiesModule ReservationsModule ContractsModule PaymentsModule InvoicesModule CRMModule MessagingModule MarketingModule AutomationModule AiModule GovernanceModule OtaModule RevenueModule SecurityModule InternationalizationModule
Étape 4-D.6 — Multi-Tenant
Tenant Context
src/core/tenancy
Service
TenantContextService
Header
X-Tenant-Id
Guard
TenantGuard
Middleware
TenantMiddleware
Objectif
Injecter automatiquement :
tenantId
dans tous les accès Prisma.
Étape 4-D.7 — Security
Guards
JwtAuthGuard RolesGuard PermissionsGuard TenantGuard MfaGuard
Decorators
@CurrentUser() @Roles() @Permissions() @Tenant()
Étape 4-D.8 — Interceptors
Interceptors globaux
LoggingInterceptor AuditInterceptor CacheInterceptor TenantInterceptor ResponseTransformInterceptor
Étape 4-D.9 — Exception Filters
Filtres
GlobalExceptionFilter PrismaExceptionFilter ValidationExceptionFilter DomainExceptionFilter
Exemple
{
"success": false,
"code": "PROPERTY_NOT_FOUND",
"message": "Property not found"
}
Étape 4-D.10 — Bootstrap
Structure
src/bootstrap ├── swagger.ts ├── validation.ts ├── security.ts └── app.ts
main.ts
async function bootstrap() {
const app =
await NestFactory.create(AppModule);
setupSwagger(app);
setupValidation(app);
setupSecurity(app);
await app.listen(3000);
}
Étape 4-D.11 — AppModule
Agrégation
AppModule ├── CoreModule ├── InfrastructureModule ├── AuthModule ├── UsersModule ├── OwnersModule ├── PropertiesModule ├── ReservationsModule ├── ContractsModule ├── PaymentsModule ├── CRMModule ├── MessagingModule ├── RevenueModule ├── SecurityModule
Contrôles qualité
Compilation
nx build api
Lint
nx lint api
Tests
nx test api
Livrables
src/core src/shared src/infrastructure src/modules src/bootstrap app.module.ts main.ts
Définition de terminé
La Phase 4-D est terminée lorsque :
✓ Architecture Hexagonale en place ✓ CQRS installé ✓ Event Bus installé ✓ Modules générés ✓ Multi-Tenant opérationnel ✓ Guards opérationnels ✓ Interceptors opérationnels ✓ Filters opérationnels ✓ Build vert
Phase 4-E — Structure NextJS Enterprise
Objectif
Construire l'architecture Frontend complète de la plateforme.
Cette phase transforme :
OpenAPI Enterprise DTO TypeScript SDK TypeScript Contrats API
en une application :
NextJS 15 React 19 TypeScript TanStack Query TailwindCSS shadcn/ui Multi-Tenant RBAC Internationalisée
Résultat attendu
À l'issue de cette phase :
✓ Frontend compilable ✓ Authentification complète ✓ Layouts Enterprise ✓ Design System ✓ Pages métier ✓ Gestion permissions ✓ Multi-tenant ✓ Multi-langues
Étape 4-E.1 — Création de l'application
Génération
cd apps npx create-next-app@latest web
Options
TypeScript YES ESLint YES TailwindCSS YES App Router YES src/ directory YES Turbopack YES Import Alias YES
Résultat
apps/web
Étape 4-E.2 — Installation des dépendances
TanStack Query
npm install @tanstack/react-query npm install @tanstack/react-query-devtools
Formulaires
npm install react-hook-form npm install zod npm install @hookform/resolvers
Auth
npm install jwt-decode
UI
npx shadcn@latest init
Composants
npx shadcn add button
npx shadcn add input
npx shadcn add dialog
npx shadcn add table
npx shadcn add dropdown-menu
npx shadcn add form
npx shadcn add card
npx shadcn add tabs
npx shadcn add toast
Étape 4-E.3 — Structure globale
Architecture
apps/web/src ├── app ├── modules ├── components ├── layouts ├── hooks ├── services ├── providers ├── stores ├── lib ├── types └── config
Étape 4-E.4 — Providers
Structure
providers ├── query-provider.tsx ├── auth-provider.tsx ├── tenant-provider.tsx ├── theme-provider.tsx └── i18n-provider.tsx
Query Provider
<QueryClientProvider>
{children}
</QueryClientProvider>
Étape 4-E.5 — SDK API
Structure
services/api ├── auth ├── users ├── properties ├── reservations ├── crm ├── finance ├── ota ├── ai └── security
Exemple
export const getProperty = ( id: string ) => sdk.properties.getProperty(id);
Étape 4-E.6 — Gestion Auth
Structure
modules/auth ├── hooks ├── services ├── components └── pages
Pages
/login /register /forgot-password /reset-password /mfa
Hook
useCurrentUser() useLogin() useLogout() usePermissions()
Étape 4-E.7 — Layouts
Public
layouts/public-layout.tsx
Auth
layouts/auth-layout.tsx
Dashboard
layouts/dashboard-layout.tsx
Owner
layouts/owner-layout.tsx
Admin
layouts/admin-layout.tsx
Étape 4-E.8 — Navigation
Sidebar
Dashboard Reservations Properties Owners CRM Finance Marketing Analytics Security Administration
Menu dynamique
Piloté par :
Permissions Tenant Feature Flags
Étape 4-E.9 — Module Properties
Pages
/properties /properties/create /properties/[id] /properties/[id]/edit
Composants
PropertyForm PropertyTable PropertyCard PropertyGallery AvailabilityCalendar
Étape 4-E.10 — Module Reservations
Pages
/reservations /reservations/create /reservations/[id]
Composants
ReservationForm ReservationDetails GuestList PricingSummary
Étape 4-E.11 — Module CRM
Pages
/crm/leads /crm/opportunities /crm/tasks /crm/customers
Composants
LeadKanban OpportunityPipeline TaskBoard CustomerTimeline
Étape 4-E.12 — Module Finance
Pages
/finance/payments /finance/invoices /finance/refunds
Composants
InvoiceTable PaymentHistory RefundManager
Étape 4-E.13 — Module OTA
Pages
/ota/channels /ota/distribution /ota/synchronization
Composants
ChannelStatus SyncDashboard DistributionTable
Étape 4-E.14 — Module IA
Pages
/ai /ai/chat /ai/recommendations /ai/knowledge-base
Composants
AiChat RecommendationPanel KnowledgeSearch AutomationDashboard
Étape 4-E.15 — Module Sécurité
Pages
/security /security/mfa /security/sessions /security/privacy /security/compliance
Composants
MfaWizard SessionManager ConsentManager RiskMatrix
Étape 4-E.16 — Dashboard
Route
/dashboard
Widgets
Revenue KPI Occupancy KPI Reservations KPI Payments KPI Lead KPI Security KPI
Étape 4-E.17 — Internationalisation
Installation
npm install next-intl
Langues
fr en es it de nl
Structure
messages ├── fr.json ├── en.json ├── es.json └── de.json
Étape 4-E.18 — Multi-Tenant
Header
X-Tenant-Id
Provider
TenantProvider
Context
TenantContext
Objectif
Changer dynamiquement :
Branding Logo Couleurs Permissions Domaine
selon le tenant.
Étape 4-E.19 — RBAC Frontend
Hooks
useRole() usePermission() useFeatureFlag()
Composant
<Can permission="properties.create">
<Button>
Ajouter
</Button>
</Can>
Étape 4-E.20 — Feature Flags
Service
FeatureFlagProvider
Exemple
<FeatureFlag code="AI_ASSISTANT"> <AiWidget /> </FeatureFlag>
Étape 4-E.21 — Gestion des erreurs
Pages
not-found.tsx error.tsx global-error.tsx
Composants
ErrorBoundary ApiErrorAlert
Étape 4-E.22 — Tests
Installation
npm install vitest npm install @testing-library/react npm install @testing-library/jest-dom
Types
Unit Integration Component
Contrôles qualité
Lint
nx lint web
Type Check
npx tsc --noEmit
Build
nx build web
Local
nx serve web
Livrables
apps/web layouts providers modules components hooks services stores
Définition de terminé
La Phase 4-E est terminée lorsque :
✓ NextJS compilable ✓ Auth fonctionnelle ✓ SDK intégré ✓ RBAC opérationnel ✓ Multi-Tenant opérationnel ✓ Internationalisation opérationnelle ✓ Dashboard opérationnel ✓ Build vert
Phase 4-F — Docker Compose Enterprise
Objectif
Industrialiser complètement l'environnement local de développement.
À l'issue de cette phase :
✓ PostgreSQL ✓ Redis ✓ NestJS ✓ NextJS ✓ PgAdmin ✓ Mailhog ✓ MinIO ✓ Nginx ✓ Monitoring ✓ Docker Network ✓ Volumes persistants
seront disponibles via une simple commande :
docker compose up -d
Architecture cible
Services
┌─────────────┐
│ NextJS │
└──────┬──────┘
│
▼
┌─────────────┐
│ NGINX │
└──────┬──────┘
│
▼
┌─────────────┐
│ NestJS │
└──────┬──────┘
│
┌─────┼─────┐
▼ ▼ ▼
Postgres Redis MinIO
│
▼
Mailhog
Étape 4-F.1 — Structure Docker
Créer
docker ├── postgres ├── redis ├── minio ├── nginx ├── mailhog ├── prometheus └── grafana
Étape 4-F.2 — Docker Network
docker-compose.yml
Créer à la racine :
docker-compose.yml
Network
networks: platform-network: driver: bridge
Étape 4-F.3 — PostgreSQL
Service
postgres: image: postgres:16 container_name: postgres restart: always environment: POSTGRES_DB: rental_platform POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data networks: - platform-network
Volume
volumes: postgres_data:
Étape 4-F.4 — PgAdmin
Service
pgadmin: image: dpage/pgadmin4 container_name: pgadmin restart: always environment: PGADMIN_DEFAULT_EMAIL: admin@local.dev PGADMIN_DEFAULT_PASSWORD: admin ports: - "5050:80" depends_on: - postgres
URL
http://localhost:5050
Étape 4-F.5 — Redis
Service
redis: image: redis:7-alpine container_name: redis restart: always ports: - "6379:6379" volumes: - redis_data:/data networks: - platform-network
Volume
redis_data:
Étape 4-F.6 — Mailhog
Service
mailhog: image: mailhog/mailhog container_name: mailhog restart: always ports: - "1025:1025" - "8025:8025" networks: - platform-network
URLs
SMTP localhost:1025 ---------------- UI http://localhost:8025
Étape 4-F.7 — MinIO
Service
minio: image: minio/minio container_name: minio command: server /data --console-address ":9001" restart: always environment: MINIO_ROOT_USER: admin MINIO_ROOT_PASSWORD: password123 ports: - "9000:9000" - "9001:9001" volumes: - minio_data:/data networks: - platform-network
Volume
minio_data:
Console
http://localhost:9001
Étape 4-F.8 — API NestJS
Dockerfile
Créer :
apps/api/Dockerfile
Contenu
FROM node:22-alpine WORKDIR /app COPY . . RUN npm install RUN npm run build api CMD ["node","dist/apps/api/main.js"]
Service
api: build: context: . dockerfile: apps/api/Dockerfile container_name: api restart: always ports: - "3000:3000" env_file: - apps/api/.env depends_on: - postgres - redis networks: - platform-network
Étape 4-F.9 — Frontend NextJS
Dockerfile
Créer :
apps/web/Dockerfile
Contenu
FROM node:22-alpine WORKDIR /app COPY . . RUN npm install RUN npm run build web CMD ["npm","run","start:web"]
Service
web: build: context: . dockerfile: apps/web/Dockerfile container_name: web restart: always ports: - "4200:3000" depends_on: - api networks: - platform-network
Étape 4-F.10 — NGINX Reverse Proxy
Fichier
docker/nginx/default.conf
Configuration
server { listen 80; location / { proxy_pass http://web:3000; } location /api { proxy_pass http://api:3000; } }
Service
nginx: image: nginx:alpine container_name: nginx ports: - "80:80" volumes: - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf depends_on: - web - api networks: - platform-network
Étape 4-F.11 — Prometheus
Configuration
docker/prometheus/prometheus.yml
Service
prometheus: image: prom/prometheus container_name: prometheus ports: - "9090:9090" volumes: - ./docker/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml networks: - platform-network
Étape 4-F.12 — Grafana
Service
grafana: image: grafana/grafana container_name: grafana ports: - "3001:3000" volumes: - grafana_data:/var/lib/grafana networks: - platform-network
Volume
grafana_data:
URL
http://localhost:3001
Étape 4-F.13 — Fichier .env Docker
Créer
.env.docker
Contenu
POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres POSTGRES_DB=rental_platform REDIS_HOST=redis REDIS_PORT=6379 MINIO_ENDPOINT=minio MINIO_ACCESS_KEY=admin MINIO_SECRET_KEY=password123
Étape 4-F.14 — Démarrage
Lancer
docker compose up -d
Vérifier
docker ps
Résultat
postgres redis mailhog minio pgadmin api web nginx prometheus grafana
Étape 4-F.15 — Vérifications
API
http://localhost:3000
Swagger
http://localhost:3000/api
Front
http://localhost:4200
PgAdmin
http://localhost:5050
Mailhog
http://localhost:8025
MinIO
http://localhost:9001
Grafana
http://localhost:3001
Prometheus
http://localhost:9090
Définition de terminé
La Phase 4-F est terminée lorsque :
✓ Tous les conteneurs démarrent ✓ PostgreSQL accessible ✓ Redis accessible ✓ API accessible ✓ Frontend accessible ✓ Swagger accessible ✓ Mailhog opérationnel ✓ MinIO opérationnel ✓ Monitoring opérationnel
Livrables
docker-compose.yml apps/api/Dockerfile apps/web/Dockerfile docker/nginx/default.conf docker/prometheus/prometheus.yml .env.docker
Phase 4-G — GitHub Actions CI/CD Enterprise
Objectif
Industrialiser complètement le cycle de développement.
À l'issue de cette phase :
✓ Build automatique ✓ Lint automatique ✓ Tests automatiques ✓ Validation Prisma ✓ Génération OpenAPI ✓ Build Docker ✓ Security Scan ✓ Release automatique ✓ Qualité contrôlée
sur chaque :
Push Pull Request Release
Architecture CI/CD
Pipelines
CI ↓ Quality ↓ Security ↓ Docker ↓ Release ↓ Deploy
Structure
Répertoire
.github
└── workflows
├── ci.yml
├── quality.yml
├── security.yml
├── docker.yml
├── release.yml
└── deploy.yml
Étape 4-G.1 — Workflow CI
Fichier
.github/workflows/ci.yml
Déclencheurs
on: push: branches: - main - develop pull_request:
Jobs
Install Lint Build Test
Exemple
name: CI jobs: install: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 - run: npm ci
Étape 4-G.2 — Lint
Job
lint: runs-on: ubuntu-latest steps: - run: nx lint api - run: nx lint web - run: nx lint contracts
Contrôle
ESLint Prettier Architecture
Étape 4-G.3 — Type Check
Job
typecheck: runs-on: ubuntu-latest steps: - run: npx tsc --noEmit
Étape 4-G.4 — Prisma Validation
Job
prisma: runs-on: ubuntu-latest steps: - run: npx prisma validate - run: npx prisma format --check
Objectif
Empêcher :
Migration cassée Relation invalide Schema incorrect
Étape 4-G.5 — Build
API
build-api: runs-on: ubuntu-latest steps: - run: nx build api
Front
build-web: runs-on: ubuntu-latest steps: - run: nx build web
Contracts
build-contracts: runs-on: ubuntu-latest steps: - run: nx build contracts
Étape 4-G.6 — Tests
Unitaires
test-unit: runs-on: ubuntu-latest steps: - run: nx test api - run: nx test web
Couverture
Minimum 80%
Contrôle
- run: npm run test:coverage
Étape 4-G.7 — PostgreSQL CI
Service
services: postgres: image: postgres:16 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: testdb ports: - 5432:5432
Migration
- run: npx prisma migrate deploy
Seed
- run: npx prisma db seed
Étape 4-G.8 — Tests E2E
Job
e2e: runs-on: ubuntu-latest
Scénarios
Register Login Create Property Create Reservation Create Invoice Payment
Commande
- run: nx e2e api-e2e
Étape 4-G.9 — Security Scan
Dépendances
- run: npm audit
Trivy
- uses: aquasecurity/trivy-action
Vérifications
CVE Secrets Images Docker
Étape 4-G.10 — Secret Scan
Gitleaks
- uses: gitleaks/gitleaks-action
Détecte
API Keys Passwords Tokens Secrets AWS
Étape 4-G.11 — OpenAPI Validation
Génération
- run: npm run swagger:generate
Validation
- run: npm run openapi:validate
Vérification
Swagger valide Contrats cohérents
Étape 4-G.12 — Build Docker
Job
docker: runs-on: ubuntu-latest
API
docker build \ -f apps/api/Dockerfile .
Front
docker build \ -f apps/web/Dockerfile .
Étape 4-G.13 — Push Registry
GitHub Container Registry
ghcr.io
Login
- uses: docker/login-action@v3
Push
docker push ghcr.io/company/api docker push ghcr.io/company/web
Étape 4-G.14 — Release Automation
Fichier
.github/workflows/release.yml
Déclencheur
on: push: tags: - 'v*'
Exemple
v1.0.0 v1.1.0 v2.0.0
Génération
Release Notes Docker Images Artifacts
Étape 4-G.15 — Artifacts
Upload
- uses: actions/upload-artifact
Artifacts
OpenAPI Coverage Build Migration SQL
Étape 4-G.16 — Badges
README
![CI] ![Coverage] ![Docker] ![Security]
Étape 4-G.17 — Branch Protection
Main
Configurer GitHub :
Require Pull Request Require CI Require Reviews Require Status Checks
Interdictions
Push direct main Merge sans review Merge sans CI
Étape 4-G.18 — Dependabot
Fichier
.github/dependabot.yml
Exemple
version: 2 updates: - package-ecosystem: npm directory: "/" schedule: interval: weekly
Étape 4-G.19 — Renovate (optionnel)
Alternative
Renovate Bot
pour :
NPM Docker GitHub Actions Terraform
Étape 4-G.20 — Qualité Enterprise
Gates
Coverage > 80% 0 erreur ESLint 0 erreur TypeScript 0 migration invalide 0 vulnérabilité critique
Arborescence finale
.github
└── workflows
├── ci.yml
├── quality.yml
├── security.yml
├── docker.yml
├── release.yml
└── deploy.yml
.github
└── dependabot.yml
Définition de terminé
La Phase 4-G est terminée lorsque :
✓ CI verte ✓ Build automatique ✓ Lint automatique ✓ Tests automatiques ✓ Docker build automatique ✓ OpenAPI validé ✓ Security scan actif ✓ Releases automatisées
Livrables
.github/workflows/* .github/dependabot.yml README.md Badges CI
Phase 4-H — Helm Charts Kubernetes Enterprise
Objectif
Préparer la plateforme pour un déploiement Cloud Native Enterprise.
Cette phase transforme :
Docker Compose ↓ Kubernetes ↓ Helm Charts
afin de permettre :
AWS EKS Azure AKS Google GKE OVH Managed Kubernetes On-Prem Kubernetes
Résultat attendu
À l'issue de cette phase :
✓ Helm Charts complets ✓ Déploiement automatisé ✓ Rolling Updates ✓ Autoscaling ✓ Secrets Kubernetes ✓ ConfigMaps ✓ Ingress ✓ Monitoring
Architecture Kubernetes
Namespace │ ├── web ├── api ├── postgres ├── redis ├── minio ├── ingress ├── monitoring └── jobs
Étape 4-H.1 — Structure Helm
Créer
deploy
└── helm
└── rental-platform
├── Chart.yaml
├── values.yaml
├── values-dev.yaml
├── values-staging.yaml
├── values-prod.yaml
└── templates
Étape 4-H.2 — Chart.yaml
Fichier
deploy/helm/rental-platform/Chart.yaml
Contenu
apiVersion: v2 name: rental-platform description: Rental Platform Enterprise type: application version: 1.0.0 appVersion: "1.0.0"
Étape 4-H.3 — values.yaml
Configuration globale
global: environment: dev domain: local.dev
Images
image: api: repository: ghcr.io/company/api tag: latest web: repository: ghcr.io/company/web tag: latest
Étape 4-H.4 — Namespace
Template
templates/namespace.yaml
Contenu
apiVersion: v1 kind: Namespace metadata: name: rental-platform
Étape 4-H.5 — API Deployment
Template
templates/api-deployment.yaml
Deployment
apiVersion: apps/v1 kind: Deployment metadata: name: api
ReplicaSet
spec: replicas: 3
Container
containers: - name: api image: "{{ .Values.image.api.repository }}:{{ .Values.image.api.tag }}"
Étape 4-H.6 — API Service
Template
templates/api-service.yaml
Service
kind: Service spec: type: ClusterIP ports: - port: 3000
Étape 4-H.7 — Web Deployment
Template
templates/web-deployment.yaml
Replicas
spec: replicas: 2
Container
containers: - name: web
Étape 4-H.8 — Web Service
Template
templates/web-service.yaml
Service
type: ClusterIP
Étape 4-H.9 — PostgreSQL
Option 1
Utiliser :
Bitnami PostgreSQL
Dépendance
dependencies: - name: postgresql version: 15.* repository: https://charts.bitnami.com/bitnami
Valeurs
postgresql: auth: database: rental_platform
Étape 4-H.10 — Redis
Dépendance
dependencies: - name: redis repository: https://charts.bitnami.com/bitnami
Valeurs
redis: architecture: standalone
Étape 4-H.11 — MinIO
Dépendance
dependencies: - name: minio repository: https://charts.bitnami.com/bitnami
Bucket
contracts properties documents uploads
Étape 4-H.12 — ConfigMap
Template
templates/configmap.yaml
Variables
DATABASE_HOST REDIS_HOST MINIO_ENDPOINT NODE_ENV
Étape 4-H.13 — Secrets
Template
templates/secret.yaml
Contenu
POSTGRES_PASSWORD JWT_SECRET MINIO_SECRET_KEY STRIPE_SECRET_KEY
Recommandation
Ne jamais stocker les secrets dans Git.
Utiliser :
External Secrets AWS Secrets Manager Azure Key Vault Hashicorp Vault
Étape 4-H.14 — Ingress
Template
templates/ingress.yaml
Domaine
api.domain.com app.domain.com
Exemple
rules: - host: api.domain.com - host: app.domain.com
Étape 4-H.15 — TLS
Cert Manager
cert-manager
Issuer
Let's Encrypt
HTTPS
TLS obligatoire
Étape 4-H.16 — Horizontal Pod Autoscaler
API
templates/api-hpa.yaml
Configuration
minReplicas: 3 maxReplicas: 20 targetCPUUtilizationPercentage: 70
Web
minReplicas: 2 maxReplicas: 10
Étape 4-H.17 — Pod Disruption Budget
API
minAvailable: 2
Web
minAvailable: 1
Étape 4-H.18 — Resources
API
requests: cpu: 500m memory: 512Mi limits: cpu: 2000m memory: 2Gi
Web
requests: cpu: 250m memory: 256Mi
Étape 4-H.19 — Liveness & Readiness
API
livenessProbe: httpGet: path: /health port: 3000
Readiness
readinessProbe: httpGet: path: /health port: 3000
Étape 4-H.20 — Jobs Kubernetes
Migrations Prisma
templates/job-migration.yaml
Commande
npx prisma migrate deploy
Seed
npx prisma db seed
Étape 4-H.21 — Monitoring
Prometheus
kube-prometheus-stack
Grafana
Dashboards API PostgreSQL Redis Kubernetes
Étape 4-H.22 — Logging
Stack
Loki Promtail Grafana
Objectif
Centraliser :
API Logs Audit Logs Security Logs Business Logs
Étape 4-H.23 — Installation
Ajouter dépendances
helm dependency update
Vérifier
helm lint deploy/helm/rental-platform
Dry Run
helm install rental-platform \ deploy/helm/rental-platform \ --dry-run
Étape 4-H.24 — Déploiement
Dev
helm upgrade \ --install rental-platform \ deploy/helm/rental-platform \ -f values-dev.yaml
Staging
helm upgrade \ --install rental-platform \ -f values-staging.yaml
Production
helm upgrade \ --install rental-platform \ -f values-prod.yaml
Arborescence finale
deploy
└── helm
└── rental-platform
├── Chart.yaml
├── values.yaml
├── values-dev.yaml
├── values-staging.yaml
├── values-prod.yaml
└── templates
├── namespace.yaml
├── api-deployment.yaml
├── api-service.yaml
├── web-deployment.yaml
├── web-service.yaml
├── ingress.yaml
├── configmap.yaml
├── secret.yaml
├── api-hpa.yaml
└── job-migration.yaml
Définition de terminé
La Phase 4-H est terminée lorsque :
✓ Helm valide ✓ Déploiement Kubernetes valide ✓ HPA opérationnel ✓ TLS opérationnel ✓ Monitoring opérationnel ✓ Logging centralisé ✓ Rolling Update opérationnel
Livrables
deploy/helm/** Chart.yaml values*.yaml templates/*
Phase 4-I — Terraform Infrastructure Enterprise
Objectif
Décrire l'intégralité de l'infrastructure Cloud sous forme de code.
Cette phase transforme :
Infrastructure manuelle ↓ Infrastructure as Code (IaC) ↓ Terraform
afin d'obtenir :
✓ Infrastructure reproductible ✓ Multi-environnements ✓ Versionnée dans Git ✓ Auditée ✓ Déployable automatiquement
Plateforme cible
Cloud principal
AWS
Compatibilité
AWS Azure GCP OVH Cloud
Architecture cible
Internet ↓ Cloudflare ↓ ALB ↓ EKS ├── API ├── WEB ├── Workers ↓ RDS PostgreSQL ↓ Elasticache Redis ↓ S3 ↓ Secrets Manager ↓ CloudWatch
Étape 4-I.1 — Structure Terraform
Créer
deploy
└── terraform
├── environments
│ ├── dev
│ ├── staging
│ └── prod
│
├── modules
│ ├── network
│ ├── eks
│ ├── rds
│ ├── redis
│ ├── s3
│ ├── dns
│ ├── monitoring
│ └── security
│
└── global
Étape 4-I.2 — Backend Terraform
Objectif
Stocker l'état Terraform.
Fichier
global/backend.tf
Exemple AWS
terraform {
backend "s3" {
bucket = "rental-platform-tf-state"
key = "prod/terraform.tfstate"
region = "eu-west-3"
encrypt = true
}
}
Étape 4-I.3 — Provider AWS
provider.tf
provider "aws" {
region = var.aws_region
}
Variables
variable "aws_region" {
default = "eu-west-3"
}
Étape 4-I.4 — Réseau (VPC)
Module
modules/network
Ressources
VPC Public Subnets Private Subnets NAT Gateway Internet Gateway Route Tables
Exemple
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
Étape 4-I.5 — Kubernetes EKS
Module
modules/eks
Cluster
resource "aws_eks_cluster" "main" {
name = "rental-platform"
}
Node Groups
System Application Jobs
Sizing
Min 3 nodes Max 20 nodes
Étape 4-I.6 — PostgreSQL RDS
Module
modules/rds
Ressource
resource "aws_db_instance" "postgres" {
engine = "postgres"
engine_version = "16"
}
Configuration
Multi-AZ Encrypted Automated Backup Point In Time Recovery
Taille initiale
db.t3.medium
Étape 4-I.7 — Redis
Module
modules/redis
Ressource
resource "aws_elasticache_replication_group" "redis" {
engine = "redis"
}
Configuration
Primary Replica Automatic Failover
Étape 4-I.8 — S3
Module
modules/s3
Buckets
contracts properties documents backups exports
Exemple
resource "aws_s3_bucket" "documents" {
bucket = "rental-platform-documents"
}
Étape 4-I.9 — DNS
Module
modules/dns
Route53
api.domain.com app.domain.com grafana.domain.com
Exemple
resource "aws_route53_record" "api" {
}
Étape 4-I.10 — Certificats SSL
ACM
resource "aws_acm_certificate" "main" {
}
Domaines
*.domain.com
Étape 4-I.11 — Load Balancer
ALB
resource "aws_lb" "main" {
}
Routing
/api ↓ NestJS ---------------- / ↓ NextJS
Étape 4-I.12 — Secrets Manager
Module
modules/security
Secrets
DATABASE_URL JWT_SECRET STRIPE_SECRET MINIO_SECRET OPENAI_API_KEY
Exemple
resource "aws_secretsmanager_secret" "jwt" {
}
Étape 4-I.13 — Monitoring
Module
modules/monitoring
Services
CloudWatch Prometheus Grafana
Dashboards
API Database Redis Kubernetes Business KPI
Étape 4-I.14 — Logging
Services
CloudWatch Logs Loki
Collecte
API Logs Audit Logs Security Logs Job Logs
Étape 4-I.15 — Alerting
Canaux
Email Slack Teams PagerDuty
Déclencheurs
CPU > 80% Memory > 80% API Down Database Down Failed Jobs
Étape 4-I.16 — WAF
Protection
AWS WAF
Règles
SQL Injection XSS Rate Limit Bots
Étape 4-I.17 — CloudFront
CDN
resource "aws_cloudfront_distribution" "main" {
}
Accélération
Images Documents Frontend Assets
Étape 4-I.18 — Environnement DEV
Dossier
environments/dev
Taille
1 node Petite RDS Petit Redis
Étape 4-I.19 — Environnement STAGING
Dossier
environments/staging
Taille
2 nodes Replica DB
Étape 4-I.20 — Environnement PROD
Dossier
environments/prod
Taille
3+ nodes Multi-AZ Autoscaling HA
Étape 4-I.21 — Variables Terraform
variables.tf
variable "environment" {}
variable "domain_name" {}
variable "db_instance_class" {}
terraform.tfvars
environment = "prod" domain_name = "example.com"
Étape 4-I.22 — Outputs
outputs.tf
output "api_url" {}
output "web_url" {}
output "database_endpoint" {}
Étape 4-I.23 — Validation
Format
terraform fmt
Validation
terraform validate
Plan
terraform plan
Apply
terraform apply
Définition de terminé
La Phase 4-I est terminée lorsque :
✓ VPC créé ✓ EKS créé ✓ PostgreSQL créé ✓ Redis créé ✓ S3 créé ✓ DNS créé ✓ SSL créé ✓ Monitoring créé ✓ Terraform validé
Livrables
deploy/terraform modules/network modules/eks modules/rds modules/redis modules/s3 modules/dns modules/security modules/monitoring
Phase 4-J — Monorepo Final Enterprise
Objectif
Assembler l'ensemble des livrables produits depuis la Phase 1 jusqu'à la Phase 4-I dans un dépôt unique, cohérent et exécutable.
À l'issue de cette phase :
✓ Monorepo finalisé ✓ Backend NestJS ✓ Frontend NextJS ✓ Prisma ✓ PostgreSQL ✓ Redis ✓ Contracts ✓ SDK ✓ Docker ✓ Helm ✓ Terraform ✓ GitHub Actions ✓ Documentation
Le projet devient alors :
Release Enterprise 4.0
prête pour le développement métier continu.
Vision finale
Dépôt Git
rental-platform/
Architecture
rental-platform ├── apps ├── libs ├── deploy ├── docker ├── docs ├── scripts ├── .github ├── package.json ├── nx.json ├── tsconfig.base.json └── README.md
Étape 4-J.1 — Applications
Structure
apps ├── api └── web
API
apps/api ├── prisma ├── src ├── test ├── Dockerfile └── project.json
WEB
apps/web ├── src ├── public ├── Dockerfile └── project.json
Étape 4-J.2 — Librairies
Structure
libs ├── contracts ├── sdk ├── ui ├── config ├── shared ├── testing └── eslint-config
contracts
DTO Types Enums Zod Schemas
sdk
OpenAPI Client React Query Hooks API Wrappers
ui
Design System Layout Components Business Components
Étape 4-J.3 — Infrastructure
Structure
deploy ├── helm └── terraform
Helm
deploy/helm/rental-platform
Terraform
deploy/terraform
Étape 4-J.4 — Docker
Structure
docker ├── nginx ├── postgres ├── redis ├── minio ├── prometheus └── grafana
Fichier principal
docker-compose.yml
Étape 4-J.5 — GitHub
Structure
.github ├── workflows └── dependabot.yml
Workflows
ci.yml quality.yml security.yml docker.yml release.yml deploy.yml
Étape 4-J.6 — Scripts
Structure
scripts ├── bootstrap.sh ├── migrate.sh ├── seed.sh ├── reset-db.sh ├── generate-sdk.sh ├── generate-openapi.sh └── release.sh
bootstrap.sh
Objectif :
Installation complète développeur
Exemple
#!/bin/bash npm install docker compose up -d npx prisma migrate dev npx prisma db seed nx run-many --target=build
Étape 4-J.7 — Documentation
Structure
docs ├── architecture ├── api ├── deployment ├── development ├── operations └── decisions
Architecture
DDD CQRS Hexagonal Multi-Tenant RBAC
API
OpenAPI Swagger SDK
Étape 4-J.8 — README principal
Sections
Présentation Architecture Prérequis Installation Développement Tests Déploiement Contribution
Démarrage rapide
git clone ... cd rental-platform npm install docker compose up -d npx prisma migrate dev npx prisma db seed nx serve api nx serve web
Étape 4-J.9 — Qualité globale
Vérifications
nx graph
Lint
nx run-many \ --target=lint \ --all
Tests
nx run-many \ --target=test \ --all
Build
nx run-many \ --target=build \ --all
Étape 4-J.10 — Génération OpenAPI
Commande
npm run swagger:generate
Livrable
docs/api/openapi.yaml
Étape 4-J.11 — Génération SDK
Commande
npm run sdk:generate
Livrable
libs/sdk
Étape 4-J.12 — Release Enterprise
Version
v1.0.0
Tag Git
git tag v1.0.0 git push origin v1.0.0
Déclenche
Release GitHub Build Docker Publication Registry Artifacts
Arborescence finale
rental-platform ├── apps │ │ ├── api │ └── web │ ├── libs │ │ ├── contracts │ ├── sdk │ ├── ui │ ├── config │ └── shared │ ├── deploy │ │ ├── helm │ └── terraform │ ├── docker │ ├── docs │ ├── scripts │ ├── .github │ ├── docker-compose.yml │ ├── package.json │ ├── nx.json │ └── README.md
Définition de terminé
La Phase 4-J est terminée lorsque :
✓ Monorepo compilable ✓ API compilable ✓ Frontend compilable ✓ Prisma opérationnel ✓ Docker opérationnel ✓ CI opérationnelle ✓ Helm valide ✓ Terraform valide ✓ OpenAPI généré ✓ SDK généré ✓ Documentation présente
Livrables finaux
Repository Enterprise complet Backend NestJS Frontend NextJS Prisma Contracts SDK Docker GitHub Actions Helm Terraform Documentation
Fin du cycle d'architecture
Le projet dispose désormais de :
Architecture fonctionnelle Architecture technique Contrat API Modèle de données Infrastructure CI/CD Industrialisation
La suite logique n'est plus la conception.
La suite logique est :
Sprint Développement 1
Implémentation réelle du domaine Authentification
Register Login JWT Refresh Token RBAC Swagger Tests
sur la base du monorepo désormais entièrement structuré et prêt à exécuter du code métier.