Avez-vous une question? (216) 97 656 803 hajjriadh@gmail.com
NestJS

TP 12 : Réaliser une application Full-Stack de gestion des stagiaires (Angular + NestJS + MySQL)

Ce TP réalise une application complète de gestion des stagiaires dans un monorepo publié sur GitHub. L'API NestJS repose sur MySQL avec TypeORM, une migration et un seed. Elle authentifie par JWT, rés...

0 chapitres 0 QCM Accès gratuit
TP 12 : Réaliser une application Full-Stack de gestion des stagiaires (Angular + NestJS + MySQL)

À propos de ce cours

Ce TP réalise une application complète de gestion des stagiaires dans un monorepo publié sur GitHub. L'API NestJS repose sur MySQL avec TypeORM, une migration et un seed. Elle authentifie par JWT, réserve les écritures aux administrateurs, pagine et filtre les stagiaires, et refuse les e-mails en double (409). L'application Angular propose la connexion, un tableau paginé avec recherche et filtre par groupe, et des formulaires de création et de modification qui affichent les erreurs de l'API, avec un intercepteur et des guards. Les interfaces sont partagées. Parcours réel dans Chrome, captures, correction et grille sur 20.

Objectifs du TP

  • Concevoir une application complète : base MySQL, API NestJS, client Angular.
  • Partager le contrat entre l'API et le client dans un monorepo.
  • Mettre en place l'authentification JWT et les rôles de bout en bout.
  • Gérer côté client chargement, pagination, formulaires et toutes les erreurs de l'API.
  • Publier le projet sur GitHub dès le départ, avec un commit par étape.

Durée: 8 h  |  Prérequis: chapitres 11, 13 et 18  |  Livrable: le dépôt gestion-stagiaires avec l'étiquette v1.0.0.

Architecture du TP 12

Un monorepo : client Angular, API NestJS, types partagés, base MySQL.

Liste des stagiaires pour un administrateur

La liste vue par l'administratrice : recherche, filtre par groupe (avec effectifs), actions et pagination.

Cahier des charges
FonctionAPIAngular
ConnexionPOST /api/auth/connexion → jeton + utilisateur ; même message pour e-mail inconnu et mot de passe fauxpage /connexion, retour à la page demandée
ListeGET /api/stagiaires?q=&groupeId=&page=&limite= → Page<Stagiaire>; tout utilisateur connectétableau, recherche (nom, prénom, e-mail), filtre par groupe, pages de 8
GroupesGET /api/groupes avec l'effectif de chaque groupeliste déroulante du filtre et du formulaire
Création, modificationPOST et PATCH /api/stagiaires; admin ; validation ; e-mail unique (409) ; groupe existant (400)formulaire commun, prérempli en modification, erreurs de l'API affichées
SuppressionDELETE /api/stagiaires/:id; admin (204)confirmation, liste rechargée
Rôlesformateur : lecture seule (403 sur les écritures)boutons masqués, routes d'édition protégées par roleGuard
Partie 1 Monorepo et dépôt GitHub
  1. Créez le dépôt gestion-stagiaires sur GitHub et la structure de la leçon 18.1 : apps/api (nest new, CommonJS), apps/web (ng new), packages/partage, package.json racine avec les workspaces et concurrently.
  2. .gitignore racine : node_modules/, dist/, .angular/, .env. Commit : chore: monorepo.
  3. Écrivez le contrat dans packages/partage/src/index.ts (correction ci-dessous) avant de coder les applications. Commit : feat: contrat partagé.
Partie 2 API : base de données
  1. Dépendances : npm install @nestjs/config @nestjs/typeorm typeorm mysql2 @nestjs/jwt bcrypt class-validator class-transformer @nestjs/mapped-types -w api.
  2. Entités Utilisateur, Groupe, Stagiaire; data-source.ts; scripts de migration et de seed (chapitre 11).
  3. Base gestion_stagiaires, migration Initialisation, seed (2 comptes, 3 groupes, 12 stagiaires). Commit : feat(api): base et données de démonstration.
$ npm run migration:generate --name=Initialisation
◇ injected env (9) from .env
Migration src/migrations/1794756939922-Initialisation.ts has been generated successfully.

$ npm run migration:run
1 migrations are new migrations must be executed.
query: INSERT INTO `gestion_stagiaires`.`migrations`(`timestamp`, `name`) VALUES (?, ?) -- PARAMETERS: [1794756939922,"Initialisation1794756939922"]
Migration Initialisation1794756939922 has been executed successfully.

$ npm run seed
Comptes : 2, groupes : 3, stagiaires : 12
Partie 3 API : authentification et routes
  1. AuthModule (connexion avec hachage factice, guard global JWT + rôles, @Public, @Roles, @Moi).
  2. GET /api/groupes avec les effectifs (attention : COUNT arrive en chaîne).
  3. StagiairesService: liste paginée filtrée en SQL, conversion entité → Stagiaire du contrat, e-mail unique, groupe vérifié ; DTO qui implements les interfaces.
  4. configurerApp: préfixe, ValidationPipe, filtre TypeORM, CORS depuis .env. Testez avec un fichier .http. Commit : feat(api): authentification et stagiaires.
Partie 4 Angular : socle
  1. Environnements (apiUrl), provideHttpClient(withFetch(), withInterceptors([authInterceptor])), withComponentInputBinding().
  2. AuthService, authInterceptor, authGuard, roleGuard, messagesErreur (leçons 18.3 et 18.4), page de connexion, en-tête avec l'utilisateur et la déconnexion.
  3. Routes : toutes les pages des stagiaires derrière authGuard; création et modification derrière roleGuard('admin'). Commit : feat(web): authentification.
Partie 5 Angular : écrans des stagiaires
  1. StagiairesService typé avec le contrat.
  2. Liste : tableau, recherche, filtre par groupe, pagination (boutons désactivés aux extrémités), actions réservées à l'admin, suppression avec confirmation.
  3. Formulaire commun création/modification : formulaire réactif, validation client, préremplissage, affichage des erreurs 400 et 409 de l'API. Commit : feat(web): gestion des stagiaires.
Partie 6 Vérifier et livrer
  1. Déroulez le scénario du résultat attendu dans votre navigateur, avec les deux comptes, et vérifiez chaque statut dans l'onglet Réseau.
  2. Vérifiez que l'API refuse les écritures d'un formateur même en appelant l'API directement (console du navigateur ou fichier .http).
  3. npm run build à la racine sans erreur. README : installation, base, migration, seed, comptes de démonstration, npm run dev, captures d'écran.
  4. Push, étiquette v1.0.0.
