Compare commits

..
Author SHA1 Message Date
jmartinandCursor 2114748d44 feat(#205): renommer absences_garde → evenements_agenda
Migration live + BDD.sql from-scratch, module Nest / API
/evenements-agenda, FK cartes id_evenement. Front stub path aligné.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:07:54 +02:00
jmartinandCursor 0842f66df8 fix: typage comment insert card_responses
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-25 10:54:02 +02:00
jmartin c3fd098464 Merge branch 'feature/fix-card-respond-id-card' into develop 2026-09-25 10:52:37 +02:00
jmartinandCursor ed3546d196 fix(#194): insert card_responses avec id_card explicite
TypeORM nullifiait id_card (conflit Column/JoinColumn) → 500 sur respond.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-25 10:52:36 +02:00
jmartin da6836cda3 Merge branch 'feature/170-fix-api-couples-am' into develop
fix(#170): API couples-garde AM + bandeau parents unifié.
2026-09-25 10:42:24 +02:00
jmartinandCursor 91f2c3e1ef fix(#170): brancher l’API couples-garde AM et unifier le bandeau
Évite le 403 en appelant /assistantes-maternelles/me/couples-garde,
parse parents[], et affiche « Prénom1 et Prénom2 » sans vignette.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 16:04:34 +02:00
jmartin 4007d7010e Merge branch 'develop' of https://git.ptits-pas.fr/jmartin/petitspas into develop 2026-09-24 12:19:40 +02:00
jmartinandCursor 4261667198 feat(#170): sélecteur couple enfant-parent(s) pour AM
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 12:19:26 +02:00
jmartin 15e2d8d850 Merge branch 'feature/171-api-couples-garde-am' into develop
API couples-garde AM (#171).
2026-09-24 12:17:09 +02:00
jmartinandCursor da71803852 feat(#171): API couples-garde AM (liste + courant)
Symétrique #168 : GET/PUT /assistantes-maternelles/me/couples-garde
avec parents[] pour le bandeau enfant|foyer. Colonne
id_placement_garde_courant sur assistantes_maternelles.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 12:14:16 +02:00
39 changed files with 899 additions and 299 deletions
+2 -2
View File
@@ -16,7 +16,7 @@ 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';
import { AbsencesGardeModule } from './modules/absences-garde';
import { EvenementsAgendaModule } from './modules/evenements-agenda';
import { CardsModule } from './modules/cards';
import { RelaisModule } from './routes/relais/relais.module';
import { DossiersModule } from './routes/dossiers/dossiers.module';
@@ -58,7 +58,7 @@ import { SuppressionsModule } from './routes/suppressions/suppressions.module';
AuthModule,
AppConfigModule,
DocumentsLegauxModule,
AbsencesGardeModule,
EvenementsAgendaModule,
CardsModule,
RelaisModule,
DossiersModule,
@@ -1,4 +1,4 @@
import { Entity, PrimaryColumn, Column, OneToOne, OneToMany, JoinColumn } from 'typeorm';
import { Entity, PrimaryColumn, Column, OneToOne, OneToMany, JoinColumn, ManyToOne } from 'typeorm';
import { Users } from './users.entity';
import { AmChildren } from './am_children.entity';
@@ -37,22 +37,32 @@ export class AssistanteMaternelle {
@Column({ name: 'ville_residence', length: 100, nullable: true })
residence_city?: string;
@Column( { name: 'date_agrement', type: 'date', nullable: true })
@Column({ name: 'date_agrement', type: 'date', nullable: true })
agreement_date?: Date;
@Column( { name: 'annee_experience', type: 'smallint', nullable: true })
@Column({ name: 'annee_experience', type: 'smallint', nullable: true })
years_experience?: number;
@Column( { name: 'specialite', length: 100, nullable: true })
@Column({ name: 'specialite', length: 100, nullable: true })
specialty?: string;
@Column( { name: 'place_disponible', type: 'integer', nullable: true })
@Column({ name: 'place_disponible', type: 'integer', nullable: true })
places_available?: number;
/** Numéro de dossier (format AAAA-NNNNNN), même valeur que sur utilisateurs (ticket #103) */
@Column({ name: 'numero_dossier', length: 20, nullable: true })
numero_dossier?: string;
/**
* Placement AM↔enfant sélectionné sur le TdB AM (couple actif) — ticket #171.
*/
@Column({ name: 'id_placement_garde_courant', type: 'uuid', nullable: true })
id_placement_garde_courant?: string;
@ManyToOne(() => AmChildren, { nullable: true, onDelete: 'SET NULL' })
@JoinColumn({ name: 'id_placement_garde_courant', referencedColumnName: 'id' })
placement_garde_courant?: AmChildren;
@OneToMany(() => AmChildren, (ac) => ac.am)
amChildren: AmChildren[];
}
@@ -9,7 +9,7 @@ import {
UpdateDateColumn,
} from 'typeorm';
import { AmChildren } from './am_children.entity';
import { AbsencesGarde } from './absences_garde.entity';
import { EvenementsAgenda } from './evenements_agenda.entity';
import { Users } from './users.entity';
import { CardType } from './card_types.entity';
import { CardAudienceMember } from './card_audience_members.entity';
@@ -45,12 +45,12 @@ export class CardInstance {
@JoinColumn({ name: 'id_placement', referencedColumnName: 'id' })
placement: AmChildren;
@Column({ name: 'id_absence', type: 'uuid', nullable: true })
id_absence?: string;
@Column({ name: 'id_evenement', type: 'uuid', nullable: true })
id_evenement?: string;
@ManyToOne(() => AbsencesGarde, { nullable: true, onDelete: 'SET NULL' })
@JoinColumn({ name: 'id_absence', referencedColumnName: 'id' })
absence?: AbsencesGarde;
@ManyToOne(() => EvenementsAgenda, { nullable: true, onDelete: 'SET NULL' })
@JoinColumn({ name: 'id_evenement', referencedColumnName: 'id' })
evenement?: EvenementsAgenda;
@Column({ name: 'cree_par', type: 'uuid', nullable: true })
cree_par?: string;
@@ -10,25 +10,25 @@ import {
import { AmChildren } from './am_children.entity';
import { Users } from './users.entity';
export enum TypeAbsenceGardeType {
export enum TypeEvenementAgendaType {
ABSENCE_ENFANT = 'absence_enfant',
CONGE_AM = 'conge_am',
ARRET_MALADIE_AM = 'arret_maladie_am',
}
export enum StatutAbsenceGardeType {
export enum StatutEvenementAgendaType {
EN_ATTENTE = 'en_attente',
ACCEPTE = 'accepte',
REFUSE = 'refuse',
}
/**
* Vérité métier des absences / congés / arrêts par couple AM↔enfant.
* Les cartes (module ultérieur) collectent ; cette table stocke.
* Ticket #193.
* Vérité métier agenda par couple AM↔enfant (placement).
* Types V1 : absences / congés / arrêts ; extensible (soins, école, mairie…).
* Les cartes collectent ; cette table historise. Ticket #205.
*/
@Entity('absences_garde', { schema: 'public' })
export class AbsencesGarde {
@Entity('evenements_agenda', { schema: 'public' })
export class EvenementsAgenda {
@PrimaryGeneratedColumn('uuid')
id: string;
@@ -41,11 +41,11 @@ export class AbsencesGarde {
@Column({
type: 'enum',
enum: TypeAbsenceGardeType,
enumName: 'type_absence_garde_type',
enum: TypeEvenementAgendaType,
enumName: 'type_evenement_agenda_type',
name: 'type',
})
type: TypeAbsenceGardeType;
type: TypeEvenementAgendaType;
@Column({ name: 'date_debut', type: 'date' })
date_debut: string;
@@ -55,12 +55,12 @@ export class AbsencesGarde {
@Column({
type: 'enum',
enum: StatutAbsenceGardeType,
enumName: 'statut_absence_garde_type',
enum: StatutEvenementAgendaType,
enumName: 'statut_evenement_agenda_type',
name: 'statut',
default: StatutAbsenceGardeType.EN_ATTENTE,
default: StatutEvenementAgendaType.EN_ATTENTE,
})
statut: StatutAbsenceGardeType;
statut: StatutEvenementAgendaType;
/** Purge auto pour en_attente/refuse ; accepte → infinity. */
@Column({ name: 'expire_at', type: 'timestamptz' })
@@ -1,2 +0,0 @@
export { AbsencesGardeModule } from './absences-garde.module';
export { AbsencesGardeService } from './absences-garde.service';
@@ -65,7 +65,7 @@ export class CardsController {
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
@HttpCode(HttpStatus.CREATED)
@ApiOperation({
summary: 'Créer une bulle (+ hook absences_garde) — #194',
summary: 'Créer une bulle (+ hook evenements_agenda) — #194',
})
@ApiBody({ type: CreerCarteDto })
@ApiResponse({ status: 201, type: CarteDto })
+2 -2
View File
@@ -2,7 +2,7 @@ import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AbsencesGardeModule } from '../absences-garde';
import { EvenementsAgendaModule } from '../evenements-agenda';
import { CardType } from 'src/entities/card_types.entity';
import { CardInstance } from 'src/entities/card_instances.entity';
import { CardAudienceMember } from 'src/entities/card_audience_members.entity';
@@ -16,7 +16,7 @@ import { CardsRealtimeService } from './cards-realtime.service';
@Module({
imports: [
AbsencesGardeModule,
EvenementsAgendaModule,
TypeOrmModule.forFeature([
CardType,
CardInstance,
@@ -3,7 +3,7 @@ import { getRepositoryToken } from '@nestjs/typeorm';
import { ForbiddenException } from '@nestjs/common';
import { CardsService } from './cards.service';
import { CardsRealtimeService } from './cards-realtime.service';
import { AbsencesGardeService } from '../absences-garde/absences-garde.service';
import { EvenementsAgendaService } from '../evenements-agenda/evenements-agenda.service';
import { CardType, CardResponseModeType } from 'src/entities/card_types.entity';
import {
CardInstance,
@@ -15,7 +15,7 @@ import { CardResponse } from 'src/entities/card_responses.entity';
import { AmChildren } from 'src/entities/am_children.entity';
import { ParentsChildren } from 'src/entities/parents_children.entity';
import { RoleType } from 'src/entities/users.entity';
import { StatutAbsenceGardeType, TypeAbsenceGardeType } from 'src/entities/absences_garde.entity';
import { StatutEvenementAgendaType, TypeEvenementAgendaType } from 'src/entities/evenements_agenda.entity';
describe('CardsService (#194)', () => {
let service: CardsService;
@@ -41,7 +41,7 @@ describe('CardsService (#194)', () => {
};
const amChildrenRepo = { findOne: jest.fn() };
const parentsChildrenRepo = { find: jest.fn(), findOne: jest.fn() };
const absencesService = {
const evenementsService = {
creer: jest.fn(),
maj: jest.fn(),
supprimer: jest.fn(),
@@ -58,7 +58,7 @@ describe('CardsService (#194)', () => {
{ provide: getRepositoryToken(CardResponse), useValue: responsesRepo },
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo },
{ provide: getRepositoryToken(ParentsChildren), useValue: parentsChildrenRepo },
{ provide: AbsencesGardeService, useValue: absencesService },
{ provide: EvenementsAgendaService, useValue: evenementsService },
{ provide: CardsRealtimeService, useValue: realtime },
],
}).compile();
@@ -88,10 +88,10 @@ describe('CardsService (#194)', () => {
enfantId: 'e-1',
date_fin: null,
});
absencesService.creer.mockResolvedValue({
evenementsService.creer.mockResolvedValue({
id: 'abs-1',
type: TypeAbsenceGardeType.CONGE_AM,
statut: StatutAbsenceGardeType.EN_ATTENTE,
type: TypeEvenementAgendaType.CONGE_AM,
statut: StatutEvenementAgendaType.EN_ATTENTE,
});
parentsChildrenRepo.find.mockResolvedValue([
{ parentId: 'p-1', enfantId: 'e-1' },
@@ -101,7 +101,7 @@ describe('CardsService (#194)', () => {
id: 'card-1',
type_code: 'conge_am',
id_placement: 'pl-1',
id_absence: 'abs-1',
id_evenement: 'abs-1',
cree_par: 'am-1',
operation: CardOperationType.CREATE,
statut: CardInstanceStatutType.OUVERTE,
@@ -130,7 +130,7 @@ describe('CardsService (#194)', () => {
date_fin: '2026-11-07',
});
expect(absencesService.creer).toHaveBeenCalled();
expect(evenementsService.creer).toHaveBeenCalled();
expect(audienceRepo.save).toHaveBeenCalled();
expect(realtime.emitToUsers).toHaveBeenCalledWith(
['am-1', 'p-1', 'p-2'],
+34 -36
View File
@@ -6,11 +6,11 @@ import {
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { IsNull, Repository } from 'typeorm';
import { AbsencesGardeService } from '../absences-garde/absences-garde.service';
import { EvenementsAgendaService } from '../evenements-agenda/evenements-agenda.service';
import {
StatutAbsenceGardeType,
TypeAbsenceGardeType,
} from 'src/entities/absences_garde.entity';
StatutEvenementAgendaType,
TypeEvenementAgendaType,
} from 'src/entities/evenements_agenda.entity';
import { AmChildren } from 'src/entities/am_children.entity';
import { ParentsChildren } from 'src/entities/parents_children.entity';
import { RoleType } from 'src/entities/users.entity';
@@ -49,7 +49,7 @@ export class CardsService {
private readonly amChildrenRepo: Repository<AmChildren>,
@InjectRepository(ParentsChildren)
private readonly parentsChildrenRepo: Repository<ParentsChildren>,
private readonly absencesService: AbsencesGardeService,
private readonly evenementsService: EvenementsAgendaService,
private readonly realtime: CardsRealtimeService,
) {}
@@ -110,11 +110,11 @@ export class CardsService {
);
const operation = dto.operation ?? CardOperationType.CREATE;
let absenceId = dto.id_absence;
let absenceId = dto.id_evenement;
const absenceType = this.mapAbsenceType(dto.type_code);
if (operation === CardOperationType.CREATE) {
const absence = await this.absencesService.creer(userId, role, {
const absence = await this.evenementsService.creer(userId, role, {
id_placement: dto.id_placement,
type: absenceType,
date_debut: dto.date_debut,
@@ -124,16 +124,16 @@ export class CardsService {
absenceId = absence.id;
} else {
if (!absenceId) {
throw new BadRequestException('id_absence requis pour operation=update');
throw new BadRequestException('id_evenement requis pour operation=update');
}
await this.absencesService.maj(userId, role, absenceId, {
await this.evenementsService.maj(userId, role, absenceId, {
date_debut: dto.date_debut,
date_fin: dto.date_fin,
motif: dto.motif,
// Congé accepté modifié → repasse en attente via cartes respond flow;
// pour absence enfant update immédiat déjà fait.
...(dto.type_code === 'conge_am'
? { statut: StatutAbsenceGardeType.EN_ATTENTE }
? { statut: StatutEvenementAgendaType.EN_ATTENTE }
: {}),
});
}
@@ -146,7 +146,7 @@ export class CardsService {
const card = this.cardsRepo.create({
type_code: type.code,
id_placement: dto.id_placement,
id_absence: absenceId,
id_evenement: absenceId,
cree_par: userId,
operation,
statut: statutInitial,
@@ -204,24 +204,22 @@ export class CardsService {
throw new BadRequestException('Motivation obligatoire en cas de refus');
}
await this.responsesRepo.save(
this.responsesRepo.create({
id_card: card.id,
id_utilisateur: userId,
action: dto.action,
comment: dto.comment?.trim(),
}),
);
await this.responsesRepo.insert({
id_card: card.id,
id_utilisateur: userId,
action: dto.action,
comment: dto.comment?.trim() || undefined,
});
if (card.id_absence) {
if (card.id_evenement) {
if (dto.action === CardResponseActionType.ACCEPT || dto.action === CardResponseActionType.ACK) {
await this.absencesService.maj(userId, role, card.id_absence, {
statut: StatutAbsenceGardeType.ACCEPTE,
await this.evenementsService.maj(userId, role, card.id_evenement, {
statut: StatutEvenementAgendaType.ACCEPTE,
});
card.statut = CardInstanceStatutType.TRAITEE;
} else if (dto.action === CardResponseActionType.REFUSE) {
await this.absencesService.maj(userId, role, card.id_absence, {
statut: StatutAbsenceGardeType.REFUSE,
await this.evenementsService.maj(userId, role, card.id_evenement, {
statut: StatutEvenementAgendaType.REFUSE,
motif: dto.comment!.trim(),
});
card.statut = CardInstanceStatutType.REFUSEE;
@@ -266,12 +264,12 @@ export class CardsService {
throw new BadRequestException('Dates invalides');
}
if (card.id_absence) {
await this.absencesService.maj(userId, role, card.id_absence, {
if (card.id_evenement) {
await this.evenementsService.maj(userId, role, card.id_evenement, {
date_debut: debut,
date_fin: fin,
motif: dto.motif,
statut: StatutAbsenceGardeType.EN_ATTENTE,
statut: StatutEvenementAgendaType.EN_ATTENTE,
});
}
@@ -300,17 +298,17 @@ export class CardsService {
throw new ForbiddenException('Seul le créateur peut supprimer cette carte');
}
const audienceIds = await this.audienceUserIds(card);
if (card.id_absence) {
if (card.id_evenement) {
const absStatut =
card.statut === CardInstanceStatutType.TRAITEE
? null
: card.id_absence;
: card.id_evenement;
// Supprime l’absence liée si pas encore acceptée définitivement
if (
card.statut === CardInstanceStatutType.OUVERTE ||
card.statut === CardInstanceStatutType.REFUSEE
) {
await this.absencesService.supprimer(userId, role, card.id_absence);
await this.evenementsService.supprimer(userId, role, card.id_evenement);
}
void absStatut;
}
@@ -338,13 +336,13 @@ export class CardsService {
return rows.map((r) => r.id_utilisateur);
}
private mapAbsenceType(typeCode: string): TypeAbsenceGardeType {
private mapAbsenceType(typeCode: string): TypeEvenementAgendaType {
if (typeCode === 'absence_enfant' || typeCode === 'absence_enfant_modif') {
return TypeAbsenceGardeType.ABSENCE_ENFANT;
return TypeEvenementAgendaType.ABSENCE_ENFANT;
}
if (typeCode === 'conge_am') return TypeAbsenceGardeType.CONGE_AM;
if (typeCode === 'conge_am') return TypeEvenementAgendaType.CONGE_AM;
if (typeCode === 'arret_maladie_am') {
return TypeAbsenceGardeType.ARRET_MALADIE_AM;
return TypeEvenementAgendaType.ARRET_MALADIE_AM;
}
throw new BadRequestException(`Type non mappé à une absence: ${typeCode}`);
}
@@ -352,7 +350,7 @@ export class CardsService {
private async linkAbsenceCard(absenceId: string, cardId: string): Promise<void> {
// Update direct pour éviter droits maj vides
await this.cardsRepo.manager.query(
`UPDATE absences_garde SET id_card_instance = $1, modifie_le = now() WHERE id = $2`,
`UPDATE evenements_agenda SET id_card_instance = $1, modifie_le = now() WHERE id = $2`,
[cardId, absenceId],
);
}
@@ -473,7 +471,7 @@ export class CardsService {
titre: card.type?.titre ?? card.type_code,
couleur: card.type?.couleur ?? null,
id_placement: card.id_placement,
id_absence: card.id_absence ?? null,
id_evenement: card.id_evenement ?? null,
operation: card.operation,
statut: card.statut,
payload: card.payload ?? {},
+3 -3
View File
@@ -38,11 +38,11 @@ export class CreerCarteDto {
motif?: string;
@ApiPropertyOptional({
description: 'Requis pour operation=update (même id absences_garde)',
description: 'Requis pour operation=update (même id evenements_agenda)',
})
@IsOptional()
@IsUUID()
id_absence?: string;
id_evenement?: string;
@ApiPropertyOptional({ enum: CardOperationType, default: CardOperationType.CREATE })
@IsOptional()
@@ -98,7 +98,7 @@ export class CarteDto {
id_placement: string;
@ApiPropertyOptional()
id_absence?: string | null;
id_evenement?: string | null;
@ApiProperty({ enum: CardOperationType })
operation: CardOperationType;
@@ -9,18 +9,18 @@ import {
MinLength,
} from 'class-validator';
import {
StatutAbsenceGardeType,
TypeAbsenceGardeType,
} from 'src/entities/absences_garde.entity';
StatutEvenementAgendaType,
TypeEvenementAgendaType,
} from 'src/entities/evenements_agenda.entity';
export class CreerAbsenceGardeDto {
export class CreerEvenementAgendaDto {
@ApiProperty({ description: 'Placement AM↔enfant (couple)' })
@IsUUID()
id_placement: string;
@ApiProperty({ enum: TypeAbsenceGardeType })
@IsEnum(TypeAbsenceGardeType)
type: TypeAbsenceGardeType;
@ApiProperty({ enum: TypeEvenementAgendaType })
@IsEnum(TypeEvenementAgendaType)
type: TypeEvenementAgendaType;
@ApiProperty({ example: '2026-10-01' })
@IsDateString()
@@ -37,7 +37,7 @@ export class CreerAbsenceGardeDto {
motif?: string;
}
export class MajAbsenceGardeDto {
export class MajEvenementAgendaDto {
@ApiPropertyOptional({ example: '2026-10-02' })
@IsOptional()
@IsDateString()
@@ -48,10 +48,10 @@ export class MajAbsenceGardeDto {
@IsDateString()
date_fin?: string;
@ApiPropertyOptional({ enum: StatutAbsenceGardeType })
@ApiPropertyOptional({ enum: StatutEvenementAgendaType })
@IsOptional()
@IsEnum(StatutAbsenceGardeType)
statut?: StatutAbsenceGardeType;
@IsEnum(StatutEvenementAgendaType)
statut?: StatutEvenementAgendaType;
@ApiPropertyOptional({
description: 'Motivation de refus (parent) ou motif créateur',
@@ -63,15 +63,15 @@ export class MajAbsenceGardeDto {
motif?: string;
}
export class AbsenceGardeDto {
export class EvenementAgendaDto {
@ApiProperty()
id: string;
@ApiProperty()
id_placement: string;
@ApiProperty({ enum: TypeAbsenceGardeType })
type: TypeAbsenceGardeType;
@ApiProperty({ enum: TypeEvenementAgendaType })
type: TypeEvenementAgendaType;
@ApiProperty()
date_debut: string;
@@ -79,8 +79,8 @@ export class AbsenceGardeDto {
@ApiProperty()
date_fin: string;
@ApiProperty({ enum: StatutAbsenceGardeType })
statut: StatutAbsenceGardeType;
@ApiProperty({ enum: StatutEvenementAgendaType })
statut: StatutEvenementAgendaType;
@ApiProperty()
expire_at: string;
@@ -113,7 +113,7 @@ export class AbsenceGardeDto {
modifie_le: string;
}
export class ListeAbsencesGardeDto {
@ApiProperty({ type: [AbsenceGardeDto] })
items: AbsenceGardeDto[];
export class ListeEvenementsAgendaDto {
@ApiProperty({ type: [EvenementAgendaDto] })
items: EvenementAgendaDto[];
}
@@ -1,13 +1,13 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AbsencesGardeController } from './absences-garde.controller';
import { AbsencesGardeService } from './absences-garde.service';
import { EvenementsAgendaController } from './evenements-agenda.controller';
import { EvenementsAgendaService } from './evenements-agenda.service';
import { AuthGuard } from 'src/common/guards/auth.guard';
import { RolesGuard } from 'src/common/guards/roles.guard';
import { RoleType } from 'src/entities/users.entity';
import { TypeAbsenceGardeType } from 'src/entities/absences_garde.entity';
import { TypeEvenementAgendaType } from 'src/entities/evenements_agenda.entity';
describe('AbsencesGardeController (#172)', () => {
let controller: AbsencesGardeController;
describe('EvenementsAgendaController (#172)', () => {
let controller: EvenementsAgendaController;
const serviceMock = {
lister: jest.fn(),
creer: jest.fn(),
@@ -17,8 +17,8 @@ describe('AbsencesGardeController (#172)', () => {
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AbsencesGardeController],
providers: [{ provide: AbsencesGardeService, useValue: serviceMock }],
controllers: [EvenementsAgendaController],
providers: [{ provide: EvenementsAgendaService, useValue: serviceMock }],
})
.overrideGuard(AuthGuard)
.useValue({ canActivate: () => true })
@@ -26,7 +26,7 @@ describe('AbsencesGardeController (#172)', () => {
.useValue({ canActivate: () => true })
.compile();
controller = module.get(AbsencesGardeController);
controller = module.get(EvenementsAgendaController);
jest.clearAllMocks();
});
@@ -59,7 +59,7 @@ describe('AbsencesGardeController (#172)', () => {
serviceMock.creer.mockResolvedValue({ id: 'a1' });
const dto = {
id_placement: 'pl-1',
type: TypeAbsenceGardeType.ABSENCE_ENFANT,
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
date_debut: '2026-10-01',
date_fin: '2026-10-02',
};
@@ -25,49 +25,49 @@ import { RolesGuard } from 'src/common/guards/roles.guard';
import { Roles } from 'src/common/decorators/roles.decorator';
import { User } from 'src/common/decorators/user.decorator';
import {
StatutAbsenceGardeType,
TypeAbsenceGardeType,
} from 'src/entities/absences_garde.entity';
StatutEvenementAgendaType,
TypeEvenementAgendaType,
} from 'src/entities/evenements_agenda.entity';
import { RoleType } from 'src/entities/users.entity';
import { AbsencesGardeService } from './absences-garde.service';
import { EvenementsAgendaService } from './evenements-agenda.service';
import {
AbsenceGardeDto,
CreerAbsenceGardeDto,
ListeAbsencesGardeDto,
MajAbsenceGardeDto,
} from './dto/absences-garde.dto';
EvenementAgendaDto,
CreerEvenementAgendaDto,
ListeEvenementsAgendaDto,
MajEvenementAgendaDto,
} from './dto/evenements-agenda.dto';
@ApiTags('Absences garde')
@ApiTags('Événements agenda')
@ApiBearerAuth('access-token')
@Controller('absences-garde')
@Controller('evenements-agenda')
@UseGuards(AuthGuard, RolesGuard)
export class AbsencesGardeController {
constructor(private readonly absencesGardeService: AbsencesGardeService) {}
export class EvenementsAgendaController {
constructor(private readonly evenementsAgendaService: EvenementsAgendaService) {}
@Get()
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
@ApiOperation({
summary: 'Lister les absences / congés / arrêts — ticket #172',
summary: 'Lister les absences / congés / arrêts — ticket #205 / ex-#172',
description:
'Sans placementId : tous les placements du user (parent = famille multi-AM ; AM = tous accueils). ' +
'Avec placementId : un couple enfant–AM.',
})
@ApiQuery({ name: 'placementId', required: false })
@ApiQuery({ name: 'type', required: false, enum: TypeAbsenceGardeType })
@ApiQuery({ name: 'statut', required: false, enum: StatutAbsenceGardeType })
@ApiQuery({ name: 'type', required: false, enum: TypeEvenementAgendaType })
@ApiQuery({ name: 'statut', required: false, enum: StatutEvenementAgendaType })
@ApiQuery({ name: 'from', required: false, description: 'YYYY-MM-DD' })
@ApiQuery({ name: 'to', required: false, description: 'YYYY-MM-DD' })
@ApiResponse({ status: 200, type: ListeAbsencesGardeDto })
@ApiResponse({ status: 200, type: ListeEvenementsAgendaDto })
lister(
@User('id') userId: string,
@User('role') role: RoleType,
@Query('placementId') placementId?: string,
@Query('type') type?: TypeAbsenceGardeType,
@Query('statut') statut?: StatutAbsenceGardeType,
@Query('type') type?: TypeEvenementAgendaType,
@Query('statut') statut?: StatutEvenementAgendaType,
@Query('from') from?: string,
@Query('to') to?: string,
): Promise<ListeAbsencesGardeDto> {
return this.absencesGardeService.lister(userId, role, {
): Promise<ListeEvenementsAgendaDto> {
return this.evenementsAgendaService.lister(userId, role, {
placementId,
type,
statut,
@@ -79,15 +79,15 @@ export class AbsencesGardeController {
@Post()
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
@ApiOperation({ summary: 'Créer une période d’absence / congé / arrêt — #172' })
@ApiBody({ type: CreerAbsenceGardeDto })
@ApiResponse({ status: 201, type: AbsenceGardeDto })
@ApiBody({ type: CreerEvenementAgendaDto })
@ApiResponse({ status: 201, type: EvenementAgendaDto })
@HttpCode(HttpStatus.CREATED)
creer(
@User('id') userId: string,
@User('role') role: RoleType,
@Body() dto: CreerAbsenceGardeDto,
): Promise<AbsenceGardeDto> {
return this.absencesGardeService.creer(userId, role, dto);
@Body() dto: CreerEvenementAgendaDto,
): Promise<EvenementAgendaDto> {
return this.evenementsAgendaService.creer(userId, role, dto);
}
@Patch(':id')
@@ -98,15 +98,15 @@ export class AbsencesGardeController {
'Parent : accept/refuse congé (motivation si refus), ack arrêt. ' +
'AM : modifier dates (en attente / refuse / accepté), republication après refus.',
})
@ApiBody({ type: MajAbsenceGardeDto })
@ApiResponse({ status: 200, type: AbsenceGardeDto })
@ApiBody({ type: MajEvenementAgendaDto })
@ApiResponse({ status: 200, type: EvenementAgendaDto })
maj(
@User('id') userId: string,
@User('role') role: RoleType,
@Param('id', ParseUUIDPipe) id: string,
@Body() dto: MajAbsenceGardeDto,
): Promise<AbsenceGardeDto> {
return this.absencesGardeService.maj(userId, role, id, dto);
@Body() dto: MajEvenementAgendaDto,
): Promise<EvenementAgendaDto> {
return this.evenementsAgendaService.maj(userId, role, id, dto);
}
@Delete(':id')
@@ -119,6 +119,6 @@ export class AbsencesGardeController {
@User('role') role: RoleType,
@Param('id', ParseUUIDPipe) id: string,
): Promise<void> {
await this.absencesGardeService.supprimer(userId, role, id);
await this.evenementsAgendaService.supprimer(userId, role, id);
}
}
@@ -2,15 +2,15 @@ import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AbsencesGarde } from 'src/entities/absences_garde.entity';
import { EvenementsAgenda } from 'src/entities/evenements_agenda.entity';
import { AmChildren } from 'src/entities/am_children.entity';
import { ParentsChildren } from 'src/entities/parents_children.entity';
import { AbsencesGardeController } from './absences-garde.controller';
import { AbsencesGardeService } from './absences-garde.service';
import { EvenementsAgendaController } from './evenements-agenda.controller';
import { EvenementsAgendaService } from './evenements-agenda.service';
@Module({
imports: [
TypeOrmModule.forFeature([AbsencesGarde, AmChildren, ParentsChildren]),
TypeOrmModule.forFeature([EvenementsAgenda, AmChildren, ParentsChildren]),
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: (config: ConfigService) => ({
@@ -20,8 +20,8 @@ import { AbsencesGardeService } from './absences-garde.service';
inject: [ConfigService],
}),
],
controllers: [AbsencesGardeController],
providers: [AbsencesGardeService],
exports: [AbsencesGardeService],
controllers: [EvenementsAgendaController],
providers: [EvenementsAgendaService],
exports: [EvenementsAgendaService],
})
export class AbsencesGardeModule {}
export class EvenementsAgendaModule {}
@@ -1,18 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { ForbiddenException, BadRequestException } from '@nestjs/common';
import { AbsencesGardeService } from './absences-garde.service';
import { EvenementsAgendaService } from './evenements-agenda.service';
import {
AbsencesGarde,
StatutAbsenceGardeType,
TypeAbsenceGardeType,
} from 'src/entities/absences_garde.entity';
EvenementsAgenda,
StatutEvenementAgendaType,
TypeEvenementAgendaType,
} from 'src/entities/evenements_agenda.entity';
import { AmChildren } from 'src/entities/am_children.entity';
import { ParentsChildren } from 'src/entities/parents_children.entity';
import { RoleType } from 'src/entities/users.entity';
describe('AbsencesGardeService (#172)', () => {
let service: AbsencesGardeService;
describe('EvenementsAgendaService (#172)', () => {
let service: EvenementsAgendaService;
const absencesRepo = {
create: jest.fn((x) => x),
save: jest.fn(async (x) => ({
@@ -37,8 +37,8 @@ describe('AbsencesGardeService (#172)', () => {
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AbsencesGardeService,
{ provide: getRepositoryToken(AbsencesGarde), useValue: absencesRepo },
EvenementsAgendaService,
{ provide: getRepositoryToken(EvenementsAgenda), useValue: absencesRepo },
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo },
{
provide: getRepositoryToken(ParentsChildren),
@@ -46,7 +46,7 @@ describe('AbsencesGardeService (#172)', () => {
},
],
}).compile();
service = module.get(AbsencesGardeService);
service = module.get(EvenementsAgendaService);
jest.clearAllMocks();
});
@@ -68,10 +68,10 @@ describe('AbsencesGardeService (#172)', () => {
absencesRepo.findOne.mockResolvedValue({
id: 'abs-1',
id_placement: 'pl-1',
type: TypeAbsenceGardeType.ABSENCE_ENFANT,
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
date_debut: '2026-10-01',
date_fin: '2026-10-02',
statut: StatutAbsenceGardeType.ACCEPTE,
statut: StatutEvenementAgendaType.ACCEPTE,
expire_at: new Date('9999-12-31'),
cree_le: new Date(),
modifie_le: new Date(),
@@ -85,15 +85,15 @@ describe('AbsencesGardeService (#172)', () => {
const res = await service.creer('p-1', RoleType.PARENT, {
id_placement: 'pl-1',
type: TypeAbsenceGardeType.ABSENCE_ENFANT,
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
date_debut: '2026-10-01',
date_fin: '2026-10-02',
});
expect(absencesRepo.save).toHaveBeenCalled();
const savedArg = absencesRepo.save.mock.calls[0][0];
expect(savedArg.statut).toBe(StatutAbsenceGardeType.ACCEPTE);
expect(res.type).toBe(TypeAbsenceGardeType.ABSENCE_ENFANT);
expect(savedArg.statut).toBe(StatutEvenementAgendaType.ACCEPTE);
expect(res.type).toBe(TypeEvenementAgendaType.ABSENCE_ENFANT);
});
it('parent ne peut pas créer un congé AM', async () => {
@@ -110,7 +110,7 @@ describe('AbsencesGardeService (#172)', () => {
await expect(
service.creer('p-1', RoleType.PARENT, {
id_placement: 'pl-1',
type: TypeAbsenceGardeType.CONGE_AM,
type: TypeEvenementAgendaType.CONGE_AM,
date_debut: '2026-10-01',
date_fin: '2026-10-05',
}),
@@ -121,10 +121,10 @@ describe('AbsencesGardeService (#172)', () => {
absencesRepo.findOne.mockResolvedValue({
id: 'abs-1',
id_placement: 'pl-1',
type: TypeAbsenceGardeType.CONGE_AM,
type: TypeEvenementAgendaType.CONGE_AM,
date_debut: '2026-10-01',
date_fin: '2026-10-05',
statut: StatutAbsenceGardeType.EN_ATTENTE,
statut: StatutEvenementAgendaType.EN_ATTENTE,
expire_at: new Date(),
});
amChildrenRepo.findOne.mockResolvedValue({
@@ -140,7 +140,7 @@ describe('AbsencesGardeService (#172)', () => {
await expect(
service.maj('p-1', RoleType.PARENT, 'abs-1', {
statut: StatutAbsenceGardeType.REFUSE,
statut: StatutEvenementAgendaType.REFUSE,
}),
).rejects.toBeInstanceOf(BadRequestException);
});
@@ -159,7 +159,7 @@ describe('AbsencesGardeService (#172)', () => {
await expect(
service.creer('p-1', RoleType.PARENT, {
id_placement: 'pl-1',
type: TypeAbsenceGardeType.ABSENCE_ENFANT,
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
date_debut: '2026-10-10',
date_fin: '2026-10-01',
}),
@@ -7,19 +7,19 @@ import {
import { InjectRepository } from '@nestjs/typeorm';
import { In, IsNull, Repository } from 'typeorm';
import {
AbsencesGarde,
StatutAbsenceGardeType,
TypeAbsenceGardeType,
} from 'src/entities/absences_garde.entity';
EvenementsAgenda,
StatutEvenementAgendaType,
TypeEvenementAgendaType,
} from 'src/entities/evenements_agenda.entity';
import { AmChildren } from 'src/entities/am_children.entity';
import { ParentsChildren } from 'src/entities/parents_children.entity';
import { RoleType } from 'src/entities/users.entity';
import {
AbsenceGardeDto,
CreerAbsenceGardeDto,
ListeAbsencesGardeDto,
MajAbsenceGardeDto,
} from './dto/absences-garde.dto';
EvenementAgendaDto,
CreerEvenementAgendaDto,
ListeEvenementsAgendaDto,
MajEvenementAgendaDto,
} from './dto/evenements-agenda.dto';
const TTL_EN_ATTENTE_MS = 15 * 24 * 60 * 60 * 1000;
const TTL_REFUSE_MS = 7 * 24 * 60 * 60 * 1000;
@@ -27,10 +27,10 @@ const TTL_REFUSE_MS = 7 * 24 * 60 * 60 * 1000;
const EXPIRE_ACCEPTE = new Date('9999-12-31T23:59:59.999Z');
@Injectable()
export class AbsencesGardeService {
export class EvenementsAgendaService {
constructor(
@InjectRepository(AbsencesGarde)
private readonly absencesRepo: Repository<AbsencesGarde>,
@InjectRepository(EvenementsAgenda)
private readonly absencesRepo: Repository<EvenementsAgenda>,
@InjectRepository(AmChildren)
private readonly amChildrenRepo: Repository<AmChildren>,
@InjectRepository(ParentsChildren)
@@ -42,12 +42,12 @@ export class AbsencesGardeService {
role: RoleType,
opts: {
placementId?: string;
type?: TypeAbsenceGardeType;
statut?: StatutAbsenceGardeType;
type?: TypeEvenementAgendaType;
statut?: StatutEvenementAgendaType;
from?: string;
to?: string;
},
): Promise<ListeAbsencesGardeDto> {
): Promise<ListeEvenementsAgendaDto> {
const placementIds = await this.resolvePlacementIds(
userId,
role,
@@ -86,8 +86,8 @@ export class AbsencesGardeService {
async creer(
userId: string,
role: RoleType,
dto: CreerAbsenceGardeDto,
): Promise<AbsenceGardeDto> {
dto: CreerEvenementAgendaDto,
): Promise<EvenementAgendaDto> {
this.assertDates(dto.date_debut, dto.date_fin);
await this.assertCanAccessPlacement(userId, role, dto.id_placement);
this.assertCanCreateType(role, dto.type);
@@ -111,8 +111,8 @@ export class AbsencesGardeService {
userId: string,
role: RoleType,
id: string,
dto: MajAbsenceGardeDto,
): Promise<AbsenceGardeDto> {
dto: MajEvenementAgendaDto,
): Promise<EvenementAgendaDto> {
const row = await this.absencesRepo.findOne({ where: { id } });
if (!row) {
throw new NotFoundException('Absence introuvable');
@@ -128,15 +128,15 @@ export class AbsencesGardeService {
this.assertCanEditDates(role, row);
row.date_debut = debut;
row.date_fin = fin;
if (row.statut === StatutAbsenceGardeType.EN_ATTENTE) {
row.expire_at = this.expireAtFor(StatutAbsenceGardeType.EN_ATTENTE);
if (row.statut === StatutEvenementAgendaType.EN_ATTENTE) {
row.expire_at = this.expireAtFor(StatutEvenementAgendaType.EN_ATTENTE);
}
}
if (dto.statut !== undefined && dto.statut !== row.statut) {
this.assertCanChangeStatut(role, row, dto.statut, dto.motif);
if (
dto.statut === StatutAbsenceGardeType.REFUSE &&
dto.statut === StatutEvenementAgendaType.REFUSE &&
(!dto.motif || !dto.motif.trim())
) {
throw new BadRequestException(
@@ -169,7 +169,7 @@ export class AbsencesGardeService {
if (
role === RoleType.PARENT &&
row.type !== TypeAbsenceGardeType.ABSENCE_ENFANT
row.type !== TypeEvenementAgendaType.ABSENCE_ENFANT
) {
throw new ForbiddenException(
'Un parent ne peut supprimer que les absences enfant',
@@ -183,7 +183,7 @@ export class AbsencesGardeService {
id: string,
userId: string,
role: RoleType,
): Promise<AbsenceGardeDto> {
): Promise<EvenementAgendaDto> {
const row = await this.absencesRepo.findOne({
where: { id },
relations: ['placement', 'placement.child', 'placement.am', 'placement.am.user'],
@@ -195,19 +195,19 @@ export class AbsencesGardeService {
return this.toDto(row);
}
private statutInitial(type: TypeAbsenceGardeType): StatutAbsenceGardeType {
if (type === TypeAbsenceGardeType.ABSENCE_ENFANT) {
return StatutAbsenceGardeType.ACCEPTE;
private statutInitial(type: TypeEvenementAgendaType): StatutEvenementAgendaType {
if (type === TypeEvenementAgendaType.ABSENCE_ENFANT) {
return StatutEvenementAgendaType.ACCEPTE;
}
return StatutAbsenceGardeType.EN_ATTENTE;
return StatutEvenementAgendaType.EN_ATTENTE;
}
private expireAtFor(statut: StatutAbsenceGardeType): Date {
private expireAtFor(statut: StatutEvenementAgendaType): Date {
const now = Date.now();
if (statut === StatutAbsenceGardeType.ACCEPTE) {
if (statut === StatutEvenementAgendaType.ACCEPTE) {
return EXPIRE_ACCEPTE;
}
if (statut === StatutAbsenceGardeType.REFUSE) {
if (statut === StatutEvenementAgendaType.REFUSE) {
return new Date(now + TTL_REFUSE_MS);
}
return new Date(now + TTL_EN_ATTENTE_MS);
@@ -221,9 +221,9 @@ export class AbsencesGardeService {
}
}
private assertCanCreateType(role: RoleType, type: TypeAbsenceGardeType): void {
private assertCanCreateType(role: RoleType, type: TypeEvenementAgendaType): void {
if (role === RoleType.PARENT) {
if (type !== TypeAbsenceGardeType.ABSENCE_ENFANT) {
if (type !== TypeEvenementAgendaType.ABSENCE_ENFANT) {
throw new ForbiddenException(
'Un parent ne peut créer que des absences enfant',
);
@@ -232,8 +232,8 @@ export class AbsencesGardeService {
}
if (role === RoleType.ASSISTANTE_MATERNELLE) {
if (
type !== TypeAbsenceGardeType.CONGE_AM &&
type !== TypeAbsenceGardeType.ARRET_MALADIE_AM
type !== TypeEvenementAgendaType.CONGE_AM &&
type !== TypeEvenementAgendaType.ARRET_MALADIE_AM
) {
throw new ForbiddenException(
'Une AM ne peut créer que congé ou arrêt maladie',
@@ -246,10 +246,10 @@ export class AbsencesGardeService {
private assertCanEditDates(
role: RoleType,
row: AbsencesGarde,
row: EvenementsAgenda,
): void {
if (role === RoleType.PARENT) {
if (row.type !== TypeAbsenceGardeType.ABSENCE_ENFANT) {
if (row.type !== TypeEvenementAgendaType.ABSENCE_ENFANT) {
throw new ForbiddenException(
'Un parent ne peut modifier que les absences enfant',
);
@@ -258,13 +258,13 @@ export class AbsencesGardeService {
}
if (role === RoleType.ASSISTANTE_MATERNELLE) {
if (
row.type === TypeAbsenceGardeType.CONGE_AM ||
row.type === TypeAbsenceGardeType.ARRET_MALADIE_AM
row.type === TypeEvenementAgendaType.CONGE_AM ||
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM
) {
if (
row.statut !== StatutAbsenceGardeType.EN_ATTENTE &&
row.statut !== StatutAbsenceGardeType.REFUSE &&
row.statut !== StatutAbsenceGardeType.ACCEPTE
row.statut !== StatutEvenementAgendaType.EN_ATTENTE &&
row.statut !== StatutEvenementAgendaType.REFUSE &&
row.statut !== StatutEvenementAgendaType.ACCEPTE
) {
throw new ForbiddenException('Statut incompatible avec une modification');
}
@@ -278,31 +278,31 @@ export class AbsencesGardeService {
private assertCanChangeStatut(
role: RoleType,
row: AbsencesGarde,
next: StatutAbsenceGardeType,
row: EvenementsAgenda,
next: StatutEvenementAgendaType,
_motif?: string,
): void {
if (role === RoleType.PARENT) {
// Accept / refuse congé ; ack arrêt (accepte)
if (
row.type === TypeAbsenceGardeType.CONGE_AM ||
row.type === TypeAbsenceGardeType.ARRET_MALADIE_AM
row.type === TypeEvenementAgendaType.CONGE_AM ||
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM
) {
if (
next !== StatutAbsenceGardeType.ACCEPTE &&
next !== StatutAbsenceGardeType.REFUSE
next !== StatutEvenementAgendaType.ACCEPTE &&
next !== StatutEvenementAgendaType.REFUSE
) {
throw new BadRequestException('Transition de statut invalide');
}
if (
row.type === TypeAbsenceGardeType.ARRET_MALADIE_AM &&
next === StatutAbsenceGardeType.REFUSE
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM &&
next === StatutEvenementAgendaType.REFUSE
) {
throw new BadRequestException(
'Un arrêt maladie ne se refuse pas (accusé seulement)',
);
}
if (row.statut !== StatutAbsenceGardeType.EN_ATTENTE) {
if (row.statut !== StatutEvenementAgendaType.EN_ATTENTE) {
throw new BadRequestException('Cette demande n’est plus en attente');
}
return;
@@ -314,9 +314,9 @@ export class AbsencesGardeService {
if (role === RoleType.ASSISTANTE_MATERNELLE) {
// Remise en attente après refus OU modification d’un congé déjà accepté (S2b)
if (
next === StatutAbsenceGardeType.EN_ATTENTE &&
(row.statut === StatutAbsenceGardeType.REFUSE ||
row.statut === StatutAbsenceGardeType.ACCEPTE)
next === StatutEvenementAgendaType.EN_ATTENTE &&
(row.statut === StatutEvenementAgendaType.REFUSE ||
row.statut === StatutEvenementAgendaType.ACCEPTE)
) {
return;
}
@@ -396,7 +396,7 @@ export class AbsencesGardeService {
throw new ForbiddenException('Rôle non autorisé');
}
private toDto(row: AbsencesGarde): AbsenceGardeDto {
private toDto(row: EvenementsAgenda): EvenementAgendaDto {
const child = row.placement?.child;
const amUser = row.placement?.am?.user;
return {
@@ -0,0 +1,2 @@
export { EvenementsAgendaModule } from './evenements-agenda.module';
export { EvenementsAgendaService } from './evenements-agenda.service';
@@ -10,7 +10,10 @@ describe('AssistantesMaternellesController', () => {
const authServiceMock = {
createAmDossierStaff: jest.fn(),
};
const amServiceMock = {};
const amServiceMock = {
listerCouplesGarde: jest.fn(),
definirCoupleGardeCourant: jest.fn(),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
@@ -66,4 +69,29 @@ describe('AssistantesMaternellesController', () => {
);
expect(res.numero_dossier).toBe('2026-000001');
});
it('listerCouplesGarde délègue au service (#171)', async () => {
amServiceMock.listerCouplesGarde.mockResolvedValue({
couples: [],
couple_courant_id: null,
});
const res = await controller.listerCouplesGarde('am-uuid');
expect(amServiceMock.listerCouplesGarde).toHaveBeenCalledWith('am-uuid');
expect(res.couple_courant_id).toBeNull();
});
it('definirCoupleGardeCourant délègue au service (#171)', async () => {
amServiceMock.definirCoupleGardeCourant.mockResolvedValue({
couples: [{ id: 'pl-1', courant: true }],
couple_courant_id: 'pl-1',
});
const res = await controller.definirCoupleGardeCourant('am-uuid', {
couple_id: 'pl-1',
});
expect(amServiceMock.definirCoupleGardeCourant).toHaveBeenCalledWith(
'am-uuid',
'pl-1',
);
expect(res.couple_courant_id).toBe('pl-1');
});
});
@@ -2,6 +2,7 @@ import {
Controller,
Get,
Post,
Put,
Body,
Patch,
Param,
@@ -20,6 +21,8 @@ import { UpdateAssistanteDto } from '../user/dto/update_assistante.dto';
import { UpdateAmFicheAdminDto } from './dto/update-am-fiche-admin.dto';
import { StaffCreateAmDossierDto } from './dto/staff-create-am-dossier.dto';
import { StaffCreateAmDossierResponseDto } from './dto/staff-create-am-dossier-response.dto';
import { CouplesGardeAmResponseDto } from './dto/couples-garde-am.dto';
import { DefinirCoupleGardeCourantAmDto } from './dto/definir-couple-garde-courant-am.dto';
import { RolesGuard } from 'src/common/guards/roles.guard';
import { AuthGuard } from 'src/common/guards/auth.guard';
import { User } from 'src/common/decorators/user.decorator';
@@ -83,6 +86,36 @@ export class AssistantesMaternellesController {
return mapAmsForApi(ams);
}
@Get('me/couples-garde')
@Roles(RoleType.ASSISTANTE_MATERNELLE)
@ApiOperation({
summary: 'Couples de garde de l’AM connectée — ticket #171',
description:
'Placements actifs (enfant + parents) pour peupler le bandeau couple TdB AM, ' +
'avec indication du couple courant.',
})
@ApiResponse({ status: 200, type: CouplesGardeAmResponseDto })
listerCouplesGarde(
@User('id') userId: string,
): Promise<CouplesGardeAmResponseDto> {
return this.assistantesMaternellesService.listerCouplesGarde(userId);
}
@Put('me/couples-garde/courant')
@Roles(RoleType.ASSISTANTE_MATERNELLE)
@ApiOperation({ summary: 'Définir le couple de garde courant (AM) — ticket #171' })
@ApiBody({ type: DefinirCoupleGardeCourantAmDto })
@ApiResponse({ status: 200, type: CouplesGardeAmResponseDto })
definirCoupleGardeCourant(
@User('id') userId: string,
@Body() dto: DefinirCoupleGardeCourantAmDto,
): Promise<CouplesGardeAmResponseDto> {
return this.assistantesMaternellesService.definirCoupleGardeCourant(
userId,
dto.couple_id,
);
}
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
@Get(':id')
@ApiParam({ name: 'id', description: "UUID de la nounou" })
@@ -4,13 +4,21 @@ import { AssistantesMaternellesController } from './assistantes_maternelles.cont
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
import { AmChildren } from 'src/entities/am_children.entity';
import { Children } from 'src/entities/children.entity';
import { ParentsChildren } from 'src/entities/parents_children.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Users } from 'src/entities/users.entity';
import { AuthModule } from '../auth/auth.module';
@Module({
imports: [TypeOrmModule.forFeature([AssistanteMaternelle, AmChildren, Children, Users]),
AuthModule
imports: [
TypeOrmModule.forFeature([
AssistanteMaternelle,
AmChildren,
Children,
Users,
ParentsChildren,
]),
AuthModule,
],
controllers: [AssistantesMaternellesController],
providers: [AssistantesMaternellesService],
@@ -19,4 +27,4 @@ import { AuthModule } from '../auth/auth.module';
TypeOrmModule,
],
})
export class AssistantesMaternellesModule { }
export class AssistantesMaternellesModule {}
@@ -1,18 +1,150 @@
import { NotFoundException } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
import { Users } from 'src/entities/users.entity';
import { AmChildren } from 'src/entities/am_children.entity';
import { Children } from 'src/entities/children.entity';
import { ParentsChildren } from 'src/entities/parents_children.entity';
describe('AssistantesMaternellesService', () => {
describe('AssistantesMaternellesService — couples de garde (#171)', () => {
let service: AssistantesMaternellesService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AssistantesMaternellesService],
}).compile();
const amRepo = { findOne: jest.fn(), update: jest.fn() };
const usersRepo = {};
const amChildrenRepo = { find: jest.fn(), findOne: jest.fn() };
const childrenRepo = {};
const parentsChildrenRepo = { find: jest.fn() };
service = module.get<AssistantesMaternellesService>(AssistantesMaternellesService);
beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
providers: [
AssistantesMaternellesService,
{ provide: getRepositoryToken(AssistanteMaternelle), useValue: amRepo },
{ provide: getRepositoryToken(Users), useValue: usersRepo },
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo },
{ provide: getRepositoryToken(Children), useValue: childrenRepo },
{
provide: getRepositoryToken(ParentsChildren),
useValue: parentsChildrenRepo,
},
],
}).compile();
service = module.get(AssistantesMaternellesService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('listerCouplesGarde', () => {
it('retourne vide si aucun placement', async () => {
amRepo.findOne.mockResolvedValue({
user_id: 'am-1',
id_placement_garde_courant: null,
});
amChildrenRepo.find.mockResolvedValue([]);
const res = await service.listerCouplesGarde('am-1');
expect(res).toEqual({ couples: [], couple_courant_id: null });
expect(parentsChildrenRepo.find).not.toHaveBeenCalled();
});
it('mappe placements + parents et marque le courant', async () => {
amRepo.findOne.mockResolvedValue({
user_id: 'am-1',
id_placement_garde_courant: 'pl-2',
});
amChildrenRepo.find.mockResolvedValue([
{
id: 'pl-1',
enfantId: 'e1',
child: { id: 'e1', first_name: 'Léa', last_name: 'M', photo_url: null },
},
{
id: 'pl-2',
enfantId: 'e2',
child: { id: 'e2', first_name: 'Emma', last_name: 'M', photo_url: null },
},
]);
parentsChildrenRepo.find.mockResolvedValue([
{
parentId: 'p1',
enfantId: 'e1',
parent: { user: { prenom: 'Claire', nom: 'Martin', photo_url: null } },
},
{
parentId: 'p2',
enfantId: 'e1',
parent: { user: { prenom: 'Thomas', nom: 'Martin', photo_url: null } },
},
{
parentId: 'p1',
enfantId: 'e2',
parent: { user: { prenom: 'Claire', nom: 'Martin', photo_url: null } },
},
]);
const res = await service.listerCouplesGarde('am-1');
expect(res.couples).toHaveLength(2);
expect(res.couple_courant_id).toBe('pl-2');
expect(res.couples[1].courant).toBe(true);
expect(res.couples[0].parents).toHaveLength(2);
expect(res.couples[0].parents[0].prenom).toBe('Claire');
expect(res.couples[0].enfant.prenom).toBe('Léa');
});
it('404 si AM inconnue', async () => {
amRepo.findOne.mockResolvedValue(null);
await expect(service.listerCouplesGarde('x')).rejects.toBeInstanceOf(
NotFoundException,
);
});
});
describe('definirCoupleGardeCourant', () => {
it('persiste si le placement appartient à l’AM', async () => {
amRepo.findOne.mockResolvedValue({
user_id: 'am-1',
id_placement_garde_courant: null,
});
amChildrenRepo.findOne.mockResolvedValue({
id: 'pl-1',
amId: 'am-1',
enfantId: 'e1',
});
amRepo.update.mockResolvedValue({ affected: 1 });
amChildrenRepo.find.mockResolvedValue([
{
id: 'pl-1',
enfantId: 'e1',
child: { id: 'e1', first_name: 'Léa', last_name: null, photo_url: null },
},
]);
parentsChildrenRepo.find.mockResolvedValue([
{
parentId: 'p1',
enfantId: 'e1',
parent: { user: { prenom: 'Claire', nom: 'M', photo_url: null } },
},
]);
const res = await service.definirCoupleGardeCourant('am-1', 'pl-1');
expect(amRepo.update).toHaveBeenCalledWith(
{ user_id: 'am-1' },
{ id_placement_garde_courant: 'pl-1' },
);
expect(res.couple_courant_id).toBe('pl-1');
expect(res.couples[0].courant).toBe(true);
});
it('404 si placement d’une autre AM', async () => {
amRepo.findOne.mockResolvedValue({ user_id: 'am-1' });
amChildrenRepo.findOne.mockResolvedValue(null);
await expect(
service.definirCoupleGardeCourant('am-1', 'pl-x'),
).rejects.toBeInstanceOf(NotFoundException);
});
});
});
@@ -5,14 +5,16 @@ import {
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { IsNull, Repository } from 'typeorm';
import { In, IsNull, Repository } from 'typeorm';
import { RoleType, Users } from 'src/entities/users.entity';
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
import { AmChildren } from 'src/entities/am_children.entity';
import { Children, StatutEnfantType } from 'src/entities/children.entity';
import { ParentsChildren } from 'src/entities/parents_children.entity';
import { CreateAssistanteDto } from '../user/dto/create_assistante.dto';
import { UpdateAssistanteDto } from '../user/dto/update_assistante.dto';
import { UpdateAmFicheAdminDto } from './dto/update-am-fiche-admin.dto';
import { CouplesGardeAmResponseDto } from './dto/couples-garde-am.dto';
import { validateNir } from 'src/common/utils/nir.util';
const AM_CHILDREN_RELATIONS = ['user', 'amChildren', 'amChildren.child'] as const;
@@ -28,6 +30,8 @@ export class AssistantesMaternellesService {
private readonly amChildrenRepository: Repository<AmChildren>,
@InjectRepository(Children)
private readonly childrenRepository: Repository<Children>,
@InjectRepository(ParentsChildren)
private readonly parentsChildrenRepository: Repository<ParentsChildren>,
) {}
async create(dto: CreateAssistanteDto): Promise<AssistanteMaternelle> {
@@ -264,4 +268,107 @@ export class AssistantesMaternellesService {
await this.assistantesMaternelleRepository.delete(id);
return { message: 'Assistante maternelle supprimée' };
}
/**
* Liste les couples de garde (enfant ↔ parents) de l’AM connectée — ticket #171.
* Un couple = un placement actif dans enfants_assistantes_maternelles pour cette AM.
*/
async listerCouplesGarde(amUserId: string): Promise<CouplesGardeAmResponseDto> {
const am = await this.assistantesMaternelleRepository.findOne({
where: { user_id: amUserId },
});
if (!am) {
throw new NotFoundException('Assistante maternelle introuvable');
}
const placements = await this.amChildrenRepository.find({
where: { amId: amUserId, date_fin: IsNull() },
relations: ['child'],
order: { date_debut: 'ASC' },
});
if (placements.length === 0) {
return { couples: [], couple_courant_id: null };
}
const enfantIds = placements.map((p) => p.enfantId);
const liens = await this.parentsChildrenRepository.find({
where: { enfantId: In(enfantIds) },
relations: ['parent', 'parent.user'],
});
const parentsByEnfant = new Map<
string,
{ id: string; prenom: string | null; nom: string | null; photo_url: string | null }[]
>();
for (const l of liens) {
const list = parentsByEnfant.get(l.enfantId) ?? [];
const u = l.parent?.user;
list.push({
id: l.parentId,
prenom: u?.prenom ?? null,
nom: u?.nom ?? null,
photo_url: u?.photo_url ?? null,
});
parentsByEnfant.set(l.enfantId, list);
}
let idCourant = am.id_placement_garde_courant ?? null;
const idsValides = new Set(placements.map((p) => p.id));
if (idCourant && !idsValides.has(idCourant)) {
idCourant = null;
await this.assistantesMaternelleRepository.update(
{ user_id: amUserId },
{ id_placement_garde_courant: () => 'NULL' },
);
}
if (!idCourant && placements.length === 1) {
idCourant = placements[0].id;
}
const couples = placements.map((p) => ({
id: p.id,
enfant: {
id: p.child.id,
prenom: p.child.first_name ?? null,
nom: p.child.last_name ?? null,
photo_url: p.child.photo_url ?? null,
},
parents: parentsByEnfant.get(p.enfantId) ?? [],
courant: idCourant != null && p.id === idCourant,
}));
return {
couples,
couple_courant_id: idCourant,
};
}
/**
* Persiste le couple de garde actif pour l’AM — ticket #171.
*/
async definirCoupleGardeCourant(
amUserId: string,
coupleId: string,
): Promise<CouplesGardeAmResponseDto> {
const am = await this.assistantesMaternelleRepository.findOne({
where: { user_id: amUserId },
});
if (!am) {
throw new NotFoundException('Assistante maternelle introuvable');
}
const placement = await this.amChildrenRepository.findOne({
where: { id: coupleId, amId: amUserId, date_fin: IsNull() },
});
if (!placement) {
throw new NotFoundException('Couple de garde introuvable ou inactif pour cette AM');
}
await this.assistantesMaternelleRepository.update(
{ user_id: amUserId },
{ id_placement_garde_courant: coupleId },
);
return this.listerCouplesGarde(amUserId);
}
}
@@ -0,0 +1,67 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
/** Identité minimale enfant — ticket #171 (miroir #168) */
export class CoupleGardeAmEnfantDto {
@ApiProperty({ format: 'uuid' })
id: string;
@ApiPropertyOptional()
prenom?: string | null;
@ApiPropertyOptional()
nom?: string | null;
@ApiPropertyOptional()
photo_url?: string | null;
}
/** Identité minimale parent pour bandeau AM — ticket #171 */
export class CoupleGardeAmParentDto {
@ApiProperty({ format: 'uuid', description: 'UUID utilisateur du parent' })
id: string;
@ApiPropertyOptional()
prenom?: string | null;
@ApiPropertyOptional()
nom?: string | null;
@ApiPropertyOptional()
photo_url?: string | null;
}
/**
* Un couple côté AM = placement actif enfant ↔ foyer parents.
* `id` = enfants_assistantes_maternelles.id (même clé que #168).
*/
export class CoupleGardeAmDto {
@ApiProperty({
format: 'uuid',
description: 'Id du placement (enfants_assistantes_maternelles.id)',
})
id: string;
@ApiProperty({ type: CoupleGardeAmEnfantDto })
enfant: CoupleGardeAmEnfantDto;
@ApiProperty({
type: [CoupleGardeAmParentDto],
description: 'Parents rattachés à l’enfant (0–2 typiquement)',
})
parents: CoupleGardeAmParentDto[];
@ApiProperty({ description: 'True si c’est le couple actuellement sélectionné' })
courant: boolean;
}
export class CouplesGardeAmResponseDto {
@ApiProperty({ type: [CoupleGardeAmDto] })
couples: CoupleGardeAmDto[];
@ApiPropertyOptional({
format: 'uuid',
nullable: true,
description: 'Id du couple courant (null si aucun)',
})
couple_courant_id: string | null;
}
@@ -0,0 +1,13 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsUUID } from 'class-validator';
/** Corps PUT couple de garde courant AM — ticket #171 */
export class DefinirCoupleGardeCourantAmDto {
@ApiProperty({
format: 'uuid',
description: 'Id du placement (enfants_assistantes_maternelles.id) à sélectionner',
})
@IsUUID()
@IsNotEmpty()
couple_id: string;
}
+29 -16
View File
@@ -35,13 +35,13 @@ DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_avenant_type') THEN
CREATE TYPE statut_avenant_type AS ENUM ('propose', 'accepte', 'refuse');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_absence_garde_type') THEN
CREATE TYPE type_absence_garde_type AS ENUM (
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_evenement_agenda_type') THEN
CREATE TYPE type_evenement_agenda_type AS ENUM (
'absence_enfant', 'conge_am', 'arret_maladie_am'
);
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_absence_garde_type') THEN
CREATE TYPE statut_absence_garde_type AS ENUM (
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_evenement_agenda_type') THEN
CREATE TYPE statut_evenement_agenda_type AS ENUM (
'en_attente', 'accepte', 'refuse'
);
END IF;
@@ -143,7 +143,10 @@ CREATE TABLE assistantes_maternelles (
annee_experience SMALLINT,
specialite VARCHAR(100),
place_disponible INT,
numero_dossier VARCHAR(20)
numero_dossier VARCHAR(20),
-- Préférence couple de garde actif (TdB quotidien AM) — ticket #171
-- FK ajoutée après création de enfants_assistantes_maternelles (voir ALTER plus bas)
id_placement_garde_courant UUID
);
CREATE INDEX idx_assistantes_maternelles_numero_dossier
@@ -221,6 +224,16 @@ CREATE INDEX idx_parents_placement_garde_courant
ON parents(id_placement_garde_courant)
WHERE id_placement_garde_courant IS NOT NULL;
-- FK couple courant AM → placement (#171)
ALTER TABLE assistantes_maternelles
ADD CONSTRAINT fk_am_placement_garde_courant
FOREIGN KEY (id_placement_garde_courant)
REFERENCES enfants_assistantes_maternelles(id) ON DELETE SET NULL;
CREATE INDEX idx_am_placement_garde_courant
ON assistantes_maternelles(id_placement_garde_courant)
WHERE id_placement_garde_courant IS NOT NULL;
-- ==========================================================
-- Table : dossier_famille (inscription parent — ticket #119)
-- ==========================================================
@@ -309,32 +322,32 @@ CREATE TABLE avenants_contrats (
);
-- ==========================================================
-- Table : absences_garde (vérité métier absences/congés/arrêt)
-- Table : evenements_agenda (vérité métier agenda (absences/congés/arrêt + futurs types))
-- 1 ligne = 1 période ; rattachement = placement AM↔enfant (#193)
-- ==========================================================
CREATE TABLE absences_garde (
CREATE TABLE evenements_agenda (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
id_placement UUID NOT NULL
REFERENCES enfants_assistantes_maternelles(id) ON DELETE CASCADE,
type type_absence_garde_type NOT NULL,
type type_evenement_agenda_type NOT NULL,
date_debut DATE NOT NULL,
date_fin DATE NOT NULL,
statut statut_absence_garde_type NOT NULL DEFAULT 'en_attente',
statut statut_evenement_agenda_type NOT NULL DEFAULT 'en_attente',
expire_at TIMESTAMPTZ NOT NULL,
cree_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
id_card_instance UUID,
motif TEXT,
cree_le TIMESTAMPTZ NOT NULL DEFAULT now(),
modifie_le TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT chk_absences_garde_dates CHECK (date_fin >= date_debut)
CONSTRAINT chk_evenements_agenda_dates CHECK (date_fin >= date_debut)
);
CREATE INDEX idx_absences_garde_placement_dates
ON absences_garde (id_placement, date_debut, date_fin);
CREATE INDEX idx_absences_garde_placement_type_statut
ON absences_garde (id_placement, type, statut);
CREATE INDEX idx_absences_garde_expire_at
ON absences_garde (expire_at)
CREATE INDEX idx_evenements_agenda_placement_dates
ON evenements_agenda (id_placement, date_debut, date_fin);
CREATE INDEX idx_evenements_agenda_placement_type_statut
ON evenements_agenda (id_placement, type, statut);
CREATE INDEX idx_evenements_agenda_expire_at
ON evenements_agenda (expire_at)
WHERE statut IN ('en_attente', 'refuse');
-- ==========================================================
+3 -3
View File
@@ -106,7 +106,7 @@ Ce document recense **toutes les valeurs énumérées** utilisées dans la base
## 7) Type d’absence de garde — `type`
**Tables/colonnes** : `absences_garde.type`
**Tables/colonnes** : `evenements_agenda.type`
**Valeurs autorisées** :
| Valeur | Description |
@@ -115,13 +115,13 @@ Ce document recense **toutes les valeurs énumérées** utilisées dans la base
| `conge_am` | Congé de l’assistante maternelle |
| `arret_maladie_am` | Arrêt maladie AM |
> Remplace l’ancien enum `type_evenement_type` / table `evenements` (supprimés ticket #193).
> Remplace l’ancien enum `type_evenement_type` / table `evenements` (supprimés ticket #205 / ex-#193).
---
## 8) Statut d’absence de garde — `statut`
**Tables/colonnes** : `absences_garde.statut`
**Tables/colonnes** : `evenements_agenda.statut`
**Valeurs autorisées** :
| Valeur | Description |
+5 -5
View File
@@ -42,8 +42,8 @@ Documenter, de façon unique et partagée, les règles de suppression/mise à jo
| **contrats(id_dossier)** → `dossiers(id)` | **CASCADE** | 1:1, contrat détruit si dossier supprimé |
| **avenants_contrats(id_contrat)** → `contrats(id)` | **CASCADE** | Avenants détruits avec le contrat |
| **avenants_contrats(initie_par)** → `utilisateurs(id)` | **SET NULL** | Historiser l’avenant sans bloquer |
| **absences_garde(id_placement)** → `enfants_assistantes_maternelles(id)` | **CASCADE** | Plus de couple = plus d’absences |
| **absences_garde(cree_par)** → `utilisateurs(id)` | **SET NULL** | Conserver la période si user supprimé |
| **evenements_agenda(id_placement)** → `enfants_assistantes_maternelles(id)` | **CASCADE** | Plus de couple = plus d’absences |
| **evenements_agenda(cree_par)** → `utilisateurs(id)` | **SET NULL** | Conserver la période si user supprimé |
| **signalements_bugs(id_utilisateur)** → `utilisateurs(id)` | **SET NULL** | Conserver le ticket même si compte supprimé |
| **uploads(id_utilisateur)** → `utilisateurs(id)` | **SET NULL** | Fichier reste référencé sans l’auteur |
| **notifications(id_utilisateur)** → `utilisateurs(id)` | **CASCADE** | Notifications propres à l’utilisateur |
@@ -77,8 +77,8 @@ Documenter, de façon unique et partagée, les règles de suppression/mise à jo
- `avenants_contrats.initie_par` → **SET NULL**
### Événements
- `absences_garde.id_placement` → **CASCADE**
- `absences_garde.cree_par` → **SET NULL**
- `evenements_agenda.id_placement` → **CASCADE**
- `evenements_agenda.cree_par` → **SET NULL**
### Divers
- `signalements_bugs.id_utilisateur` → **SET NULL**
@@ -105,7 +105,7 @@ Documenter, de façon unique et partagée, les règles de suppression/mise à jo
4. **Suppression d’un enfant**
- Supprimer `enfants(id=childA)`
- Attendu : `enfants_parents` (CASCADE), `dossiers` du childA (CASCADE), `absences_garde` des placements du childA (CASCADE via EAM).
- Attendu : `enfants_parents` (CASCADE), `dossiers` du childA (CASCADE), `evenements_agenda` des placements du childA (CASCADE via EAM).
5. **Suppression d’un utilisateur AM**
- Supprimer `utilisateurs(id=amB)`
@@ -0,0 +1,10 @@
-- Ticket #171 — Couple de garde courant (préférence AM)
-- Idempotent : safe à rejouer.
ALTER TABLE assistantes_maternelles
ADD COLUMN IF NOT EXISTS id_placement_garde_courant UUID
REFERENCES enfants_assistantes_maternelles(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_am_placement_garde_courant
ON assistantes_maternelles(id_placement_garde_courant)
WHERE id_placement_garde_courant IS NOT NULL;
@@ -0,0 +1,106 @@
-- Ticket #205 — Renommer absences_garde → evenements_agenda
-- Migration base live. Idempotent autant que possible.
-- ---------------------------------------------------------------------------
-- 1. Table + enums
-- ---------------------------------------------------------------------------
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'absences_garde')
AND NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'evenements_agenda') THEN
ALTER TABLE absences_garde RENAME TO evenements_agenda;
END IF;
END $$;
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_absence_garde_type')
AND NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_evenement_agenda_type') THEN
ALTER TYPE type_absence_garde_type RENAME TO type_evenement_agenda_type;
END IF;
IF EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_absence_garde_type')
AND NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_evenement_agenda_type') THEN
ALTER TYPE statut_absence_garde_type RENAME TO statut_evenement_agenda_type;
END IF;
END $$;
-- Contraintes / index (noms)
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'chk_absences_garde_dates') THEN
ALTER TABLE evenements_agenda RENAME CONSTRAINT chk_absences_garde_dates TO chk_evenements_agenda_dates;
END IF;
END $$;
ALTER INDEX IF EXISTS idx_absences_garde_placement_dates
RENAME TO idx_evenements_agenda_placement_dates;
ALTER INDEX IF EXISTS idx_absences_garde_placement_type_statut
RENAME TO idx_evenements_agenda_placement_type_statut;
ALTER INDEX IF EXISTS idx_absences_garde_expire_at
RENAME TO idx_evenements_agenda_expire_at;
ALTER INDEX IF EXISTS absences_garde_pkey
RENAME TO evenements_agenda_pkey;
COMMENT ON TABLE evenements_agenda IS
'Vérité métier agenda (absences, congés, arrêts, futurs soins/école/mairie/sorties…) par placement. Les cartes collectent ; cette table historise.';
COMMENT ON COLUMN evenements_agenda.expire_at IS
'Purge auto (job) pour en_attente/refuse. accepte → infinity.';
COMMENT ON COLUMN evenements_agenda.id_card_instance IS
'Réf. carte de collecte (module Cartes).';
-- ---------------------------------------------------------------------------
-- 2. card_instances.id_absence → id_evenement
-- ---------------------------------------------------------------------------
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'card_instances' AND column_name = 'id_absence'
) AND NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'card_instances' AND column_name = 'id_evenement'
) THEN
ALTER TABLE card_instances RENAME COLUMN id_absence TO id_evenement;
END IF;
END $$;
-- Recréer index si ancien nom
ALTER INDEX IF EXISTS idx_card_instances_absence
RENAME TO idx_card_instances_evenement;
-- FK : drop ancienne (nom variable) puis recreate
DO $$
DECLARE
fk_name text;
BEGIN
SELECT conname INTO fk_name
FROM pg_constraint
WHERE conrelid = 'card_instances'::regclass
AND contype = 'f'
AND pg_get_constraintdef(oid) ILIKE '%id_evenement%'
LIMIT 1;
IF fk_name IS NULL THEN
SELECT conname INTO fk_name
FROM pg_constraint
WHERE conrelid = 'card_instances'::regclass
AND contype = 'f'
AND pg_get_constraintdef(oid) ILIKE '%id_absence%'
LIMIT 1;
END IF;
IF fk_name IS NOT NULL THEN
EXECUTE format('ALTER TABLE card_instances DROP CONSTRAINT %I', fk_name);
END IF;
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'card_instances_id_evenement_fkey'
) THEN
ALTER TABLE card_instances
ADD CONSTRAINT card_instances_id_evenement_fkey
FOREIGN KEY (id_evenement)
REFERENCES evenements_agenda(id)
ON DELETE SET NULL;
END IF;
END $$;
+5 -5
View File
@@ -81,7 +81,7 @@ ORDER BY c.cree_le DESC;
\echo '=== 9) Absences_garde (30 derniers jours) ====================='
SELECT ag.id, ag.type, ag.id_placement, ag.date_debut, ag.date_fin, ag.statut, ag.expire_at
FROM absences_garde ag
FROM evenements_agenda ag
WHERE ag.date_debut >= (NOW()::date - INTERVAL '30 days')
ORDER BY ag.date_debut DESC;
@@ -136,7 +136,7 @@ WHERE c.id IS NULL;
-- Absences sans placement
SELECT ag.*
FROM absences_garde ag
FROM evenements_agenda ag
LEFT JOIN enfants_assistantes_maternelles eam ON eam.id = ag.id_placement
WHERE eam.id IS NULL;
@@ -150,10 +150,10 @@ WHERE m.id_dossier = 'dddddddd-dddd-dddd-dddd-dddddddddddd'
ORDER BY m.cree_le DESC
LIMIT 20;
-- Absences par placement et période (idx_absences_garde_placement_dates)
-- Absences par placement et période (idx_evenements_agenda_placement_dates)
EXPLAIN ANALYZE
SELECT ag.*
FROM absences_garde ag
FROM evenements_agenda ag
WHERE ag.id_placement IS NOT NULL
AND ag.date_debut >= '2025-01-01';
@@ -198,7 +198,7 @@ SELECT
(SELECT COUNT(*) FROM messages) AS nb_messages,
(SELECT COUNT(*) FROM contrats) AS nb_contrats,
(SELECT COUNT(*) FROM avenants_contrats) AS nb_avenants,
(SELECT COUNT(*) FROM absences_garde) AS nb_absences_garde,
(SELECT COUNT(*) FROM evenements_agenda) AS nb_evenements_agenda,
(SELECT COUNT(*) FROM uploads) AS nb_uploads,
(SELECT COUNT(*) FROM notifications) AS nb_notifications,
(SELECT COUNT(*) FROM validations) AS nb_validations;
+2 -2
View File
@@ -572,7 +572,7 @@ POST /repos/jmartin/petitspas/pulls/{index}/merge
### 32. Module Absences + Cartes (séparation back / collecte)
**Décision** : ✅ **Back `absences_garde` = vérité métier** ; **Cartes = file d’attention / collecte** (plugin isolé). Types SYSTEM (absence, congé, arrêt) indéboulonnables ; types OPTIONNELS (sondages…) plus tard. Annulation = DELETE. `expire_at` dès V1.
**Décision** : ✅ **Back `evenements_agenda` = vérité métier** ; **Cartes = file d’attention / collecte** (plugin isolé). Types SYSTEM (absence, congé, arrêt) indéboulonnables ; types OPTIONNELS (sondages…) plus tard. Annulation = DELETE. `expire_at` dès V1.
**Justification** :
- Premier vrai module d’interaction multi-acteurs
@@ -615,7 +615,7 @@ POST /repos/jmartin/petitspas/pulls/{index}/merge
| 25/11/2025 | 1.0 | Création du document - Toutes les décisions initiales |
| 09/02/2026 | 1.1 | Configuration initiale : un seul panneau Paramètres (3 sections) dans le dashboard, plus de Setup Wizard dédié ; navigation bloquée jusqu'à sauvegarde |
| 16/06/2026 | 1.2 | Décision 5bis — familles recomposées, contournement v1.0.0 ; lien doc [28](./28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md) |
| 24/09/2026 | 1.4 | Décision 32 — Absences (`absences_garde`) ≠ Cartes ; Epic C recentré ; drop `evenements` |
| 24/09/2026 | 1.4 | Décision 32 — Absences (`evenements_agenda`) ≠ Cartes ; Epic C recentré ; drop `evenements` |
---
+2 -2
View File
@@ -98,13 +98,13 @@ Liste des enfants / foyers pour l’AM + contexte courant (symétrique A3).
## Epic C — Absences + Cartes (file d’attention)
**Séparation :** back **`absences_garde`** = vérité métier (périodes / placement) ; module **Cartes** = collecte / bulles / workflow. Annulation = DELETE. `expire_at` dès le modèle.
**Séparation :** back **`evenements_agenda`** = vérité métier (périodes / placement) ; module **Cartes** = collecte / bulles / workflow. Annulation = DELETE. `expire_at` dès le modèle.
### Back (ordre)
| Étape | Contenu |
|-------|---------|
| BDD | Table `absences_garde` + drop `evenements` |
| BDD | Table `evenements_agenda` + drop `evenements` |
| API | CRUD + **GET liste** (`placementId` \| tous les placements du user) |
| Cartes SYSTEM | Module `cards/` types S1–S3 (sans sondages V1) |
| Realtime | WS/SSE bulles → **SSE** `GET /cards/stream` (#195) |
+1 -1
View File
@@ -72,7 +72,7 @@ Bandeau : **TdB** · **Agenda** · **Contrat** · menu user (recherche AM, param
| Maladie AM | AM | Parent **ack** (« bien reçu ») ; **aucun** doc médical |
| Sortie / sondage | — | **Plus tard** (types optionnels) |
**Stockage :** table `absences_garde` (1 ligne = période, `id_placement`, `expire_at`). Les **cartes** collectent ; elles ne sont pas la source de vérité. Annulation = DELETE.
**Stockage :** table `evenements_agenda` (1 ligne = période, `id_placement`, `expire_at`). Les **cartes** collectent ; elles ne sont pas la source de vérité. Annulation = DELETE.
**Péremption cartes :** mémoire courte (`retention_days` / `purge_at`) — pas un historique de vie (≠ messagerie).
+14 -5
View File
@@ -39,13 +39,15 @@ class CoupleMembre {
class CoupleGarde {
final String id;
final CoupleMembre enfant;
final CoupleMembre am;
final CoupleMembre? am;
final List<CoupleMembre> parents;
final bool courant;
const CoupleGarde({
required this.id,
required this.enfant,
required this.am,
this.am,
this.parents = const [],
this.courant = false,
});
@@ -55,9 +57,15 @@ class CoupleGarde {
enfant: CoupleMembre.fromJson(
Map<String, dynamic>.from(json['enfant'] ?? const {}),
),
am: CoupleMembre.fromJson(
Map<String, dynamic>.from(json['am'] ?? const {}),
),
am: json['am'] != null
? CoupleMembre.fromJson(Map<String, dynamic>.from(json['am']))
: null,
parents: json['parents'] != null
? (json['parents'] as List)
.whereType<Map>()
.map((e) => CoupleMembre.fromJson(Map<String, dynamic>.from(e)))
.toList()
: const [],
courant: json['courant'] == true,
);
}
@@ -67,6 +75,7 @@ class CoupleGarde {
id: id,
enfant: enfant,
am: am,
parents: parents,
courant: courant ?? this.courant,
);
}
@@ -45,9 +45,7 @@ class _AmDashboardScreenState extends State<AmDashboardScreen> {
_couplesError = null;
});
try {
// TODO: Pour l'instant on utilise le service générique de test (CoupleGardeService.getCouplesGarde).
// Dans le futur, l'API pour l'AM (enfants_accueillis) fournira la vraie liste.
final res = await CoupleGardeService.getCouplesGarde();
final res = await CoupleGardeService.getAmCouplesGarde();
if (!mounted) return;
setState(() {
_couples = res.couples;
@@ -67,7 +65,7 @@ class _AmDashboardScreenState extends State<AmDashboardScreen> {
if (couple.id == _selectedCoupleId) return;
setState(() => _selectedCoupleId = couple.id);
try {
final res = await CoupleGardeService.definirCoupleCourant(couple.id);
final res = await CoupleGardeService.definirAmCoupleCourant(couple.id);
if (!mounted) return;
setState(() {
_couples = res.couples;
@@ -10,7 +10,7 @@ class AbsencesGardeService {
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
final uri = Uri.parse(ApiConfig.baseUrl +
'/absences-garde' +
'/evenements-agenda' +
(placementId != null ? '?placementId=$placementId' : ''));
final res = await http.get(uri, headers: headers);
@@ -33,7 +33,7 @@ class AbsencesGardeService {
final token = await TokenService.getToken();
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
final uri = Uri.parse('${ApiConfig.baseUrl}/absences-garde');
final uri = Uri.parse('${ApiConfig.baseUrl}/evenements-agenda');
final res = await http.post(
uri,
headers: headers,
@@ -62,7 +62,7 @@ class AbsencesGardeService {
final token = await TokenService.getToken();
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
final uri = Uri.parse('${ApiConfig.baseUrl}/absences-garde/$id');
final uri = Uri.parse('${ApiConfig.baseUrl}/evenements-agenda/$id');
final Map<String, dynamic> body = {};
if (dateDebut != null) body['date_debut'] = dateDebut;
if (dateFin != null) body['date_fin'] = dateFin;
@@ -85,7 +85,7 @@ class AbsencesGardeService {
final token = await TokenService.getToken();
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
final uri = Uri.parse('${ApiConfig.baseUrl}/absences-garde/$id');
final uri = Uri.parse('${ApiConfig.baseUrl}/evenements-agenda/$id');
final res = await http.delete(uri, headers: headers);
if (res.statusCode != 204) {
throw Exception("Erreur de suppression d'absence : ${res.statusCode}");
+5 -1
View File
@@ -67,7 +67,11 @@ class ApiConfig {
static const String parentsCoupleGardeCourant =
'/parents/me/couples-garde/courant';
static const String assistantesMaternelles = '/assistantes-maternelles';
/// Création dossier AM actif par le staff (#156) — body type register AM.
/// Couples de garde de l'AM connectée (#170 / #171).
static const String assistantesMaternellesCouplesGarde =
'/assistantes-maternelles/me/couples-garde';
static const String assistantesMaternellesCoupleGardeCourant =
'/assistantes-maternelles/me/couples-garde/courant';
static const String assistantesMaternellesDossier =
'/assistantes-maternelles/dossier';
static const String enfants = '/enfants';
@@ -73,4 +73,45 @@ class CoupleGardeService {
Map<String, dynamic>.from(decoded as Map),
);
}
/// Liste les couples de garde et le couple courant de l'AM connectée.
static Future<CouplesGardeResponse> getAmCouplesGarde() async {
final response = await http.get(
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.assistantesMaternellesCouplesGarde}'),
headers: await _headers(),
);
if (response.statusCode != 200) {
throw Exception(
_extractError(response.body, 'Erreur chargement des couples de garde (AM)'),
);
}
final decoded = jsonDecode(response.body);
return CouplesGardeResponse.fromJson(
Map<String, dynamic>.from(decoded as Map),
);
}
/// Persiste le couple courant (AM) et renvoie la liste à jour.
static Future<CouplesGardeResponse> definirAmCoupleCourant(
String coupleId,
) async {
final response = await http.put(
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.assistantesMaternellesCoupleGardeCourant}'),
headers: await _headers(),
body: jsonEncode({'couple_id': coupleId}),
);
if (response.statusCode != 200) {
throw Exception(
_extractError(response.body, 'Erreur sélection du couple de garde (AM)'),
);
}
final decoded = jsonDecode(response.body);
return CouplesGardeResponse.fromJson(
Map<String, dynamic>.from(decoded as Map),
);
}
}
@@ -37,7 +37,7 @@ class CoupleSelectorBandeau extends StatelessWidget {
CoupleGarde? get _selected {
if (couples.isEmpty) return null;
if (selectedCoupleId != null) {
if (selectedCoupleId != null) {
for (final c in couples) {
if (c.id == selectedCoupleId) return c;
}
@@ -133,17 +133,46 @@ class _CoupleCard extends StatelessWidget {
required this.colorIndex,
});
/// Libellé parents côté AM : « Sophie » ou « Thomas et Claire ».
static String _parentsLabel(List<CoupleMembre> parents) {
if (parents.isEmpty) return 'Parents';
String prenomOf(CoupleMembre p) {
final prenom = (p.prenom ?? '').trim();
if (prenom.isNotEmpty) return prenom;
return p.displayName(fallback: 'Parent');
}
if (parents.length == 1) return prenomOf(parents.first);
return '${prenomOf(parents[0])} et ${prenomOf(parents[1])}';
}
@override
Widget build(BuildContext context) {
// Parent mode: enfant | AM
// AM mode: enfant | parent(s)
// Parent mode: enfant | AM (photo + prénom)
// AM mode: enfant | parent(s) — texte seul, pas de vignette parent
final isParentMode = mode == CoupleBandeauMode.parent;
final fallbackRoleIcon = isParentMode ? Icons.volunteer_activism : Icons.person_outline;
final fallbackRoleName = isParentMode ? 'Nounou' : 'Parent';
// TODO: In AM mode, we should ideally display "parent1+parent2 empilés" or centered.
// For now, CoupleGarde only gives us `am` (which in AM mode might just represent one parent, or the system needs to feed both parents here).
// Assuming backend will populate `am` field with the parent data when called by AM.
Widget amOrParentsWidget;
if (isParentMode) {
amOrParentsWidget = _MembreTile(
photoUrl: couple.am?.photoUrl,
name: (couple.am?.prenom != null && couple.am!.prenom!.isNotEmpty)
? couple.am!.prenom!
: (couple.am?.displayName(fallback: 'Nounou') ?? 'Nounou'),
fallbackIcon: Icons.volunteer_activism,
);
} else {
amOrParentsWidget = Text(
_parentsLabel(couple.parents),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: GoogleFonts.merienda(
fontSize: 22,
fontWeight: FontWeight.bold,
color: QuotidienTheme.ink,
),
);
}
return Container(
height: 90,
@@ -181,13 +210,7 @@ class _CoupleCard extends StatelessWidget {
Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 12),
child: _MembreTile(
photoUrl: couple.am.photoUrl,
name: (couple.am.prenom != null && couple.am.prenom!.isNotEmpty)
? couple.am.prenom!
: couple.am.displayName(fallback: fallbackRoleName),
fallbackIcon: fallbackRoleIcon,
),
child: amOrParentsWidget,
),
),
SizedBox(