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:
2026-01-27 14:56:49 +01:00
249 changed files with 33816 additions and 1449 deletions
+22
View File
@@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
+17
View File
@@ -0,0 +1,17 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getOverView() {
return this.appService.getOverView();
}
@Get('hello')
getHello(): string {
return this.appService.getHello();
}
}
+61 -7
View File
@@ -1,17 +1,71 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { PrismaModule } from './prisma/prisma.module';
import { AuthModule } from './auth/auth.module';
import { AdminModule } from './admin/admin.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import appConfig from './config/app.config';
import databaseConfig from './config/database.config';
import jwtConfig from './config/jwt.config';
import { configValidationSchema } from './config/validation.schema';
import { UserModule } from './routes/user/user.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { APP_FILTER } from '@nestjs/core';
import { ParentsModule } from './routes/parents/parents.module';
import { AuthModule } from './routes/auth/auth.module';
import { SentryGlobalFilter } from '@sentry/nestjs/setup';
import { AllExceptionsFilter } from './common/filters/all_exceptions.filters';
import { EnfantsModule } from './routes/enfants/enfants.module';
import { AppConfigModule } from './modules/config/config.module';
import { DocumentsLegauxModule } from './modules/documents-legaux';
@Module({
imports: [
ConfigModule.forRoot({
// Gestion dynamique des fichiers .env
envFilePath: [`.env.${process.env.NODE_ENV || 'development'}`, '.env'],
// envFilePath: '.env',
// Chargement de configurations typées
load: [appConfig, databaseConfig, jwtConfig],
isGlobal: true,
validationSchema: configValidationSchema,
}),
PrismaModule,
TypeOrmModule.forRootAsync({
imports: [ConfigModule,
],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
type: 'postgres',
host: config.get('database.host'),
port: config.get<number>('database.port'),
username: config.get('database.username'),
password: config.get('database.password'),
database: config.get('database.database'),
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: false,
migrations: [__dirname + '/migrations/**/*{.ts,.js}'],
logging: true,
}),
}),
UserModule,
ParentsModule,
EnfantsModule,
AuthModule,
AdminModule,
AppConfigModule,
DocumentsLegauxModule,
],
controllers: [AppController],
providers: [
AppService,
{
provide: APP_FILTER,
useClass: SentryGlobalFilter
},
{
provide: APP_FILTER,
useClass: AllExceptionsFilter,
}
],
})
export class AppModule {}
export class AppModule { }
+62
View File
@@ -0,0 +1,62 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello Test!!!';
}
getOverView() {
return {
name: "P'titsPas API",
version: "1.0",
description: "Documentation rapide des endpoints disponibles",
authentication: "JWT Bearer Token requis",
endpoints: [
{
method: "GET",
path: "/parents",
description: "Liste tous les parents",
roles: ["SUPER_ADMIN", "GESTIONNAIRE"]
},
{
method: "GET",
path: "/parents/:id",
description: "Récupère un parent par ID utilisateur",
roles: ["SUPER_ADMIN", "GESTIONNAIRE"],
params: ["id (UUID)"]
},
{
method: "POST",
path: "/parents",
description: "Crée un parent",
roles: ["SUPER_ADMIN", "GESTIONNAIRE"],
body: {
user_id: "UUID",
co_parent_id: "UUID (optionnel)"
}
},
{
method: "PATCH",
path: "/parents/:id",
description: "Met à jour un parent",
roles: ["SUPER_ADMIN", "GESTIONNAIRE"],
params: ["id (UUID)"],
body: {
user_id: "UUID (optionnel)",
co_parent_id: "UUID (optionnel)"
}
},
{
method: "DELETE",
path: "/parents/:id",
description: "Supprime un parent",
roles: ["SUPER_ADMIN"],
params: ["id (UUID)"]
}
],
docs: "/api/docs"
};
}
}
@@ -0,0 +1,4 @@
import { SetMetadata } from "@nestjs/common";
export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
@@ -0,0 +1,3 @@
import { SetMetadata } from "@nestjs/common";
export const Roles = (...roles: string[]) => SetMetadata("roles", roles);
@@ -0,0 +1,7 @@
import { createParamDecorator, ExecutionContext } from "@nestjs/common";
export const User = createParamDecorator((data: string | undefined, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
const user = request.user;
return data ? user?.[data] : user;
});
@@ -0,0 +1,11 @@
import { IsDateString, IsOptional } from "class-validator";
export class DateRangeQueryDto {
@IsOptional()
@IsDateString()
start?: string;
@IsOptional()
@IsDateString()
end?: string;
}
+6
View File
@@ -0,0 +1,6 @@
import { IsUUID } from "class-validator";
export class IdParamDto {
@IsUUID()
id: string;
}
@@ -0,0 +1,11 @@
import { IsOptional, IsPositive } from "class-validator";
export class PaginationQueryDto {
@IsOptional()
@IsPositive()
offset?: number;
@IsOptional()
@IsPositive()
limit?: number;
}
@@ -0,0 +1,8 @@
import { IsOptional, IsString, MinLength } from "class-validator";
export class SearchQueryDto {
@IsOptional()
@IsString()
@MinLength(2)
q?: string;
}
@@ -0,0 +1,27 @@
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from "@nestjs/common";
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const request = ctx.getRequest();
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const message =
exception instanceof HttpException
? exception.getResponse()
: { message: 'Internal server error' };
response.status(status).json({
success: false,
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
message,
});
}
}
+49
View File
@@ -0,0 +1,49 @@
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { JwtService } from "@nestjs/jwt";
import { Request } from 'express';
import { IS_PUBLIC_KEY } from "../decorators/public.decorator";
import { ConfigService } from "@nestjs/config";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private readonly jwtService: JwtService,
private readonly reflector: Reflector,
private readonly configService: ConfigService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) return true;
const request = context.switchToHttp().getRequest<Request>();
if (request.path.startsWith('/api-docs')) {
return true;
}
const authHeader = request.headers['authorization'] as string | undefined;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
throw new UnauthorizedException('Token manquant ou invalide');
}
const token = authHeader.split(' ')[1];
try {
const payload = await this.jwtService.verifyAsync(token, {
secret: this.configService.get<string>('jwt.accessSecret'),
});
request.user = {
...payload,
id: payload.sub,
};
return true;
} catch (error) {
throw new UnauthorizedException('Token invalide ou expiré');
}
}
}
+26
View File
@@ -0,0 +1,26 @@
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Observable } from "rxjs";
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
const requiredRoles = this.reflector.getAllAndOverride<string[]>('roles', [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles || requiredRoles.length === 0) {
return true;
}
const request = context.switchToHttp().getRequest();
const user = request.user;
if (!user || !user.role) {
return false;
}
return requiredRoles.includes(user.role);
}
}
@@ -0,0 +1,15 @@
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
import { map, Observable, timestamp } from "rxjs";
@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((data) => ({
success: true,
timestamp: new Date().toISOString(),
data
})),
);
}
}
+6
View File
@@ -0,0 +1,6 @@
import { registerAs } from '@nestjs/config';
export default registerAs('', () => ({
port: process.env.PORT,
env: process.env.NODE_ENV,
}));
+9
View File
@@ -0,0 +1,9 @@
import { registerAs } from '@nestjs/config';
export default registerAs('database', () => ({
host: process.env.POSTGRES_HOST,
port: process.env.POSTGRES_PORT,
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
}));
+8
View File
@@ -0,0 +1,8 @@
import { registerAs } from '@nestjs/config';
export default registerAs('jwt', () => ({
accessSecret: process.env.JWT_ACCESS_SECRET,
accessExpiresIn: process.env.JWT_ACCESS_EXPIRES,
refreshSecret: process.env.JWT_REFRESH_SECRET,
refreshExpiresIn: process.env.JWT_REFRESH_EXPIRES,
}));
+21
View File
@@ -0,0 +1,21 @@
import * as Joi from 'joi';
export const configValidationSchema = Joi.object({
NODE_ENV: Joi.string()
.valid('development', 'production', 'test')
.default('development'),
PORT: Joi.number().optional(),
// Base de données
POSTGRES_HOST: Joi.string().required(),
POSTGRES_PORT: Joi.number().required(),
POSTGRES_USER: Joi.string().required(),
POSTGRES_PASSWORD: Joi.string().required(),
POSTGRES_DB: Joi.string().required(),
// JWT
JWT_ACCESS_SECRET: Joi.string().required(),
JWT_ACCESS_EXPIRES: Joi.string().required(),
JWT_REFRESH_SECRET: Joi.string().required(),
JWT_REFRESH_EXPIRES: Joi.string().required(),
});
@@ -0,0 +1,40 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
CreateDateColumn,
} from 'typeorm';
import { Users } from './users.entity';
import { DocumentLegal } from './document-legal.entity';
@Entity('acceptations_documents')
export class AcceptationDocument {
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToOne(() => Users, { nullable: false, onDelete: 'CASCADE' })
@JoinColumn({ name: 'id_utilisateur' })
utilisateur: Users;
@ManyToOne(() => DocumentLegal, { nullable: true })
@JoinColumn({ name: 'id_document' })
document: DocumentLegal | null;
@Column({ type: 'varchar', length: 50, nullable: false })
type_document: 'cgu' | 'privacy';
@Column({ type: 'integer', nullable: false })
version_document: number;
@CreateDateColumn({ name: 'accepte_le', type: 'timestamptz' })
accepteLe: Date;
@Column({ type: 'inet', nullable: true })
ip_address: string | null;
@Column({ type: 'text', nullable: true })
user_agent: string | null;
}
@@ -0,0 +1,51 @@
import { Entity, PrimaryColumn, Column, OneToOne, JoinColumn } from 'typeorm';
import { Users } from './users.entity';
@Entity('assistantes_maternelles')
export class AssistanteMaternelle {
// PK = FK vers utilisateurs.id
@PrimaryColumn('uuid', { name: 'id_utilisateur' })
user_id: string;
@OneToOne(() => Users, (user) => user.assistanteMaternelle, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'id_utilisateur', referencedColumnName: 'id' })
user: Users;
@Column({ name: 'numero_agrement', length: 50, nullable: true })
approval_number?: string;
@Column({ name: 'nir_chiffre', length: 15, nullable: true })
nir?: string;
@Column({ name: 'nb_max_enfants', type: 'int', nullable: true })
max_children?: number;
@Column({ name: 'biographie', type: 'text', nullable: true })
biography?: string;
@Column({
name: 'disponible',
type: 'boolean',
default: true,
nullable: true,
})
available?: boolean;
@Column({ name: 'ville_residence', length: 100, nullable: true })
residence_city?: string;
@Column( { name: 'date_agrement', type: 'date', nullable: true })
agreement_date?: Date;
@Column( { name: 'annee_experience', type: 'smallint', nullable: true })
years_experience?: number;
@Column( { name: 'specialite', length: 100, nullable: true })
specialty?: string;
@Column( { name: 'place_disponible', type: 'integer', nullable: true })
places_available?: number;
}
@@ -0,0 +1,42 @@
import { Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
import { Contrat } from "./contrats.entity";
import { Users } from "./users.entity";
export enum StatutAvenantType {
PROPOSE = 'propose',
ACCEPTE = 'accepte',
REFUSE = 'refuse',
}
@Entity('avenants_contrats')
export class AvenantContrat {
// Define your columns and relationships here
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToOne(() => Contrat, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'id_contrat' })
contrat: Contrat;
@Column({ type: 'jsonb', nullable: true, name: 'modifications' })
modifications?: any;
@ManyToOne(() => Users, { nullable: true })
@JoinColumn({ name: 'initie_par', referencedColumnName: 'id' })
initiator?: Users;
@Column({
type: 'enum',
enum: StatutAvenantType,
enumName: 'statut_avenant_type',
default: StatutAvenantType.PROPOSE,
name: 'statut'
})
statut: StatutAvenantType;
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
createdAt: Date;
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
updatedAt: Date;
}
+74
View File
@@ -0,0 +1,74 @@
import {
Entity, PrimaryGeneratedColumn, Column,
OneToMany, ManyToMany, CreateDateColumn, JoinTable
} from 'typeorm';
import { Parents } from './parents.entity';
import { ParentsChildren } from './parents_children.entity';
import { Dossier } from './dossiers.entity';
export enum StatutEnfantType {
A_NAITRE = 'a_naitre',
ACTIF = 'actif',
SCOLARISE = 'scolarise',
}
export enum GenreType {
H = 'H',
F = 'F',
AUTRE = 'Autre',
}
@Entity('enfants')
export class Children {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({
type: 'enum',
enum: StatutEnfantType,
enumName: 'statut_enfant_type',
name: 'statut'
})
status: StatutEnfantType;
@Column({ name: 'prenom', length: 100, nullable: true })
first_name?: string;
@Column({ name: 'nom', length: 100, nullable: true })
last_name?: string;
@Column({
type: 'enum',
enum: GenreType,
enumName: 'genre_type',
nullable: true,
name: 'genre'
})
gender?: GenreType;
@Column({ type: 'date', nullable: true, name: 'date_naissance' })
birth_date?: Date;
@Column({ type: 'date', nullable: true, name: 'date_prevue_naissance' })
due_date?: Date;
@Column({ nullable: true, name: 'photo_url', type: 'text' })
photo_url?: string;
@Column({ default: false, name: 'consentement_photo', type: 'boolean' })
consent_photo: boolean;
@Column({ type: 'timestamptz', nullable: true, name: 'date_consentement_photo' })
consent_photo_at?: Date;
@Column({ default: false, name: 'est_multiple', type: 'boolean' })
is_multiple: boolean;
// Lien via table de jointure enfants_parents
@OneToMany(() => ParentsChildren, pc => pc.child)
parentLinks: ParentsChildren[];
// Relation avec Dossier
@OneToMany(() => Dossier, d => d.child)
dossiers: Dossier[];
}
@@ -0,0 +1,39 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
CreateDateColumn,
UpdateDateColumn,
} from 'typeorm';
import { Users } from './users.entity';
@Entity('configuration')
export class Configuration {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 100, unique: true, nullable: false })
cle: string;
@Column({ type: 'text', nullable: true })
valeur: string | null;
@Column({ type: 'varchar', length: 50, nullable: false })
type: 'string' | 'number' | 'boolean' | 'json' | 'encrypted';
@Column({ type: 'varchar', length: 50, nullable: true })
categorie: 'email' | 'app' | 'security' | null;
@Column({ type: 'text', nullable: true })
description: string | null;
@UpdateDateColumn({ name: 'modifie_le' })
modifieLe: Date;
@ManyToOne(() => Users, { nullable: true })
@JoinColumn({ name: 'modifie_par' })
modifiePar: Users | null;
}
+57
View File
@@ -0,0 +1,57 @@
import { Column, CreateDateColumn, Entity, JoinColumn, OneToOne, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
import { Dossier } from "./dossiers.entity";
export enum StatutContratType {
BROUILLON = 'brouillon',
EN_ATTENTE_SIGNATURE = 'en_attente_signature',
VALIDE = 'valide',
RESILIE = 'resilie',
}
@Entity('contrats')
export class Contrat {
// Define your columns and relationships here
@PrimaryGeneratedColumn('uuid')
id: string;
@OneToOne(() => Dossier, {onDelete: 'CASCADE'} )
@JoinColumn({ name: 'id_dossier'})
dossier: Dossier;
@Column({type: 'jsonb', nullable: true, name: 'planning'})
planning?: any;
@Column({type: 'numeric', precision: 6, scale: 2, nullable: true, name: 'tarif_horaire'})
hourly_rate?: string;
@Column({type: 'numeric', precision: 6, scale: 2, nullable: true, name: 'indemnites_repas'})
meal_indemnity?: string;
@Column( { name: 'date_debut', type: 'date', nullable: true })
start_date?: Date;
@Column({
type: 'enum',
enum: StatutContratType,
enumName: 'statut_contrat_type',
default: StatutContratType.BROUILLON,
name: 'statut'
})
statut: StatutContratType;
@Column({type: 'boolean', default: false, name: 'signe_parent'})
signed_by_parent: boolean;
@Column({type: 'boolean', default: false, name: 'signe_am'})
signed_by_am: boolean;
@Column({type: 'timestamptz', nullable: true, name: 'finalise_le'})
finalized_at?: Date;
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
created_at: Date;
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
updated_at: Date;
}
@@ -0,0 +1,44 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
CreateDateColumn,
} from 'typeorm';
import { Users } from './users.entity';
@Entity('documents_legaux')
export class DocumentLegal {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ type: 'varchar', length: 50, nullable: false })
type: 'cgu' | 'privacy';
@Column({ type: 'integer', nullable: false })
version: number;
@Column({ type: 'varchar', length: 255, nullable: false })
fichier_nom: string;
@Column({ type: 'varchar', length: 500, nullable: false })
fichier_path: string;
@Column({ type: 'varchar', length: 64, nullable: false })
fichier_hash: string;
@Column({ type: 'boolean', default: false })
actif: boolean;
@ManyToOne(() => Users, { nullable: true })
@JoinColumn({ name: 'televerse_par' })
televersePar: Users | null;
@CreateDateColumn({ name: 'televerse_le', type: 'timestamptz' })
televerseLe: Date;
@Column({ name: 'active_le', type: 'timestamptz', nullable: true })
activeLe: Date | null;
}
+61
View File
@@ -0,0 +1,61 @@
import {
Entity, PrimaryGeneratedColumn, Column,
ManyToOne, OneToMany, CreateDateColumn, UpdateDateColumn, JoinColumn
} from 'typeorm';
import { Parents } from './parents.entity';
import { Children } from './children.entity';
import { Message } from './messages.entity';
export enum StatutDossierType {
ENVOYE = 'envoye',
ACCEPTE = 'accepte',
REFUSE = 'refuse',
CLOTURE = 'cloture',
}
@Entity('dossiers')
export class Dossier {
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToOne(() => Parents, p => p.dossiers, { onDelete: 'CASCADE', nullable: false })
@JoinColumn({ name: 'id_parent', referencedColumnName: 'user_id' })
parent: Parents;
@ManyToOne(() => Children, c => c.dossiers, { onDelete: 'CASCADE', nullable: false })
@JoinColumn({ name: 'id_enfant', referencedColumnName: 'id' })
child: Children;
@Column({ type: 'text', nullable: true, name: 'presentation' })
presentation?: string;
@Column({ type: 'varchar', length: 50, nullable: true, name: 'type_contrat' })
type_contrat?: string;
@Column({ type: 'boolean', default: false, name: 'repas' })
meals: boolean;
@Column({ type: 'numeric', precision: 10, scale: 2, nullable: true, name: 'budget' })
budget?: number;
@Column({ type: 'jsonb', nullable: true, name: 'planning_souhaite' })
desired_schedule?: any;
@Column({
type: 'enum',
enum: StatutDossierType,
enumName: 'statut_dossier_type',
default: StatutDossierType.ENVOYE,
name: 'statut'
})
status: StatutDossierType;
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
created_at: Date;
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
updated_at: Date;
@OneToMany(() => Message, m => m.dossier)
messages: Message[];
}
+79
View File
@@ -0,0 +1,79 @@
import { Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
import { Children } from "./children.entity";
import { Users } from "./users.entity";
import { Parents } from "./parents.entity";
export enum TypeEvenementType {
ABSENCE_ENFANT = 'absence_enfant',
CONGE_AM = 'conge_am',
CONGE_PARENT = 'conge_parent',
ARRET_MALADIE_AM = 'arret_maladie_am',
EVENEMENT_RPE = 'evenement_rpe',
}
export enum StatutEvenementType {
PROPOSE = 'propose',
VALIDE = 'valide',
REFUSE = 'refuse',
}
@Entity('evenements')
export class Evenement {
// Define your columns and relationships here
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({
type: 'enum',
enum: TypeEvenementType,
enumName: 'type_evenement_type',
name: 'type'
})
type: TypeEvenementType;
@ManyToOne(() => Children, { onDelete: 'CASCADE', nullable: true })
@JoinColumn({ name: 'id_enfant', referencedColumnName: 'id' })
child?: Children;
@ManyToOne(() => Users, { nullable: true })
@JoinColumn({ name: 'id_am', referencedColumnName: 'id' })
assistanteMaternelle?: Users;
@ManyToOne(() => Parents, { nullable: true })
@JoinColumn({ name: 'id_parent', referencedColumnName: 'user_id' })
parent?: Parents;
@ManyToOne(() => Users, { nullable: true })
@JoinColumn({ name: 'cree_par', referencedColumnName: 'id' })
created_by?: Users;
@Column({ type: 'timestamptz', nullable: true, name: 'date_debut' })
start_date?: Date;
@Column({ type: 'timestamptz', nullable: true, name: 'date_fin' })
end_date?: Date;
@Column({ type: 'text', nullable: true, name: 'commentaires' })
comments?: string;
@Column({
type: 'enum',
enum: StatutEvenementType,
enumName: 'statut_evenement_type',
name: 'statut',
default: StatutEvenementType.PROPOSE
})
status: StatutEvenementType;
@Column({type: 'timestamptz', nullable: true, name: 'delai_grace'})
grace_deadline?: Date;
@Column({type: 'boolean', default: false, name: 'urgent'})
urgent: boolean;
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
created_at: Date;
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
updated_at: Date;
}
+29
View File
@@ -0,0 +1,29 @@
import {
Entity, PrimaryGeneratedColumn, Column,
ManyToOne, JoinColumn, CreateDateColumn
} from 'typeorm';
import { Dossier } from './dossiers.entity';
import { Users } from './users.entity';
@Entity('messages')
export class Message {
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToOne(() => Dossier, d => d.messages, { onDelete: 'CASCADE', nullable: false })
@JoinColumn({ name: 'id_dossier' })
dossier: Dossier;
@ManyToOne(() => Users, u => u.messages, { onDelete: 'CASCADE', nullable: false })
@JoinColumn({ name: 'id_expediteur' })
sender: Users;
@Column({ type: 'text', name: 'contenu' })
content: string;
@Column({ type: 'boolean', name: 're_redige_par_ia', default: false })
reRedigeParIA: boolean;
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
created_at: Date;
}
@@ -0,0 +1,23 @@
import { Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
import { Users } from "./users.entity";
@Entity('notifications')
export class Notification {
// Define your columns and relationships here
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToOne(() => Users, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'id_utilisateur', referencedColumnName: 'id' })
user: Users;
@Column({ type: 'text', name: 'contenu' })
content: string;
@Column({type: 'boolean', name: 'lu', default: false})
read: boolean;
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
created_at: Date;
}
+31
View File
@@ -0,0 +1,31 @@
import {
Entity, PrimaryColumn, OneToOne, JoinColumn,
ManyToOne, OneToMany
} from 'typeorm';
import { Users } from './users.entity';
import { ParentsChildren } from './parents_children.entity';
import { Dossier } from './dossiers.entity';
@Entity('parents', { schema: 'public' })
export class Parents {
// PK = FK vers utilisateurs.id
@PrimaryColumn('uuid', { name: 'id_utilisateur' })
user_id: string;
@OneToOne(() => Users, user => user.parent, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'id_utilisateur', referencedColumnName: 'id' })
user: Users;
// Co-parent (nullable) → FK vers utilisateurs.id
@ManyToOne(() => Users, { nullable: true })
@JoinColumn({ name: 'id_co_parent', referencedColumnName: 'id' })
co_parent?: Users;
// Lien vers enfants via la table enfants_parents
@OneToMany(() => ParentsChildren, pc => pc.parent)
parentChildren: ParentsChildren[];
// Lien vers les dossiers de ce parent
@OneToMany(() => Dossier, d => d.parent)
dossiers: Dossier[];
}
@@ -0,0 +1,22 @@
import {
Entity, ManyToOne, JoinColumn, PrimaryColumn
} from 'typeorm';
import { Parents } from './parents.entity';
import { Children } from './children.entity';
@Entity('enfants_parents', { schema: 'public' })
export class ParentsChildren {
@PrimaryColumn('uuid', { name: 'id_parent' })
parentId: string;
@PrimaryColumn('uuid', { name: 'id_enfant' })
enfantId: string;
@ManyToOne(() => Parents, p => p.parentChildren, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'id_parent', referencedColumnName: 'user_id' })
parent: Parents;
@ManyToOne(() => Children, c => c.parentLinks, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'id_enfant', referencedColumnName: 'id' })
child: Children;
}
@@ -0,0 +1,19 @@
import { Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
import { Users } from "./users.entity";
@Entity('signalements_bugs')
export class SignalementBug {
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToOne(() => Users, {nullable: true})
@JoinColumn({ name: 'id_utilisateur', referencedColumnName: 'id' })
user?: Users;
@Column({ type: 'text', name: 'description'})
description: string;
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
created_at: Date;
}
+21
View File
@@ -0,0 +1,21 @@
import { Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
import { Users } from "./users.entity";
@Entity('uploads')
export class Upload {
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToOne(() => Users, { onDelete: 'SET NULL', nullable: true })
@JoinColumn({ name: 'id_utilisateur', referencedColumnName: 'id' })
user?: Users;
@Column({ type: 'text', name: 'fichier_url' })
file_url: string;
@Column({type: 'varchar', length: 50, nullable: true, name: 'type'})
type?: string;
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
created_at: Date;
}
+150
View File
@@ -0,0 +1,150 @@
import {
Entity, PrimaryGeneratedColumn, Column,
CreateDateColumn, UpdateDateColumn,
OneToOne, OneToMany
} from 'typeorm';
import { AssistanteMaternelle } from './assistantes_maternelles.entity';
import { Parents } from './parents.entity';
import { Message } from './messages.entity';
// Enums alignés avec la BDD PostgreSQL
export enum RoleType {
PARENT = 'parent',
GESTIONNAIRE = 'gestionnaire',
SUPER_ADMIN = 'super_admin',
ASSISTANTE_MATERNELLE = 'assistante_maternelle',
ADMINISTRATEUR = 'administrateur',
}
//Enum pour definir le genre
export enum GenreType {
H = 'H',
F = 'F',
AUTRE = 'Autre',
}
//Enum pour definir le statut utilisateur
export enum StatutUtilisateurType {
EN_ATTENTE = 'en_attente',
ACTIF = 'actif',
SUSPENDU = 'suspendu',
}
export enum SituationFamilialeType {
CELIBATAIRE = 'celibataire',
MARIE = 'marie',
DIVORCE = 'divorce',
VEUF = 'veuf',
PACSE = 'pacse',
SEPARE = 'separe',
PARENT_ISOLE = 'parent_isole',
CONCUBINAGE = 'concubinage',
}
//Declaration de l'entite utilisateur
@Entity('utilisateurs', { schema: 'public' })
export class Users {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ unique: true, name: 'email' })
email: string;
@Column({ name: 'password', nullable: true })
password?: string;
@Column({ name: 'prenom', nullable: true })
prenom?: string;
@Column({ name: 'nom', nullable: true })
nom?: string;
@Column({
type: 'enum',
enum: GenreType,
enumName: 'genre_type', // correspond à l'enum de la db psql
nullable: true,
name: 'genre'
})
genre?: GenreType;
@Column({
type: 'enum',
enum: RoleType,
enumName: 'role_type', // correspond à l'enum de la db psql
name: 'role'
})
role: RoleType;
@Column({
type: 'enum',
enum: StatutUtilisateurType,
enumName: 'statut_utilisateur_type', // correspond à l'enum de la db psql
default: StatutUtilisateurType.EN_ATTENTE,
name: 'statut'
})
statut: StatutUtilisateurType;
@Column({ type: 'enum',
enum: SituationFamilialeType,
enumName: 'situation_familiale_type',
nullable: true,
name: 'situation_familiale'
})
situation_familiale?: SituationFamilialeType;
@Column({ nullable: true, name: 'telephone' })
telephone?: string;
@Column({ nullable: true, name: 'adresse' })
adresse?: string;
@Column({ nullable: true, name: 'photo_url' })
photo_url?: string;
@Column({ default: false, name: 'consentement_photo' })
consentement_photo: boolean;
@Column({ type: 'timestamptz', nullable: true, name: 'date_consentement_photo' })
date_consentement_photo?: Date;
@Column({ default: false, name: 'changement_mdp_obligatoire' })
changement_mdp_obligatoire: boolean;
@Column({ nullable: true, name: 'token_creation_mdp', length: 255 })
token_creation_mdp?: string;
@Column({ type: 'timestamptz', nullable: true, name: 'token_creation_mdp_expire_le' })
token_creation_mdp_expire_le?: Date;
@Column({ nullable: true, name: 'ville' })
ville?: string;
@Column({ nullable: true, name: 'code_postal' })
code_postal?: string;
@Column({ nullable: true, name: 'profession' })
profession?: string;
@Column({ name: 'date_naissance', type: 'date', nullable: true })
date_naissance?: Date;
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
cree_le: Date;
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
modifie_le: Date;
// Relations
@OneToOne(() => AssistanteMaternelle, a => a.user)
assistanteMaternelle?: AssistanteMaternelle;
@OneToOne(() => Parents, p => p.user)
parent?: Parents;
@OneToMany(() => Message, m => m.sender)
messages?: Message[];
@OneToMany(() => Parents, parent => parent.co_parent)
co_parent_in?: Parents[];
}
@@ -0,0 +1,44 @@
import { Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
import { Users } from "./users.entity";
export enum StatutValidationType {
EN_ATTENTE = 'en_attente',
VALIDE = 'valide',
REFUSE = 'refuse',
}
@Entity('validations')
export class Validation {
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToOne(() => Users, { nullable: true })
@JoinColumn({ name: 'id_utilisateur', referencedColumnName: 'id' })
user?: Users;
@Column({ type: 'varchar', length: 50, name: 'type', nullable: true })
type: string;
@Column({
type: 'enum',
enum: StatutValidationType,
enumName: 'statut_validation_type',
name: 'statut',
default: StatutValidationType.EN_ATTENTE
})
status: StatutValidationType;
@ManyToOne(() => Users, { nullable: true })
@JoinColumn({ name: 'valide_par', referencedColumnName: 'id' })
validated_by?: Users;
@Column( { name: 'commentaire', type: 'text', nullable: true })
comment?: string;
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
created_at: Date;
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
updated_at: Date;
}
-28
View File
@@ -1,28 +0,0 @@
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import themeRoutes from './routes/theme.routes';
const app = express();
const port = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(helmet());
app.use(morgan('dev'));
app.use(express.json());
// Routes
app.use('/api/themes', themeRoutes);
// Gestion des erreurs
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
console.error(err.stack);
res.status(500).json({ error: 'Une erreur est survenue' });
});
// Démarrage du serveur
app.listen(port, () => {
console.log(`Serveur démarré sur le port ${port}`);
});
+59
View File
@@ -0,0 +1,59 @@
import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { SwaggerModule } from '@nestjs/swagger/dist/swagger-module';
import { DocumentBuilder } from '@nestjs/swagger';
import { AuthGuard } from './common/guards/auth.guard';
import { JwtService } from '@nestjs/jwt';
import { RolesGuard } from './common/guards/roles.guard';
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule,
{ logger: ['error', 'warn', 'log', 'debug', 'verbose'] });
app.enableCors();
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
})
);
const configService = app.get(ConfigService);
const port = configService.get<number>('app.port', 3000);
app.setGlobalPrefix('api/v1');
const config = new DocumentBuilder()
.setTitle("P'titsPas API")
.setDescription("API pour l'application P'titsPas")
.setVersion('1.0.0')
.addBearerAuth(
{
type: 'http',
scheme: 'Bearer',
bearerFormat: 'JWT',
name: 'Authorization',
description: 'Enter JWT token',
in: 'header',
},
'access-token',
)
//.addServer('/api/v1')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api/v1/swagger', app, document);
await app.listen(port);
console.log(`✅ P'titsPas API is running on: ${await app.getUrl()}`);
}
bootstrap().catch((err) => {
console.error('❌ Error starting the application:', err);
process.exit(1);
});
@@ -0,0 +1,232 @@
import {
Controller,
Get,
Patch,
Post,
Body,
Param,
UseGuards,
Request,
HttpStatus,
HttpException,
} from '@nestjs/common';
import { AppConfigService } from './config.service';
import { UpdateConfigDto } from './dto/update-config.dto';
import { TestSmtpDto } from './dto/test-smtp.dto';
@Controller('configuration')
export class ConfigController {
constructor(private readonly configService: AppConfigService) {}
/**
* Vérifier si la configuration initiale est terminée
* GET /api/v1/configuration/setup/status
*/
@Get('setup/status')
async getSetupStatus() {
try {
const isCompleted = this.configService.isSetupCompleted();
return {
success: true,
data: {
setupCompleted: isCompleted,
},
};
} catch (error) {
throw new HttpException(
{
success: false,
message: 'Erreur lors de la vérification du statut de configuration',
error: error.message,
},
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
/**
* Marquer la configuration initiale comme terminée
* POST /api/v1/configuration/setup/complete
*/
@Post('setup/complete')
// @UseGuards(JwtAuthGuard, RolesGuard)
// @Roles('super_admin')
async completeSetup(@Request() req: any) {
try {
// TODO: Récupérer l'ID utilisateur depuis le JWT
const userId = req.user?.id || 'system';
await this.configService.markSetupCompleted(userId);
return {
success: true,
message: 'Configuration initiale terminée avec succès',
};
} catch (error) {
throw new HttpException(
{
success: false,
message: 'Erreur lors de la finalisation de la configuration',
error: error.message,
},
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
/**
* Test de la connexion SMTP
* POST /api/v1/configuration/test-smtp
*/
@Post('test-smtp')
// @UseGuards(JwtAuthGuard, RolesGuard)
// @Roles('super_admin')
async testSmtp(@Body() testSmtpDto: TestSmtpDto) {
try {
const result = await this.configService.testSmtpConnection(testSmtpDto.testEmail);
if (result.success) {
return {
success: true,
message: 'Connexion SMTP réussie. Email de test envoyé.',
};
} else {
return {
success: false,
message: 'Échec du test SMTP',
error: result.error,
};
}
} catch (error) {
throw new HttpException(
{
success: false,
message: 'Erreur lors du test SMTP',
error: error.message,
},
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
/**
* Mise à jour multiple des configurations
* PATCH /api/v1/configuration/bulk
*/
@Patch('bulk')
// @UseGuards(JwtAuthGuard, RolesGuard)
// @Roles('super_admin')
async updateBulk(@Body() updateConfigDto: UpdateConfigDto, @Request() req: any) {
try {
// TODO: Récupérer l'ID utilisateur depuis le JWT
const userId = req.user?.id || null;
let updated = 0;
const errors: string[] = [];
// Parcourir toutes les clés du DTO
for (const [key, value] of Object.entries(updateConfigDto)) {
if (value !== undefined) {
try {
await this.configService.set(key, value, userId);
updated++;
} catch (error) {
errors.push(`${key}: ${error.message}`);
}
}
}
// Recharger le cache après les modifications
await this.configService.loadCache();
if (errors.length > 0) {
return {
success: false,
message: 'Certaines configurations n\'ont pas pu être mises à jour',
updated,
errors,
};
}
return {
success: true,
message: 'Configuration mise à jour avec succès',
updated,
};
} catch (error) {
throw new HttpException(
{
success: false,
message: 'Erreur lors de la mise à jour des configurations',
error: error.message,
},
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
/**
* Récupérer toutes les configurations (pour l'admin)
* GET /api/v1/configuration
*/
@Get()
// @UseGuards(JwtAuthGuard, RolesGuard)
// @Roles('super_admin')
async getAll() {
try {
const configs = await this.configService.getAll();
return {
success: true,
data: configs,
};
} catch (error) {
throw new HttpException(
{
success: false,
message: 'Erreur lors de la récupération des configurations',
error: error.message,
},
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
/**
* Récupérer les configurations par catégorie
* GET /api/v1/configuration/:category
*/
@Get(':category')
// @UseGuards(JwtAuthGuard, RolesGuard)
// @Roles('super_admin')
async getByCategory(@Param('category') category: string) {
try {
if (!['email', 'app', 'security'].includes(category)) {
throw new HttpException(
{
success: false,
message: 'Catégorie invalide. Valeurs acceptées: email, app, security',
},
HttpStatus.BAD_REQUEST,
);
}
const configs = await this.configService.getByCategory(category);
return {
success: true,
data: configs,
};
} catch (error) {
if (error instanceof HttpException) {
throw error;
}
throw new HttpException(
{
success: false,
message: 'Erreur lors de la récupération des configurations',
error: error.message,
},
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
}
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Configuration } from '../../entities/configuration.entity';
import { AppConfigService } from './config.service';
import { ConfigController } from './config.controller';
@Module({
imports: [TypeOrmModule.forFeature([Configuration])],
controllers: [ConfigController],
providers: [AppConfigService],
exports: [AppConfigService],
})
export class AppConfigModule {}
@@ -0,0 +1,338 @@
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Configuration } from '../../entities/configuration.entity';
import * as crypto from 'crypto';
@Injectable()
export class AppConfigService implements OnModuleInit {
private readonly logger = new Logger(AppConfigService.name);
private cache: Map<string, any> = new Map();
private readonly ENCRYPTION_KEY: string;
private readonly ENCRYPTION_ALGORITHM = 'aes-256-cbc';
private readonly IV_LENGTH = 16;
constructor(
@InjectRepository(Configuration)
private configRepo: Repository<Configuration>,
) {
// Clé de chiffrement depuis les variables d'environnement
// En production, cette clé doit être générée de manière sécurisée
this.ENCRYPTION_KEY =
process.env.CONFIG_ENCRYPTION_KEY ||
crypto.randomBytes(32).toString('hex');
if (!process.env.CONFIG_ENCRYPTION_KEY) {
this.logger.warn(
'⚠️ CONFIG_ENCRYPTION_KEY non définie. Utilisation d\'une clé temporaire (NON RECOMMANDÉ EN PRODUCTION)',
);
}
}
/**
* Chargement du cache au démarrage de l'application
*/
async onModuleInit() {
await this.loadCache();
}
/**
* Chargement de toutes les configurations en cache
*/
async loadCache(): Promise<void> {
try {
const configs = await this.configRepo.find();
this.logger.log(`📦 Chargement de ${configs.length} configurations en cache`);
for (const config of configs) {
let value = config.valeur;
// Déchiffrement si nécessaire
if (config.type === 'encrypted' && value) {
try {
value = this.decrypt(value);
} catch (error) {
this.logger.error(
`❌ Erreur de déchiffrement pour la clé '${config.cle}'`,
error,
);
value = null;
}
}
// Conversion de type
const convertedValue = this.convertType(value, config.type);
this.cache.set(config.cle, convertedValue);
}
this.logger.log('✅ Cache de configuration chargé avec succès');
} catch (error) {
this.logger.error('❌ Erreur lors du chargement du cache', error);
throw error;
}
}
/**
* Récupération d'une valeur de configuration
* @param key Clé de configuration
* @param defaultValue Valeur par défaut si la clé n'existe pas
* @returns Valeur de configuration
*/
get<T = any>(key: string, defaultValue?: T): T {
if (this.cache.has(key)) {
return this.cache.get(key) as T;
}
if (defaultValue !== undefined) {
return defaultValue;
}
this.logger.warn(`⚠️ Configuration '${key}' non trouvée et aucune valeur par défaut fournie`);
return undefined as T;
}
/**
* Mise à jour d'une valeur de configuration
* @param key Clé de configuration
* @param value Nouvelle valeur
* @param userId ID de l'utilisateur qui modifie
*/
async set(key: string, value: any, userId?: string): Promise<void> {
const config = await this.configRepo.findOne({ where: { cle: key } });
if (!config) {
throw new Error(`Configuration '${key}' non trouvée`);
}
let valueToStore = value !== null && value !== undefined ? String(value) : null;
// Chiffrement si nécessaire
if (config.type === 'encrypted' && valueToStore) {
valueToStore = this.encrypt(valueToStore);
}
config.valeur = valueToStore;
config.modifieLe = new Date();
if (userId) {
config.modifiePar = { id: userId } as any;
}
await this.configRepo.save(config);
// Mise à jour du cache (avec la valeur déchiffrée)
this.cache.set(key, value);
this.logger.log(`✅ Configuration '${key}' mise à jour`);
}
/**
* Récupération de toutes les configurations par catégorie
* @param category Catégorie de configuration
* @returns Objet clé/valeur des configurations
*/
async getByCategory(category: string): Promise<Record<string, any>> {
const configs = await this.configRepo.find({
where: { categorie: category as any },
});
const result: Record<string, any> = {};
for (const config of configs) {
let value = config.valeur;
// Masquer les mots de passe
if (config.type === 'encrypted') {
value = value ? '***********' : null;
} else {
value = this.convertType(value, config.type);
}
result[config.cle] = {
value,
type: config.type,
description: config.description,
};
}
return result;
}
/**
* Récupération de toutes les configurations (pour l'admin)
* @returns Liste de toutes les configurations
*/
async getAll(): Promise<Configuration[]> {
const configs = await this.configRepo.find({
order: { categorie: 'ASC', cle: 'ASC' },
});
// Masquer les valeurs chiffrées
return configs.map((config) => ({
...config,
valeur: config.type === 'encrypted' && config.valeur ? '***********' : config.valeur,
}));
}
/**
* Test de la configuration SMTP
* @param testEmail Email de destination pour le test
* @returns Objet avec success et error éventuel
*/
async testSmtpConnection(testEmail?: string): Promise<{ success: boolean; error?: string }> {
try {
this.logger.log('🧪 Test de connexion SMTP...');
// Récupération de la configuration SMTP
const smtpHost = this.get<string>('smtp_host');
const smtpPort = this.get<number>('smtp_port');
const smtpSecure = this.get<boolean>('smtp_secure');
const smtpAuthRequired = this.get<boolean>('smtp_auth_required');
const smtpUser = this.get<string>('smtp_user');
const smtpPassword = this.get<string>('smtp_password');
const emailFromName = this.get<string>('email_from_name');
const emailFromAddress = this.get<string>('email_from_address');
// Import dynamique de nodemailer
const nodemailer = await import('nodemailer');
// Configuration du transporteur
const transportConfig: any = {
host: smtpHost,
port: smtpPort,
secure: smtpSecure,
};
if (smtpAuthRequired && smtpUser && smtpPassword) {
transportConfig.auth = {
user: smtpUser,
pass: smtpPassword,
};
}
const transporter = nodemailer.createTransport(transportConfig);
// Vérification de la connexion
await transporter.verify();
this.logger.log('✅ Connexion SMTP vérifiée');
// Si un email de test est fourni, on envoie un email
if (testEmail) {
await transporter.sendMail({
from: `"${emailFromName}" <${emailFromAddress}>`,
to: testEmail,
subject: '🧪 Test de configuration SMTP - P\'titsPas',
text: 'Ceci est un email de test pour vérifier la configuration SMTP de votre application P\'titsPas.',
html: `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
<h2 style="color: #4CAF50;">✅ Test de configuration SMTP réussi !</h2>
<p>Ceci est un email de test pour vérifier la configuration SMTP de votre application <strong>P'titsPas</strong>.</p>
<p>Si vous recevez cet email, cela signifie que votre configuration SMTP fonctionne correctement.</p>
<hr style="border: 1px solid #eee; margin: 20px 0;">
<p style="color: #666; font-size: 12px;">
Cet email a été envoyé automatiquement depuis votre application P'titsPas.<br>
Configuration testée le ${new Date().toLocaleString('fr-FR')}
</p>
</div>
`,
});
this.logger.log(`📧 Email de test envoyé à ${testEmail}`);
}
return { success: true };
} catch (error) {
this.logger.error('❌ Échec du test SMTP', error);
return {
success: false,
error: error.message || 'Erreur inconnue lors du test SMTP',
};
}
}
/**
* Vérification si la configuration initiale est terminée
* @returns true si la configuration est terminée
*/
isSetupCompleted(): boolean {
return this.get<boolean>('setup_completed', false);
}
/**
* Marquer la configuration initiale comme terminée
* @param userId ID de l'utilisateur qui termine la configuration
*/
async markSetupCompleted(userId: string): Promise<void> {
await this.set('setup_completed', 'true', userId);
this.logger.log('✅ Configuration initiale marquée comme terminée');
}
/**
* Conversion de type selon le type de configuration
* @param value Valeur à convertir
* @param type Type cible
* @returns Valeur convertie
*/
private convertType(value: string | null, type: string): any {
if (value === null || value === undefined) {
return null;
}
switch (type) {
case 'number':
return parseFloat(value);
case 'boolean':
return value === 'true' || value === '1';
case 'json':
try {
return JSON.parse(value);
} catch {
return null;
}
case 'string':
case 'encrypted':
default:
return value;
}
}
/**
* Chiffrement AES-256-CBC
* @param text Texte à chiffrer
* @returns Texte chiffré (format: iv:encrypted)
*/
private encrypt(text: string): string {
const iv = crypto.randomBytes(this.IV_LENGTH);
const key = Buffer.from(this.ENCRYPTION_KEY, 'hex');
const cipher = crypto.createCipheriv(this.ENCRYPTION_ALGORITHM, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
// Format: iv:encrypted
return `${iv.toString('hex')}:${encrypted}`;
}
/**
* Déchiffrement AES-256-CBC
* @param encryptedText Texte chiffré (format: iv:encrypted)
* @returns Texte déchiffré
*/
private decrypt(encryptedText: string): string {
const parts = encryptedText.split(':');
if (parts.length !== 2) {
throw new Error('Format de chiffrement invalide');
}
const iv = Buffer.from(parts[0], 'hex');
const encrypted = parts[1];
const key = Buffer.from(this.ENCRYPTION_KEY, 'hex');
const decipher = crypto.createDecipheriv(this.ENCRYPTION_ALGORITHM, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
}
@@ -0,0 +1,7 @@
import { IsEmail } from 'class-validator';
export class TestSmtpDto {
@IsEmail()
testEmail: string;
}
@@ -0,0 +1,67 @@
import { IsString, IsOptional, IsNumber, IsBoolean, IsEmail, IsUrl } from 'class-validator';
export class UpdateConfigDto {
// Configuration Email (SMTP)
@IsOptional()
@IsString()
smtp_host?: string;
@IsOptional()
@IsNumber()
smtp_port?: number;
@IsOptional()
@IsBoolean()
smtp_secure?: boolean;
@IsOptional()
@IsBoolean()
smtp_auth_required?: boolean;
@IsOptional()
@IsString()
smtp_user?: string;
@IsOptional()
@IsString()
smtp_password?: string;
@IsOptional()
@IsString()
email_from_name?: string;
@IsOptional()
@IsEmail()
email_from_address?: string;
// Configuration Application
@IsOptional()
@IsString()
app_name?: string;
@IsOptional()
@IsUrl()
app_url?: string;
@IsOptional()
@IsString()
app_logo_url?: string;
// Configuration Sécurité
@IsOptional()
@IsNumber()
password_reset_token_expiry_days?: number;
@IsOptional()
@IsNumber()
jwt_expiry_hours?: number;
@IsOptional()
@IsNumber()
max_upload_size_mb?: number;
@IsOptional()
@IsNumber()
bcrypt_rounds?: number;
}
+3
View File
@@ -0,0 +1,3 @@
export * from './config.module';
export * from './config.service';
@@ -0,0 +1,202 @@
import {
Controller,
Get,
Post,
Patch,
Param,
Body,
UseInterceptors,
UploadedFile,
Res,
HttpStatus,
BadRequestException,
ParseUUIDPipe,
StreamableFile,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import type { Response } from 'express';
import { DocumentsLegauxService } from './documents-legaux.service';
import { UploadDocumentDto } from './dto/upload-document.dto';
import { DocumentsActifsResponseDto } from './dto/documents-actifs.dto';
import { DocumentVersionDto } from './dto/document-version.dto';
@Controller('documents-legaux')
export class DocumentsLegauxController {
constructor(private readonly documentsService: DocumentsLegauxService) {}
/**
* GET /api/v1/documents-legaux/actifs
* Récupérer les documents actifs (CGU + Privacy)
* PUBLIC
*/
@Get('actifs')
async getDocumentsActifs(): Promise<DocumentsActifsResponseDto> {
const { cgu, privacy } = await this.documentsService.getDocumentsActifs();
return {
cgu: {
id: cgu.id,
type: cgu.type,
version: cgu.version,
url: `/api/v1/documents-legaux/${cgu.id}/download`,
activeLe: cgu.activeLe,
},
privacy: {
id: privacy.id,
type: privacy.type,
version: privacy.version,
url: `/api/v1/documents-legaux/${privacy.id}/download`,
activeLe: privacy.activeLe,
},
};
}
/**
* GET /api/v1/documents-legaux/:type/versions
* Lister toutes les versions d'un type de document
* ADMIN ONLY
*/
@Get(':type/versions')
// @UseGuards(JwtAuthGuard, RolesGuard)
// @Roles('super_admin', 'administrateur')
async listerVersions(@Param('type') type: string): Promise<DocumentVersionDto[]> {
if (type !== 'cgu' && type !== 'privacy') {
throw new BadRequestException('Le type doit être "cgu" ou "privacy"');
}
const documents = await this.documentsService.listerVersions(type as 'cgu' | 'privacy');
return documents.map((doc) => ({
id: doc.id,
version: doc.version,
fichier_nom: doc.fichier_nom,
actif: doc.actif,
televersePar: doc.televersePar
? {
id: doc.televersePar.id,
prenom: doc.televersePar.prenom,
nom: doc.televersePar.nom,
}
: null,
televerseLe: doc.televerseLe,
activeLe: doc.activeLe,
}));
}
/**
* POST /api/v1/documents-legaux
* Upload une nouvelle version d'un document
* ADMIN ONLY
*/
@Post()
@UseInterceptors(FileInterceptor('file'))
// @UseGuards(JwtAuthGuard, RolesGuard)
// @Roles('super_admin', 'administrateur')
async uploadDocument(
@Body() uploadDto: UploadDocumentDto,
@UploadedFile() file: Express.Multer.File,
// @CurrentUser() user: any, // TODO: Décommenter quand le guard sera implémenté
) {
if (!file) {
throw new BadRequestException('Aucun fichier fourni');
}
// TODO: Récupérer l'ID utilisateur depuis le guard
const userId = '00000000-0000-0000-0000-000000000000'; // Temporaire
const document = await this.documentsService.uploadNouvelleVersion(
uploadDto.type,
file,
userId,
);
return {
id: document.id,
type: document.type,
version: document.version,
fichier_nom: document.fichier_nom,
actif: document.actif,
televerseLe: document.televerseLe,
};
}
/**
* PATCH /api/v1/documents-legaux/:id/activer
* Activer une version d'un document
* ADMIN ONLY
*/
@Patch(':id/activer')
// @UseGuards(JwtAuthGuard, RolesGuard)
// @Roles('super_admin', 'administrateur')
async activerVersion(@Param('id', ParseUUIDPipe) documentId: string) {
await this.documentsService.activerVersion(documentId);
// Récupérer le document pour retourner les infos
const documents = await this.documentsService.listerVersions('cgu');
const document = documents.find((d) => d.id === documentId);
if (!document) {
const documentsPrivacy = await this.documentsService.listerVersions('privacy');
const docPrivacy = documentsPrivacy.find((d) => d.id === documentId);
if (!docPrivacy) {
throw new BadRequestException('Document non trouvé');
}
return {
message: 'Document activé avec succès',
documentId: docPrivacy.id,
type: docPrivacy.type,
version: docPrivacy.version,
};
}
return {
message: 'Document activé avec succès',
documentId: document.id,
type: document.type,
version: document.version,
};
}
/**
* GET /api/v1/documents-legaux/:id/download
* Télécharger un document
* PUBLIC
*/
@Get(':id/download')
async telechargerDocument(
@Param('id', ParseUUIDPipe) documentId: string,
@Res() res: Response,
) {
const { stream, filename } = await this.documentsService.telechargerDocument(documentId);
res.set({
'Content-Type': 'application/pdf',
'Content-Disposition': `attachment; filename="${filename}"`,
});
res.status(HttpStatus.OK).send(stream);
}
/**
* GET /api/v1/documents-legaux/:id/verifier-integrite
* Vérifier l'intégrité d'un document (hash SHA-256)
* ADMIN ONLY
*/
@Get(':id/verifier-integrite')
// @UseGuards(JwtAuthGuard, RolesGuard)
// @Roles('super_admin', 'administrateur')
async verifierIntegrite(@Param('id', ParseUUIDPipe) documentId: string) {
const integre = await this.documentsService.verifierIntegrite(documentId);
return {
documentId,
integre,
message: integre
? 'Le document est intègre (hash valide)'
: 'ALERTE : Le document a été modifié (hash invalide)',
};
}
}
@@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { DocumentLegal } from '../../entities/document-legal.entity';
import { AcceptationDocument } from '../../entities/acceptation-document.entity';
import { DocumentsLegauxService } from './documents-legaux.service';
import { DocumentsLegauxController } from './documents-legaux.controller';
@Module({
imports: [TypeOrmModule.forFeature([DocumentLegal, AcceptationDocument])],
providers: [DocumentsLegauxService],
controllers: [DocumentsLegauxController],
exports: [DocumentsLegauxService],
})
export class DocumentsLegauxModule {}
@@ -0,0 +1,209 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { DocumentLegal } from '../../entities/document-legal.entity';
import { AcceptationDocument } from '../../entities/acceptation-document.entity';
import * as crypto from 'crypto';
import * as fs from 'fs/promises';
import * as path from 'path';
@Injectable()
export class DocumentsLegauxService {
private readonly UPLOAD_DIR = '/app/documents/legaux';
constructor(
@InjectRepository(DocumentLegal)
private docRepo: Repository<DocumentLegal>,
@InjectRepository(AcceptationDocument)
private acceptationRepo: Repository<AcceptationDocument>,
) {}
/**
* Récupérer les documents actifs (CGU + Privacy)
*/
async getDocumentsActifs(): Promise<{ cgu: DocumentLegal; privacy: DocumentLegal }> {
const cgu = await this.docRepo.findOne({
where: { type: 'cgu', actif: true },
});
const privacy = await this.docRepo.findOne({
where: { type: 'privacy', actif: true },
});
if (!cgu || !privacy) {
throw new NotFoundException('Documents légaux manquants');
}
return { cgu, privacy };
}
/**
* Uploader une nouvelle version d'un document
*/
async uploadNouvelleVersion(
type: 'cgu' | 'privacy',
file: Express.Multer.File,
userId: string,
): Promise<DocumentLegal> {
// Validation du type de fichier
if (file.mimetype !== 'application/pdf') {
throw new BadRequestException('Seuls les fichiers PDF sont acceptés');
}
// Validation de la taille (max 10MB)
const maxSize = 10 * 1024 * 1024; // 10MB
if (file.size > maxSize) {
throw new BadRequestException('Le fichier ne doit pas dépasser 10MB');
}
// 1. Calculer la prochaine version
const lastDoc = await this.docRepo.findOne({
where: { type },
order: { version: 'DESC' },
});
const nouvelleVersion = (lastDoc?.version || 0) + 1;
// 2. Calculer le hash SHA-256 du fichier
const fileBuffer = file.buffer;
const hash = crypto.createHash('sha256').update(fileBuffer).digest('hex');
// 3. Générer le nom de fichier unique
const timestamp = Date.now();
const fileName = `${type}_v${nouvelleVersion}_${timestamp}.pdf`;
const filePath = path.join(this.UPLOAD_DIR, fileName);
// 4. Créer le répertoire si nécessaire et sauvegarder le fichier
await fs.mkdir(this.UPLOAD_DIR, { recursive: true });
await fs.writeFile(filePath, fileBuffer);
// 5. Créer l'entrée en BDD
const document = this.docRepo.create({
type,
version: nouvelleVersion,
fichier_nom: file.originalname,
fichier_path: filePath,
fichier_hash: hash,
actif: false, // Pas actif par défaut
televersePar: { id: userId } as any,
televerseLe: new Date(),
});
return await this.docRepo.save(document);
}
/**
* Activer une version (désactive automatiquement l'ancienne)
*/
async activerVersion(documentId: string): Promise<void> {
const document = await this.docRepo.findOne({ where: { id: documentId } });
if (!document) {
throw new NotFoundException('Document non trouvé');
}
// Transaction : désactiver l'ancienne version, activer la nouvelle
await this.docRepo.manager.transaction(async (manager) => {
// Désactiver toutes les versions de ce type
await manager.update(
DocumentLegal,
{ type: document.type, actif: true },
{ actif: false },
);
// Activer la nouvelle version
await manager.update(
DocumentLegal,
{ id: documentId },
{ actif: true, activeLe: new Date() },
);
});
}
/**
* Lister toutes les versions d'un type de document
*/
async listerVersions(type: 'cgu' | 'privacy'): Promise<DocumentLegal[]> {
return await this.docRepo.find({
where: { type },
order: { version: 'DESC' },
relations: ['televersePar'],
});
}
/**
* Télécharger un document (retourne le buffer et le nom)
*/
async telechargerDocument(documentId: string): Promise<{ stream: Buffer; filename: string }> {
const document = await this.docRepo.findOne({ where: { id: documentId } });
if (!document) {
throw new NotFoundException('Document non trouvé');
}
try {
const fileBuffer = await fs.readFile(document.fichier_path);
return {
stream: fileBuffer,
filename: document.fichier_nom,
};
} catch (error) {
throw new NotFoundException('Fichier introuvable sur le système de fichiers');
}
}
/**
* Vérifier l'intégrité d'un document (hash SHA-256)
*/
async verifierIntegrite(documentId: string): Promise<boolean> {
const document = await this.docRepo.findOne({ where: { id: documentId } });
if (!document) {
throw new NotFoundException('Document non trouvé');
}
try {
const fileBuffer = await fs.readFile(document.fichier_path);
const hash = crypto.createHash('sha256').update(fileBuffer).digest('hex');
return hash === document.fichier_hash;
} catch (error) {
return false;
}
}
/**
* Enregistrer une acceptation de document (lors de l'inscription)
*/
async enregistrerAcceptation(
userId: string,
documentId: string,
typeDocument: 'cgu' | 'privacy',
versionDocument: number,
ipAddress: string | null,
userAgent: string | null,
): Promise<AcceptationDocument> {
const acceptation = this.acceptationRepo.create({
utilisateur: { id: userId } as any,
document: { id: documentId } as any,
type_document: typeDocument,
version_document: versionDocument,
ip_address: ipAddress,
user_agent: userAgent,
});
return await this.acceptationRepo.save(acceptation);
}
/**
* Récupérer l'historique des acceptations d'un utilisateur
*/
async getAcceptationsUtilisateur(userId: string): Promise<AcceptationDocument[]> {
return await this.acceptationRepo.find({
where: { utilisateur: { id: userId } },
order: { accepteLe: 'DESC' },
relations: ['document'],
});
}
}
@@ -0,0 +1,14 @@
export class DocumentVersionDto {
id: string;
version: number;
fichier_nom: string;
actif: boolean;
televersePar: {
id: string;
prenom?: string;
nom?: string;
} | null;
televerseLe: Date;
activeLe: Date | null;
}
@@ -0,0 +1,13 @@
export class DocumentActifDto {
id: string;
type: 'cgu' | 'privacy';
version: number;
url: string;
activeLe: Date | null;
}
export class DocumentsActifsResponseDto {
cgu: DocumentActifDto;
privacy: DocumentActifDto;
}
@@ -0,0 +1,8 @@
import { IsEnum, IsNotEmpty } from 'class-validator';
export class UploadDocumentDto {
@IsEnum(['cgu', 'privacy'], { message: 'Le type doit être "cgu" ou "privacy"' })
@IsNotEmpty({ message: 'Le type est requis' })
type: 'cgu' | 'privacy';
}
@@ -0,0 +1,3 @@
export * from './documents-legaux.module';
export * from './documents-legaux.service';
@@ -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 dune 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 dune 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();
});
});
+100
View File
@@ -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);
}
}
+31
View File
@@ -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();
});
});
+461
View File
@@ -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;
}
+17
View File
@@ -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 dun 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 dun 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 dun 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);
}
}
+28
View File
@@ -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 { }

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