Résultat attendu

Parcours réel dans Chrome avec la correction (requêtes observées vers l'API) :

1. Visiteur non connecté sur /stagiaires
   → /connexion?retour=%2Fstagiaires
2. Connexion de l'administratrice
  POST /api/auth/connexion → 200
  GET /api/groupes → 200
  GET /api/stagiaires?page=1&limite=8 → 200
   lignes : 8 — Page 1 / 2 · 12 stagiaire(s)
3. Page suivante, puis filtre DEV101 et recherche « ra »
  GET /api/stagiaires?page=2&limite=8 → 200
   Page 2 / 2 · 12 stagiaire(s)
  GET /api/stagiaires?page=1&limite=8&groupeId=1 → 200
   Page 1 / 1 · 6 stagiaire(s)
  GET /api/stagiaires?page=1&limite=8&q=ra&groupeId=1 → 200
   Mejri
4. Nouveau stagiaire avec un e-mail déjà utilisé
  GET /api/groupes → 200
  POST /api/stagiaires → 409
   message : Un stagiaire utilise déjà cet e-mail
5. E-mail corrigé
  POST /api/stagiaires → 201
  GET /api/groupes → 200
  GET /api/stagiaires?page=1&limite=8 → 200
  GET /api/stagiaires?page=1&limite=8&q=kefi → 200
   Kefi | Aziz | aziz.kefi@exemple.tn | DEV101 | 21/03/2005 | Modifier · Supprimer
6. Modification : groupe MM301
  GET /api/groupes → 200
  GET /api/stagiaires/15 → 200
   formulaire prérempli : aziz.kefi@exemple.tn
  PATCH /api/stagiaires/15 → 200
  GET /api/groupes → 200
  GET /api/stagiaires?page=1&limite=8 → 200
  GET /api/stagiaires?page=1&limite=8&q=kefi → 200
   Kefi | Aziz | aziz.kefi@exemple.tn | MM301 | 21/03/2005 | Modifier · Supprimer
7. Suppression
  DELETE /api/stagiaires/15 → 204
  GET /api/stagiaires?page=1&limite=8&q=kefi → 200
   Aucun stagiaire ne correspond.
8. Déconnexion, connexion de la formatrice
  POST /api/auth/connexion → 200
  GET /api/groupes → 200
  GET /api/stagiaires?page=1&limite=8 → 200
   bouton « Nouveau » : 0 ; colonnes : 5
   /stagiaires/nouveau → /acces-refuse
9. Appel direct à l'API avec le jeton de la formatrice (contournement de l'interface)
  DELETE /api/stagiaires/1 → 403
   DELETE /api/stagiaires/1 → 403 {"message":"Action réservée aux administrateurs","error":"Forbidden","statusCode":403}

Formulaire avec erreur 409

Le formulaire après le 409 de l'API : l'e-mail est déjà utilisé.

Liste vue par une formatrice

La même liste pour la formatrice : lecture seule, sans bouton ni colonne d'actions.

À vérifier : redirection vers la connexion sans session ; pagination, filtre et recherche faits par l'API (paramètres dans l'URL des requêtes) ; 409 affiché dans le formulaire ; formulaire prérempli en modification ; suppression ; pour la formatrice, aucun bouton d'écriture, /stagiaires/nouveau redirigé vers /acces-refuse, et 403 de l'API pour un appel direct.

