Files
petitspas/backend/src/modules/evenements-agenda/evenements-agenda.service.ts
T
2026-10-16 14:52:13 +00:00

658 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
BadRequestException,
ForbiddenException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, IsNull, Repository } from 'typeorm';
import {
EvenementsAgenda,
StatutEvenementAgendaType,
TypeEvenementAgendaType,
} from 'src/entities/evenements_agenda.entity';
import { AgendaLotStatutType } from 'src/entities/agenda_lots.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 {
EvenementAgendaDto,
EvenementAgendaActionsDto,
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;
/** Sentinel « pas de purge » pour les périodes acceptées */
const EXPIRE_ACCEPTE = new Date('9999-12-31T23:59:59.999Z');
@Injectable()
export class EvenementsAgendaService {
constructor(
@InjectRepository(EvenementsAgenda)
private readonly absencesRepo: Repository<EvenementsAgenda>,
@InjectRepository(AmChildren)
private readonly amChildrenRepo: Repository<AmChildren>,
@InjectRepository(ParentsChildren)
private readonly parentsChildrenRepo: Repository<ParentsChildren>,
) {}
async lister(
userId: string,
role: RoleType,
opts: {
placementId?: string;
type?: TypeEvenementAgendaType;
statut?: StatutEvenementAgendaType;
from?: string;
to?: string;
},
): Promise<ListeEvenementsAgendaDto> {
this.assertDateRange(opts.from, opts.to);
// Agenda : historique inclus (placements terminés) — #217
const placementIds = await this.resolvePlacementIds(
userId,
role,
opts.placementId,
{ includeEnded: true },
);
if (placementIds.length === 0) {
return { items: [] };
}
const qb = this.absencesRepo
.createQueryBuilder('ag')
.leftJoinAndSelect('ag.placement', 'placement')
.leftJoinAndSelect('placement.child', 'child')
.leftJoinAndSelect('placement.am', 'am')
.leftJoinAndSelect('am.user', 'amUser')
.leftJoinAndSelect('ag.lot', 'lot')
.where('ag.id_placement IN (:...placementIds)', { placementIds })
.orderBy('ag.date_debut', 'DESC');
if (opts.type) {
qb.andWhere('ag.type = :type', { type: opts.type });
}
// Exclusion des annulés par défaut ; statut=annule demande explicitement les annulés
if (opts.statut) {
qb.andWhere('ag.statut = :statut', { statut: opts.statut });
} else {
qb.andWhere('ag.statut != :annule', {
annule: StatutEvenementAgendaType.ANNULE,
});
}
// Chevauchement inclusif : date_debut <= to AND date_fin >= from
if (opts.from) {
qb.andWhere('ag.date_fin >= :from', { from: opts.from });
}
if (opts.to) {
qb.andWhere('ag.date_debut <= :to', { to: opts.to });
}
const rows = await qb.getMany();
return {
items: rows.map((r) => this.toDto(r, userId, role)),
};
}
/** GET :id — #215 */
async getById(
id: string,
userId: string,
role: RoleType,
): Promise<EvenementAgendaDto> {
return this.getByIdForUser(id, userId, role);
}
async creer(
userId: string,
role: RoleType,
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);
const statut = this.statutInitial(dto.type);
const entity = this.absencesRepo.create({
id_placement: dto.id_placement,
type: dto.type,
date_debut: dto.date_debut,
date_fin: dto.date_fin,
statut,
expire_at: this.expireAtFor(statut),
cree_par: userId,
motif: dto.motif?.trim() || undefined,
});
const saved = await this.absencesRepo.save(entity);
return this.getByIdForUser(saved.id, userId, role);
}
async maj(
userId: string,
role: RoleType,
id: string,
dto: MajEvenementAgendaDto,
): Promise<EvenementAgendaDto> {
const row = await this.absencesRepo.findOne({ where: { id } });
if (!row) {
throw new NotFoundException('Absence introuvable');
}
await this.assertCanAccessPlacement(userId, role, row.id_placement);
if (dto.date_debut !== undefined || dto.date_fin !== undefined) {
const debut = dto.date_debut ?? row.date_debut;
const fin = dto.date_fin ?? row.date_fin;
this.assertDates(debut, fin);
// Parent : peut modifier ses absences enfant
// AM : peut modifier congé/arrêt en_attente (avant accept) ou dates si créateur
this.assertCanEditDates(role, row);
row.date_debut = debut;
row.date_fin = fin;
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 === StatutEvenementAgendaType.REFUSE &&
(!dto.motif || !dto.motif.trim())
) {
throw new BadRequestException(
'Une motivation est obligatoire en cas de refus',
);
}
row.statut = dto.statut;
row.expire_at = this.expireAtFor(dto.statut);
if (dto.motif?.trim()) {
row.motif = dto.motif.trim();
}
} else if (dto.motif !== undefined) {
row.motif = dto.motif.trim() || undefined;
}
await this.absencesRepo.save(row);
return this.getByIdForUser(id, userId, role);
}
async supprimer(
userId: string,
role: RoleType,
id: string,
): Promise<void> {
const row = await this.absencesRepo.findOne({ where: { id } });
if (!row) {
throw new NotFoundException('Absence introuvable');
}
await this.assertCanAccessPlacement(userId, role, row.id_placement);
if (
role === RoleType.PARENT &&
row.type !== TypeEvenementAgendaType.ABSENCE_ENFANT
) {
throw new ForbiddenException(
'Un parent ne peut supprimer que les absences enfant',
);
}
await this.absencesRepo.delete({ id });
}
private async getByIdForUser(
id: string,
userId: string,
role: RoleType,
): Promise<EvenementAgendaDto> {
const row = await this.absencesRepo.findOne({
where: { id },
relations: [
'placement',
'placement.child',
'placement.am',
'placement.am.user',
'lot',
],
});
if (!row) {
throw new NotFoundException('Événement introuvable');
}
// Lecture : historique autorisé même si placement terminé (B1 / prépare B3)
await this.assertCanAccessPlacement(userId, role, row.id_placement, {
allowEnded: true,
});
return this.toDto(row, userId, role);
}
private statutInitial(type: TypeEvenementAgendaType): StatutEvenementAgendaType {
if (type === TypeEvenementAgendaType.ABSENCE_ENFANT || type === TypeEvenementAgendaType.SOIN_ENFANT) {
return StatutEvenementAgendaType.ACCEPTE;
}
return StatutEvenementAgendaType.EN_ATTENTE;
}
private expireAtFor(statut: StatutEvenementAgendaType): Date {
const now = Date.now();
if (statut === StatutEvenementAgendaType.ACCEPTE) {
return EXPIRE_ACCEPTE;
}
if (statut === StatutEvenementAgendaType.REFUSE) {
return new Date(now + TTL_REFUSE_MS);
}
return new Date(now + TTL_EN_ATTENTE_MS);
}
private assertDates(debut: string, fin: string): void {
if (fin < debut) {
throw new BadRequestException(
'date_fin doit être supérieure ou égale à date_debut',
);
}
}
/** Bornes calendaires YYYY-MM-DD (comparaison lexicographique = calendaire, DST-safe). #217 */
private assertDateRange(from?: string, to?: string): void {
if (from) this.assertCalendarDate(from, 'from');
if (to) this.assertCalendarDate(to, 'to');
if (from && to && from > to) {
throw new BadRequestException('from doit être inférieure ou égale à to');
}
}
private assertCalendarDate(value: string, field: string): void {
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) {
throw new BadRequestException(
`${field} doit être une date YYYY-MM-DD`,
);
}
const [y, m, d] = value.split('-').map(Number);
// UTC : évite qu’un parse local fasse glisser le jour à l’heure d’hiver
const dt = new Date(Date.UTC(y, m - 1, d));
if (
dt.getUTCFullYear() !== y ||
dt.getUTCMonth() !== m - 1 ||
dt.getUTCDate() !== d
) {
throw new BadRequestException(`${field} n’est pas une date calendaire valide`);
}
}
private assertCanCreateType(role: RoleType, type: TypeEvenementAgendaType): void {
if (role === RoleType.PARENT) {
if (type !== TypeEvenementAgendaType.ABSENCE_ENFANT) {
throw new ForbiddenException(
'Un parent ne peut créer que des absences enfant',
);
}
return;
}
if (role === RoleType.ASSISTANTE_MATERNELLE) {
if (
type !== TypeEvenementAgendaType.CONGE_AM &&
type !== TypeEvenementAgendaType.ARRET_MALADIE_AM &&
type !== TypeEvenementAgendaType.SOIN_ENFANT
) {
throw new ForbiddenException(
'Une AM ne peut créer que congé, arrêt maladie ou soin enfant',
);
}
return;
}
throw new ForbiddenException('Rôle non autorisé à créer une absence');
}
private assertCanEditDates(
role: RoleType,
row: EvenementsAgenda,
): void {
if (role === RoleType.PARENT) {
if (row.type !== TypeEvenementAgendaType.ABSENCE_ENFANT) {
throw new ForbiddenException(
'Un parent ne peut modifier que les absences enfant',
);
}
return;
}
if (role === RoleType.ASSISTANTE_MATERNELLE) {
if (
row.type === TypeEvenementAgendaType.CONGE_AM ||
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM
) {
if (
row.statut !== StatutEvenementAgendaType.EN_ATTENTE &&
row.statut !== StatutEvenementAgendaType.REFUSE &&
row.statut !== StatutEvenementAgendaType.ACCEPTE
) {
throw new ForbiddenException('Statut incompatible avec une modification');
}
// Accepté : autorisé (S2b — re-validation via cartes plus tard ; API permet update dates)
return;
}
throw new ForbiddenException('Type non modifiable par l’AM');
}
throw new ForbiddenException('Modification non autorisée');
}
private assertCanChangeStatut(
role: RoleType,
row: EvenementsAgenda,
next: StatutEvenementAgendaType,
_motif?: string,
): void {
if (role === RoleType.PARENT) {
// Accept / refuse congé ; ack arrêt (accepte)
if (
row.type === TypeEvenementAgendaType.CONGE_AM ||
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM
) {
if (
next !== StatutEvenementAgendaType.ACCEPTE &&
next !== StatutEvenementAgendaType.REFUSE
) {
throw new BadRequestException('Transition de statut invalide');
}
if (
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 !== StatutEvenementAgendaType.EN_ATTENTE) {
throw new BadRequestException('Cette demande n’est plus en attente');
}
return;
}
throw new ForbiddenException(
'Pas de changement de statut sur ce type pour un parent',
);
}
if (role === RoleType.ASSISTANTE_MATERNELLE) {
// Remise en attente après refus OU modification d’un congé déjà accepté (S2b)
if (
next === StatutEvenementAgendaType.EN_ATTENTE &&
(row.statut === StatutEvenementAgendaType.REFUSE ||
row.statut === StatutEvenementAgendaType.ACCEPTE)
) {
return;
}
throw new ForbiddenException(
'L’AM ne valide pas elle-même (sauf republication / modification)',
);
}
throw new ForbiddenException('Changement de statut non autorisé');
}
private async resolvePlacementIds(
userId: string,
role: RoleType,
placementId?: string,
opts?: { includeEnded?: boolean },
): Promise<string[]> {
if (placementId) {
await this.assertCanAccessPlacement(userId, role, placementId, {
allowEnded: opts?.includeEnded === true,
});
return [placementId];
}
if (role === RoleType.PARENT) {
const liens = await this.parentsChildrenRepo.find({
where: { parentId: userId },
select: ['enfantId'],
});
const enfantIds = liens.map((l) => l.enfantId);
if (enfantIds.length === 0) return [];
const placements = await this.amChildrenRepo.find({
where: opts?.includeEnded
? { enfantId: In(enfantIds) }
: { enfantId: In(enfantIds), date_fin: IsNull() },
select: ['id'],
});
return placements.map((p) => p.id);
}
if (role === RoleType.ASSISTANTE_MATERNELLE) {
const placements = await this.amChildrenRepo.find({
where: opts?.includeEnded
? { amId: userId }
: { amId: userId, date_fin: IsNull() },
select: ['id'],
});
return placements.map((p) => p.id);
}
throw new ForbiddenException('Rôle non autorisé');
}
private async assertCanAccessPlacement(
userId: string,
role: RoleType,
placementId: string,
opts?: { allowEnded?: boolean },
): Promise<AmChildren> {
const placement = await this.amChildrenRepo.findOne({
where: opts?.allowEnded
? { id: placementId }
: { id: placementId, date_fin: IsNull() },
});
if (!placement) {
throw new NotFoundException(
opts?.allowEnded
? 'Placement / couple introuvable'
: 'Placement / couple introuvable ou inactif',
);
}
if (role === RoleType.ASSISTANTE_MATERNELLE) {
if (placement.amId !== userId) {
throw new ForbiddenException('Ce placement ne vous appartient pas');
}
return placement;
}
if (role === RoleType.PARENT) {
const lien = await this.parentsChildrenRepo.findOne({
where: { parentId: userId, enfantId: placement.enfantId },
});
if (!lien) {
throw new ForbiddenException(
'Ce placement ne concerne pas un de vos enfants',
);
}
return placement;
}
throw new ForbiddenException('Rôle non autorisé');
}
private toDto(
row: EvenementsAgenda,
userId?: string,
role?: RoleType,
): EvenementAgendaDto {
const child = row.placement?.child;
const amUser = row.placement?.am?.user;
const statutLot = (row.lot?.statut as AgendaLotStatutType | undefined) ?? null;
const statutEffectif = this.statutEffectif(row, statutLot);
return {
id: row.id,
id_placement: row.id_placement,
id_lot: row.id_lot ?? null,
id_card_instance: row.id_card_instance ?? null,
type: row.type,
date_debut: row.date_debut,
date_fin: row.date_fin,
heure: this.formatHeure(row.heure),
statut: row.statut,
statut_lot: statutLot,
statut_effectif: statutEffectif,
expire_at: row.expire_at?.toISOString?.() ?? String(row.expire_at),
verrouille_le: row.verrouille_le
? row.verrouille_le.toISOString?.() ?? String(row.verrouille_le)
: null,
refuse_le: row.refuse_le
? row.refuse_le.toISOString?.() ?? String(row.refuse_le)
: null,
annule_le: row.annule_le
? row.annule_le.toISOString?.() ?? String(row.annule_le)
: null,
cree_par: row.cree_par ?? null,
motif: row.motif ?? null,
libelle_refus: this.libelleRefus(row, statutLot, userId, role),
id_enfant: child?.id ?? row.placement?.enfantId ?? null,
prenom_enfant: child?.first_name ?? null,
id_am: row.placement?.amId ?? null,
prenom_am: amUser?.prenom ?? null,
nom_am: amUser?.nom ?? null,
actions: this.actionsPour(row, statutLot, userId, role),
cree_le: row.cree_le?.toISOString?.() ?? String(row.cree_le),
modifie_le: row.modifie_le?.toISOString?.() ?? String(row.modifie_le),
};
}
private formatHeure(heure?: string | null): string | null {
if (!heure) return null;
const s = String(heure);
return s.length >= 5 ? s.slice(0, 5) : s;
}
private statutEffectif(
row: EvenementsAgenda,
statutLot: AgendaLotStatutType | null,
): StatutEvenementAgendaType {
if (row.statut === StatutEvenementAgendaType.ANNULE) {
return StatutEvenementAgendaType.ANNULE;
}
if (statutLot === AgendaLotStatutType.ANNULE) {
return StatutEvenementAgendaType.ANNULE;
}
if (statutLot === AgendaLotStatutType.REFUSE) {
return StatutEvenementAgendaType.REFUSE;
}
return row.statut;
}
/**
* Anonymise l’auteur du refus : jamais le nom d’une autre famille.
* B1 : si refusé et viewer ≠ créateur → « autre famille » ;
* si viewer est parent créateur/foyer et motif présent → « autre parent » pour co-parent
* (sans id répondant en B1 : défaut « autre famille » pour parent destinataire).
*/
private libelleRefus(
row: EvenementsAgenda,
statutLot: AgendaLotStatutType | null,
userId?: string,
role?: RoleType,
): string | null {
const refuse =
row.statut === StatutEvenementAgendaType.REFUSE ||
statutLot === AgendaLotStatutType.REFUSE;
if (!refuse) return null;
if (!userId || !role) return 'Refusé';
if (role === RoleType.ASSISTANTE_MATERNELLE) {
return 'Refusé par une famille';
}
// Parent : ne jamais citer quelle famille. Si ce n’est pas le créateur AM, message générique.
if (row.cree_par && row.cree_par === userId) {
return null;
}
return 'Refusé par une autre famille';
}
private actionsPour(
row: EvenementsAgenda,
statutLot: AgendaLotStatutType | null,
userId?: string,
role?: RoleType,
): EvenementAgendaActionsDto {
const none: EvenementAgendaActionsDto = {
peut_modifier: false,
peut_supprimer: false,
peut_accepter_refuser: false,
peut_ack: false,
};
if (!userId || !role) return none;
if (
row.statut === StatutEvenementAgendaType.ANNULE ||
statutLot === AgendaLotStatutType.ANNULE
) {
return none;
}
const isCreator = row.cree_par === userId;
const today = new Date().toISOString().slice(0, 10);
const notStarted = row.date_debut > today;
const enAttente =
row.statut === StatutEvenementAgendaType.EN_ATTENTE ||
statutLot === AgendaLotStatutType.EN_ATTENTE;
const refuse =
row.statut === StatutEvenementAgendaType.REFUSE ||
statutLot === AgendaLotStatutType.REFUSE;
const accepte =
row.statut === StatutEvenementAgendaType.ACCEPTE ||
statutLot === AgendaLotStatutType.ACCEPTE;
if (role === RoleType.ASSISTANTE_MATERNELLE && isCreator) {
const congeFuturModifiable =
row.type === TypeEvenementAgendaType.CONGE_AM &&
accepte &&
notStarted;
return {
peut_modifier:
enAttente || refuse || congeFuturModifiable ||
(row.type !== TypeEvenementAgendaType.CONGE_AM &&
row.type !== TypeEvenementAgendaType.SOIN_ENFANT &&
accepte),
peut_supprimer:
enAttente ||
refuse ||
(row.type === TypeEvenementAgendaType.CONGE_AM &&
accepte &&
notStarted) ||
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM ||
row.type === TypeEvenementAgendaType.SOIN_ENFANT,
peut_accepter_refuser: false,
peut_ack: false,
};
}
if (role === RoleType.PARENT && !isCreator) {
// ANNULE déjà exclu en tête de actionsPour (narrowing TS)
const congeEnAttente =
row.type === TypeEvenementAgendaType.CONGE_AM &&
row.statut === StatutEvenementAgendaType.EN_ATTENTE &&
statutLot !== AgendaLotStatutType.REFUSE;
const arretAck =
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM;
const soinAck = row.type === TypeEvenementAgendaType.SOIN_ENFANT;
return {
peut_modifier: false,
peut_supprimer: false,
peut_accepter_refuser: congeEnAttente,
peut_ack: arretAck || soinAck,
};
}
if (
role === RoleType.PARENT &&
isCreator &&
row.type === TypeEvenementAgendaType.ABSENCE_ENFANT
) {
return {
peut_modifier: true,
peut_supprimer: true,
peut_accepter_refuser: false,
peut_ack: false,
};
}
return none;
}
}