feat: Intégration du backend NestJS depuis YNOV
- Framework: NestJS avec TypeORM - Authentification: JWT (access + refresh tokens) - Gestion utilisateurs: CRUD complet avec validation - Routes: auth, users, parents, assistantes maternelles - Dockerfile pour conteneurisation
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' };
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
import { Router } from 'express';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
const router = Router();
|
||||
const prisma = new PrismaClient();
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
|
||||
|
||||
// Route de connexion
|
||||
router.post('/login', async (req, res) => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
|
||||
// Vérifier les identifiants
|
||||
const admin = await prisma.admin.findUnique({
|
||||
where: { email }
|
||||
});
|
||||
|
||||
if (!admin) {
|
||||
return res.status(401).json({ error: 'Identifiants invalides' });
|
||||
}
|
||||
|
||||
// Vérifier le mot de passe
|
||||
const validPassword = await bcrypt.compare(password, admin.password);
|
||||
if (!validPassword) {
|
||||
return res.status(401).json({ error: 'Identifiants invalides' });
|
||||
}
|
||||
|
||||
// Vérifier si le mot de passe doit être changé
|
||||
if (!admin.passwordChanged) {
|
||||
return res.status(403).json({
|
||||
error: 'Changement de mot de passe requis',
|
||||
requiresPasswordChange: true
|
||||
});
|
||||
}
|
||||
|
||||
// Générer le token JWT
|
||||
const token = jwt.sign(
|
||||
{
|
||||
id: admin.id,
|
||||
email: admin.email,
|
||||
role: 'admin'
|
||||
},
|
||||
JWT_SECRET,
|
||||
{ expiresIn: '24h' }
|
||||
);
|
||||
|
||||
res.json({ token });
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la connexion:', error);
|
||||
res.status(500).json({ error: 'Erreur serveur' });
|
||||
}
|
||||
});
|
||||
|
||||
// Route de changement de mot de passe
|
||||
router.post('/change-password', async (req, res) => {
|
||||
try {
|
||||
const { email, currentPassword, newPassword } = req.body;
|
||||
|
||||
// Vérifier l'administrateur
|
||||
const admin = await prisma.admin.findUnique({
|
||||
where: { email }
|
||||
});
|
||||
|
||||
if (!admin) {
|
||||
return res.status(404).json({ error: 'Administrateur non trouvé' });
|
||||
}
|
||||
|
||||
// Vérifier l'ancien mot de passe
|
||||
const validPassword = await bcrypt.compare(currentPassword, admin.password);
|
||||
if (!validPassword) {
|
||||
return res.status(401).json({ error: 'Mot de passe actuel incorrect' });
|
||||
}
|
||||
|
||||
// Hasher le nouveau mot de passe
|
||||
const hashedPassword = await bcrypt.hash(newPassword, 10);
|
||||
|
||||
// Mettre à jour le mot de passe
|
||||
await prisma.admin.update({
|
||||
where: { id: admin.id },
|
||||
data: {
|
||||
password: hashedPassword,
|
||||
passwordChanged: true
|
||||
}
|
||||
});
|
||||
|
||||
res.json({ message: 'Mot de passe changé avec succès' });
|
||||
} catch (error) {
|
||||
console.error('Erreur lors du changement de mot de passe:', error);
|
||||
res.status(500).json({ error: 'Erreur serveur' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -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,75 @@
|
||||
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 { 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' })
|
||||
async register(@Body() dto: RegisterDto) {
|
||||
return this.authService.register(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,24 @@
|
||||
import { forwardRef, Module } from '@nestjs/common';
|
||||
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';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
forwardRef(() => UserModule),
|
||||
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,137 @@
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { UserService } from '../user/user.service';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { RoleType, StatutUtilisateurType, Users } from 'src/entities/users.entity';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly usersService: UserService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly configService: ConfigService,
|
||||
) { }
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
try {
|
||||
const user = await this.usersService.findByEmailOrNull(dto.email);
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('Email invalide');
|
||||
}
|
||||
console.log("Tentative login:", dto.email, JSON.stringify(dto.password));
|
||||
console.log("Utilisateur trouvé:", user.email, user.password);
|
||||
|
||||
const isMatch = await bcrypt.compare(dto.password, user.password);
|
||||
console.log("Résultat bcrypt.compare:", isMatch);
|
||||
if (!isMatch) {
|
||||
throw new UnauthorizedException('Mot de passe invalide');
|
||||
}
|
||||
// if (user.password !== dto.password) {
|
||||
// throw new UnauthorizedException('Mot de passe invalide');
|
||||
// }
|
||||
|
||||
return this.generateTokens(user.id, user.email, user.role);
|
||||
} catch (error) {
|
||||
console.error('Erreur de connexion :', error);
|
||||
throw new UnauthorizedException('Identifiants invalides');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 lambda (parent ou assistante maternelle)
|
||||
*/
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async logout(userId: string) {
|
||||
// Pour le moment envoyer un message clair
|
||||
return { success: true, message: 'Deconnexion'}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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,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, required: false })
|
||||
@IsOptional()
|
||||
@IsEnum(GenreType)
|
||||
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,70 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Patch,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
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()
|
||||
create(@Body() dto: CreateEnfantsDto, @User() currentUser: Users) {
|
||||
return this.enfantsService.create(dto, currentUser);
|
||||
}
|
||||
|
||||
@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,113 @@
|
||||
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): Promise<Children> {
|
||||
const parent = await this.parentsRepository.findOne({
|
||||
where: { user_id: currentUser.id },
|
||||
});
|
||||
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à');
|
||||
|
||||
// Création
|
||||
const child = this.childrenRepository.create(dto);
|
||||
await this.childrenRepository.save(child);
|
||||
|
||||
// Lien parent-enfant
|
||||
const parentLink = this.parentsChildrenRepository.create({
|
||||
parentId: parent.user_id,
|
||||
enfantId: child.id,
|
||||
});
|
||||
await this.parentsChildrenRepository.save(parentLink);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { Router } from 'express';
|
||||
import { ThemeController } from '../controllers/theme.controller';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Routes pour les thèmes
|
||||
router.post('/', ThemeController.createTheme);
|
||||
router.get('/', ThemeController.getAllThemes);
|
||||
router.get('/active', ThemeController.getActiveTheme);
|
||||
router.put('/:themeId/activate', ThemeController.activateTheme);
|
||||
router.put('/:themeId', ThemeController.updateTheme);
|
||||
router.delete('/:themeId', ThemeController.deleteTheme);
|
||||
|
||||
export default router;
|
||||
@@ -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