Pour aller plus loin
  • Tri par colonne (clic sur l'en-tête), avec un paramètre tri validé par l'API (leçon 11.7).
  • Recherche pendant la saisie avec debounceTime et switchMap (leçon 18.3, activité 2).
  • Refresh token et rejeu des requêtes dans l'intercepteur (leçon 18.4, activité 3).
  • Tests e2e de l'API (chapitre 17) et tests unitaires des services Angular.
  • Page de détail d'un stagiaire avec ses notes (TP 8) et son dossier de documents (TP 9).
Correction : API et contrat
packages/partage/src/index.ts
// Contrat partagé entre l'API (apps/api) et le client Angular (apps/web) : uniquement des types.

export type Role = 'admin' | 'formateur';

export interface Utilisateur {
  id: number;
  email: string;
  nom: string;
  role: Role;
}

export interface Connexion {
  email: string;
  motDePasse: string;
}

export interface ReponseConnexion {
  access_token: string;
  expires_in: number;
  utilisateur: Utilisateur;
}

export interface Groupe {
  id: number;
  code: string;
  intitule: string;
  effectif: number;
}

export interface Stagiaire {
  id: number;
  nom: string;
  prenom: string;
  email: string;
  dateNaissance: string;          // AAAA-MM-JJ
  groupe: Pick<Groupe, 'id' | 'code'> | null;
  creeLe: string;
}

export interface CreerStagiaire {
  nom: string;
  prenom: string;
  email: string;
  dateNaissance: string;
  groupeId: number | null;
}

export type ModifierStagiaire = Partial<CreerStagiaire>;

export interface FiltreStagiaires {
  q?: string;
  groupeId?: number;
  page?: number;
  limite?: number;
}

export interface Page<T> {
  donnees: T[];
  total: number;
  page: number;
  pages: number;
}

export interface ErreurApi {
  statusCode: number;
  message: string | string[];
  error?: string;
}
apps/api/package.json
{
  "name": "api",
  "version": "0.0.1",
  "description": "",
  "author": "",
  "private": true,
  "license": "UNLICENSED",
  "scripts": {
    "build": "nest build",
    "deploy": "nest deploy",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "oxlint --type-aware src/ test/",
    "test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js",
    "test:watch": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --watch",
    "test:cov": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --coverage",
    "test:debug": "node --inspect-brk --experimental-vm-modules -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config ./test/jest-e2e.json",
    "typeorm": "typeorm -d dist/data-source.js",
    "migration:generate": "npm run build && typeorm migration:generate -d dist/data-source.js src/migrations/$npm_config_name",
    "migration:run": "npm run build && typeorm migration:run -d dist/data-source.js",
    "seed": "npm run build && node dist/seeds/seed.js"
  },
  "dependencies": {
    "@nestjs/common": "^12.0.1",
    "@nestjs/config": "^12.1.1",
    "@nestjs/core": "^12.0.1",
    "@nestjs/jwt": "^12.0.5",
    "@nestjs/mapped-types": "^12.0.1",
    "@nestjs/platform-express": "^12.0.1",
    "bcrypt": "^6.0.0",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.15.1",
    "reflect-metadata": "^0.2.2",
    "rxjs": "^7.8.1",
    "@nestjs/typeorm": "^12.0.3",
    "typeorm": "^1.1.3",
    "mysql2": "^3.24.6"
  },
  "devDependencies": {
    "@nestjs/cli": "^12.0.0",
    "@nestjs/mau": "^0.2.6",
    "@nestjs/schematics": "^12.0.0",
    "@nestjs/testing": "^12.0.1",
    "@types/bcrypt": "^6.0.0",
    "@types/express": "^5.0.0",
    "@types/jest": "^30.0.0",
    "@types/node": "^24.0.0",
    "@types/supertest": "^7.0.0",
    "jest": "^30.0.0",
    "oxlint": "^1.58.0",
    "oxlint-tsgolint": "^7.0.2001",
    "prettier": "^3.4.2",
    "source-map-support": "^0.5.21",
    "supertest": "^7.0.0",
    "ts-jest": "^29.4.0",
    "ts-loader": "^9.5.2",
    "ts-node": "^10.9.2",
    "tsconfig-paths": "^4.2.0",
    "typescript": "^6.0.2"
  }
}
apps/api/src/data-source.ts
import 'dotenv/config';
import { DataSource } from 'typeorm';

// Utilisée par la CLI TypeORM (migrations) ; l'application utilise TypeOrmModule
export default new DataSource({
  type: 'mysql',
  host: process.env.DB_HOTE,
  port: Number(process.env.DB_PORT ?? 3306),
  username: process.env.DB_UTILISATEUR,
  password: process.env.DB_MOT_DE_PASSE,
  database: process.env.DB_NOM,
  entities: [__dirname + '/**/*.entity.js'],
  migrations: [__dirname + '/migrations/*.js'],
});
apps/api/src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { GroupesModule } from './groupes/groupes.module';
import { StagiairesModule } from './stagiaires/stagiaires.module';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (c: ConfigService) => ({
        type: 'mysql',
        host: c.getOrThrow('DB_HOTE'),
        port: Number(c.get('DB_PORT', 3306)),
        username: c.getOrThrow('DB_UTILISATEUR'),
        password: c.get('DB_MOT_DE_PASSE', ''),
        database: c.getOrThrow('DB_NOM'),
        autoLoadEntities: true,
        synchronize: false,                  // le schéma vient des migrations
      }),
    }),
    AuthModule,
    GroupesModule,
    StagiairesModule,
  ],
})
export class AppModule {}
apps/api/src/configurer-app.ts
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { TypeOrmErreursFilter } from './commun/typeorm-erreurs.filter';

// Partagé par main.ts et les tests e2e (leçon 17.4)
export function configurerApp(app: INestApplication) {
  app.setGlobalPrefix('api');
  app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
  app.useGlobalFilters(new TypeOrmErreursFilter());
  app.enableCors({
    origin: (process.env.CORS_ORIGINES ?? '').split(',').map((o) => o.trim()).filter(Boolean),
    methods: ['GET', 'POST', 'PATCH', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization'],
  });
  return app;
}
apps/api/src/utilisateurs/utilisateur.entity.ts
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
import type { Role } from '@gestion/partage';

@Entity('utilisateurs')
export class Utilisateur {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 120, unique: true })
  email: string;

  @Column({ length: 80 })
  nom: string;

  @Column({ type: 'enum', enum: ['admin', 'formateur'], default: 'formateur' })
  role: Role;

  @Column({ name: 'mot_de_passe', length: 60, select: false })
  motDePasse: string;
}
apps/api/src/groupes/groupe.entity.ts
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm';
import { Stagiaire } from '../stagiaires/stagiaire.entity';

@Entity('groupes')
export class Groupe {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 10, unique: true })
  code: string;

  @Column({ length: 100 })
  intitule: string;

  @OneToMany(() => Stagiaire, (s) => s.groupe)
  stagiaires: Stagiaire[];
}
apps/api/src/stagiaires/stagiaire.entity.ts
import { Column, CreateDateColumn, Entity, Index, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { Groupe } from '../groupes/groupe.entity';

@Entity('stagiaires')
export class Stagiaire {
  @PrimaryGeneratedColumn()
  id: number;

  @Index()
  @Column({ length: 60 })
  nom: string;

  @Column({ length: 60 })
  prenom: string;

  @Column({ length: 120, unique: true })
  email: string;

  @Column({ type: 'date', name: 'date_naissance' })
  dateNaissance: string;

  @ManyToOne(() => Groupe, (g) => g.stagiaires, { nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'groupe_id' })
  groupe: Groupe | null;

  @CreateDateColumn({ name: 'cree_le' })
  creeLe: Date;
}
apps/api/src/auth/decorateurs.ts
import { createParamDecorator, ExecutionContext, SetMetadata } from '@nestjs/common';
import type { Role, Utilisateur } from '@gestion/partage';

export const Public = () => SetMetadata('public', true);
export const Roles = (...roles: Role[]) => SetMetadata('roles', roles);
export const Moi = createParamDecorator((_: unknown, ctx: ExecutionContext): Utilisateur => ctx.switchToHttp().getRequest().user);
apps/api/src/auth/auth.guard.ts
import { CanActivate, ExecutionContext, ForbiddenException, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import type { Role, Utilisateur } from '@gestion/partage';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly jwt: JwtService, private readonly reflector: Reflector) {}

  async canActivate(ctx: ExecutionContext) {
    const cibles = [ctx.getHandler(), ctx.getClass()];
    if (this.reflector.getAllAndOverride<boolean>('public', cibles)) return true;
    const req = ctx.switchToHttp().getRequest();
    const [type, jeton] = (req.headers.authorization ?? '').split(' ');
    if (type !== 'Bearer' || !jeton) throw new UnauthorizedException('Jeton manquant');
    try {
      req.user = await this.jwt.verifyAsync<Utilisateur>(jeton);
    } catch {
      throw new UnauthorizedException('Jeton invalide ou expiré');
    }
    const roles = this.reflector.getAllAndOverride<Role[]>('roles', cibles);
    if (roles?.length && !roles.includes(req.user.role)) throw new ForbiddenException('Action réservée aux administrateurs');
    return true;
  }
}
apps/api/src/auth/auth.service.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import * as bcrypt from 'bcrypt';
import type { ReponseConnexion } from '@gestion/partage';
import { Repository } from 'typeorm';
import { Utilisateur } from '../utilisateurs/utilisateur.entity';

