Merge master into develop - Synchronisation des branches
Fusion des travaux : - Backend complet (ConfigService, DocumentsLegaux, Auth, etc.) - Frontend étapes inscription 1-2 - Infrastructure Docker - Documentation technique Résolution des conflits : - Images déplacées vers frontend/assets/images/ - Dossier Archives supprimé - Backend : version master conservée - Frontend : améliorations UI de develop conservées
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AssistantesMaternellesController } from './assistantes_maternelles.controller';
|
||||
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
||||
|
||||
describe('AssistantesMaternellesController', () => {
|
||||
let controller: AssistantesMaternellesController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AssistantesMaternellesController],
|
||||
providers: [AssistantesMaternellesService],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<AssistantesMaternellesController>(AssistantesMaternellesController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Patch,
|
||||
Param,
|
||||
Delete,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||
import { RoleType } from 'src/entities/users.entity';
|
||||
import { CreateAssistanteDto } from '../user/dto/create_assistante.dto';
|
||||
import { UpdateAssistanteDto } from '../user/dto/update_assistante.dto';
|
||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||
|
||||
@ApiTags("Assistantes Maternelles")
|
||||
@ApiBearerAuth('access-token')
|
||||
@UseGuards(AuthGuard, RolesGuard)
|
||||
@Controller('assistantes-maternelles')
|
||||
export class AssistantesMaternellesController {
|
||||
constructor(private readonly assistantesMaternellesService: AssistantesMaternellesService) { }
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||
@ApiOperation({ summary: 'Créer nounou' })
|
||||
@ApiResponse({ status: 201, description: 'Nounou créée avec succès' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé : Réservé aux super_admins et gestionnaires' })
|
||||
@ApiBody({ type: CreateAssistanteDto })
|
||||
@Post()
|
||||
create(@Body() dto: CreateAssistanteDto): Promise<AssistanteMaternelle> {
|
||||
return this.assistantesMaternellesService.create(dto);
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Récupérer la liste des nounous' })
|
||||
@ApiResponse({ status: 200, description: 'Liste des nounous' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé : Réservé aux super_admins et gestionnaires' })
|
||||
getAll(): Promise<AssistanteMaternelle[]> {
|
||||
return this.assistantesMaternellesService.findAll();
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||
@Get(':id')
|
||||
@ApiParam({ name: 'id', description: "UUID de la nounou" })
|
||||
@ApiOperation({ summary: 'Récupérer une nounou par id' })
|
||||
@ApiResponse({ status: 200, description: 'Détails de la nounou' })
|
||||
@ApiResponse({ status: 404, description: 'Nounou non trouvée' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé : Réservé aux super_admins et gestionnaires' })
|
||||
getOne(@Param('id') user_id: string): Promise<AssistanteMaternelle> {
|
||||
return this.assistantesMaternellesService.findOne(user_id);
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||
@ApiBody({ type: UpdateAssistanteDto })
|
||||
@ApiOperation({ summary: 'Mettre à jour une nounou' })
|
||||
@ApiResponse({ status: 200, description: 'Nounou mise à jour avec succès' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé : Réservé aux super_admins et gestionnaires' })
|
||||
@ApiResponse({ status: 404, description: 'Nounou non trouvée' })
|
||||
@ApiParam({ name: 'id', description: "UUID de la nounou" })
|
||||
@Patch(':id')
|
||||
update(@Param('id') id: string, @Body() dto: UpdateAssistanteDto): Promise<AssistanteMaternelle> {
|
||||
return this.assistantesMaternellesService.update(id, dto);
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Supprimer une nounou' })
|
||||
@ApiResponse({ status: 200, description: 'Nounou supprimée avec succès' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé : Réservé aux super_admins, gestionnaires et administrateurs' })
|
||||
@ApiResponse({ status: 404, description: 'Nounou non trouvée' })
|
||||
@ApiParam({ name: 'id', description: "UUID de la nounou" })
|
||||
@Delete(':id')
|
||||
remove(@Param('id') id: string): Promise<{ message: string }>
|
||||
{
|
||||
return this.assistantesMaternellesService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
||||
import { AssistantesMaternellesController } from './assistantes_maternelles.controller';
|
||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([AssistanteMaternelle, Users]),
|
||||
AuthModule
|
||||
],
|
||||
controllers: [AssistantesMaternellesController],
|
||||
providers: [AssistantesMaternellesService],
|
||||
exports: [
|
||||
AssistantesMaternellesService,
|
||||
TypeOrmModule,
|
||||
],
|
||||
})
|
||||
export class AssistantesMaternellesModule { }
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
||||
|
||||
describe('AssistantesMaternellesService', () => {
|
||||
let service: AssistantesMaternellesService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [AssistantesMaternellesService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<AssistantesMaternellesService>(AssistantesMaternellesService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { RoleType, Users } from 'src/entities/users.entity';
|
||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||
import { CreateAssistanteDto } from '../user/dto/create_assistante.dto';
|
||||
import { UpdateAssistanteDto } from '../user/dto/update_assistante.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AssistantesMaternellesService {
|
||||
constructor(
|
||||
@InjectRepository(AssistanteMaternelle)
|
||||
private readonly assistantesMaternelleRepository: Repository<AssistanteMaternelle>,
|
||||
@InjectRepository(Users)
|
||||
private readonly usersRepository: Repository<Users>
|
||||
) {}
|
||||
|
||||
// Création d’une assistante maternelle
|
||||
async create(dto: CreateAssistanteDto): Promise<AssistanteMaternelle> {
|
||||
const user = await this.usersRepository.findOneBy({ id: dto.user_id });
|
||||
if (!user) throw new NotFoundException('Utilisateur introuvable');
|
||||
if (user.role !== RoleType.ASSISTANTE_MATERNELLE) {
|
||||
throw new BadRequestException('Accès réservé aux assistantes maternelles');
|
||||
}
|
||||
|
||||
const exist = await this.assistantesMaternelleRepository.findOneBy({ user_id: dto.user_id });
|
||||
if (exist) throw new ConflictException('Assistante maternelle déjà existante');
|
||||
|
||||
const entity = this.assistantesMaternelleRepository.create({
|
||||
user_id: dto.user_id,
|
||||
user: { ...user, role: RoleType.ASSISTANTE_MATERNELLE },
|
||||
approval_number: dto.approval_number,
|
||||
nir: dto.nir,
|
||||
max_children: dto.max_children,
|
||||
biography: dto.biography,
|
||||
available: dto.available ?? true,
|
||||
residence_city: dto.residence_city,
|
||||
agreement_date: dto.agreement_date ? new Date(dto.agreement_date) : undefined,
|
||||
years_experience: dto.years_experience,
|
||||
specialty: dto.specialty,
|
||||
places_available: dto.places_available,
|
||||
});
|
||||
|
||||
return this.assistantesMaternelleRepository.save(entity);
|
||||
}
|
||||
|
||||
// Liste des assistantes maternelles
|
||||
async findAll(): Promise<AssistanteMaternelle[]> {
|
||||
return this.assistantesMaternelleRepository.find({
|
||||
relations: ['user'],
|
||||
});
|
||||
}
|
||||
|
||||
// Récupérer une assistante maternelle par user_id
|
||||
async findOne(user_id: string): Promise<AssistanteMaternelle> {
|
||||
const assistante = await this.assistantesMaternelleRepository.findOne({
|
||||
where: { user_id },
|
||||
relations: ['user'],
|
||||
});
|
||||
if (!assistante) throw new NotFoundException('Assistante maternelle introuvable');
|
||||
return assistante;
|
||||
}
|
||||
|
||||
// Mise à jour
|
||||
async update(id: string, dto: UpdateAssistanteDto): Promise<AssistanteMaternelle> {
|
||||
await this.assistantesMaternelleRepository.update(id, dto);
|
||||
return this.findOne(id);
|
||||
}
|
||||
|
||||
// Suppression d’une assistante maternelle
|
||||
async remove(id: string): Promise<{ message: string }> {
|
||||
await this.assistantesMaternelleRepository.delete(id);
|
||||
return { message: 'Assistante maternelle supprimée' };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthController } from './auth.controller';
|
||||
|
||||
describe('AuthController', () => {
|
||||
let controller: AuthController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AuthController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<AuthController>(AuthController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { Body, Controller, Get, Post, Req, UnauthorizedException, UseGuards } from '@nestjs/common';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { AuthService } from './auth.service';
|
||||
import { Public } from 'src/common/decorators/public.decorator';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
import { RegisterParentDto } from './dto/register-parent.dto';
|
||||
import { RegisterParentCompletDto } from './dto/register-parent-complet.dto';
|
||||
import { ApiBearerAuth, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||
import type { Request } from 'express';
|
||||
import { UserService } from '../user/user.service';
|
||||
import { ProfileResponseDto } from './dto/profile_response.dto';
|
||||
import { RefreshTokenDto } from './dto/refresh_token.dto';
|
||||
import { User } from 'src/common/decorators/user.decorator';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
|
||||
@ApiTags('Authentification')
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(
|
||||
private readonly authService: AuthService,
|
||||
private readonly userService: UserService,
|
||||
) { }
|
||||
|
||||
|
||||
@Public()
|
||||
@ApiOperation({ summary: 'Connexion' })
|
||||
@Post('login')
|
||||
async login(@Body() dto: LoginDto) {
|
||||
return this.authService.login(dto);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('register')
|
||||
@ApiOperation({ summary: 'Inscription (OBSOLÈTE - utiliser /register/parent)' })
|
||||
@ApiResponse({ status: 409, description: 'Email déjà utilisé' })
|
||||
async register(@Body() dto: RegisterDto) {
|
||||
return this.authService.register(dto);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('register/parent')
|
||||
@ApiOperation({
|
||||
summary: 'Inscription Parent COMPLÈTE - Workflow 6 étapes',
|
||||
description: 'Crée Parent 1 + Parent 2 (opt) + Enfants + Présentation + CGU en une transaction'
|
||||
})
|
||||
@ApiResponse({ status: 201, description: 'Inscription réussie - Dossier en attente de validation' })
|
||||
@ApiResponse({ status: 400, description: 'Données invalides ou CGU non acceptées' })
|
||||
@ApiResponse({ status: 409, description: 'Email déjà utilisé' })
|
||||
async inscrireParentComplet(@Body() dto: RegisterParentCompletDto) {
|
||||
return this.authService.inscrireParentComplet(dto);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('register/parent/legacy')
|
||||
@ApiOperation({ summary: '[OBSOLÈTE] Inscription Parent (étape 1/6 uniquement)' })
|
||||
@ApiResponse({ status: 201, description: 'Inscription réussie' })
|
||||
@ApiResponse({ status: 409, description: 'Email déjà utilisé' })
|
||||
async registerParentLegacy(@Body() dto: RegisterParentDto) {
|
||||
return this.authService.registerParent(dto);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('refresh')
|
||||
@ApiBearerAuth('refresh_token')
|
||||
@ApiResponse({ status: 200, description: 'Nouveaux tokens générés avec succès.' })
|
||||
@ApiResponse({ status: 401, description: 'Token de rafraîchissement invalide ou expiré.' })
|
||||
@ApiOperation({ summary: 'Rafraichir les tokens' })
|
||||
async refresh(@Body() dto: RefreshTokenDto) {
|
||||
return this.authService.refreshTokens(dto.refresh_token);
|
||||
}
|
||||
|
||||
@Get('me')
|
||||
@UseGuards(AuthGuard)
|
||||
@ApiBearerAuth('access-token')
|
||||
@ApiOperation({ summary: "Récupérer le profil complet de l'utilisateur connecté" })
|
||||
@ApiResponse({ status: 200, type: ProfileResponseDto })
|
||||
async getProfile(@Req() req: Request): Promise<ProfileResponseDto> {
|
||||
if (!req.user || !req.user.sub) {
|
||||
throw new UnauthorizedException('Utilisateur non authentifié');
|
||||
}
|
||||
const user = await this.userService.findOne(req.user.sub);
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
prenom: user.prenom ?? '',
|
||||
nom: user.nom ?? '',
|
||||
statut: user.statut,
|
||||
};
|
||||
}
|
||||
|
||||
@UseGuards(AuthGuard)
|
||||
@ApiBearerAuth('access-token')
|
||||
@Post('logout')
|
||||
logout(@User() currentUser: Users) {
|
||||
return this.authService.logout(currentUser.id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { forwardRef, Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { UserModule } from '../user/user.module';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { Children } from 'src/entities/children.entity';
|
||||
import { AppConfigModule } from 'src/modules/config';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Users, Parents, Children]),
|
||||
forwardRef(() => UserModule),
|
||||
AppConfigModule,
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
secret: config.get('jwt.secret'),
|
||||
signOptions: { expiresIn: config.get('jwt.expirationTime') },
|
||||
}),
|
||||
inject: [ConfigService],
|
||||
})
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService],
|
||||
exports: [AuthService, JwtModule],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let service: AuthService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [AuthService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<AuthService>(AuthService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,461 @@
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { UserService } from '../user/user.service';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import * as crypto from 'crypto';
|
||||
import * as fs from 'fs/promises';
|
||||
import * as path from 'path';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
import { RegisterParentDto } from './dto/register-parent.dto';
|
||||
import { RegisterParentCompletDto } from './dto/register-parent-complet.dto';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { RoleType, StatutUtilisateurType, Users } from 'src/entities/users.entity';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { Children, StatutEnfantType } from 'src/entities/children.entity';
|
||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { AppConfigService } from 'src/modules/config/config.service';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly usersService: UserService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly configService: ConfigService,
|
||||
private readonly appConfigService: AppConfigService,
|
||||
@InjectRepository(Parents)
|
||||
private readonly parentsRepo: Repository<Parents>,
|
||||
@InjectRepository(Users)
|
||||
private readonly usersRepo: Repository<Users>,
|
||||
@InjectRepository(Children)
|
||||
private readonly childrenRepo: Repository<Children>,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Génère un access_token et un refresh_token
|
||||
*/
|
||||
async generateTokens(userId: string, email: string, role: RoleType) {
|
||||
const accessSecret = this.configService.get<string>('jwt.accessSecret');
|
||||
const accessExpiresIn = this.configService.get<string>('jwt.accessExpiresIn');
|
||||
const refreshSecret = this.configService.get<string>('jwt.refreshSecret');
|
||||
const refreshExpiresIn = this.configService.get<string>('jwt.refreshExpiresIn');
|
||||
|
||||
const [accessToken, refreshToken] = await Promise.all([
|
||||
this.jwtService.signAsync({ sub: userId, email, role }, { secret: accessSecret, expiresIn: accessExpiresIn }),
|
||||
this.jwtService.signAsync({ sub: userId }, { secret: refreshSecret, expiresIn: refreshExpiresIn }),
|
||||
]);
|
||||
|
||||
return {
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Connexion utilisateur
|
||||
*/
|
||||
async login(dto: LoginDto) {
|
||||
const user = await this.usersService.findByEmailOrNull(dto.email);
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('Identifiants invalides');
|
||||
}
|
||||
|
||||
// Vérifier que le mot de passe existe (compte activé)
|
||||
if (!user.password) {
|
||||
throw new UnauthorizedException(
|
||||
'Compte non activé. Veuillez créer votre mot de passe via le lien reçu par email.',
|
||||
);
|
||||
}
|
||||
|
||||
// Vérifier le mot de passe
|
||||
const isMatch = await bcrypt.compare(dto.password, user.password);
|
||||
if (!isMatch) {
|
||||
throw new UnauthorizedException('Identifiants invalides');
|
||||
}
|
||||
|
||||
// Vérifier le statut du compte
|
||||
if (user.statut === StatutUtilisateurType.EN_ATTENTE) {
|
||||
throw new UnauthorizedException(
|
||||
'Votre compte est en attente de validation par un gestionnaire.',
|
||||
);
|
||||
}
|
||||
|
||||
if (user.statut === StatutUtilisateurType.SUSPENDU) {
|
||||
throw new UnauthorizedException('Votre compte a été suspendu. Contactez un administrateur.');
|
||||
}
|
||||
|
||||
return this.generateTokens(user.id, user.email, user.role);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rafraîchir les tokens
|
||||
*/
|
||||
async refreshTokens(refreshToken: string) {
|
||||
try {
|
||||
const payload = await this.jwtService.verifyAsync(refreshToken, {
|
||||
secret: this.configService.get<string>('jwt.refreshSecret'),
|
||||
});
|
||||
|
||||
const user = await this.usersService.findOne(payload.sub);
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('Utilisateur introuvable');
|
||||
}
|
||||
|
||||
return this.generateTokens(user.id, user.email, user.role);
|
||||
} catch {
|
||||
throw new UnauthorizedException('Refresh token invalide');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inscription utilisateur OBSOLÈTE - Utiliser registerParent() ou registerAM()
|
||||
* @deprecated
|
||||
*/
|
||||
async register(registerDto: RegisterDto) {
|
||||
const exists = await this.usersService.findByEmailOrNull(registerDto.email);
|
||||
if (exists) {
|
||||
throw new ConflictException('Email déjà utilisé');
|
||||
}
|
||||
|
||||
const allowedRoles = new Set<RoleType>([RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE]);
|
||||
if (!allowedRoles.has(registerDto.role)) {
|
||||
registerDto.role = RoleType.PARENT;
|
||||
}
|
||||
|
||||
registerDto.statut = StatutUtilisateurType.EN_ATTENTE;
|
||||
|
||||
if (!registerDto.consentement_photo) {
|
||||
registerDto.date_consentement_photo = null;
|
||||
} else if (registerDto.date_consentement_photo) {
|
||||
const date = new Date(registerDto.date_consentement_photo);
|
||||
if (isNaN(date.getTime())) {
|
||||
registerDto.date_consentement_photo = null;
|
||||
}
|
||||
}
|
||||
|
||||
const user = await this.usersService.createUser(registerDto);
|
||||
const tokens = await this.generateTokens(user.id, user.email, user.role);
|
||||
|
||||
return {
|
||||
...tokens,
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
prenom: user.prenom,
|
||||
nom: user.nom,
|
||||
statut: user.statut,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Inscription Parent (étape 1/6 du workflow CDC)
|
||||
* SANS mot de passe - Token de création MDP généré
|
||||
*/
|
||||
async registerParent(dto: RegisterParentDto) {
|
||||
// 1. Vérifier que l'email n'existe pas
|
||||
const exists = await this.usersService.findByEmailOrNull(dto.email);
|
||||
if (exists) {
|
||||
throw new ConflictException('Un compte avec cet email existe déjà');
|
||||
}
|
||||
|
||||
// 2. Vérifier l'email du co-parent s'il existe
|
||||
if (dto.co_parent_email) {
|
||||
const coParentExists = await this.usersService.findByEmailOrNull(dto.co_parent_email);
|
||||
if (coParentExists) {
|
||||
throw new ConflictException('L\'email du co-parent est déjà utilisé');
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Récupérer la durée d'expiration du token depuis la config
|
||||
const tokenExpiryDays = await this.appConfigService.get<number>(
|
||||
'password_reset_token_expiry_days',
|
||||
7,
|
||||
);
|
||||
|
||||
// 4. Générer les tokens de création de mot de passe
|
||||
const tokenCreationMdp = crypto.randomUUID();
|
||||
const tokenExpiration = new Date();
|
||||
tokenExpiration.setDate(tokenExpiration.getDate() + tokenExpiryDays);
|
||||
|
||||
// 5. Transaction : Créer Parent 1 + Parent 2 (si existe) + entités parents
|
||||
const result = await this.usersRepo.manager.transaction(async (manager) => {
|
||||
// Créer Parent 1
|
||||
const parent1 = manager.create(Users, {
|
||||
email: dto.email,
|
||||
prenom: dto.prenom,
|
||||
nom: dto.nom,
|
||||
role: RoleType.PARENT,
|
||||
statut: StatutUtilisateurType.EN_ATTENTE,
|
||||
telephone: dto.telephone,
|
||||
adresse: dto.adresse,
|
||||
code_postal: dto.code_postal,
|
||||
ville: dto.ville,
|
||||
token_creation_mdp: tokenCreationMdp,
|
||||
token_creation_mdp_expire_le: tokenExpiration,
|
||||
});
|
||||
|
||||
const savedParent1 = await manager.save(Users, parent1);
|
||||
|
||||
// Créer Parent 2 si renseigné
|
||||
let savedParent2: Users | null = null;
|
||||
let tokenCoParent: string | null = null;
|
||||
|
||||
if (dto.co_parent_email && dto.co_parent_prenom && dto.co_parent_nom) {
|
||||
tokenCoParent = crypto.randomUUID();
|
||||
const tokenExpirationCoParent = new Date();
|
||||
tokenExpirationCoParent.setDate(tokenExpirationCoParent.getDate() + tokenExpiryDays);
|
||||
|
||||
const parent2 = manager.create(Users, {
|
||||
email: dto.co_parent_email,
|
||||
prenom: dto.co_parent_prenom,
|
||||
nom: dto.co_parent_nom,
|
||||
role: RoleType.PARENT,
|
||||
statut: StatutUtilisateurType.EN_ATTENTE,
|
||||
telephone: dto.co_parent_telephone,
|
||||
adresse: dto.co_parent_meme_adresse ? dto.adresse : dto.co_parent_adresse,
|
||||
code_postal: dto.co_parent_meme_adresse ? dto.code_postal : dto.co_parent_code_postal,
|
||||
ville: dto.co_parent_meme_adresse ? dto.ville : dto.co_parent_ville,
|
||||
token_creation_mdp: tokenCoParent,
|
||||
token_creation_mdp_expire_le: tokenExpirationCoParent,
|
||||
});
|
||||
|
||||
savedParent2 = await manager.save(Users, parent2);
|
||||
}
|
||||
|
||||
// Créer l'entité métier Parents pour Parent 1
|
||||
const parentEntity = manager.create(Parents, {
|
||||
user_id: savedParent1.id,
|
||||
});
|
||||
parentEntity.user = savedParent1;
|
||||
if (savedParent2) {
|
||||
parentEntity.co_parent = savedParent2;
|
||||
}
|
||||
|
||||
await manager.save(Parents, parentEntity);
|
||||
|
||||
// Créer l'entité métier Parents pour Parent 2 (si existe)
|
||||
if (savedParent2) {
|
||||
const coParentEntity = manager.create(Parents, {
|
||||
user_id: savedParent2.id,
|
||||
});
|
||||
coParentEntity.user = savedParent2;
|
||||
coParentEntity.co_parent = savedParent1;
|
||||
|
||||
await manager.save(Parents, coParentEntity);
|
||||
}
|
||||
|
||||
return {
|
||||
parent1: savedParent1,
|
||||
parent2: savedParent2,
|
||||
tokenCreationMdp,
|
||||
tokenCoParent,
|
||||
};
|
||||
});
|
||||
|
||||
// 6. TODO: Envoyer email avec lien de création de MDP
|
||||
// await this.mailService.sendPasswordCreationEmail(result.parent1, result.tokenCreationMdp);
|
||||
// if (result.parent2 && result.tokenCoParent) {
|
||||
// await this.mailService.sendPasswordCreationEmail(result.parent2, result.tokenCoParent);
|
||||
// }
|
||||
|
||||
return {
|
||||
message: 'Inscription réussie. Un email de validation vous a été envoyé.',
|
||||
parent_id: result.parent1.id,
|
||||
co_parent_id: result.parent2?.id,
|
||||
statut: StatutUtilisateurType.EN_ATTENTE,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Inscription Parent COMPLÈTE - Workflow CDC 6 étapes en 1 transaction
|
||||
* Gère : Parent 1 + Parent 2 (opt) + Enfants + Présentation + CGU
|
||||
*/
|
||||
async inscrireParentComplet(dto: RegisterParentCompletDto) {
|
||||
if (!dto.acceptation_cgu || !dto.acceptation_privacy) {
|
||||
throw new BadRequestException('L\'acceptation des CGU et de la politique de confidentialité est obligatoire');
|
||||
}
|
||||
|
||||
if (!dto.enfants || dto.enfants.length === 0) {
|
||||
throw new BadRequestException('Au moins un enfant est requis');
|
||||
}
|
||||
|
||||
const existe = await this.usersService.findByEmailOrNull(dto.email);
|
||||
if (existe) {
|
||||
throw new ConflictException('Un compte avec cet email existe déjà');
|
||||
}
|
||||
|
||||
if (dto.co_parent_email) {
|
||||
const coParentExiste = await this.usersService.findByEmailOrNull(dto.co_parent_email);
|
||||
if (coParentExiste) {
|
||||
throw new ConflictException('L\'email du co-parent est déjà utilisé');
|
||||
}
|
||||
}
|
||||
|
||||
const joursExpirationToken = await this.appConfigService.get<number>(
|
||||
'password_reset_token_expiry_days',
|
||||
7,
|
||||
);
|
||||
|
||||
const tokenCreationMdp = crypto.randomUUID();
|
||||
const dateExpiration = new Date();
|
||||
dateExpiration.setDate(dateExpiration.getDate() + joursExpirationToken);
|
||||
|
||||
const resultat = await this.usersRepo.manager.transaction(async (manager) => {
|
||||
const parent1 = manager.create(Users, {
|
||||
email: dto.email,
|
||||
prenom: dto.prenom,
|
||||
nom: dto.nom,
|
||||
role: RoleType.PARENT,
|
||||
statut: StatutUtilisateurType.EN_ATTENTE,
|
||||
telephone: dto.telephone,
|
||||
adresse: dto.adresse,
|
||||
code_postal: dto.code_postal,
|
||||
ville: dto.ville,
|
||||
token_creation_mdp: tokenCreationMdp,
|
||||
token_creation_mdp_expire_le: dateExpiration,
|
||||
});
|
||||
|
||||
const parent1Enregistre = await manager.save(Users, parent1);
|
||||
|
||||
let parent2Enregistre: Users | null = null;
|
||||
let tokenCoParent: string | null = null;
|
||||
|
||||
if (dto.co_parent_email && dto.co_parent_prenom && dto.co_parent_nom) {
|
||||
tokenCoParent = crypto.randomUUID();
|
||||
const dateExpirationCoParent = new Date();
|
||||
dateExpirationCoParent.setDate(dateExpirationCoParent.getDate() + joursExpirationToken);
|
||||
|
||||
const parent2 = manager.create(Users, {
|
||||
email: dto.co_parent_email,
|
||||
prenom: dto.co_parent_prenom,
|
||||
nom: dto.co_parent_nom,
|
||||
role: RoleType.PARENT,
|
||||
statut: StatutUtilisateurType.EN_ATTENTE,
|
||||
telephone: dto.co_parent_telephone,
|
||||
adresse: dto.co_parent_meme_adresse ? dto.adresse : dto.co_parent_adresse,
|
||||
code_postal: dto.co_parent_meme_adresse ? dto.code_postal : dto.co_parent_code_postal,
|
||||
ville: dto.co_parent_meme_adresse ? dto.ville : dto.co_parent_ville,
|
||||
token_creation_mdp: tokenCoParent,
|
||||
token_creation_mdp_expire_le: dateExpirationCoParent,
|
||||
});
|
||||
|
||||
parent2Enregistre = await manager.save(Users, parent2);
|
||||
}
|
||||
|
||||
const entiteParent = manager.create(Parents, {
|
||||
user_id: parent1Enregistre.id,
|
||||
});
|
||||
entiteParent.user = parent1Enregistre;
|
||||
if (parent2Enregistre) {
|
||||
entiteParent.co_parent = parent2Enregistre;
|
||||
}
|
||||
|
||||
await manager.save(Parents, entiteParent);
|
||||
|
||||
if (parent2Enregistre) {
|
||||
const entiteCoParent = manager.create(Parents, {
|
||||
user_id: parent2Enregistre.id,
|
||||
});
|
||||
entiteCoParent.user = parent2Enregistre;
|
||||
entiteCoParent.co_parent = parent1Enregistre;
|
||||
|
||||
await manager.save(Parents, entiteCoParent);
|
||||
}
|
||||
|
||||
const enfantsEnregistres: Children[] = [];
|
||||
for (const enfantDto of dto.enfants) {
|
||||
let urlPhoto: string | null = null;
|
||||
|
||||
if (enfantDto.photo_base64 && enfantDto.photo_filename) {
|
||||
urlPhoto = await this.sauvegarderPhotoDepuisBase64(
|
||||
enfantDto.photo_base64,
|
||||
enfantDto.photo_filename,
|
||||
);
|
||||
}
|
||||
|
||||
const enfant = new Children();
|
||||
enfant.first_name = enfantDto.prenom;
|
||||
enfant.last_name = enfantDto.nom || dto.nom;
|
||||
enfant.gender = enfantDto.genre;
|
||||
enfant.birth_date = enfantDto.date_naissance ? new Date(enfantDto.date_naissance) : undefined;
|
||||
enfant.due_date = enfantDto.date_previsionnelle_naissance
|
||||
? new Date(enfantDto.date_previsionnelle_naissance)
|
||||
: undefined;
|
||||
enfant.photo_url = urlPhoto || undefined;
|
||||
enfant.status = enfantDto.date_naissance ? StatutEnfantType.ACTIF : StatutEnfantType.A_NAITRE;
|
||||
enfant.consent_photo = false;
|
||||
enfant.is_multiple = enfantDto.grossesse_multiple || false;
|
||||
|
||||
const enfantEnregistre = await manager.save(Children, enfant);
|
||||
enfantsEnregistres.push(enfantEnregistre);
|
||||
|
||||
const lienParentEnfant1 = manager.create(ParentsChildren, {
|
||||
parentId: parent1Enregistre.id,
|
||||
enfantId: enfantEnregistre.id,
|
||||
});
|
||||
await manager.save(ParentsChildren, lienParentEnfant1);
|
||||
|
||||
if (parent2Enregistre) {
|
||||
const lienParentEnfant2 = manager.create(ParentsChildren, {
|
||||
parentId: parent2Enregistre.id,
|
||||
enfantId: enfantEnregistre.id,
|
||||
});
|
||||
await manager.save(ParentsChildren, lienParentEnfant2);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
parent1: parent1Enregistre,
|
||||
parent2: parent2Enregistre,
|
||||
enfants: enfantsEnregistres,
|
||||
tokenCreationMdp,
|
||||
tokenCoParent,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
message: 'Inscription réussie. Votre dossier est en attente de validation par un gestionnaire.',
|
||||
parent_id: resultat.parent1.id,
|
||||
co_parent_id: resultat.parent2?.id,
|
||||
enfants_ids: resultat.enfants.map(e => e.id),
|
||||
statut: StatutUtilisateurType.EN_ATTENTE,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Sauvegarde une photo depuis base64 vers le système de fichiers
|
||||
*/
|
||||
private async sauvegarderPhotoDepuisBase64(donneesBase64: string, nomFichier: string): Promise<string> {
|
||||
const correspondances = donneesBase64.match(/^data:image\/(\w+);base64,(.+)$/);
|
||||
if (!correspondances) {
|
||||
throw new BadRequestException('Format de photo invalide (doit être base64)');
|
||||
}
|
||||
|
||||
const extension = correspondances[1];
|
||||
const tamponImage = Buffer.from(correspondances[2], 'base64');
|
||||
|
||||
const dossierUpload = '/app/uploads/photos';
|
||||
await fs.mkdir(dossierUpload, { recursive: true });
|
||||
|
||||
const nomFichierUnique = `${Date.now()}-${crypto.randomUUID()}.${extension}`;
|
||||
const cheminFichier = path.join(dossierUpload, nomFichierUnique);
|
||||
|
||||
await fs.writeFile(cheminFichier, tamponImage);
|
||||
|
||||
return `/uploads/photos/${nomFichierUnique}`;
|
||||
}
|
||||
|
||||
async logout(userId: string) {
|
||||
return { success: true, message: 'Deconnexion'}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
IsString,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsEnum,
|
||||
IsDateString,
|
||||
IsBoolean,
|
||||
MinLength,
|
||||
MaxLength,
|
||||
} from 'class-validator';
|
||||
import { GenreType } from 'src/entities/children.entity';
|
||||
|
||||
export class EnfantInscriptionDto {
|
||||
@ApiProperty({ example: 'Emma', required: false, description: 'Prénom de l\'enfant (obligatoire si déjà né)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(2, { message: 'Le prénom doit contenir au moins 2 caractères' })
|
||||
@MaxLength(100, { message: 'Le prénom ne peut pas dépasser 100 caractères' })
|
||||
prenom?: string;
|
||||
|
||||
@ApiProperty({ example: 'MARTIN', required: false, description: 'Nom de l\'enfant (hérité des parents si non fourni)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(2, { message: 'Le nom doit contenir au moins 2 caractères' })
|
||||
@MaxLength(100, { message: 'Le nom ne peut pas dépasser 100 caractères' })
|
||||
nom?: string;
|
||||
|
||||
@ApiProperty({ example: '2023-02-15', required: false, description: 'Date de naissance (si enfant déjà né)' })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
date_naissance?: string;
|
||||
|
||||
@ApiProperty({ example: '2025-06-15', required: false, description: 'Date prévisionnelle de naissance (si enfant à naître)' })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
date_previsionnelle_naissance?: string;
|
||||
|
||||
@ApiProperty({ enum: GenreType, example: GenreType.F })
|
||||
@IsEnum(GenreType, { message: 'Le genre doit être H, F ou Autre' })
|
||||
@IsNotEmpty({ message: 'Le genre est requis' })
|
||||
genre: GenreType;
|
||||
|
||||
@ApiProperty({
|
||||
example: 'data:image/jpeg;base64,/9j/4AAQSkZJRg...',
|
||||
required: false,
|
||||
description: 'Photo de l\'enfant en base64 (obligatoire si déjà né)'
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
photo_base64?: string;
|
||||
|
||||
@ApiProperty({ example: 'emma_martin.jpg', required: false, description: 'Nom du fichier photo' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
photo_filename?: string;
|
||||
|
||||
@ApiProperty({ example: false, required: false, description: 'Grossesse multiple (jumeaux, triplés, etc.)' })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
grossesse_multiple?: boolean;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsEmail, IsString, MaxLength, MinLength } from "class-validator";
|
||||
|
||||
export class LoginDto {
|
||||
@ApiProperty({ example: 'mon.utilisateur@exemple.com', description: "Adresse email de l'utililisateur" })
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: "Mon_motdepasse_fort_1234?",
|
||||
description: "Mot de passe de l'utilisateur"
|
||||
})
|
||||
@IsString({ message: 'Le mot de passe doit etre une chaine de caracteres' })
|
||||
//@MinLength(8, { message: 'Le mot de passe doit contenir au moins 8 caracteres' })
|
||||
@MaxLength(50)
|
||||
password: string;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { RoleType, StatutUtilisateurType } from 'src/entities/users.entity';
|
||||
|
||||
export class ProfileResponseDto {
|
||||
@ApiProperty()
|
||||
id: string;
|
||||
|
||||
@ApiProperty()
|
||||
email: string;
|
||||
|
||||
@ApiProperty({ enum: RoleType })
|
||||
role: RoleType;
|
||||
|
||||
@ApiProperty()
|
||||
prenom?: string;
|
||||
|
||||
@ApiProperty()
|
||||
nom?: string;
|
||||
|
||||
@ApiProperty({ enum: StatutUtilisateurType })
|
||||
statut: StatutUtilisateurType;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsString } from "class-validator";
|
||||
|
||||
export class RefreshTokenDto {
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Token de rafraîchissement',
|
||||
example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
|
||||
})
|
||||
@IsString()
|
||||
refresh_token: string;
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
IsEmail,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsDateString,
|
||||
IsEnum,
|
||||
IsBoolean,
|
||||
IsArray,
|
||||
ValidateNested,
|
||||
MinLength,
|
||||
MaxLength,
|
||||
Matches,
|
||||
} from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
import { SituationFamilialeType } from 'src/entities/users.entity';
|
||||
import { EnfantInscriptionDto } from './enfant-inscription.dto';
|
||||
|
||||
export class RegisterParentCompletDto {
|
||||
// ============================================
|
||||
// ÉTAPE 1 : PARENT 1 (Obligatoire)
|
||||
// ============================================
|
||||
|
||||
@ApiProperty({ example: 'claire.martin@ptits-pas.fr' })
|
||||
@IsEmail({}, { message: 'Email invalide' })
|
||||
@IsNotEmpty({ message: 'L\'email est requis' })
|
||||
email: string;
|
||||
|
||||
@ApiProperty({ example: 'Claire' })
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: 'Le prénom est requis' })
|
||||
@MinLength(2, { message: 'Le prénom doit contenir au moins 2 caractères' })
|
||||
@MaxLength(100, { message: 'Le prénom ne peut pas dépasser 100 caractères' })
|
||||
prenom: string;
|
||||
|
||||
@ApiProperty({ example: 'MARTIN' })
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: 'Le nom est requis' })
|
||||
@MinLength(2, { message: 'Le nom doit contenir au moins 2 caractères' })
|
||||
@MaxLength(100, { message: 'Le nom ne peut pas dépasser 100 caractères' })
|
||||
nom: string;
|
||||
|
||||
@ApiProperty({ example: '0689567890' })
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: 'Le téléphone est requis' })
|
||||
@Matches(/^(\+33|0)[1-9](\d{2}){4}$/, {
|
||||
message: 'Le numéro de téléphone doit être valide (ex: 0689567890 ou +33689567890)',
|
||||
})
|
||||
telephone: string;
|
||||
|
||||
@ApiProperty({ example: '5 Avenue du Général de Gaulle', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
adresse?: string;
|
||||
|
||||
@ApiProperty({ example: '95870', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(10)
|
||||
code_postal?: string;
|
||||
|
||||
@ApiProperty({ example: 'Bezons', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(150)
|
||||
ville?: string;
|
||||
|
||||
// ============================================
|
||||
// ÉTAPE 2 : PARENT 2 / CO-PARENT (Optionnel)
|
||||
// ============================================
|
||||
|
||||
@ApiProperty({ example: 'thomas.martin@ptits-pas.fr', required: false })
|
||||
@IsOptional()
|
||||
@IsEmail({}, { message: 'Email du co-parent invalide' })
|
||||
co_parent_email?: string;
|
||||
|
||||
@ApiProperty({ example: 'Thomas', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
co_parent_prenom?: string;
|
||||
|
||||
@ApiProperty({ example: 'MARTIN', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
co_parent_nom?: string;
|
||||
|
||||
@ApiProperty({ example: '0678456789', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Matches(/^(\+33|0)[1-9](\d{2}){4}$/, {
|
||||
message: 'Le numéro de téléphone du co-parent doit être valide',
|
||||
})
|
||||
co_parent_telephone?: string;
|
||||
|
||||
@ApiProperty({ example: true, description: 'Le co-parent habite à la même adresse', required: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
co_parent_meme_adresse?: boolean;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
co_parent_adresse?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
co_parent_code_postal?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
co_parent_ville?: string;
|
||||
|
||||
// ============================================
|
||||
// ÉTAPE 3 : ENFANT(S) (Au moins 1 requis)
|
||||
// ============================================
|
||||
|
||||
@ApiProperty({
|
||||
type: [EnfantInscriptionDto],
|
||||
description: 'Liste des enfants (au moins 1 requis)',
|
||||
example: [{
|
||||
prenom: 'Emma',
|
||||
nom: 'MARTIN',
|
||||
date_naissance: '2023-02-15',
|
||||
genre: 'F',
|
||||
photo_base64: 'data:image/jpeg;base64,...',
|
||||
photo_filename: 'emma_martin.jpg'
|
||||
}]
|
||||
})
|
||||
@IsArray({ message: 'La liste des enfants doit être un tableau' })
|
||||
@IsNotEmpty({ message: 'Au moins un enfant est requis' })
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => EnfantInscriptionDto)
|
||||
enfants: EnfantInscriptionDto[];
|
||||
|
||||
// ============================================
|
||||
// ÉTAPE 4 : PRÉSENTATION DU DOSSIER (Optionnel)
|
||||
// ============================================
|
||||
|
||||
@ApiProperty({
|
||||
example: 'Nous recherchons une assistante maternelle bienveillante pour nos triplés...',
|
||||
required: false,
|
||||
description: 'Présentation du dossier (max 2000 caractères)'
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(2000, { message: 'La présentation ne peut pas dépasser 2000 caractères' })
|
||||
presentation_dossier?: string;
|
||||
|
||||
// ============================================
|
||||
// ÉTAPE 5 : ACCEPTATION CGU (Obligatoire)
|
||||
// ============================================
|
||||
|
||||
@ApiProperty({ example: true, description: 'Acceptation des Conditions Générales d\'Utilisation' })
|
||||
@IsBoolean()
|
||||
@IsNotEmpty({ message: 'L\'acceptation des CGU est requise' })
|
||||
acceptation_cgu: boolean;
|
||||
|
||||
@ApiProperty({ example: true, description: 'Acceptation de la Politique de confidentialité' })
|
||||
@IsBoolean()
|
||||
@IsNotEmpty({ message: 'L\'acceptation de la politique de confidentialité est requise' })
|
||||
acceptation_privacy: boolean;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
IsEmail,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsDateString,
|
||||
IsEnum,
|
||||
MinLength,
|
||||
MaxLength,
|
||||
Matches,
|
||||
} from 'class-validator';
|
||||
import { SituationFamilialeType } from 'src/entities/users.entity';
|
||||
|
||||
export class RegisterParentDto {
|
||||
// === Informations obligatoires ===
|
||||
@ApiProperty({ example: 'claire.martin@ptits-pas.fr' })
|
||||
@IsEmail({}, { message: 'Email invalide' })
|
||||
@IsNotEmpty({ message: 'L\'email est requis' })
|
||||
email: string;
|
||||
|
||||
@ApiProperty({ example: 'Claire' })
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: 'Le prénom est requis' })
|
||||
@MinLength(2, { message: 'Le prénom doit contenir au moins 2 caractères' })
|
||||
@MaxLength(100, { message: 'Le prénom ne peut pas dépasser 100 caractères' })
|
||||
prenom: string;
|
||||
|
||||
@ApiProperty({ example: 'MARTIN' })
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: 'Le nom est requis' })
|
||||
@MinLength(2, { message: 'Le nom doit contenir au moins 2 caractères' })
|
||||
@MaxLength(100, { message: 'Le nom ne peut pas dépasser 100 caractères' })
|
||||
nom: string;
|
||||
|
||||
@ApiProperty({ example: '0689567890' })
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: 'Le téléphone est requis' })
|
||||
@Matches(/^(\+33|0)[1-9](\d{2}){4}$/, {
|
||||
message: 'Le numéro de téléphone doit être valide (ex: 0689567890 ou +33689567890)',
|
||||
})
|
||||
telephone: string;
|
||||
|
||||
// === Informations optionnelles ===
|
||||
@ApiProperty({ example: '5 Avenue du Général de Gaulle', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
adresse?: string;
|
||||
|
||||
@ApiProperty({ example: '95870', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(10)
|
||||
code_postal?: string;
|
||||
|
||||
@ApiProperty({ example: 'Bezons', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(150)
|
||||
ville?: string;
|
||||
|
||||
// === Informations co-parent (optionnel) ===
|
||||
@ApiProperty({ example: 'thomas.martin@ptits-pas.fr', required: false })
|
||||
@IsOptional()
|
||||
@IsEmail({}, { message: 'Email du co-parent invalide' })
|
||||
co_parent_email?: string;
|
||||
|
||||
@ApiProperty({ example: 'Thomas', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
co_parent_prenom?: string;
|
||||
|
||||
@ApiProperty({ example: 'MARTIN', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
co_parent_nom?: string;
|
||||
|
||||
@ApiProperty({ example: '0612345678', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Matches(/^(\+33|0)[1-9](\d{2}){4}$/, {
|
||||
message: 'Le numéro de téléphone du co-parent doit être valide',
|
||||
})
|
||||
co_parent_telephone?: string;
|
||||
|
||||
@ApiProperty({ example: 'true', description: 'Le co-parent habite à la même adresse', required: false })
|
||||
@IsOptional()
|
||||
co_parent_meme_adresse?: boolean;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
co_parent_adresse?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
co_parent_code_postal?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
co_parent_ville?: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ApiProperty, OmitType } from '@nestjs/swagger';
|
||||
import { IsEnum, IsOptional } from 'class-validator';
|
||||
import { CreateUserDto } from '../../user/dto/create_user.dto';
|
||||
import { RoleType, StatutUtilisateurType } from 'src/entities/users.entity';
|
||||
|
||||
export class RegisterDto extends OmitType(CreateUserDto, ['changement_mdp_obligatoire'] as const) {
|
||||
@ApiProperty({ enum: [RoleType.ASSISTANTE_MATERNELLE, RoleType.PARENT], default: RoleType.PARENT })
|
||||
@IsEnum(RoleType)
|
||||
role: RoleType = RoleType.PARENT;
|
||||
|
||||
@IsEnum(StatutUtilisateurType)
|
||||
@IsOptional()
|
||||
statut?: StatutUtilisateurType = StatutUtilisateurType.EN_ATTENTE;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
@Module({})
|
||||
export class DossiersModule {}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
IsBoolean,
|
||||
IsDateString,
|
||||
IsEnum,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
ValidateIf,
|
||||
} from 'class-validator';
|
||||
import { GenreType, StatutEnfantType } from 'src/entities/children.entity';
|
||||
|
||||
export class CreateEnfantsDto {
|
||||
@ApiProperty({ enum: StatutEnfantType, example: StatutEnfantType.ACTIF })
|
||||
@IsEnum(StatutEnfantType)
|
||||
@IsNotEmpty()
|
||||
status: StatutEnfantType;
|
||||
|
||||
@ApiProperty({ example: 'Georges', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
first_name?: string;
|
||||
|
||||
@ApiProperty({ example: 'Dupont', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
last_name?: string;
|
||||
|
||||
@ApiProperty({ enum: GenreType })
|
||||
@IsEnum(GenreType)
|
||||
@IsNotEmpty()
|
||||
gender: GenreType;
|
||||
|
||||
@ApiProperty({ example: '2018-06-24', required: false })
|
||||
@ValidateIf(o => o.status !== StatutEnfantType.A_NAITRE)
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
birth_date?: string;
|
||||
|
||||
@ApiProperty({ example: '2025-12-15', required: false })
|
||||
@ValidateIf(o => o.status === StatutEnfantType.A_NAITRE)
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
due_date?: string;
|
||||
|
||||
@ApiProperty({ example: 'https://monimage.com/photo.jpg', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
photo_url?: string;
|
||||
|
||||
@ApiProperty({ default: false })
|
||||
@IsBoolean()
|
||||
consent_photo: boolean;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
consent_photo_at?: string;
|
||||
|
||||
@ApiProperty({ default: false })
|
||||
@IsBoolean()
|
||||
is_multiple: boolean;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { GenreType, StatutEnfantType } from 'src/entities/children.entity';
|
||||
|
||||
export class EnfantResponseDto {
|
||||
@ApiProperty({ example: 'UUID-enfant' })
|
||||
id: string;
|
||||
|
||||
@ApiProperty({ enum: StatutEnfantType })
|
||||
status: StatutEnfantType;
|
||||
|
||||
@ApiProperty({ example: 'Georges', required: false })
|
||||
first_name?: string;
|
||||
|
||||
@ApiProperty({ example: 'Dupont', required: false })
|
||||
last_name?: string;
|
||||
|
||||
@ApiProperty({ enum: GenreType, required: false })
|
||||
gender?: GenreType;
|
||||
|
||||
@ApiProperty({ example: '2018-06-24', required: false })
|
||||
birth_date?: string;
|
||||
|
||||
@ApiProperty({ example: '2025-12-15', required: false })
|
||||
due_date?: string;
|
||||
|
||||
@ApiProperty({ example: 'https://monimage.com/photo.jpg', required: false })
|
||||
photo_url?: string;
|
||||
|
||||
@ApiProperty({ example: false })
|
||||
consent_photo: boolean;
|
||||
|
||||
@ApiProperty({ example: false })
|
||||
is_multiple: boolean;
|
||||
|
||||
@ApiProperty({ example: 'UUID-parent' })
|
||||
parent_id: string;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateEnfantsDto } from './create_enfants.dto';
|
||||
|
||||
export class UpdateEnfantsDto extends PartialType(CreateEnfantsDto) {}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { EnfantsController } from './enfants.controller';
|
||||
|
||||
describe('EnfantsController', () => {
|
||||
let controller: EnfantsController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [EnfantsController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<EnfantsController>(EnfantsController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Patch,
|
||||
Post,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
UploadedFile,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { ApiBearerAuth, ApiTags, ApiConsumes } from '@nestjs/swagger';
|
||||
import { diskStorage } from 'multer';
|
||||
import { extname } from 'path';
|
||||
import { EnfantsService } from './enfants.service';
|
||||
import { CreateEnfantsDto } from './dto/create_enfants.dto';
|
||||
import { UpdateEnfantsDto } from './dto/update_enfants.dto';
|
||||
import { RoleType, Users } from 'src/entities/users.entity';
|
||||
import { User } from 'src/common/decorators/user.decorator';
|
||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||
|
||||
@ApiBearerAuth('access-token')
|
||||
@ApiTags('Enfants')
|
||||
@UseGuards(AuthGuard, RolesGuard)
|
||||
@Controller('enfants')
|
||||
export class EnfantsController {
|
||||
constructor(private readonly enfantsService: EnfantsService) { }
|
||||
|
||||
@Roles(RoleType.PARENT)
|
||||
@Post()
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(
|
||||
FileInterceptor('photo', {
|
||||
storage: diskStorage({
|
||||
destination: './uploads/photos',
|
||||
filename: (req, file, cb) => {
|
||||
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
|
||||
const ext = extname(file.originalname);
|
||||
cb(null, `enfant-${uniqueSuffix}${ext}`);
|
||||
},
|
||||
}),
|
||||
fileFilter: (req, file, cb) => {
|
||||
if (!file.mimetype.match(/\/(jpg|jpeg|png|gif)$/)) {
|
||||
return cb(new Error('Seules les images sont autorisées'), false);
|
||||
}
|
||||
cb(null, true);
|
||||
},
|
||||
limits: {
|
||||
fileSize: 5 * 1024 * 1024,
|
||||
},
|
||||
}),
|
||||
)
|
||||
create(
|
||||
@Body() dto: CreateEnfantsDto,
|
||||
@UploadedFile() photo: Express.Multer.File,
|
||||
@User() currentUser: Users,
|
||||
) {
|
||||
return this.enfantsService.create(dto, currentUser, photo);
|
||||
}
|
||||
|
||||
@Roles(RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE, RoleType.SUPER_ADMIN)
|
||||
@Get()
|
||||
findAll() {
|
||||
return this.enfantsService.findAll();
|
||||
}
|
||||
|
||||
@Roles(
|
||||
RoleType.PARENT,
|
||||
RoleType.ADMINISTRATEUR,
|
||||
RoleType.SUPER_ADMIN,
|
||||
RoleType.GESTIONNAIRE
|
||||
)
|
||||
@Get(':id')
|
||||
findOne(
|
||||
@Param('id', new ParseUUIDPipe()) id: string,
|
||||
@User() currentUser: Users
|
||||
) {
|
||||
return this.enfantsService.findOne(id, currentUser);
|
||||
}
|
||||
|
||||
@Roles(RoleType.ADMINISTRATEUR, RoleType.SUPER_ADMIN, RoleType.PARENT)
|
||||
@Patch(':id')
|
||||
update(
|
||||
@Param('id', new ParseUUIDPipe()) id: string,
|
||||
@Body() dto: UpdateEnfantsDto,
|
||||
@User() currentUser: Users,
|
||||
) {
|
||||
return this.enfantsService.update(id, dto, currentUser);
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@Delete(':id')
|
||||
remove(@Param('id', new ParseUUIDPipe()) id: string) {
|
||||
return this.enfantsService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { EnfantsController } from './enfants.controller';
|
||||
import { EnfantsService } from './enfants.service';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Children } from 'src/entities/children.entity';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Children, Parents, ParentsChildren]),
|
||||
AuthModule
|
||||
|
||||
],
|
||||
controllers: [EnfantsController],
|
||||
providers: [EnfantsService]
|
||||
})
|
||||
export class EnfantsModule { }
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { EnfantsService } from './enfants.service';
|
||||
|
||||
describe('EnfantsService', () => {
|
||||
let service: EnfantsService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [EnfantsService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<EnfantsService>(EnfantsService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { Children, StatutEnfantType } from 'src/entities/children.entity';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||
import { RoleType, Users } from 'src/entities/users.entity';
|
||||
import { CreateEnfantsDto } from './dto/create_enfants.dto';
|
||||
|
||||
@Injectable()
|
||||
export class EnfantsService {
|
||||
constructor(
|
||||
@InjectRepository(Children)
|
||||
private readonly childrenRepository: Repository<Children>,
|
||||
@InjectRepository(Parents)
|
||||
private readonly parentsRepository: Repository<Parents>,
|
||||
@InjectRepository(ParentsChildren)
|
||||
private readonly parentsChildrenRepository: Repository<ParentsChildren>,
|
||||
) { }
|
||||
|
||||
// Création d'un enfant
|
||||
async create(dto: CreateEnfantsDto, currentUser: Users, photoFile?: Express.Multer.File): Promise<Children> {
|
||||
const parent = await this.parentsRepository.findOne({
|
||||
where: { user_id: currentUser.id },
|
||||
relations: ['co_parent'],
|
||||
});
|
||||
if (!parent) throw new NotFoundException('Parent introuvable');
|
||||
|
||||
// Vérif métier simple
|
||||
if (dto.status !== StatutEnfantType.A_NAITRE && !dto.birth_date) {
|
||||
throw new BadRequestException('Un enfant actif doit avoir une date de naissance');
|
||||
}
|
||||
|
||||
// Vérif doublon éventuel (ex: même prénom + date de naissance pour ce parent)
|
||||
const exist = await this.childrenRepository.findOne({
|
||||
where: {
|
||||
first_name: dto.first_name,
|
||||
last_name: dto.last_name,
|
||||
birth_date: dto.birth_date ? new Date(dto.birth_date) : undefined,
|
||||
},
|
||||
});
|
||||
if (exist) throw new ConflictException('Cet enfant existe déjà');
|
||||
|
||||
// Gestion de la photo uploadée
|
||||
if (photoFile) {
|
||||
dto.photo_url = `/uploads/photos/${photoFile.filename}`;
|
||||
if (dto.consent_photo) {
|
||||
dto.consent_photo_at = new Date().toISOString();
|
||||
}
|
||||
}
|
||||
|
||||
// Création
|
||||
const child = this.childrenRepository.create(dto);
|
||||
await this.childrenRepository.save(child);
|
||||
|
||||
// Lien parent-enfant (Parent 1)
|
||||
const parentLink = this.parentsChildrenRepository.create({
|
||||
parentId: parent.user_id,
|
||||
enfantId: child.id,
|
||||
});
|
||||
await this.parentsChildrenRepository.save(parentLink);
|
||||
|
||||
// Rattachement automatique au co-parent s'il existe
|
||||
if (parent.co_parent) {
|
||||
const coParentLink = this.parentsChildrenRepository.create({
|
||||
parentId: parent.co_parent.id,
|
||||
enfantId: child.id,
|
||||
});
|
||||
await this.parentsChildrenRepository.save(coParentLink);
|
||||
}
|
||||
|
||||
return this.findOne(child.id, currentUser);
|
||||
}
|
||||
|
||||
// Liste des enfants
|
||||
async findAll(): Promise<Children[]> {
|
||||
return this.childrenRepository.find({
|
||||
relations: ['parentLinks'],
|
||||
order: { last_name: 'ASC', first_name: 'ASC' },
|
||||
});
|
||||
}
|
||||
|
||||
// Récupérer un enfant par id
|
||||
async findOne(id: string, currentUser: Users): Promise<Children> {
|
||||
const child = await this.childrenRepository.findOne({
|
||||
where: { id },
|
||||
relations: ['parentLinks'],
|
||||
});
|
||||
if (!child) throw new NotFoundException('Enfant introuvable');
|
||||
|
||||
switch (currentUser.role) {
|
||||
case RoleType.PARENT:
|
||||
if (!child.parentLinks.some(link => link.parentId === currentUser.id)) {
|
||||
throw new ForbiddenException('Cet enfant ne vous appartient pas');
|
||||
}
|
||||
break;
|
||||
|
||||
case RoleType.ADMINISTRATEUR:
|
||||
case RoleType.SUPER_ADMIN:
|
||||
case RoleType.GESTIONNAIRE:
|
||||
// accès complet
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new ForbiddenException('Accès interdit');
|
||||
}
|
||||
|
||||
return child;
|
||||
}
|
||||
|
||||
|
||||
// Mise à jour
|
||||
async update(id: string, dto: Partial<CreateEnfantsDto>, currentUser: Users): Promise<Children> {
|
||||
const child = await this.childrenRepository.findOne({ where: { id } });
|
||||
if (!child) throw new NotFoundException('Enfant introuvable');
|
||||
|
||||
await this.childrenRepository.update(id, dto);
|
||||
return this.findOne(id, currentUser);
|
||||
}
|
||||
|
||||
// Suppression
|
||||
async remove(id: string): Promise<void> {
|
||||
await this.childrenRepository.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ParentsController } from './parents.controller';
|
||||
|
||||
describe('ParentsController', () => {
|
||||
let controller: ParentsController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [ParentsController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<ParentsController>(ParentsController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
} from '@nestjs/common';
|
||||
import { ParentsService } from './parents.service';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||
import { RoleType } from 'src/entities/users.entity';
|
||||
import { ApiBody, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { CreateParentDto } from '../user/dto/create_parent.dto';
|
||||
import { UpdateParentsDto } from '../user/dto/update_parent.dto';
|
||||
|
||||
@ApiTags('Parents')
|
||||
@Controller('parents')
|
||||
export class ParentsController {
|
||||
constructor(private readonly parentsService: ParentsService) {}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||
@Get()
|
||||
@ApiResponse({ status: 200, type: [Parents], description: 'Liste des parents' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé !' })
|
||||
getAll(): Promise<Parents[]> {
|
||||
return this.parentsService.findAll();
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||
@Get(':id')
|
||||
@ApiResponse({ status: 200, type: Parents, description: 'Détails du parent par ID utilisateur' })
|
||||
@ApiResponse({ status: 404, description: 'Parent non trouvé' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé !' })
|
||||
getOne(@Param('id') user_id: string): Promise<Parents> {
|
||||
return this.parentsService.findOne(user_id);
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||
@Post()
|
||||
@ApiBody({ type: CreateParentDto })
|
||||
@ApiResponse({ status: 201, type: Parents, description: 'Parent créé avec succès' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé !' })
|
||||
create(@Body() dto: CreateParentDto): Promise<Parents> {
|
||||
return this.parentsService.create(dto);
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||
@Patch(':id')
|
||||
@ApiBody({ type: UpdateParentsDto })
|
||||
@ApiResponse({ status: 200, type: Parents, description: 'Parent mis à jour avec succès' })
|
||||
@ApiResponse({ status: 404, description: 'Parent introuvable' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé !' })
|
||||
update(@Param('id') id: string, @Body() dto: UpdateParentsDto): Promise<Parents> {
|
||||
return this.parentsService.update(id, dto);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { ParentsController } from './parents.controller';
|
||||
import { ParentsService } from './parents.service';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Parents, Users])],
|
||||
controllers: [ParentsController],
|
||||
providers: [ParentsService],
|
||||
exports: [ParentsService,
|
||||
TypeOrmModule,
|
||||
],
|
||||
})
|
||||
export class ParentsModule { }
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ParentsService } from './parents.service';
|
||||
|
||||
describe('ParentsService', () => {
|
||||
let service: ParentsService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [ParentsService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<ParentsService>(ParentsService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { RoleType, Users } from 'src/entities/users.entity';
|
||||
import { CreateParentDto } from '../user/dto/create_parent.dto';
|
||||
import { UpdateParentsDto } from '../user/dto/update_parent.dto';
|
||||
|
||||
@Injectable()
|
||||
export class ParentsService {
|
||||
constructor(
|
||||
@InjectRepository(Parents)
|
||||
private readonly parentsRepository: Repository<Parents>,
|
||||
@InjectRepository(Users)
|
||||
private readonly usersRepository: Repository<Users>,
|
||||
) {}
|
||||
|
||||
// Création d’un parent
|
||||
async create(dto: CreateParentDto): Promise<Parents> {
|
||||
const user = await this.usersRepository.findOneBy({ id: dto.user_id });
|
||||
if (!user) throw new NotFoundException('Utilisateur introuvable');
|
||||
if (user.role !== RoleType.PARENT) {
|
||||
throw new BadRequestException('Accès réservé aux parents');
|
||||
}
|
||||
|
||||
const exist = await this.parentsRepository.findOneBy({ user_id: dto.user_id });
|
||||
if (exist) throw new ConflictException('Ce parent existe déjà');
|
||||
|
||||
let co_parent: Users | null = null;
|
||||
if (dto.co_parent_id) {
|
||||
co_parent = await this.usersRepository.findOneBy({ id: dto.co_parent_id });
|
||||
if (!co_parent) throw new NotFoundException('Co-parent introuvable');
|
||||
if (co_parent.role !== RoleType.PARENT) {
|
||||
throw new BadRequestException('Accès réservé aux parents');
|
||||
}
|
||||
}
|
||||
|
||||
const entity = this.parentsRepository.create({
|
||||
user_id: dto.user_id,
|
||||
user,
|
||||
co_parent: co_parent ?? undefined,
|
||||
});
|
||||
|
||||
return this.parentsRepository.save(entity);
|
||||
}
|
||||
|
||||
// Liste des parents
|
||||
async findAll(): Promise<Parents[]> {
|
||||
return this.parentsRepository.find({
|
||||
relations: ['user', 'co_parent', 'parentChildren', 'dossiers'],
|
||||
});
|
||||
}
|
||||
|
||||
// Récupérer un parent par user_id
|
||||
async findOne(user_id: string): Promise<Parents> {
|
||||
const parent = await this.parentsRepository.findOne({
|
||||
where: { user_id },
|
||||
relations: ['user', 'co_parent', 'parentChildren', 'dossiers'],
|
||||
});
|
||||
if (!parent) throw new NotFoundException('Parent introuvable');
|
||||
return parent;
|
||||
}
|
||||
|
||||
// Mise à jour
|
||||
async update(id: string, dto: UpdateParentsDto): Promise<Parents> {
|
||||
await this.parentsRepository.update(id, dto);
|
||||
return this.findOne(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { OmitType } from "@nestjs/swagger";
|
||||
import { CreateUserDto } from "./create_user.dto";
|
||||
|
||||
export class CreateAdminDto extends OmitType(CreateUserDto, ['role'] as const) {}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { OmitType } from "@nestjs/swagger";
|
||||
import { IsBoolean, IsDateString, IsInt, IsNotEmpty, IsOptional, IsString, IsUUID, Length, Matches, Max, Min } from "class-validator";
|
||||
import { CreateUserDto } from "./create_user.dto";
|
||||
|
||||
export class CreateAssistanteDto extends OmitType(CreateUserDto, ['role', 'photo_url', 'consentement_photo'] as const) {
|
||||
@IsUUID()
|
||||
@IsNotEmpty()
|
||||
user_id?: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@Length(1, 50)
|
||||
approval_number: string;
|
||||
|
||||
@Matches(/^\d{15}$/)
|
||||
@IsNotEmpty()
|
||||
nir: string;
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(10)
|
||||
@IsNotEmpty()
|
||||
max_children: number;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
photo_url: string;
|
||||
|
||||
@IsBoolean()
|
||||
@IsNotEmpty()
|
||||
consentement_photo: boolean;
|
||||
|
||||
@IsDateString()
|
||||
@IsNotEmpty()
|
||||
agreement_date: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@Length(1, 100)
|
||||
residence_city: string;
|
||||
|
||||
@IsOptional()
|
||||
biography?: string;
|
||||
|
||||
@IsOptional()
|
||||
available?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
years_experience?: number;
|
||||
|
||||
@IsOptional()
|
||||
specialty?: string;
|
||||
|
||||
@IsOptional()
|
||||
places_available?: number;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { OmitType } from "@nestjs/swagger";
|
||||
import { CreateUserDto } from "./create_user.dto";
|
||||
|
||||
export class CreateGestionnaireDto extends OmitType(CreateUserDto, ['role'] as const) {}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { OmitType } from "@nestjs/swagger";
|
||||
import { CreateUserDto } from "./create_user.dto";
|
||||
import { IsNotEmpty, IsOptional, IsString, IsUUID } from "class-validator";
|
||||
|
||||
export class CreateParentDto extends OmitType(CreateUserDto, ['role', 'photo_url'] as const) {
|
||||
@IsUUID()
|
||||
@IsNotEmpty()
|
||||
user_id: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
co_parent_id?: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
photo_url: string;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
IsBoolean,
|
||||
IsDateString,
|
||||
IsEmail,
|
||||
IsEnum,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MinLength,
|
||||
MaxLength,
|
||||
} from 'class-validator';
|
||||
import { RoleType, GenreType, StatutUtilisateurType, SituationFamilialeType } from 'src/entities/users.entity';
|
||||
|
||||
export class CreateUserDto {
|
||||
@ApiProperty({ example: 'sosso.test@example.com' })
|
||||
@IsEmail()
|
||||
@IsNotEmpty()
|
||||
email: string;
|
||||
|
||||
@ApiProperty({ minLength: 6, example: 'Mon_motdepasse_fort_1234?' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MinLength(6)
|
||||
password: string;
|
||||
|
||||
@ApiProperty({ example: 'Julien' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(100)
|
||||
prenom: string;
|
||||
|
||||
@ApiProperty({ example: 'Dupont' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(100)
|
||||
nom: string;
|
||||
|
||||
@ApiProperty({ enum: GenreType, required: false, default: GenreType.AUTRE })
|
||||
@IsOptional()
|
||||
@IsEnum(GenreType)
|
||||
genre?: GenreType = GenreType.AUTRE;
|
||||
|
||||
@ApiProperty({ enum: RoleType })
|
||||
@IsEnum(RoleType)
|
||||
role: RoleType;
|
||||
|
||||
@ApiProperty({ enum: StatutUtilisateurType, required: false, default: StatutUtilisateurType.EN_ATTENTE })
|
||||
@IsOptional()
|
||||
@IsEnum(StatutUtilisateurType)
|
||||
statut?: StatutUtilisateurType = StatutUtilisateurType.EN_ATTENTE;
|
||||
|
||||
@ApiProperty({ example: SituationFamilialeType.MARIE, required: false, enum: SituationFamilialeType, default: SituationFamilialeType.MARIE})
|
||||
@IsOptional()
|
||||
@IsEnum(SituationFamilialeType)
|
||||
situation_familiale?: SituationFamilialeType;
|
||||
|
||||
@ApiProperty({ example: '+33123456789' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(20)
|
||||
telephone: string;
|
||||
|
||||
@ApiProperty({ example: 'Paris', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(150)
|
||||
ville?: string;
|
||||
|
||||
@ApiProperty({ example: '75000', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(10)
|
||||
code_postal?: string;
|
||||
|
||||
@ApiProperty({ example: '10 rue de la paix, 75000 Paris' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
adresse: string;
|
||||
|
||||
@ApiProperty({ example: 'https://example.com/photo.jpg', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
photo_url?: string;
|
||||
|
||||
@ApiProperty({ default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
consentement_photo?: boolean = false;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsDateString({}, { message: 'date_consentement_photo doit être une date ISO valide' })
|
||||
date_consentement_photo?: string | null;
|
||||
|
||||
@ApiProperty({ default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
changement_mdp_obligatoire?: boolean = false;
|
||||
|
||||
@ApiProperty({ example: true })
|
||||
@IsBoolean()
|
||||
@IsNotEmpty()
|
||||
cguAccepted: boolean;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { CreateAdminDto } from "./create_admin.dto";
|
||||
|
||||
export class UpdateAdminDto extends PartialType(CreateAdminDto) {}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { CreateAssistanteDto } from "./create_assistante.dto";
|
||||
|
||||
export class UpdateAssistanteDto extends PartialType(CreateAssistanteDto) {}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { CreateGestionnaireDto } from "./create_gestionnaire.dto";
|
||||
|
||||
export class UpdateGestionnaireDto extends PartialType(CreateGestionnaireDto) {}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { CreateParentDto } from "./create_parent.dto";
|
||||
|
||||
export class UpdateParentsDto extends PartialType(CreateParentDto) {}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { CreateUserDto } from "./create_user.dto";
|
||||
|
||||
export class UpdateUserDto extends PartialType(CreateUserDto) {}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { GestionnairesController } from './gestionnaires.controller';
|
||||
import { GestionnairesService } from './gestionnaires.service';
|
||||
|
||||
describe('GestionnairesController', () => {
|
||||
let controller: GestionnairesController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [GestionnairesController],
|
||||
providers: [GestionnairesService],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<GestionnairesController>(GestionnairesController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Patch,
|
||||
Param,
|
||||
Delete,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { GestionnairesService } from './gestionnaires.service';
|
||||
import { RoleType, Users } from 'src/entities/users.entity';
|
||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||
import { UpdateGestionnaireDto } from '../dto/update_gestionnaire.dto';
|
||||
import { CreateGestionnaireDto } from '../dto/create_gestionnaire.dto';
|
||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||
|
||||
|
||||
@ApiTags('Gestionnaires')
|
||||
@ApiBearerAuth('access-token')
|
||||
@UseGuards(AuthGuard, RolesGuard)
|
||||
@Controller('gestionnaires')
|
||||
export class GestionnairesController {
|
||||
constructor(private readonly gestionnairesService: GestionnairesService) { }
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@ApiResponse({ status: 201, description: 'Le gestionnaire a été créé avec succès.', type: Users })
|
||||
@ApiResponse({ status: 409, description: 'Conflit. L\'email est déjà utilisé.' })
|
||||
@ApiOperation({ summary: 'Création d\'un gestionnaire' })
|
||||
@ApiBody({ type: CreateGestionnaireDto })
|
||||
@Post()
|
||||
create(@Body() dto: CreateGestionnaireDto): Promise<Users> {
|
||||
return this.gestionnairesService.create(dto);
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||
@ApiOperation({ summary: 'Liste des gestionnaires' })
|
||||
@ApiResponse({ status: 200, description: 'Liste des gestionnaires : ', type: [Users] })
|
||||
@Get()
|
||||
getAll(): Promise<Users[]> {
|
||||
return this.gestionnairesService.findAll();
|
||||
}
|
||||
|
||||
@Roles(RoleType.GESTIONNAIRE, RoleType.SUPER_ADMIN)
|
||||
@ApiOperation({ summary: 'Récupérer un gestionnaire par ID' })
|
||||
@ApiResponse({ status: 400, description: 'ID invalide' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||
@ApiResponse({ status: 401, description: 'Non authentifié' })
|
||||
@ApiParam({ name: 'id', description: 'ID du gestionnaire' })
|
||||
@ApiResponse({ status: 200, description: 'Gestionnaire trouvé', type: Users })
|
||||
@ApiResponse({ status: 404, description: 'Gestionnaire non trouvé' })
|
||||
@Get(':id')
|
||||
findOne(@Param('id') id: string): Promise<Users> {
|
||||
return this.gestionnairesService.findOne(id);
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@ApiOperation({ summary: 'Mettre à jour un gestionnaire' })
|
||||
@ApiResponse({ status: 200, description: 'Le gestionnaire a été mis à jour avec succès.', type: Users })
|
||||
@ApiResponse({ status: 404, description: 'Gestionnaire non trouvé' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||
@ApiResponse({ status: 401, description: 'Non authentifié' })
|
||||
@ApiParam({ name: 'id', description: 'ID du gestionnaire' })
|
||||
@Patch(':id')
|
||||
update(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateGestionnaireDto,
|
||||
): Promise<Users | null> {
|
||||
return this.gestionnairesService.update(id, dto);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { GestionnairesService } from './gestionnaires.service';
|
||||
import { GestionnairesController } from './gestionnaires.controller';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Users])],
|
||||
controllers: [GestionnairesController],
|
||||
providers: [GestionnairesService],
|
||||
})
|
||||
export class GestionnairesModule { }
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { GestionnairesService } from './gestionnaires.service';
|
||||
|
||||
describe('GestionnairesService', () => {
|
||||
let service: GestionnairesService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [GestionnairesService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<GestionnairesService>(GestionnairesService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { RoleType, Users } from 'src/entities/users.entity';
|
||||
import { CreateGestionnaireDto } from '../dto/create_gestionnaire.dto';
|
||||
import { UpdateGestionnaireDto } from '../dto/update_gestionnaire.dto';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
|
||||
@Injectable()
|
||||
export class GestionnairesService {
|
||||
constructor(
|
||||
@InjectRepository(Users)
|
||||
private readonly gestionnaireRepository: Repository<Users>,
|
||||
) { }
|
||||
|
||||
// Création d’un gestionnaire
|
||||
async create(dto: CreateGestionnaireDto): Promise<Users> {
|
||||
const exist = await this.gestionnaireRepository.findOneBy({ email: dto.email });
|
||||
if (exist) throw new ConflictException('Email déjà utilisé');
|
||||
|
||||
const salt = await bcrypt.genSalt();
|
||||
const hashedPassword = await bcrypt.hash(dto.password, salt);
|
||||
|
||||
const entity = this.gestionnaireRepository.create({
|
||||
email: dto.email,
|
||||
password: hashedPassword,
|
||||
prenom: dto.prenom,
|
||||
nom: dto.nom,
|
||||
genre: dto.genre,
|
||||
statut: dto.statut,
|
||||
telephone: dto.telephone,
|
||||
adresse: dto.adresse,
|
||||
photo_url: dto.photo_url,
|
||||
consentement_photo: dto.consentement_photo ?? false,
|
||||
date_consentement_photo: dto.date_consentement_photo
|
||||
? new Date(dto.date_consentement_photo)
|
||||
: undefined,
|
||||
changement_mdp_obligatoire: dto.changement_mdp_obligatoire ?? false,
|
||||
role: RoleType.GESTIONNAIRE,
|
||||
});
|
||||
return this.gestionnaireRepository.save(entity);
|
||||
}
|
||||
|
||||
// Liste des gestionnaires
|
||||
async findAll(): Promise<Users[]> {
|
||||
return this.gestionnaireRepository.find({ where: { role: RoleType.GESTIONNAIRE } });
|
||||
}
|
||||
|
||||
// Récupérer un gestionnaire par ID
|
||||
async findOne(id: string): Promise<Users> {
|
||||
const gestionnaire = await this.gestionnaireRepository.findOne({
|
||||
where: { id, role: RoleType.GESTIONNAIRE },
|
||||
});
|
||||
if (!gestionnaire) throw new NotFoundException('Gestionnaire introuvable');
|
||||
return gestionnaire;
|
||||
}
|
||||
|
||||
// Mise à jour d’un gestionnaire
|
||||
async update(id: string, dto: UpdateGestionnaireDto): Promise<Users> {
|
||||
const gestionnaire = await this.findOne(id);
|
||||
|
||||
if (dto.password) {
|
||||
const salt = await bcrypt.genSalt();
|
||||
gestionnaire.password = await bcrypt.hash(dto.password, salt);
|
||||
}
|
||||
|
||||
if (dto.date_consentement_photo !== undefined) {
|
||||
gestionnaire.date_consentement_photo = dto.date_consentement_photo
|
||||
? new Date(dto.date_consentement_photo)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
const { password, date_consentement_photo, ...rest } = dto;
|
||||
Object.entries(rest).forEach(([key, value]) => {
|
||||
if (value !== undefined) {
|
||||
(gestionnaire as any)[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
return this.gestionnaireRepository.save(gestionnaire);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UserController } from './user.controller';
|
||||
import { UserService } from './user.service';
|
||||
|
||||
describe('UserController', () => {
|
||||
let controller: UserController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [UserController],
|
||||
providers: [UserService],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<UserController>(UserController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post, UseGuards } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||
import { User } from 'src/common/decorators/user.decorator';
|
||||
import { RoleType, Users } from 'src/entities/users.entity';
|
||||
import { UserService } from './user.service';
|
||||
import { CreateUserDto } from './dto/create_user.dto';
|
||||
import { UpdateUserDto } from './dto/update_user.dto';
|
||||
|
||||
@ApiTags('Utilisateurs')
|
||||
@ApiBearerAuth('access-token')
|
||||
@UseGuards(AuthGuard)
|
||||
@Controller('users')
|
||||
export class UserController {
|
||||
constructor(private readonly userService: UserService) { }
|
||||
|
||||
// Création d'un utilisateur (réservée aux super admins)
|
||||
@Post()
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@ApiOperation({ summary: 'Créer un nouvel utilisateur (super admin seulement)' })
|
||||
createUser(
|
||||
@Body() dto: CreateUserDto,
|
||||
@User() currentUser: Users
|
||||
) {
|
||||
return this.userService.createUser(dto, currentUser);
|
||||
}
|
||||
|
||||
// Lister tous les utilisateurs (super_admin uniquement)
|
||||
@Get()
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@ApiOperation({ summary: 'Lister tous les utilisateurs' })
|
||||
findAll() {
|
||||
return this.userService.findAll();
|
||||
}
|
||||
|
||||
// Récupérer un utilisateur par son ID
|
||||
@Get(':id')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||
@ApiOperation({ summary: 'Trouver un utilisateur par son id' })
|
||||
@ApiParam({ name: 'id', description: "UUID de l'utilisateur" })
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.userService.findOne(id);
|
||||
}
|
||||
|
||||
// Modifier un utilisateur (réservé super_admin)
|
||||
@Patch(':id')
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@ApiOperation({ summary: 'Mettre à jour un utilisateur' })
|
||||
@ApiParam({ name: 'id', description: "UUID de l'utilisateur" })
|
||||
updateUser(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateUserDto,
|
||||
@User() currentUser: Users
|
||||
) {
|
||||
return this.userService.updateUser(id, dto, currentUser);
|
||||
}
|
||||
|
||||
@Patch(':id/valider')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Valider un compte utilisateur' })
|
||||
@ApiParam({ name: 'id', description: "UUID de l'utilisateur" })
|
||||
@ApiResponse({ status: 400, description: 'ID invalide' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||
@ApiResponse({ status: 200, description: 'Compte validé avec succès' })
|
||||
validate(
|
||||
@Param('id') id: string,
|
||||
@User() currentUser: Users,
|
||||
@Body('comment') comment?: string,
|
||||
) {
|
||||
return this.userService.validateUser(id, currentUser, comment);
|
||||
}
|
||||
|
||||
@Patch(':id/suspendre')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Suspendre un compte utilisateur' })
|
||||
@ApiParam({ name: 'id', description: "UUID de l'utilisateur" })
|
||||
suspend(
|
||||
@Param('id') id: string,
|
||||
@User() currentUser: Users,
|
||||
@Body('comment') comment?: string,
|
||||
) {
|
||||
return this.userService.suspendUser(id, currentUser, comment);
|
||||
}
|
||||
|
||||
// Supprimer un utilisateur (super_admin uniquement)
|
||||
@Delete(':id')
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@ApiOperation({ summary: 'Supprimer un utilisateur' })
|
||||
@ApiParam({ name: 'id', description: "UUID de l'utilisateur" })
|
||||
remove(@Param('id') id: string, @User() currentUser: Users) {
|
||||
return this.userService.remove(id, currentUser);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { forwardRef, Module } from '@nestjs/common';
|
||||
import { UserController } from './user.controller';
|
||||
import { UserService } from './user.service';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { Validation } from 'src/entities/validations.entity';
|
||||
import { ParentsModule } from '../parents/parents.module';
|
||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||
import { AssistantesMaternellesModule } from '../assistantes_maternelles/assistantes_maternelles.module';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature(
|
||||
[
|
||||
Users,
|
||||
Validation,
|
||||
Parents,
|
||||
AssistanteMaternelle,
|
||||
]), forwardRef(() => AuthModule),
|
||||
ParentsModule,
|
||||
AssistantesMaternellesModule,
|
||||
],
|
||||
controllers: [UserController],
|
||||
providers: [UserService],
|
||||
exports: [UserService],
|
||||
})
|
||||
export class UserModule { }
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UserService } from './user.service';
|
||||
|
||||
describe('UserService', () => {
|
||||
let service: UserService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [UserService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<UserService>(UserService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,233 @@
|
||||
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { RoleType, StatutUtilisateurType, Users } from "src/entities/users.entity";
|
||||
import { In, Repository } from "typeorm";
|
||||
import { CreateUserDto } from "./dto/create_user.dto";
|
||||
import { UpdateUserDto } from "./dto/update_user.dto";
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { StatutValidationType, Validation } from "src/entities/validations.entity";
|
||||
import { Parents } from "src/entities/parents.entity";
|
||||
import { AssistanteMaternelle } from "src/entities/assistantes_maternelles.entity";
|
||||
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
constructor(
|
||||
@InjectRepository(Users)
|
||||
private readonly usersRepository: Repository<Users>,
|
||||
|
||||
@InjectRepository(Validation)
|
||||
private readonly validationRepository: Repository<Validation>,
|
||||
|
||||
@InjectRepository(Parents)
|
||||
private readonly parentsRepository: Repository<Parents>,
|
||||
|
||||
@InjectRepository(AssistanteMaternelle)
|
||||
private readonly assistantesRepository: Repository<AssistanteMaternelle>
|
||||
) { }
|
||||
|
||||
async createUser(dto: CreateUserDto, currentUser?: Users): Promise<Users> {
|
||||
if (!dto.cguAccepted) {
|
||||
throw new BadRequestException(
|
||||
'Vous devez accepter les CGU et la Politique de confidentialité pour créer un compte.',
|
||||
);
|
||||
}
|
||||
|
||||
const exist = await this.usersRepository.findOneBy({ email: dto.email });
|
||||
if (exist) throw new BadRequestException('Email déjà utilisé');
|
||||
|
||||
const isSuperAdmin = currentUser?.role === RoleType.SUPER_ADMIN;
|
||||
const isAdmin = currentUser?.role === RoleType.ADMINISTRATEUR;
|
||||
|
||||
let role: RoleType;
|
||||
|
||||
if (dto.role === RoleType.GESTIONNAIRE) {
|
||||
if (!isAdmin && !isSuperAdmin) {
|
||||
throw new ForbiddenException('Seuls les administrateurs peuvent créer un gestionnaire');
|
||||
}
|
||||
role = RoleType.GESTIONNAIRE;
|
||||
} else if (dto.role === RoleType.ADMINISTRATEUR) {
|
||||
if (!isAdmin && !isSuperAdmin) {
|
||||
throw new ForbiddenException('Seuls les administrateurs peuvent créer un administrateur');
|
||||
}
|
||||
role = RoleType.ADMINISTRATEUR;
|
||||
} else if (dto.role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||
role = RoleType.ASSISTANTE_MATERNELLE;
|
||||
if (!dto.photo_url) {
|
||||
throw new BadRequestException(
|
||||
'La photo de profil est obligatoire pour les assistantes maternelles.',
|
||||
);
|
||||
}
|
||||
} else {
|
||||
role = RoleType.PARENT;
|
||||
}
|
||||
|
||||
const statut = isSuperAdmin
|
||||
? dto.statut ?? StatutUtilisateurType.EN_ATTENTE
|
||||
: StatutUtilisateurType.EN_ATTENTE;
|
||||
|
||||
if (!dto.nom?.trim()) throw new BadRequestException('Nom est obligatoire.');
|
||||
if (!dto.prenom?.trim()) throw new BadRequestException('Prénom est obligatoire.');
|
||||
if (!dto.adresse?.trim()) throw new BadRequestException('Adresse est obligatoire.');
|
||||
if (!dto.telephone?.trim()) throw new BadRequestException('Téléphone est obligatoire.');
|
||||
|
||||
let consentDate: Date | undefined;
|
||||
if (dto.consentement_photo && dto.date_consentement_photo) {
|
||||
const parsed = new Date(dto.date_consentement_photo);
|
||||
if (!isNaN(parsed.getTime())) {
|
||||
consentDate = parsed;
|
||||
}
|
||||
}
|
||||
|
||||
const salt = await bcrypt.genSalt();
|
||||
const hashedPassword = await bcrypt.hash(dto.password, salt);
|
||||
|
||||
const entity = this.usersRepository.create({
|
||||
email: dto.email,
|
||||
password: hashedPassword,
|
||||
prenom: dto.prenom,
|
||||
nom: dto.nom,
|
||||
role,
|
||||
statut,
|
||||
genre: dto.genre,
|
||||
telephone: dto.telephone,
|
||||
ville: dto.ville,
|
||||
code_postal: dto.code_postal,
|
||||
adresse: dto.adresse,
|
||||
photo_url: dto.photo_url,
|
||||
consentement_photo: dto.consentement_photo ?? false,
|
||||
date_consentement_photo: consentDate,
|
||||
changement_mdp_obligatoire:
|
||||
role === RoleType.ADMINISTRATEUR || role === RoleType.GESTIONNAIRE
|
||||
? true
|
||||
: dto.changement_mdp_obligatoire ?? false,
|
||||
});
|
||||
|
||||
const saved = await this.usersRepository.save(entity);
|
||||
return this.findOne(saved.id);
|
||||
}
|
||||
|
||||
async findAll(): Promise<Users[]> {
|
||||
return this.usersRepository.find();
|
||||
}
|
||||
|
||||
async findOneBy(where: Partial<Users>): Promise<Users | null> {
|
||||
return this.usersRepository.findOne({ where });
|
||||
}
|
||||
|
||||
async findOne(id: string): Promise<Users> {
|
||||
const user = await this.usersRepository.findOne({ where: { id } });
|
||||
if (!user) {
|
||||
throw new NotFoundException('Utilisateur introuvable');
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
async findByEmailOrNull(email: string): Promise<Users | null> {
|
||||
return this.usersRepository.findOne({ where: { email } });
|
||||
}
|
||||
|
||||
async updateUser(id: string, dto: UpdateUserDto, currentUser: Users): Promise<Users> {
|
||||
const user = await this.findOne(id);
|
||||
|
||||
// Interdire changement de rôle si pas super admin
|
||||
if (dto.role && currentUser.role !== RoleType.SUPER_ADMIN) {
|
||||
throw new ForbiddenException('Accès réservé aux super admins');
|
||||
}
|
||||
|
||||
// Empêcher de modifier le flag changement_mdp_obligatoire pour admin/gestionnaire
|
||||
if (
|
||||
(user.role === RoleType.ADMINISTRATEUR || user.role === RoleType.GESTIONNAIRE) &&
|
||||
dto.changement_mdp_obligatoire === false
|
||||
) {
|
||||
throw new ForbiddenException(
|
||||
'Impossible de désactiver l’obligation de changement de mot de passe pour ce rôle',
|
||||
);
|
||||
}
|
||||
|
||||
// Gestion du mot de passe
|
||||
if (dto.password) {
|
||||
const salt = await bcrypt.genSalt();
|
||||
user.password = await bcrypt.hash(dto.password, salt);
|
||||
delete (dto as any).password;
|
||||
// Une fois le mot de passe changé, on peut lever l’obligation
|
||||
user.changement_mdp_obligatoire = false;
|
||||
}
|
||||
|
||||
// Conversion de la date de consentement
|
||||
if (dto.date_consentement_photo !== undefined) {
|
||||
user.date_consentement_photo = dto.date_consentement_photo
|
||||
? new Date(dto.date_consentement_photo)
|
||||
: undefined;
|
||||
delete (dto as any).date_consentement_photo;
|
||||
}
|
||||
|
||||
Object.assign(user, dto);
|
||||
return this.usersRepository.save(user);
|
||||
}
|
||||
|
||||
// Valider un compte utilisateur
|
||||
async validateUser(user_id: string, currentUser: Users, comment?: string): Promise<Users> {
|
||||
if (![RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE].includes(currentUser.role)) {
|
||||
throw new ForbiddenException('Accès réservé aux super admins, administrateurs et gestionnaires');
|
||||
}
|
||||
|
||||
const user = await this.usersRepository.findOne({ where: { id: user_id } });
|
||||
if (!user) throw new NotFoundException('Utilisateur introuvable');
|
||||
|
||||
user.statut = StatutUtilisateurType.ACTIF;
|
||||
const savedUser = await this.usersRepository.save(user);
|
||||
if (user.role === RoleType.PARENT) {
|
||||
const existParent = await this.parentsRepository.findOneBy({ user_id: user.id });
|
||||
if (!existParent) {
|
||||
const parentEntity = this.parentsRepository.create({ user_id: user.id, user });
|
||||
await this.parentsRepository.save(parentEntity);
|
||||
}
|
||||
} else if (user.role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||
const existAssistante = await this.assistantesRepository.findOneBy({ user_id: user.id });
|
||||
if (!existAssistante) {
|
||||
const assistanteEntity = this.assistantesRepository.create({ user_id: user.id, user });
|
||||
await this.assistantesRepository.save(assistanteEntity);
|
||||
}
|
||||
}
|
||||
const validation = this.validationRepository.create({
|
||||
user: savedUser,
|
||||
type: 'validation_compte',
|
||||
status: StatutValidationType.VALIDE,
|
||||
validated_by: currentUser,
|
||||
comment,
|
||||
});
|
||||
await this.validationRepository.save(validation);
|
||||
return savedUser;
|
||||
}
|
||||
|
||||
|
||||
// Mettre un compte en statut suspendu
|
||||
async suspendUser(user_id: string, currentUser: Users, comment?: string): Promise<Users> {
|
||||
if (![RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE].includes(currentUser.role)) {
|
||||
throw new ForbiddenException('Accès réservé aux super admins, administrateurs et gestionnaires');
|
||||
}
|
||||
const user = await this.usersRepository.findOne({ where: { id: user_id } });
|
||||
if (!user) throw new NotFoundException('Utilisateur introuvable');
|
||||
user.statut = StatutUtilisateurType.SUSPENDU;
|
||||
const savedUser = await this.usersRepository.save(user);
|
||||
|
||||
const suspend = this.validationRepository.create({
|
||||
user: savedUser,
|
||||
type: 'suspension_compte',
|
||||
status: StatutValidationType.VALIDE,
|
||||
validated_by: currentUser,
|
||||
comment,
|
||||
})
|
||||
await this.validationRepository.save(suspend);
|
||||
return savedUser;
|
||||
}
|
||||
async remove(id: string, currentUser: Users): Promise<void> {
|
||||
if (currentUser.role !== RoleType.SUPER_ADMIN) {
|
||||
throw new ForbiddenException('Accès réservé aux super admins');
|
||||
}
|
||||
const result = await this.usersRepository.delete(id);
|
||||
if (result.affected === 0) {
|
||||
throw new NotFoundException('Utilisateur introuvable');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user