const HACHAGE_FACTICE = bcrypt.hashSync('factice', 10);     // même durée de réponse si le compte n'existe pas (13.3)

@Injectable()
export class AuthService {
  constructor(@InjectRepository(Utilisateur) private readonly utilisateurs: Repository<Utilisateur>, private readonly jwt: JwtService) {}

  async connecter(email: string, motDePasse: string): Promise<ReponseConnexion> {
    const u = await this.utilisateurs.findOne({ where: { email: email.toLowerCase() }, select: { id: true, email: true, nom: true, role: true, motDePasse: true } });
    const valide = await bcrypt.compare(motDePasse, u?.motDePasse ?? HACHAGE_FACTICE);
    if (!u || !valide) throw new UnauthorizedException('E-mail ou mot de passe incorrect');
    const utilisateur = { id: u.id, email: u.email, nom: u.nom, role: u.role };
    return { access_token: await this.jwt.signAsync(utilisateur), expires_in: 3600, utilisateur };
  }
}
apps/api/src/auth/auth.controller.ts
import { Body, Controller, Get, HttpCode, Post } from '@nestjs/common';
import { IsEmail, IsString } from 'class-validator';
import type { Connexion, Utilisateur } from '@gestion/partage';
import { AuthService } from './auth.service';
import { Moi, Public } from './decorateurs';

export class ConnexionDto implements Connexion {
  @IsEmail() email: string;
  @IsString() motDePasse: string;
}

@Controller('auth')
export class AuthController {
  constructor(private readonly auth: AuthService) {}

  @Public()
  @Post('connexion')
  @HttpCode(200)
  connecter(@Body() dto: ConnexionDto) {
    return this.auth.connecter(dto.email, dto.motDePasse);
  }

  @Get('profil')
  profil(@Moi() moi: Utilisateur) {
    return { id: moi.id, email: moi.email, nom: moi.nom, role: moi.role };
  }
}
apps/api/src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { APP_GUARD } from '@nestjs/core';
import { JwtModule } from '@nestjs/jwt';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Utilisateur } from '../utilisateurs/utilisateur.entity';
import { AuthController } from './auth.controller';
import { AuthGuard } from './auth.guard';
import { AuthService } from './auth.service';

@Module({
  imports: [
    TypeOrmModule.forFeature([Utilisateur]),
    JwtModule.registerAsync({
      inject: [ConfigService],
      useFactory: (c: ConfigService) => ({ secret: c.getOrThrow('JWT_SECRET'), signOptions: { expiresIn: c.get('JWT_DUREE', '1h') } }),
    }),
  ],
  controllers: [AuthController],
  providers: [AuthService, { provide: APP_GUARD, useClass: AuthGuard }],
})
export class AuthModule {}
apps/api/src/groupes/groupes.controller.ts
import { Controller, Get } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import type { Groupe as GroupeVue } from '@gestion/partage';
import { Repository } from 'typeorm';
import { Groupe } from './groupe.entity';

@Controller('groupes')
export class GroupesController {
  constructor(@InjectRepository(Groupe) private readonly groupes: Repository<Groupe>) {}

  @Get()
  async lister(): Promise<GroupeVue[]> {
    const lignes = await this.groupes.createQueryBuilder('g')
      .leftJoin('g.stagiaires', 's')
      .select(['g.id AS id', 'g.code AS code', 'g.intitule AS intitule'])
      .addSelect('COUNT(s.id)', 'effectif')
      .groupBy('g.id').orderBy('g.code')
      .getRawMany<{ id: number; code: string; intitule: string; effectif: string }>();
    return lignes.map((l) => ({ ...l, effectif: Number(l.effectif) }));   // COUNT arrive en chaîne (leçon 11.6)
  }
}
apps/api/src/stagiaires/stagiaire.dto.ts
import { PartialType } from '@nestjs/mapped-types';
import { Transform, Type } from 'class-transformer';
import { IsDateString, IsEmail, IsInt, IsOptional, IsPositive, IsString, Length, Max, Min, ValidateIf } from 'class-validator';
import type { CreerStagiaire, FiltreStagiaires } from '@gestion/partage';

const nettoyer = ({ value }: { value: unknown }) => (typeof value === 'string' ? value.trim() : value);

export class CreerStagiaireDto implements CreerStagiaire {
  @Transform(nettoyer) @IsString() @Length(2, 60)
  nom: string;

  @Transform(nettoyer) @IsString() @Length(2, 60)
  prenom: string;

  @Transform(({ value }) => (typeof value === 'string' ? value.trim().toLowerCase() : value)) @IsEmail()
  email: string;

  @IsDateString({ strict: true }, { message: 'dateNaissance doit être une date AAAA-MM-JJ' })
  dateNaissance: string;

  @ValidateIf((o) => o.groupeId !== null) @IsInt() @IsPositive()
  groupeId: number | null;
}

export class ModifierStagiaireDto extends PartialType(CreerStagiaireDto) {}

export class FiltreStagiairesDto implements FiltreStagiaires {
  @IsOptional() @IsString()
  q?: string;

  @IsOptional() @Type(() => Number) @IsInt()
  groupeId?: number;

  @IsOptional() @Type(() => Number) @IsInt() @Min(1)
  page: number = 1;

  @IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(50)
  limite: number = 10;
}
apps/api/src/stagiaires/stagiaires.service.ts
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import type { Page, Stagiaire as StagiaireVue } from '@gestion/partage';
import { Brackets, Not, Repository } from 'typeorm';
import { Groupe } from '../groupes/groupe.entity';
import { CreerStagiaireDto, FiltreStagiairesDto, ModifierStagiaireDto } from './stagiaire.dto';
import { Stagiaire } from './stagiaire.entity';

// Entité → objet du contrat partagé (pas d'entité TypeORM envoyée telle quelle au client)
const versVue = (s: Stagiaire): StagiaireVue => ({
  id: s.id, nom: s.nom, prenom: s.prenom, email: s.email, dateNaissance: s.dateNaissance,
  groupe: s.groupe ? { id: s.groupe.id, code: s.groupe.code } : null,
  creeLe: s.creeLe.toISOString(),
});

@Injectable()
export class StagiairesService {
  constructor(
    @InjectRepository(Stagiaire) private readonly stagiaires: Repository<Stagiaire>,
    @InjectRepository(Groupe) private readonly groupes: Repository<Groupe>,
  ) {}

  async lister(f: FiltreStagiairesDto): Promise<Page<StagiaireVue>> {
    const qb = this.stagiaires.createQueryBuilder('s').leftJoinAndSelect('s.groupe', 'g')
      .orderBy('s.nom').addOrderBy('s.prenom')
      .skip((f.page - 1) * f.limite).take(f.limite);
    if (f.q) {
      qb.andWhere(new Brackets((w) => w.where('s.nom LIKE :q', { q: `%${f.q}%` }).orWhere('s.prenom LIKE :q').orWhere('s.email LIKE :q')));
    }
    if (f.groupeId) qb.andWhere('g.id = :g', { g: f.groupeId });
    const [lignes, total] = await qb.getManyAndCount();
    return { donnees: lignes.map(versVue), total, page: f.page, pages: Math.max(1, Math.ceil(total / f.limite)) };
  }

  async trouver(id: number): Promise<StagiaireVue> {
    return versVue(await this.charger(id));
  }

  async creer(dto: CreerStagiaireDto): Promise<StagiaireVue> {
    await this.verifierEmail(dto.email);
    const { groupeId, ...donnees } = dto;
    const s = await this.stagiaires.save(this.stagiaires.create({ ...donnees, groupe: await this.groupe(groupeId) }));
    return this.trouver(s.id);
  }

  async modifier(id: number, dto: ModifierStagiaireDto): Promise<StagiaireVue> {
    const s = await this.charger(id);
    if (dto.email && dto.email !== s.email) await this.verifierEmail(dto.email, id);
    const { groupeId, ...donnees } = dto;
    Object.assign(s, donnees);
    if (groupeId !== undefined) s.groupe = await this.groupe(groupeId);
    await this.stagiaires.save(s);
    return this.trouver(id);
  }

  async supprimer(id: number) {
    await this.stagiaires.remove(await this.charger(id));
  }

  private async charger(id: number) {
    const s = await this.stagiaires.findOne({ where: { id }, relations: { groupe: true } });
    if (!s) throw new NotFoundException(`Stagiaire ${id} introuvable`);
    return s;
  }

  private async groupe(id: number | null) {
    if (id === null) return null;
    const g = await this.groupes.findOneBy({ id });
    if (!g) throw new BadRequestException(`Groupe ${id} inexistant`);
    return g;
  }

  private async verifierEmail(email: string, sauf?: number) {
    if (await this.stagiaires.existsBy({ email, ...(sauf ? { id: Not(sauf) } : {}) })) {
      throw new ConflictException('Un stagiaire utilise déjà cet e-mail');
    }
  }
}
apps/api/src/stagiaires/stagiaires.controller.ts
import { Body, Controller, Delete, Get, HttpCode, Param, ParseIntPipe, Patch, Post, Query } from '@nestjs/common';
import { Roles } from '../auth/decorateurs';
import { CreerStagiaireDto, FiltreStagiairesDto, ModifierStagiaireDto } from './stagiaire.dto';
import { StagiairesService } from './stagiaires.service';

// Lecture : tout utilisateur connecté (guard global) ; écriture : admin seulement
@Controller('stagiaires')
export class StagiairesController {
  constructor(private readonly service: StagiairesService) {}

  @Get()
  lister(@Query() filtre: FiltreStagiairesDto) {
    return this.service.lister(filtre);
  }

  @Get(':id')
  trouver(@Param('id', ParseIntPipe) id: number) {
    return this.service.trouver(id);
  }

  @Roles('admin')
  @Post()
  creer(@Body() dto: CreerStagiaireDto) {
    return this.service.creer(dto);
  }

  @Roles('admin')
  @Patch(':id')
  modifier(@Param('id', ParseIntPipe) id: number, @Body() dto: ModifierStagiaireDto) {
    return this.service.modifier(id, dto);
  }

  @Roles('admin')
  @Delete(':id')
  @HttpCode(204)
  supprimer(@Param('id', ParseIntPipe) id: number) {
    return this.service.supprimer(id);
  }
}
apps/api/src/commun/typeorm-erreurs.filter.ts
import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';
import { QueryFailedError } from 'typeorm';

// Contraintes de la base → statuts HTTP compréhensibles (chapitre 11)
@Catch(QueryFailedError)
export class TypeOrmErreursFilter implements ExceptionFilter {
  catch(e: QueryFailedError & { code?: string }, host: ArgumentsHost) {
    const [statut, message] =
      e.code === 'ER_DUP_ENTRY' ? [409, 'Cette valeur existe déjà'] :
      e.code === 'ER_NO_REFERENCED_ROW_2' ? [400, 'Référence vers un élément inexistant'] :
      [500, 'Erreur de base de données'];
    host.switchToHttp().getResponse().status(statut).json({ statusCode: statut, message });
  }
}
apps/api/src/seeds/seed.ts
import * as bcrypt from 'bcrypt';
import source from '../data-source';
import { Groupe } from '../groupes/groupe.entity';
import { Stagiaire } from '../stagiaires/stagiaire.entity';
import { Utilisateur } from '../utilisateurs/utilisateur.entity';

// Données de démonstration (idempotent : ne fait rien si des groupes existent déjà)
async function seed() {
  await source.initialize();
  if (await source.getRepository(Groupe).count()) {
    console.log('Données déjà présentes : rien à faire');
    return source.destroy();
  }
  await source.getRepository(Utilisateur).save([
    { email: 'admin@exemple.tn', nom: 'Administratrice', role: 'admin', motDePasse: await bcrypt.hash('Admin2026!', 10) },
    { email: 'mansouri@exemple.tn', nom: 'Lina Mansouri', role: 'formateur', motDePasse: await bcrypt.hash('Formateur2026', 10) },
  ]);
  const [dev, res, mm] = await source.getRepository(Groupe).save([
    { code: 'DEV101', intitule: 'Développement web 1' },
    { code: 'RES201', intitule: 'Réseaux informatiques' },
    { code: 'MM301', intitule: 'Multimédia' },
  ]);
  const noms: [string, string, Groupe][] = [
    ['Ben Ali', 'Sami', dev], ['Trabelsi', 'Ines', res], ['Gharbi', 'Yasmine', dev], ['Jlassi', 'Omar', res],
    ['Hamdi', 'Amine', mm], ['Mejri', 'Rania', dev], ['Saidi', 'Karim', mm], ['Ayari', 'Nour', dev],
    ['Bouazizi', 'Mehdi', res], ['Chaabane', 'Salma', dev], ['Dridi', 'Walid', mm], ['Ferchichi', 'Hiba', dev],
  ];
  await source.getRepository(Stagiaire).save(noms.map(([nom, prenom, groupe], i) => ({
    nom, prenom, groupe,
    email: `${prenom.toLowerCase()}.${nom.toLowerCase().replace(/ /g, '')}@exemple.tn`,
    dateNaissance: `200${i % 6}-0${1 + (i % 9)}-1${i % 9}`,
  })));
  console.log('Comptes : 2, groupes : 3, stagiaires :', noms.length);
  await source.destroy();
}
seed();
Correction : Angular
apps/web/src/app/app.config.ts
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';
import { authInterceptor } from './core/auth.interceptor';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes, withComponentInputBinding()),
    provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
  ],
};
apps/web/src/app/app.routes.ts
import { Routes } from '@angular/router';
import { authGuard, roleGuard } from './core/auth.guard';

export const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'stagiaires' },
  {
    path: 'stagiaires',
    canActivate: [authGuard],
    children: [
      { path: '', loadComponent: () => import('./stagiaires/liste').then((m) => m.ListeStagiaires) },
      { path: 'nouveau', canActivate: [roleGuard('admin')], loadComponent: () => import('./stagiaires/formulaire').then((m) => m.FormulaireStagiaire) },
      { path: ':id/modifier', canActivate: [roleGuard('admin')], loadComponent: () => import('./stagiaires/formulaire').then((m) => m.FormulaireStagiaire) },
    ],
  },
  { path: 'connexion', loadComponent: () => import('./connexion').then((m) => m.Connexion) },
  { path: 'acces-refuse', loadComponent: () => import('./acces-refuse').then((m) => m.AccesRefuse) },
  { path: '**', redirectTo: 'stagiaires' },
];
apps/web/src/app/core/auth.service.ts
import { HttpClient } from '@angular/common/http';
import { computed, inject, Injectable, signal } from '@angular/core';
import { Router } from '@angular/router';
import type { Connexion, ReponseConnexion, Utilisateur } from '@gestion/partage';
import { tap } from 'rxjs';
import { environment } from '../../environments/environment';

const CLE = 'session';

interface Session { jeton: string; utilisateur: Utilisateur; expire: number }

@Injectable({ providedIn: 'root' })
export class AuthService {
  private readonly http = inject(HttpClient);
  private readonly router = inject(Router);
  private readonly session = signal<Session | null>(this.lire());

  readonly utilisateur = computed(() => this.session()?.utilisateur ?? null);
  readonly estConnecte = computed(() => this.session() !== null);
  readonly estAdmin = computed(() => this.utilisateur()?.role === 'admin');

  jeton(): string | null {
    const s = this.session();
    if (s && Date.now() > s.expire) {          // jeton expiré : on oublie la session
      this.deconnecter();
      return null;
    }
    return s?.jeton ?? null;
  }

  connecter(identifiants: Connexion) {
    return this.http.post<ReponseConnexion>(`${environment.apiUrl}/auth/connexion`, identifiants).pipe(
      tap((r) => {
        const session = { jeton: r.access_token, utilisateur: r.utilisateur, expire: Date.now() + r.expires_in * 1000 };
        localStorage.setItem(CLE, JSON.stringify(session));
        this.session.set(session);
      }),
    );
  }

  deconnecter(retour?: string) {
    localStorage.removeItem(CLE);
    this.session.set(null);
    this.router.navigate(['/connexion'], { queryParams: retour ? { retour } : {} });
  }

  private lire(): Session | null {
    try {
      const s = JSON.parse(localStorage.getItem(CLE) ?? 'null') as Session | null;
      return s && Date.now() < s.expire ? s : null;
    } catch {
      return null;
    }
  }
}
apps/web/src/app/core/auth.interceptor.ts
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, throwError } from 'rxjs';
import { environment } from '../../environments/environment';
import { AuthService } from './auth.service';

// Ajoute le jeton aux requêtes vers NOTRE API (jamais vers un autre domaine) et réagit aux 401
export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const auth = inject(AuthService);
  const router = inject(Router);
  const jeton = auth.jeton();
  const versApi = req.url.startsWith(environment.apiUrl);

  const requete = jeton && versApi ? req.clone({ setHeaders: { Authorization: `Bearer ${jeton}` } }) : req;

  return next(requete).pipe(
    catchError((err: HttpErrorResponse) => {
      if (err.status === 401 && versApi && !req.url.endsWith('/auth/connexion')) {
        auth.deconnecter(router.url);          // session expirée ou jeton refusé : retour à la connexion
      }
      return throwError(() => err);
    }),
  );
};
apps/web/src/app/core/auth.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import type { Role } from '@gestion/partage';
import { AuthService } from './auth.service';

// Connecté ? Sinon, redirection vers /connexion en mémorisant la page demandée
export const authGuard: CanActivateFn = (_route, etat) => {
  const auth = inject(AuthService);
  return auth.jeton() ? true : inject(Router).createUrlTree(['/connexion'], { queryParams: { retour: etat.url } });
};

// Fabrique de guard : roleGuard('admin')
export const roleGuard = (...roles: Role[]): CanActivateFn => () => {
  const role = inject(AuthService).utilisateur()?.role;
  return role && roles.includes(role) ? true : inject(Router).createUrlTree(['/acces-refuse']);
};
apps/web/src/app/stagiaires/stagiaires.service.ts
import { HttpClient, HttpParams } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import type { CreerStagiaire, FiltreStagiaires, Groupe, ModifierStagiaire, Page, Stagiaire } from '@gestion/partage';
import { environment } from '../../environments/environment';

@Injectable({ providedIn: 'root' })
export class StagiairesService {
  private readonly http = inject(HttpClient);
  private readonly url = `${environment.apiUrl}/stagiaires`;

  lister(f: FiltreStagiaires) {
    let params = new HttpParams().set('page', f.page ?? 1).set('limite', f.limite ?? 10);
    if (f.q) params = params.set('q', f.q);
    if (f.groupeId) params = params.set('groupeId', f.groupeId);
    return this.http.get<Page<Stagiaire>>(this.url, { params });
  }

  trouver(id: number) {
    return this.http.get<Stagiaire>(`${this.url}/${id}`);
  }

  creer(donnees: CreerStagiaire) {
    return this.http.post<Stagiaire>(this.url, donnees);
  }

  modifier(id: number, donnees: ModifierStagiaire) {
    return this.http.patch<Stagiaire>(`${this.url}/${id}`, donnees);
  }

  supprimer(id: number) {
    return this.http.delete<void>(`${this.url}/${id}`);
  }

  groupes() {
    return this.http.get<Groupe[]>(`${environment.apiUrl}/groupes`);
  }
}
apps/web/src/app/stagiaires/liste.ts
import { DatePipe } from '@angular/common';
import { Component, inject, OnInit, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterLink } from '@angular/router';
import type { Groupe, Page, Stagiaire } from '@gestion/partage';
import { AuthService } from '../core/auth.service';
import { messagesErreur } from '../core/erreurs';
import { StagiairesService } from './stagiaires.service';

@Component({
  selector: 'app-liste-stagiaires',
  imports: [FormsModule, RouterLink, DatePipe],
  template: `
    <div class="titre">
      <h1>Stagiaires</h1>
      @if (auth.estAdmin()) { <a class="bouton" routerLink="/stagiaires/nouveau">+ Nouveau stagiaire</a> }
    </div>
    <form class="filtres" (ngSubmit)="aller(1)">
      <input name="q" [(ngModel)]="q" placeholder="Nom, prénom ou e-mail…" />
      <select name="groupe" [(ngModel)]="groupeId" (change)="aller(1)">
        <option [ngValue]="0">Tous les groupes</option>
        @for (g of groupes(); track g.id) { <option [ngValue]="g.id">{{ g.code }} ({{ g.effectif }})</option> }
      </select>
      <button>Rechercher</button>
    </form>
    @if (erreurs().length) { <p class="erreur">{{ erreurs().join(' ; ') }}</p> }
    @if (page(); as p) {
      <table>
        <thead><tr><th>Nom</th><th>Prénom</th><th>E-mail</th><th>Groupe</th><th>Naissance</th>@if (auth.estAdmin()) {<th></th>}</tr></thead>
        <tbody>
          @for (s of p.donnees; track s.id) {
            <tr>
              <td>{{ s.nom }}</td><td>{{ s.prenom }}</td><td>{{ s.email }}</td>
              <td>{{ s.groupe?.code ?? '—' }}</td><td>{{ s.dateNaissance | date: 'dd/MM/yyyy' }}</td>
              @if (auth.estAdmin()) {
                <td class="actions">
                  <a [routerLink]="['/stagiaires', s.id, 'modifier']">Modifier</a>
                  <button class="lien danger" (click)="supprimer(s)">Supprimer</button>
                </td>
              }
            </tr>
          } @empty {
            <tr><td colspan="6">Aucun stagiaire ne correspond.</td></tr>
          }
        </tbody>
      </table>
      <div class="pagination">
        <button [disabled]="p.page <= 1" (click)="aller(p.page - 1)">‹ Précédente</button>
        <span>Page {{ p.page }} / {{ p.pages }} · {{ p.total }} stagiaire(s)</span>
        <button [disabled]="p.page >= p.pages" (click)="aller(p.page + 1)">Suivante ›</button>
      </div>
    }
  `,
})
export class ListeStagiaires implements OnInit {
  private readonly service = inject(StagiairesService);
  protected readonly auth = inject(AuthService);
  protected q = '';
  protected groupeId = 0;
  protected readonly page = signal<Page<Stagiaire> | null>(null);
  protected readonly groupes = signal<Groupe[]>([]);
  protected readonly erreurs = signal<string[]>([]);

  ngOnInit() {
    this.service.groupes().subscribe((g) => this.groupes.set(g));
    this.aller(1);
  }

  aller(numero: number) {
    this.erreurs.set([]);
    this.service.lister({ q: this.q.trim(), groupeId: this.groupeId || undefined, page: numero, limite: 8 }).subscribe({
      next: (p) => this.page.set(p),
      error: (e) => this.erreurs.set(messagesErreur(e)),
    });
  }

  supprimer(s: Stagiaire) {
    if (!confirm(`Supprimer ${s.prenom} ${s.nom} ?`)) return;
    this.service.supprimer(s.id).subscribe({
      next: () => this.aller(this.page()?.page ?? 1),
      error: (e) => this.erreurs.set(messagesErreur(e)),
    });
  }
}
apps/web/src/app/stagiaires/formulaire.ts
import { Component, inject, input, OnInit, signal } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import type { CreerStagiaire, Groupe } from '@gestion/partage';
import { messagesErreur } from '../core/erreurs';
import { StagiairesService } from './stagiaires.service';

@Component({
  selector: 'app-formulaire-stagiaire',
  imports: [ReactiveFormsModule, RouterLink],
  template: `
    <a routerLink="/stagiaires">← Retour à la liste</a>
    <h1>{{ id() ? 'Modifier le stagiaire' : 'Nouveau stagiaire' }}</h1>
    <form class="formulaire" [formGroup]="form" (ngSubmit)="enregistrer()">
      <label>Nom <input formControlName="nom" />
        @if (invalide('nom')) { <small class="erreur">2 caractères au moins</small> }</label>
      <label>Prénom <input formControlName="prenom" />
        @if (invalide('prenom')) { <small class="erreur">2 caractères au moins</small> }</label>
      <label>E-mail <input type="email" formControlName="email" />
        @if (invalide('email')) { <small class="erreur">Adresse e-mail invalide</small> }</label>
      <label>Date de naissance <input type="date" formControlName="dateNaissance" /></label>
      <label>Groupe
        <select formControlName="groupeId">
          <option [ngValue]="null">Aucun groupe</option>
          @for (g of groupes(); track g.id) { <option [ngValue]="g.id">{{ g.code }} · {{ g.intitule }}</option> }
        </select>
      </label>
      @if (erreurs().length) { <ul class="erreur">@for (m of erreurs(); track m) { <li>{{ m }}</li> }</ul> }
      <button [disabled]="form.invalid || envoi()">Enregistrer</button>
    </form>
  `,
})
export class FormulaireStagiaire implements OnInit {
  readonly id = input<string>();                 // présent sur /stagiaires/:id/modifier
  private readonly service = inject(StagiairesService);
  private readonly router = inject(Router);
  protected readonly groupes = signal<Groupe[]>([]);
  protected readonly erreurs = signal<string[]>([]);
  protected readonly envoi = signal(false);
  protected readonly form = inject(NonNullableFormBuilder).group({
    nom: ['', [Validators.required, Validators.minLength(2)]],
    prenom: ['', [Validators.required, Validators.minLength(2)]],
    email: ['', [Validators.required, Validators.email]],
    dateNaissance: ['', Validators.required],
    groupeId: [null as number | null],
  });

  ngOnInit() {
    this.service.groupes().subscribe((g) => this.groupes.set(g));
    const id = this.id();
    if (id) {
      this.service.trouver(Number(id)).subscribe({
        next: (s) => this.form.setValue({ nom: s.nom, prenom: s.prenom, email: s.email, dateNaissance: s.dateNaissance, groupeId: s.groupe?.id ?? null }),
        error: (e) => this.erreurs.set(messagesErreur(e)),
      });
    }
  }

  invalide(champ: keyof CreerStagiaire) {
    const c = this.form.controls[champ];
    return c.invalid && c.touched;
  }

  enregistrer() {
    this.envoi.set(true);
    this.erreurs.set([]);
    const donnees: CreerStagiaire = this.form.getRawValue();
    const id = this.id();
    const requete = id ? this.service.modifier(Number(id), donnees) : this.service.creer(donnees);
    requete.subscribe({
      next: () => this.router.navigate(['/stagiaires']),
      error: (e) => {
        this.erreurs.set(messagesErreur(e));        // 400 (validation) ou 409 (e-mail déjà utilisé) de l'API
        this.envoi.set(false);
      },
    });
  }
}
apps/web/src/app/connexion.ts
import { Component, inject, input, signal } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from './core/auth.service';
import { messagesErreur } from './core/erreurs';

@Component({
  selector: 'app-connexion',
  imports: [ReactiveFormsModule],
  template: `
    <h1>Connexion</h1>
    <form class="formulaire etroit" [formGroup]="form" (ngSubmit)="connecter()">
      <label>E-mail <input type="email" formControlName="email" autocomplete="username" /></label>
      <label>Mot de passe <input type="password" formControlName="motDePasse" autocomplete="current-password" /></label>
      @if (erreur()) { <p class="erreur">{{ erreur() }}</p> }
      <button [disabled]="form.invalid">Se connecter</button>
    </form>
  `,
})
export class Connexion {
  readonly retour = input<string>('/stagiaires');            // ?retour=… (paramètre de requête → input)
  private readonly auth = inject(AuthService);
  private readonly router = inject(Router);
  protected readonly erreur = signal('');
  protected readonly form = inject(NonNullableFormBuilder).group({
    email: ['', [Validators.required, Validators.email]],
    motDePasse: ['', Validators.required],
  });

  connecter() {
    this.auth.connecter(this.form.getRawValue()).subscribe({
      next: () => this.router.navigateByUrl(this.retour() || '/stagiaires'),
      error: (e) => this.erreur.set(messagesErreur(e)[0]),
    });
  }
}
apps/web/src/styles.css
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, Arial, sans-serif; background: #f1f5f9; color: #0f172a; }
header { display: flex; align-items: center; gap: 14px; background: #e0234e; color: #fff; padding: 12px 24px; }
header a, header .lien { color: #fff; text-decoration: none; background: none; border: none; font: inherit; cursor: pointer; }
.logo { font-weight: bold; } .espace { flex: 1; }
main { max-width: 960px; margin: 0 auto; padding: 16px 24px; }
h1 { font-size: 24px; }
.filtres { display: flex; gap: 8px; flex-wrap: wrap; }
input, select, textarea, button, .bouton { font: inherit; padding: 8px 10px; border-radius: 6px; border: 1px solid #cbd5e1; }
button, .bouton { background: #e0234e; color: #fff; border: none; cursor: pointer; text-decoration: none; }
button:disabled { opacity: .5; } button.danger { background: #b91c1c; }
.cartes { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; }
.carte { background: #fff; border-radius: 10px; padding: 14px; color: inherit; text-decoration: none; box-shadow: 0 1px 3px #0002; }
.carte h2 { font-size: 17px; margin: 8px 0 4px; } .carte p { color: #475569; font-size: 14px; } .carte small { color: #64748b; }
.badge { font-size: 12px; padding: 2px 8px; border-radius: 10px; background: #e2e8f0; }
.badge.debutant { background: #dcfce7; } .badge.intermediaire { background: #dbeafe; } .badge.avance { background: #ede9fe; }
.formulaire { display: grid; gap: 10px; max-width: 520px; background: #fff; padding: 16px; border-radius: 10px; }
.formulaire.etroit { max-width: 360px; } .formulaire label { display: grid; gap: 4px; font-size: 14px; }
.erreur { color: #b91c1c; } .info { color: #64748b; }
.titre { display: flex; align-items: center; justify-content: space-between; }
table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 10px; overflow: hidden; margin-top: 12px; font-size: 14px; }
th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid #e2e8f0; }
th { background: #f8fafc; } .actions { display: flex; gap: 10px; align-items: center; }
table button.lien { background: none; color: #2563eb; padding: 0; } table button.lien.danger { color: #b91c1c; }
.pagination { display: flex; gap: 12px; align-items: center; margin-top: 12px; }
.formulaire small { font-size: 12px; }
Grille d'évaluation
CritèrePoints
Monorepo (workspaces, scripts), dépôt GitHub dès le départ, commits par étape, README, étiquette2
Contrat partagé utilisé des deux côtés (import type, DTO implements)2
Base : entités, migration, seed2
API : authentification, guard global, rôles (403 vérifié par appel direct)3
API : liste paginée et filtrée en SQL, validation, 409 et 400, CORS3
Angular : intercepteur, guards, connexion avec retour, déconnexion3
Angular : liste (recherche, filtre, pagination), formulaire commun, erreurs de l'API affichées, suppression4
Interface adaptée au rôle et soin général1
Total20

Cet article vous a-t-il aidé ?