Compare commits

..
Author SHA1 Message Date
jmartinandCursor 9f4c5303fb fix(#217): retire comparaison ANNULE redondante (TS2367)
Après le early-return ANNULE dans actionsPour, le narrowing TS
rendait la comparaison inutile et cassait le build Docker.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 16:52:10 +02:00
12 changed files with 66 additions and 951 deletions
-49
View File
@@ -15,7 +15,6 @@
"@nestjs/jwt": "^11.0.0", "@nestjs/jwt": "^11.0.0",
"@nestjs/mapped-types": "^2.1.0", "@nestjs/mapped-types": "^2.1.0",
"@nestjs/platform-express": "^11.0.1", "@nestjs/platform-express": "^11.0.1",
"@nestjs/schedule": "^12.0.2",
"@nestjs/swagger": "^11.2.0", "@nestjs/swagger": "^11.2.0",
"@nestjs/typeorm": "^11.0.0", "@nestjs/typeorm": "^11.0.0",
"@sentry/nestjs": "^10.10.0", "@sentry/nestjs": "^10.10.0",
@@ -2545,22 +2544,6 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/@nestjs/schedule": {
"version": "12.0.2",
"resolved": "https://registry.npmjs.org/@nestjs/schedule/-/schedule-12.0.2.tgz",
"integrity": "sha512-5iAvJEtk0njbfTrG4JQr+SXw8ZrqgDM1wJH9nUs6tVLCX5pWGd1LJ0a8b089UT1FDeDWaThRRfSLixFz9zztcA==",
"license": "MIT",
"dependencies": {
"cron": "4.4.0"
},
"engines": {
"node": ">=20.19.0"
},
"peerDependencies": {
"@nestjs/common": "^11.0.0 || ^12.0.0",
"@nestjs/core": "^11.0.0 || ^12.0.0"
}
},
"node_modules/@nestjs/schematics": { "node_modules/@nestjs/schematics": {
"version": "11.0.7", "version": "11.0.7",
"resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-11.0.7.tgz", "resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-11.0.7.tgz",
@@ -3784,12 +3767,6 @@
"@types/node": "*" "@types/node": "*"
} }
}, },
"node_modules/@types/luxon": {
"version": "3.7.6",
"resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.7.6.tgz",
"integrity": "sha512-6KSjliQAXK8ZLgFQO4B7iE4Rpf/B3rItzCFuXezBY/XIAGxOdLd7vRNK9/StRPwiS/yJsVbB7HKpW46B8tcEuQ==",
"license": "MIT"
},
"node_modules/@types/methods": { "node_modules/@types/methods": {
"version": "1.1.4", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz", "resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",
@@ -5879,23 +5856,6 @@
"devOptional": true, "devOptional": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/cron": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/cron/-/cron-4.4.0.tgz",
"integrity": "sha512-fkdfq+b+AHI4cKdhZlppHveI/mgz2qpiYxcm+t5E5TsxX7QrLS1VE0+7GENEk9z0EeGPcpSciGv6ez24duWhwQ==",
"license": "MIT",
"dependencies": {
"@types/luxon": "~3.7.0",
"luxon": "~3.7.0"
},
"engines": {
"node": ">=18.x"
},
"funding": {
"type": "ko-fi",
"url": "https://ko-fi.com/intcreator"
}
},
"node_modules/cross-spawn": { "node_modules/cross-spawn": {
"version": "7.0.6", "version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -8826,15 +8786,6 @@
"yallist": "^3.0.2" "yallist": "^3.0.2"
} }
}, },
"node_modules/luxon": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz",
"integrity": "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==",
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/magic-string": { "node_modules/magic-string": {
"version": "0.30.17", "version": "0.30.17",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz",
-1
View File
@@ -29,7 +29,6 @@
"@nestjs/jwt": "^11.0.0", "@nestjs/jwt": "^11.0.0",
"@nestjs/mapped-types": "^2.1.0", "@nestjs/mapped-types": "^2.1.0",
"@nestjs/platform-express": "^11.0.1", "@nestjs/platform-express": "^11.0.1",
"@nestjs/schedule": "^12.0.2",
"@nestjs/swagger": "^11.2.0", "@nestjs/swagger": "^11.2.0",
"@nestjs/typeorm": "^11.0.0", "@nestjs/typeorm": "^11.0.0",
"@sentry/nestjs": "^10.10.0", "@sentry/nestjs": "^10.10.0",
-2
View File
@@ -1,6 +1,5 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config'; import { ConfigModule, ConfigService } from '@nestjs/config';
import { ScheduleModule } from '@nestjs/schedule';
import { AppController } from './app.controller'; import { AppController } from './app.controller';
import { AppService } from './app.service'; import { AppService } from './app.service';
import appConfig from './config/app.config'; import appConfig from './config/app.config';
@@ -59,7 +58,6 @@ import { SuppressionsModule } from './routes/suppressions/suppressions.module';
AuthModule, AuthModule,
AppConfigModule, AppConfigModule,
DocumentsLegauxModule, DocumentsLegauxModule,
ScheduleModule.forRoot(),
EvenementsAgendaModule, EvenementsAgendaModule,
CardsModule, CardsModule,
RelaisModule, RelaisModule,
-31
View File
@@ -1,31 +0,0 @@
/** Dates calendaires Europe/Paris — comparaison lexicographique YYYY-MM-DD = calendaire (DST-safe). */
const PARIS_YMD = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Europe/Paris',
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
/** Aujourd’hui civil à Paris (YYYY-MM-DD). */
export function todayParis(): string {
return PARIS_YMD.format(new Date());
}
/** Décale une date calendaire YYYY-MM-DD de `deltaDays` (UTC, sans glissement DST). */
export function shiftYmd(ymd: string, deltaDays: number): string {
const [y, m, d] = ymd.split('-').map(Number);
const dt = new Date(Date.UTC(y, m - 1, d + deltaDays));
const yy = dt.getUTCFullYear();
const mm = String(dt.getUTCMonth() + 1).padStart(2, '0');
const dd = String(dt.getUTCDate()).padStart(2, '0');
return `${yy}-${mm}-${dd}`;
}
export function yesterdayParis(): string {
return shiftYmd(todayParis(), -1);
}
/** Fenêtre temporelle exacte en ms (ex. 7×24 h = 168 h). */
export const MS_24H = 24 * 60 * 60 * 1000;
export const MS_7X24H = 7 * MS_24H;
@@ -373,80 +373,4 @@ describe('CardsService (#194)', () => {
]), ]),
); );
}); });
describe('B2 — #216 soft-cancel + ack arrêt', () => {
it('ack arrêt maladie → pas de maj événement + carte traitée', async () => {
cardsRepo.findOne.mockResolvedValue({
id: 'card-arret',
type_code: 'arret_maladie_am',
id_placement: 'pl-1',
id_evenement: 'ev-arret',
cree_par: 'am-1',
statut: CardInstanceStatutType.OUVERTE,
purge_at: new Date(Date.now() - 60_000), // déjà hors fil
payload: {},
type: {
titre: 'Arrêt',
response_mode: CardResponseModeType.ACK,
retention_days: 7,
},
responses: [],
audience: [
{ id_utilisateur: 'am-1' },
{ id_utilisateur: 'p-1' },
],
});
audienceRepo.findOne.mockResolvedValue({
id_card: 'card-arret',
id_utilisateur: 'p-1',
});
const res = await service.repondre('p-1', RoleType.PARENT, 'card-arret', {
action: 'ack' as never,
});
expect(evenementsService.maj).not.toHaveBeenCalled();
expect(cardsRepo.update).toHaveBeenCalledWith(
{ id: 'card-arret' },
expect.objectContaining({ statut: CardInstanceStatutType.TRAITEE }),
);
expect(res.statut).toBe(CardInstanceStatutType.TRAITEE);
});
it('supprimer carte → soft-cancel (update ANNULEE), pas delete', async () => {
cardsRepo.findOne.mockResolvedValue({
id: 'card-1',
type_code: 'absence_enfant',
id_placement: 'pl-1',
id_evenement: 'ev-1',
cree_par: 'p-1',
statut: CardInstanceStatutType.OUVERTE,
cree_le: new Date(),
audience: [{ id_utilisateur: 'p-1' }, { id_utilisateur: 'am-1' }],
type: { retention_days: 14 },
});
evenementsService.supprimer.mockResolvedValue(undefined);
await service.supprimer('p-1', RoleType.PARENT, 'card-1');
expect(cardsRepo.delete).not.toHaveBeenCalled();
expect(evenementsService.supprimer).toHaveBeenCalledWith(
'p-1',
RoleType.PARENT,
'ev-1',
);
expect(cardsRepo.update).toHaveBeenCalledWith(
{ id: 'card-1' },
expect.objectContaining({
statut: CardInstanceStatutType.ANNULEE,
}),
);
expect(realtime.emitToUsers).toHaveBeenCalledWith(
expect.any(Array),
'card.deleted',
'card-1',
expect.any(Object),
);
});
});
}); });
+22 -26
View File
@@ -92,11 +92,11 @@ export class CardsService {
.leftJoinAndSelect('c.type', 'type') .leftJoinAndSelect('c.type', 'type')
.leftJoinAndSelect('c.responses', 'responses') .leftJoinAndSelect('c.responses', 'responses')
.where('c.purge_at > now()') .where('c.purge_at > now()')
.andWhere('c.statut != :annulee', { .orderBy(
annulee: CardInstanceStatutType.ANNULEE, `CASE c.statut WHEN 'refusee' THEN 0 WHEN 'ouverte' THEN 1 ELSE 2 END`,
}) 'ASC',
// Tri fil : COALESCE(remonte_le, cree_le) DESC (mini-spec §10) )
.orderBy('COALESCE(c.remonte_le, c.cree_le)', 'DESC'); .addOrderBy('c.modifie_le', 'DESC');
if (placementId) { if (placementId) {
await this.assertPlacementAccess(userId, role, placementId); await this.assertPlacementAccess(userId, role, placementId);
@@ -251,10 +251,6 @@ export class CardsService {
): Promise<CarteDto> { ): Promise<CarteDto> {
const card = await this.loadCard(cardId); const card = await this.loadCard(cardId);
await this.assertInAudience(card, userId); await this.assertInAudience(card, userId);
// Respond OK même après purge_at (sortie du fil) — AC #216
if (card.statut === CardInstanceStatutType.ANNULEE) {
throw new BadRequestException('Cette carte est annulée');
}
if (card.statut !== CardInstanceStatutType.OUVERTE) { if (card.statut !== CardInstanceStatutType.OUVERTE) {
throw new BadRequestException('Cette carte n’est plus ouverte'); throw new BadRequestException('Cette carte n’est plus ouverte');
} }
@@ -289,11 +285,8 @@ export class CardsService {
}), }),
); );
// ACK informatif (arrêt / soin) : n’écrit plus sur l’événement (#216) if (card.id_evenement) {
if (dto.action === CardResponseActionType.ACK) { if (dto.action === CardResponseActionType.ACCEPT || dto.action === CardResponseActionType.ACK) {
card.statut = CardInstanceStatutType.TRAITEE;
} else if (card.id_evenement) {
if (dto.action === CardResponseActionType.ACCEPT) {
await this.evenementsService.maj(userId, role, card.id_evenement, { await this.evenementsService.maj(userId, role, card.id_evenement, {
statut: StatutEvenementAgendaType.ACCEPTE, statut: StatutEvenementAgendaType.ACCEPTE,
}); });
@@ -305,6 +298,8 @@ export class CardsService {
}); });
card.statut = CardInstanceStatutType.REFUSEE; card.statut = CardInstanceStatutType.REFUSEE;
} }
} else if (dto.action === CardResponseActionType.ACK) {
card.statut = CardInstanceStatutType.TRAITEE;
} }
card.purge_at = this.purgeAt(card.type.retention_days, card.statut); card.purge_at = this.purgeAt(card.type.retention_days, card.statut);
@@ -461,21 +456,22 @@ export class CardsService {
} }
const audienceIds = await this.audienceUserIds(card); const audienceIds = await this.audienceUserIds(card);
// Soft-cancel événement lié (matrice temporelle côté evenements) — #216
if (card.id_evenement) { if (card.id_evenement) {
const absStatut =
card.statut === CardInstanceStatutType.TRAITEE
? null
: card.id_evenement;
// Supprime l’absence liée si pas encore acceptée définitivement (ou si soin_enfant dans les 24h)
if (
card.statut === CardInstanceStatutType.OUVERTE ||
card.statut === CardInstanceStatutType.REFUSEE ||
card.type_code === 'soin_enfant'
) {
await this.evenementsService.supprimer(userId, role, card.id_evenement); await this.evenementsService.supprimer(userId, role, card.id_evenement);
} }
// Soft-cancel carte — aucun DELETE physique applicatif (#216) void absStatut;
const now = new Date(); }
await this.cardsRepo.update( await this.cardsRepo.delete({ id: cardId });
{ id: cardId },
{
statut: CardInstanceStatutType.ANNULEE,
annule_le: now,
annule_par: userId,
purge_at: now,
},
);
this.realtime.emitToUsers(audienceIds, 'card.deleted', cardId, { this.realtime.emitToUsers(audienceIds, 'card.deleted', cardId, {
id: cardId, id: cardId,
}); });
@@ -1,50 +0,0 @@
jest.mock('@nestjs/schedule', () => ({
Cron: () => () => undefined,
CronExpression: { EVERY_HOUR: '0 * * * *' },
}));
import { AgendaExpirationCron } from './agenda-expiration.cron';
import { EvenementsAgendaService } from './evenements-agenda.service';
describe('AgendaExpirationCron (#216)', () => {
const evenements = {
autoValiderCongesExpires: jest.fn().mockResolvedValue(2),
softCancelRefusesExpires: jest.fn().mockResolvedValue(1),
};
beforeEach(() => jest.clearAllMocks());
it('runOnce agrège auto-valid + soft-cancel', async () => {
const cron = new AgendaExpirationCron(
evenements as unknown as EvenementsAgendaService,
);
const res = await cron.runOnce();
expect(res).toEqual({ autoValid: 2, softCancel: 1 });
expect(evenements.autoValiderCongesExpires).toHaveBeenCalledTimes(1);
expect(evenements.softCancelRefusesExpires).toHaveBeenCalledTimes(1);
});
it('double appel concurrent : 2e skip (lock)', async () => {
let release!: () => void;
const gate = new Promise<void>((r) => {
release = r;
});
evenements.autoValiderCongesExpires.mockImplementation(async () => {
await gate;
return 1;
});
evenements.softCancelRefusesExpires.mockResolvedValue(0);
const cron = new AgendaExpirationCron(
evenements as unknown as EvenementsAgendaService,
);
const p1 = cron.runOnce();
const p2 = cron.runOnce();
release();
const [a, b] = await Promise.all([p1, p2]);
const skipped = [a, b].filter((x) => x.autoValid === 0 && x.softCancel === 0);
const ran = [a, b].filter((x) => x.autoValid === 1);
expect(skipped).toHaveLength(1);
expect(ran).toHaveLength(1);
});
});
@@ -1,38 +0,0 @@
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { EvenementsAgendaService } from './evenements-agenda.service';
/**
* Échéances Agenda (#216) : auto-valid congés J+7, soft-cancel refusés J+7.
* Idempotent ; rattrapage au redémarrage via le prochain tick.
*/
@Injectable()
export class AgendaExpirationCron {
private readonly logger = new Logger(AgendaExpirationCron.name);
private running = false;
constructor(private readonly evenements: EvenementsAgendaService) {}
@Cron(CronExpression.EVERY_HOUR)
async tick(): Promise<void> {
await this.runOnce();
}
/** Exposé pour tests / appel manuel (double-appel = no-op côté rows déjà traités). */
async runOnce(
now = new Date(),
): Promise<{ autoValid: number; softCancel: number }> {
if (this.running) {
this.logger.debug('Cron agenda déjà en cours — skip');
return { autoValid: 0, softCancel: 0 };
}
this.running = true;
try {
const autoValid = await this.evenements.autoValiderCongesExpires(now);
const softCancel = await this.evenements.softCancelRefusesExpires(now);
return { autoValid, softCancel };
} finally {
this.running = false;
}
}
}
@@ -3,23 +3,14 @@ import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt'; import { JwtModule } from '@nestjs/jwt';
import { TypeOrmModule } from '@nestjs/typeorm'; import { TypeOrmModule } from '@nestjs/typeorm';
import { EvenementsAgenda } from 'src/entities/evenements_agenda.entity'; import { EvenementsAgenda } from 'src/entities/evenements_agenda.entity';
import { AgendaLots } from 'src/entities/agenda_lots.entity';
import { CardInstance } from 'src/entities/card_instances.entity';
import { AmChildren } from 'src/entities/am_children.entity'; import { AmChildren } from 'src/entities/am_children.entity';
import { ParentsChildren } from 'src/entities/parents_children.entity'; import { ParentsChildren } from 'src/entities/parents_children.entity';
import { EvenementsAgendaController } from './evenements-agenda.controller'; import { EvenementsAgendaController } from './evenements-agenda.controller';
import { EvenementsAgendaService } from './evenements-agenda.service'; import { EvenementsAgendaService } from './evenements-agenda.service';
import { AgendaExpirationCron } from './agenda-expiration.cron';
@Module({ @Module({
imports: [ imports: [
TypeOrmModule.forFeature([ TypeOrmModule.forFeature([EvenementsAgenda, AmChildren, ParentsChildren]),
EvenementsAgenda,
AgendaLots,
CardInstance,
AmChildren,
ParentsChildren,
]),
JwtModule.registerAsync({ JwtModule.registerAsync({
imports: [ConfigModule], imports: [ConfigModule],
useFactory: (config: ConfigService) => ({ useFactory: (config: ConfigService) => ({
@@ -30,7 +21,7 @@ import { AgendaExpirationCron } from './agenda-expiration.cron';
}), }),
], ],
controllers: [EvenementsAgendaController], controllers: [EvenementsAgendaController],
providers: [EvenementsAgendaService, AgendaExpirationCron], providers: [EvenementsAgendaService],
exports: [EvenementsAgendaService], exports: [EvenementsAgendaService],
}) })
export class EvenementsAgendaModule {} export class EvenementsAgendaModule {}
@@ -7,22 +7,9 @@ import {
StatutEvenementAgendaType, StatutEvenementAgendaType,
TypeEvenementAgendaType, TypeEvenementAgendaType,
} from 'src/entities/evenements_agenda.entity'; } from 'src/entities/evenements_agenda.entity';
import { AgendaLots } from 'src/entities/agenda_lots.entity';
import { CardInstance } from 'src/entities/card_instances.entity';
import { AmChildren } from 'src/entities/am_children.entity'; import { AmChildren } from 'src/entities/am_children.entity';
import { ParentsChildren } from 'src/entities/parents_children.entity'; import { ParentsChildren } from 'src/entities/parents_children.entity';
import { RoleType } from 'src/entities/users.entity'; import { RoleType } from 'src/entities/users.entity';
import { todayParis, yesterdayParis } from 'src/common/utils/paris-date';
function qbUpdateMock() {
const chain: Record<string, jest.Mock> = {};
chain.update = jest.fn().mockReturnValue(chain);
chain.set = jest.fn().mockReturnValue(chain);
chain.where = jest.fn().mockReturnValue(chain);
chain.andWhere = jest.fn().mockReturnValue(chain);
chain.execute = jest.fn().mockResolvedValue({ affected: 1 });
return chain;
}
describe('EvenementsAgendaService (#172)', () => { describe('EvenementsAgendaService (#172)', () => {
let service: EvenementsAgendaService; let service: EvenementsAgendaService;
@@ -35,19 +22,9 @@ describe('EvenementsAgendaService (#172)', () => {
modifie_le: new Date(), modifie_le: new Date(),
})), })),
findOne: jest.fn(), findOne: jest.fn(),
find: jest.fn(),
update: jest.fn(async () => ({ affected: 1 })),
delete: jest.fn(), delete: jest.fn(),
createQueryBuilder: jest.fn(), createQueryBuilder: jest.fn(),
}; };
const lotsRepo = {
findOne: jest.fn(),
update: jest.fn(async () => ({ affected: 1 })),
createQueryBuilder: jest.fn(() => qbUpdateMock()),
};
const cardsRepo = {
createQueryBuilder: jest.fn(() => qbUpdateMock()),
};
const amChildrenRepo = { const amChildrenRepo = {
find: jest.fn(), find: jest.fn(),
findOne: jest.fn(), findOne: jest.fn(),
@@ -62,8 +39,6 @@ describe('EvenementsAgendaService (#172)', () => {
providers: [ providers: [
EvenementsAgendaService, EvenementsAgendaService,
{ provide: getRepositoryToken(EvenementsAgenda), useValue: absencesRepo }, { provide: getRepositoryToken(EvenementsAgenda), useValue: absencesRepo },
{ provide: getRepositoryToken(AgendaLots), useValue: lotsRepo },
{ provide: getRepositoryToken(CardInstance), useValue: cardsRepo },
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo }, { provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo },
{ {
provide: getRepositoryToken(ParentsChildren), provide: getRepositoryToken(ParentsChildren),
@@ -73,8 +48,6 @@ describe('EvenementsAgendaService (#172)', () => {
}).compile(); }).compile();
service = module.get(EvenementsAgendaService); service = module.get(EvenementsAgendaService);
jest.clearAllMocks(); jest.clearAllMocks();
lotsRepo.createQueryBuilder.mockImplementation(() => qbUpdateMock());
cardsRepo.createQueryBuilder.mockImplementation(() => qbUpdateMock());
}); });
it('should be defined', () => { it('should be defined', () => {
@@ -399,270 +372,4 @@ describe('EvenementsAgendaService (#172)', () => {
expect(res.statut_effectif).toBe(StatutEvenementAgendaType.REFUSE); expect(res.statut_effectif).toBe(StatutEvenementAgendaType.REFUSE);
expect(res.libelle_refus).not.toMatch(/p-2|Dupont|famille B/i); expect(res.libelle_refus).not.toMatch(/p-2|Dupont|famille B/i);
}); });
describe('B2 — #216 matrice + soft-cancel + cron', () => {
it('arrêt maladie créé → statut accepte + verrouille_le', async () => {
amChildrenRepo.findOne.mockResolvedValue({
id: 'pl-1',
amId: 'am-1',
enfantId: 'e-1',
date_fin: null,
});
absencesRepo.findOne.mockResolvedValue({
id: 'abs-1',
id_placement: 'pl-1',
type: TypeEvenementAgendaType.ARRET_MALADIE_AM,
date_debut: '2026-10-01',
date_fin: '2026-10-05',
statut: StatutEvenementAgendaType.ACCEPTE,
expire_at: new Date('9999-12-31'),
verrouille_le: new Date(),
cree_le: new Date(),
modifie_le: new Date(),
placement: {
enfantId: 'e-1',
amId: 'am-1',
child: { id: 'e-1', first_name: 'Léo' },
am: { user: { prenom: 'Marie', nom: 'AM' } },
},
});
await service.creer('am-1', RoleType.ASSISTANTE_MATERNELLE, {
id_placement: 'pl-1',
type: TypeEvenementAgendaType.ARRET_MALADIE_AM,
date_debut: '2026-10-01',
date_fin: '2026-10-05',
});
const saved = absencesRepo.save.mock.calls[0][0];
expect(saved.statut).toBe(StatutEvenementAgendaType.ACCEPTE);
expect(saved.verrouille_le).toBeInstanceOf(Date);
});
it('parent maj statut arrêt → 400 (ack n’écrit pas sur l’événement)', async () => {
absencesRepo.findOne.mockResolvedValue({
id: 'abs-1',
id_placement: 'pl-1',
type: TypeEvenementAgendaType.ARRET_MALADIE_AM,
date_debut: '2026-10-01',
date_fin: '2026-10-05',
statut: StatutEvenementAgendaType.ACCEPTE,
expire_at: new Date('9999-12-31'),
cree_le: new Date(),
verrouille_le: new Date(),
});
amChildrenRepo.findOne.mockResolvedValue({
id: 'pl-1',
amId: 'am-1',
enfantId: 'e-1',
date_fin: null,
});
parentsChildrenRepo.findOne.mockResolvedValue({
parentId: 'p-1',
enfantId: 'e-1',
});
await expect(
service.maj('p-1', RoleType.PARENT, 'abs-1', {
statut: StatutEvenementAgendaType.ACCEPTE,
}),
).rejects.toBeInstanceOf(BadRequestException);
});
it('soin hors [hier, auj.] → BadRequest', async () => {
amChildrenRepo.findOne.mockResolvedValue({
id: 'pl-1',
amId: 'am-1',
enfantId: 'e-1',
date_fin: null,
});
await expect(
service.creer('am-1', RoleType.ASSISTANTE_MATERNELLE, {
id_placement: 'pl-1',
type: TypeEvenementAgendaType.SOIN_ENFANT,
date_debut: '2020-01-01',
date_fin: '2020-01-01',
}),
).rejects.toBeInstanceOf(BadRequestException);
});
it('soin daté aujourd’hui (Paris) → OK', async () => {
const auj = todayParis();
amChildrenRepo.findOne.mockResolvedValue({
id: 'pl-1',
amId: 'am-1',
enfantId: 'e-1',
date_fin: null,
});
absencesRepo.findOne.mockResolvedValue({
id: 'abs-1',
id_placement: 'pl-1',
type: TypeEvenementAgendaType.SOIN_ENFANT,
date_debut: auj,
date_fin: auj,
statut: StatutEvenementAgendaType.ACCEPTE,
expire_at: new Date('9999-12-31'),
cree_le: new Date(),
modifie_le: new Date(),
placement: {
enfantId: 'e-1',
amId: 'am-1',
child: { id: 'e-1', first_name: 'Léo' },
am: { user: { prenom: 'Marie', nom: 'AM' } },
},
});
await expect(
service.creer('am-1', RoleType.ASSISTANTE_MATERNELLE, {
id_placement: 'pl-1',
type: TypeEvenementAgendaType.SOIN_ENFANT,
date_debut: auj,
date_fin: auj,
}),
).resolves.toBeDefined();
// hier aussi OK
const hier = yesterdayParis();
absencesRepo.findOne.mockResolvedValue({
id: 'abs-2',
id_placement: 'pl-1',
type: TypeEvenementAgendaType.SOIN_ENFANT,
date_debut: hier,
date_fin: hier,
statut: StatutEvenementAgendaType.ACCEPTE,
expire_at: new Date('9999-12-31'),
cree_le: new Date(),
modifie_le: new Date(),
placement: {
enfantId: 'e-1',
amId: 'am-1',
child: { id: 'e-1', first_name: 'Léo' },
am: { user: { prenom: 'Marie', nom: 'AM' } },
},
});
await expect(
service.creer('am-1', RoleType.ASSISTANTE_MATERNELLE, {
id_placement: 'pl-1',
type: TypeEvenementAgendaType.SOIN_ENFANT,
date_debut: hier,
date_fin: hier,
}),
).resolves.toBeDefined();
});
it('supprimer → soft-cancel (update ANNULE), pas delete physique', async () => {
absencesRepo.findOne.mockResolvedValue({
id: 'abs-1',
id_placement: 'pl-1',
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
date_debut: '2026-10-01',
date_fin: '2026-10-02',
statut: StatutEvenementAgendaType.ACCEPTE,
cree_le: new Date(),
verrouille_le: new Date(),
cree_par: 'p-1',
});
amChildrenRepo.findOne.mockResolvedValue({
id: 'pl-1',
amId: 'am-1',
enfantId: 'e-1',
date_fin: null,
});
parentsChildrenRepo.findOne.mockResolvedValue({
parentId: 'p-1',
enfantId: 'e-1',
});
await service.supprimer('p-1', RoleType.PARENT, 'abs-1');
expect(absencesRepo.delete).not.toHaveBeenCalled();
expect(absencesRepo.update).toHaveBeenCalledWith(
{ id: 'abs-1' },
expect.objectContaining({
statut: StatutEvenementAgendaType.ANNULE,
}),
);
});
it('cron auto-valid + soft-cancel refusés ; double appel idempotent', async () => {
const old = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000);
absencesRepo.find.mockResolvedValue([
{
id: 'c1',
type: TypeEvenementAgendaType.CONGE_AM,
statut: StatutEvenementAgendaType.EN_ATTENTE,
verrouille_le: old,
},
]);
const legacyQb = {
where: jest.fn().mockReturnThis(),
andWhere: jest.fn().mockReturnThis(),
getMany: jest.fn().mockResolvedValue([]),
};
const refuseQb = {
where: jest.fn().mockReturnThis(),
andWhere: jest.fn().mockReturnThis(),
getMany: jest.fn().mockResolvedValue([
{
id: 'r1',
statut: StatutEvenementAgendaType.REFUSE,
refuse_le: old,
},
]),
};
absencesRepo.createQueryBuilder
.mockReturnValueOnce(legacyQb) // autoValider legacy
.mockReturnValueOnce(refuseQb); // softCancelRefuses
absencesRepo.findOne.mockImplementation(async ({ where }) => {
if (where?.id === 'r1') {
return {
id: 'r1',
statut: StatutEvenementAgendaType.REFUSE,
refuse_le: old,
};
}
return null;
});
const n1 = await service.autoValiderCongesExpires();
expect(n1).toBe(1);
expect(absencesRepo.update).toHaveBeenCalledWith(
{ id: 'c1', statut: StatutEvenementAgendaType.EN_ATTENTE },
expect.objectContaining({
statut: StatutEvenementAgendaType.ACCEPTE,
}),
);
absencesRepo.find.mockResolvedValue([]); // déjà validés
const emptyQb = {
where: jest.fn().mockReturnThis(),
andWhere: jest.fn().mockReturnThis(),
getMany: jest.fn().mockResolvedValue([]),
};
absencesRepo.createQueryBuilder.mockReset();
absencesRepo.createQueryBuilder.mockReturnValue(emptyQb);
const n2 = await service.autoValiderCongesExpires();
expect(n2).toBe(0);
// soft-cancel refusés
absencesRepo.createQueryBuilder.mockReturnValue(refuseQb);
refuseQb.getMany.mockResolvedValue([
{ id: 'r1', statut: StatutEvenementAgendaType.REFUSE, refuse_le: old },
]);
absencesRepo.findOne.mockResolvedValue({
id: 'r1',
statut: StatutEvenementAgendaType.REFUSE,
refuse_le: old,
});
const sc1 = await service.softCancelRefusesExpires();
expect(sc1).toBe(1);
// 2e passage : déjà ANNULE → 0
absencesRepo.findOne.mockResolvedValue({
id: 'r1',
statut: StatutEvenementAgendaType.ANNULE,
});
refuseQb.getMany.mockResolvedValue([
{ id: 'r1', statut: StatutEvenementAgendaType.ANNULE },
]);
const sc2 = await service.softCancelRefusesExpires();
expect(sc2).toBe(0);
});
});
}); });
@@ -2,24 +2,16 @@ import {
BadRequestException, BadRequestException,
ForbiddenException, ForbiddenException,
Injectable, Injectable,
Logger,
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
import { In, IsNull, LessThanOrEqual, Repository } from 'typeorm'; import { In, IsNull, Repository } from 'typeorm';
import { import {
EvenementsAgenda, EvenementsAgenda,
StatutEvenementAgendaType, StatutEvenementAgendaType,
TypeEvenementAgendaType, TypeEvenementAgendaType,
} from 'src/entities/evenements_agenda.entity'; } from 'src/entities/evenements_agenda.entity';
import { import { AgendaLotStatutType } from 'src/entities/agenda_lots.entity';
AgendaLots,
AgendaLotStatutType,
} from 'src/entities/agenda_lots.entity';
import {
CardInstance,
CardInstanceStatutType,
} from 'src/entities/card_instances.entity';
import { AmChildren } from 'src/entities/am_children.entity'; import { AmChildren } from 'src/entities/am_children.entity';
import { ParentsChildren } from 'src/entities/parents_children.entity'; import { ParentsChildren } from 'src/entities/parents_children.entity';
import { RoleType } from 'src/entities/users.entity'; import { RoleType } from 'src/entities/users.entity';
@@ -30,30 +22,17 @@ import {
ListeEvenementsAgendaDto, ListeEvenementsAgendaDto,
MajEvenementAgendaDto, MajEvenementAgendaDto,
} from './dto/evenements-agenda.dto'; } from './dto/evenements-agenda.dto';
import {
MS_24H,
MS_7X24H,
todayParis,
yesterdayParis,
} from 'src/common/utils/paris-date';
/** Auto-valid / soft-cancel refusés = 7×24 h (mini-spec §5). */ const TTL_EN_ATTENTE_MS = 15 * 24 * 60 * 60 * 1000;
const TTL_EN_ATTENTE_MS = MS_7X24H; const TTL_REFUSE_MS = 7 * 24 * 60 * 60 * 1000;
const TTL_REFUSE_MS = MS_7X24H;
/** Sentinel « pas de purge » pour les périodes acceptées */ /** Sentinel « pas de purge » pour les périodes acceptées */
const EXPIRE_ACCEPTE = new Date('9999-12-31T23:59:59.999Z'); const EXPIRE_ACCEPTE = new Date('9999-12-31T23:59:59.999Z');
@Injectable() @Injectable()
export class EvenementsAgendaService { export class EvenementsAgendaService {
private readonly logger = new Logger(EvenementsAgendaService.name);
constructor( constructor(
@InjectRepository(EvenementsAgenda) @InjectRepository(EvenementsAgenda)
private readonly absencesRepo: Repository<EvenementsAgenda>, private readonly absencesRepo: Repository<EvenementsAgenda>,
@InjectRepository(AgendaLots)
private readonly lotsRepo: Repository<AgendaLots>,
@InjectRepository(CardInstance)
private readonly cardsRepo: Repository<CardInstance>,
@InjectRepository(AmChildren) @InjectRepository(AmChildren)
private readonly amChildrenRepo: Repository<AmChildren>, private readonly amChildrenRepo: Repository<AmChildren>,
@InjectRepository(ParentsChildren) @InjectRepository(ParentsChildren)
@@ -134,23 +113,17 @@ export class EvenementsAgendaService {
dto: CreerEvenementAgendaDto, dto: CreerEvenementAgendaDto,
): Promise<EvenementAgendaDto> { ): Promise<EvenementAgendaDto> {
this.assertDates(dto.date_debut, dto.date_fin); this.assertDates(dto.date_debut, dto.date_fin);
this.assertCalendarDate(dto.date_debut, 'date_debut');
this.assertCalendarDate(dto.date_fin, 'date_fin');
await this.assertCanAccessPlacement(userId, role, dto.id_placement); await this.assertCanAccessPlacement(userId, role, dto.id_placement);
this.assertCanCreateType(role, dto.type); this.assertCanCreateType(role, dto.type);
this.assertTemporalCreate(dto.type, dto.date_debut, dto.date_fin);
const statut = this.statutInitial(dto.type); const statut = this.statutInitial(dto.type);
const now = new Date();
const entity = this.absencesRepo.create({ const entity = this.absencesRepo.create({
id_placement: dto.id_placement, id_placement: dto.id_placement,
type: dto.type, type: dto.type,
date_debut: dto.date_debut, date_debut: dto.date_debut,
date_fin: dto.date_fin, date_fin: dto.date_fin,
statut, statut,
expire_at: this.expireAtFor(statut, now), expire_at: this.expireAtFor(statut),
// verrouille_le à la soumission seulement — jamais en GET (#216)
verrouille_le: now,
cree_par: userId, cree_par: userId,
motif: dto.motif?.trim() || undefined, motif: dto.motif?.trim() || undefined,
}); });
@@ -168,48 +141,23 @@ export class EvenementsAgendaService {
if (!row) { if (!row) {
throw new NotFoundException('Absence introuvable'); throw new NotFoundException('Absence introuvable');
} }
if (row.statut === StatutEvenementAgendaType.ANNULE) {
throw new BadRequestException('Événement annulé');
}
await this.assertCanAccessPlacement(userId, role, row.id_placement); await this.assertCanAccessPlacement(userId, role, row.id_placement);
const datesChange =
(dto.date_debut !== undefined && dto.date_debut !== row.date_debut) ||
(dto.date_fin !== undefined && dto.date_fin !== row.date_fin);
if (dto.date_debut !== undefined || dto.date_fin !== undefined) { if (dto.date_debut !== undefined || dto.date_fin !== undefined) {
const debut = dto.date_debut ?? row.date_debut; const debut = dto.date_debut ?? row.date_debut;
const fin = dto.date_fin ?? row.date_fin; const fin = dto.date_fin ?? row.date_fin;
this.assertDates(debut, fin); this.assertDates(debut, fin);
this.assertCalendarDate(debut, 'date_debut'); // Parent : peut modifier ses absences enfant
this.assertCalendarDate(fin, 'date_fin'); // AM : peut modifier congé/arrêt en_attente (avant accept) ou dates si créateur
this.assertCanEditDates(role, row); this.assertCanEditDates(role, row);
this.assertTemporalEdit(row);
row.date_debut = debut; row.date_debut = debut;
row.date_fin = fin; row.date_fin = fin;
if (row.statut === StatutEvenementAgendaType.EN_ATTENTE) {
// Toute modif de dates d’un événement soumis à validation → nouvelle revision row.expire_at = this.expireAtFor(StatutEvenementAgendaType.EN_ATTENTE);
if (datesChange && this.needsRevalidationOnDateChange(row)) {
await this.bumpRevisionForDateChange(row, userId);
} else if (row.statut === StatutEvenementAgendaType.EN_ATTENTE) {
row.expire_at = this.expireAtFor(
StatutEvenementAgendaType.EN_ATTENTE,
row.verrouille_le ?? row.cree_le,
);
} }
} }
if (dto.statut !== undefined) { if (dto.statut !== undefined && dto.statut !== row.statut) {
// Ack arrêt = informatif carte seulement — toute maj statut parent sur arrêt → 400
if (
role === RoleType.PARENT &&
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM
) {
throw new BadRequestException(
'L’accusé de réception d’un arrêt maladie n’écrit pas sur l’événement',
);
}
if (dto.statut !== row.statut) {
this.assertCanChangeStatut(role, row, dto.statut, dto.motif); this.assertCanChangeStatut(role, row, dto.statut, dto.motif);
if ( if (
dto.statut === StatutEvenementAgendaType.REFUSE && dto.statut === StatutEvenementAgendaType.REFUSE &&
@@ -219,25 +167,12 @@ export class EvenementsAgendaService {
'Une motivation est obligatoire en cas de refus', 'Une motivation est obligatoire en cas de refus',
); );
} }
const now = new Date();
row.statut = dto.statut; row.statut = dto.statut;
row.expire_at = this.expireAtFor(dto.statut, now); row.expire_at = this.expireAtFor(dto.statut);
if (dto.statut === StatutEvenementAgendaType.REFUSE) {
row.refuse_le = now;
}
if (
dto.statut === StatutEvenementAgendaType.EN_ATTENTE &&
datesChange
) {
// resoumission : nouveau verrou (pas un GET)
row.verrouille_le = now;
}
if (dto.motif?.trim()) { if (dto.motif?.trim()) {
row.motif = dto.motif.trim(); row.motif = dto.motif.trim();
} }
}
} else if (dto.motif !== undefined) { } else if (dto.motif !== undefined) {
// Motif seul ne relance pas l’unanimité
row.motif = dto.motif.trim() || undefined; row.motif = dto.motif.trim() || undefined;
} }
@@ -245,10 +180,6 @@ export class EvenementsAgendaService {
return this.getByIdForUser(id, userId, role); return this.getByIdForUser(id, userId, role);
} }
/**
* Soft-cancel applicatif — remplace tout DELETE physique événement (#216).
* Idempotent si déjà annulé.
*/
async supprimer( async supprimer(
userId: string, userId: string,
role: RoleType, role: RoleType,
@@ -269,140 +200,7 @@ export class EvenementsAgendaService {
); );
} }
this.assertCanSoftCancel(role, row); await this.absencesRepo.delete({ id });
await this.softCancelEvent(row, userId);
}
/** Soft-cancel sans re-check role (cron / carte liée). Idempotent. */
async softCancelById(id: string, userId?: string | null): Promise<boolean> {
const row = await this.absencesRepo.findOne({ where: { id } });
if (!row) return false;
return this.softCancelEvent(row, userId ?? null);
}
private async softCancelEvent(
row: EvenementsAgenda,
userId: string | null,
): Promise<boolean> {
if (row.statut === StatutEvenementAgendaType.ANNULE) {
return false;
}
const now = new Date();
await this.absencesRepo.update(
{ id: row.id },
{
statut: StatutEvenementAgendaType.ANNULE,
annule_le: now,
annule_par: userId ?? undefined,
expire_at: now,
},
);
// Cartes liées : soft-cancel (pas de DELETE physique)
await this.cardsRepo
.createQueryBuilder()
.update(CardInstance)
.set({
statut: CardInstanceStatutType.ANNULEE,
annule_le: now,
annule_par: userId ?? undefined,
purge_at: now,
})
.where('id_evenement = :eid', { eid: row.id })
.andWhere('statut != :annulee', {
annulee: CardInstanceStatutType.ANNULEE,
})
.execute();
if (row.id_lot) {
await this.lotsRepo
.createQueryBuilder()
.update(AgendaLots)
.set({
statut: AgendaLotStatutType.ANNULE,
annule_le: now,
annule_par: userId ?? undefined,
})
.where('id = :id', { id: row.id_lot })
.andWhere('statut != :annule', { annule: AgendaLotStatutType.ANNULE })
.execute();
}
return true;
}
/**
* Cron : auto-valide les congés encore en_attente après 7×24 h depuis verrouille_le.
* Idempotent. Retourne le nombre mis à jour.
*/
async autoValiderCongesExpires(now = new Date()): Promise<number> {
const threshold = new Date(now.getTime() - TTL_EN_ATTENTE_MS);
const rows = await this.absencesRepo.find({
where: {
type: TypeEvenementAgendaType.CONGE_AM,
statut: StatutEvenementAgendaType.EN_ATTENTE,
verrouille_le: LessThanOrEqual(threshold),
},
});
// Fallback cree_le si verrouille_le null (données pré-B2)
const legacy = await this.absencesRepo
.createQueryBuilder('ag')
.where('ag.type = :type', { type: TypeEvenementAgendaType.CONGE_AM })
.andWhere('ag.statut = :statut', {
statut: StatutEvenementAgendaType.EN_ATTENTE,
})
.andWhere('ag.verrouille_le IS NULL')
.andWhere('ag.cree_le <= :threshold', { threshold })
.getMany();
const byId = new Map<string, EvenementsAgenda>();
for (const r of [...rows, ...legacy]) byId.set(r.id, r);
let n = 0;
for (const row of byId.values()) {
await this.absencesRepo.update(
{ id: row.id, statut: StatutEvenementAgendaType.EN_ATTENTE },
{
statut: StatutEvenementAgendaType.ACCEPTE,
expire_at: EXPIRE_ACCEPTE,
},
);
if (row.id_lot) {
await this.lotsRepo.update(
{ id: row.id_lot, statut: AgendaLotStatutType.EN_ATTENTE },
{ statut: AgendaLotStatutType.ACCEPTE },
);
}
n += 1;
}
if (n > 0) {
this.logger.log(`Cron auto-valid congés : ${n} événement(s)`);
}
return n;
}
/**
* Cron : soft-cancel des refusés après 7×24 h (refuse_le / expire_at).
* Idempotent.
*/
async softCancelRefusesExpires(now = new Date()): Promise<number> {
const threshold = new Date(now.getTime() - TTL_REFUSE_MS);
const rows = await this.absencesRepo
.createQueryBuilder('ag')
.where('ag.statut = :statut', {
statut: StatutEvenementAgendaType.REFUSE,
})
.andWhere(
'(ag.refuse_le IS NOT NULL AND ag.refuse_le <= :threshold) OR (ag.refuse_le IS NULL AND ag.expire_at <= :now)',
{ threshold, now },
)
.getMany();
let n = 0;
for (const row of rows) {
if (await this.softCancelEvent(row, null)) n += 1;
}
if (n > 0) {
this.logger.log(`Cron soft-cancel refusés : ${n} événement(s)`);
}
return n;
} }
private async getByIdForUser( private async getByIdForUser(
@@ -431,152 +229,21 @@ export class EvenementsAgendaService {
} }
private statutInitial(type: TypeEvenementAgendaType): StatutEvenementAgendaType { private statutInitial(type: TypeEvenementAgendaType): StatutEvenementAgendaType {
// Arrêt maladie : accepté dès soumission (ack parent informatif seulement) — #216 if (type === TypeEvenementAgendaType.ABSENCE_ENFANT || type === TypeEvenementAgendaType.SOIN_ENFANT) {
if (
type === TypeEvenementAgendaType.ABSENCE_ENFANT ||
type === TypeEvenementAgendaType.SOIN_ENFANT ||
type === TypeEvenementAgendaType.ARRET_MALADIE_AM
) {
return StatutEvenementAgendaType.ACCEPTE; return StatutEvenementAgendaType.ACCEPTE;
} }
return StatutEvenementAgendaType.EN_ATTENTE; return StatutEvenementAgendaType.EN_ATTENTE;
} }
private expireAtFor( private expireAtFor(statut: StatutEvenementAgendaType): Date {
statut: StatutEvenementAgendaType, const now = Date.now();
from: Date = new Date(), if (statut === StatutEvenementAgendaType.ACCEPTE) {
): Date { return EXPIRE_ACCEPTE;
const t = from.getTime();
if (
statut === StatutEvenementAgendaType.ACCEPTE ||
statut === StatutEvenementAgendaType.ANNULE
) {
return statut === StatutEvenementAgendaType.ANNULE
? from
: EXPIRE_ACCEPTE;
} }
if (statut === StatutEvenementAgendaType.REFUSE) { if (statut === StatutEvenementAgendaType.REFUSE) {
return new Date(t + TTL_REFUSE_MS); return new Date(now + TTL_REFUSE_MS);
}
return new Date(t + TTL_EN_ATTENTE_MS);
}
/** Soin : date ∈ [hier, aujourd’hui] Paris. Autres : passé OK. */
private assertTemporalCreate(
type: TypeEvenementAgendaType,
debut: string,
fin: string,
): void {
if (type !== TypeEvenementAgendaType.SOIN_ENFANT) return;
const hier = yesterdayParis();
const auj = todayParis();
if (debut < hier || debut > auj || fin < hier || fin > auj) {
throw new BadRequestException(
'Un soin enfant doit être daté entre hier et aujourd’hui',
);
}
}
/**
* Fenêtres d’édition (#216) :
* - soin : ≤ 24 h depuis cree_le
* - congé futur accepté : libre tant que date_debut non commencé
* - sinon congé/arrêt/absence : ≤ 7×24 h depuis verrouille_le (soumission)
*/
private assertTemporalEdit(row: EvenementsAgenda): void {
const now = Date.now();
if (row.type === TypeEvenementAgendaType.SOIN_ENFANT) {
const since = now - new Date(row.cree_le).getTime();
if (since > MS_24H) {
throw new BadRequestException(
'Délai de correction de 24 h dépassé pour ce soin',
);
}
return;
}
const today = todayParis();
if (
row.type === TypeEvenementAgendaType.CONGE_AM &&
row.statut === StatutEvenementAgendaType.ACCEPTE &&
row.date_debut > today
) {
return; // futur validé : modifiable/annulable
}
const anchor = row.verrouille_le ?? row.cree_le;
const since = now - new Date(anchor).getTime();
if (since > MS_7X24H) {
throw new BadRequestException(
'Délai d’édition de 7×24 h dépassé pour cet événement',
);
}
}
private assertCanSoftCancel(role: RoleType, row: EvenementsAgenda): void {
if (row.statut === StatutEvenementAgendaType.ANNULE) return;
if (row.type === TypeEvenementAgendaType.SOIN_ENFANT) {
const since = Date.now() - new Date(row.cree_le).getTime();
if (since > MS_24H) {
throw new BadRequestException(
'Délai de suppression de 24 h dépassé pour ce soin',
);
}
return;
}
const today = todayParis();
if (
row.type === TypeEvenementAgendaType.CONGE_AM &&
row.statut === StatutEvenementAgendaType.ACCEPTE &&
row.date_debut > today
) {
return; // congé futur validé annulable
}
if (
row.statut === StatutEvenementAgendaType.EN_ATTENTE ||
row.statut === StatutEvenementAgendaType.REFUSE
) {
return;
}
// Absence / arrêt acceptés : fenêtre 7×24 h
const anchor = row.verrouille_le ?? row.cree_le;
if (Date.now() - new Date(anchor).getTime() <= MS_7X24H) {
return;
}
throw new BadRequestException('Cet événement ne peut plus être annulé');
}
private needsRevalidationOnDateChange(row: EvenementsAgenda): boolean {
return (
row.type === TypeEvenementAgendaType.CONGE_AM &&
row.statut !== StatutEvenementAgendaType.ANNULE
);
}
/** Nouvelle revision + repasse en_attente + nouveau verrouille_le. */
private async bumpRevisionForDateChange(
row: EvenementsAgenda,
_userId: string,
): Promise<void> {
const now = new Date();
row.statut = StatutEvenementAgendaType.EN_ATTENTE;
row.verrouille_le = now;
row.expire_at = this.expireAtFor(StatutEvenementAgendaType.EN_ATTENTE, now);
row.refuse_le = undefined;
if (row.id_lot) {
await this.lotsRepo
.createQueryBuilder()
.update(AgendaLots)
.set({
revision: () => 'revision + 1',
statut: AgendaLotStatutType.EN_ATTENTE,
verrouille_le: now,
soumis_le: now,
refuse_le: () => 'NULL',
})
.where('id = :id', { id: row.id_lot })
.execute();
} }
return new Date(now + TTL_EN_ATTENTE_MS);
} }
private assertDates(debut: string, fin: string): void { private assertDates(debut: string, fin: string): void {
@@ -651,9 +318,6 @@ export class EvenementsAgendaService {
return; return;
} }
if (role === RoleType.ASSISTANTE_MATERNELLE) { if (role === RoleType.ASSISTANTE_MATERNELLE) {
if (row.type === TypeEvenementAgendaType.SOIN_ENFANT) {
return; // fenêtre 24 h gérée par assertTemporalEdit
}
if ( if (
row.type === TypeEvenementAgendaType.CONGE_AM || row.type === TypeEvenementAgendaType.CONGE_AM ||
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM
@@ -665,6 +329,7 @@ export class EvenementsAgendaService {
) { ) {
throw new ForbiddenException('Statut incompatible avec une modification'); throw new ForbiddenException('Statut incompatible avec une modification');
} }
// Accepté : autorisé (S2b — re-validation via cartes plus tard ; API permet update dates)
return; return;
} }
throw new ForbiddenException('Type non modifiable par l’AM'); throw new ForbiddenException('Type non modifiable par l’AM');
@@ -679,20 +344,25 @@ export class EvenementsAgendaService {
_motif?: string, _motif?: string,
): void { ): void {
if (role === RoleType.PARENT) { if (role === RoleType.PARENT) {
// Arrêt : déjà accepté à la soumission — ack carte n’écrit plus ici (#216) // Accept / refuse congé ; ack arrêt (accepte)
if (row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM) { if (
throw new BadRequestException( row.type === TypeEvenementAgendaType.CONGE_AM ||
'L’accusé de réception d’un arrêt maladie n’écrit pas sur l’événement', row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM
); ) {
}
// Accept / refuse congé uniquement
if (row.type === TypeEvenementAgendaType.CONGE_AM) {
if ( if (
next !== StatutEvenementAgendaType.ACCEPTE && next !== StatutEvenementAgendaType.ACCEPTE &&
next !== StatutEvenementAgendaType.REFUSE next !== StatutEvenementAgendaType.REFUSE
) { ) {
throw new BadRequestException('Transition de statut invalide'); 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) { if (row.statut !== StatutEvenementAgendaType.EN_ATTENTE) {
throw new BadRequestException('Cette demande n’est plus en attente'); throw new BadRequestException('Cette demande n’est plus en attente');
} }
+1 -3
View File
@@ -14,12 +14,10 @@ services:
networks: networks:
- ptitspas_network - ptitspas_network
# Interface d'administration DB (optionnel — pas démarré par défaut) # Interface d'administration DB
# Relancer : docker compose --profile tools up -d pgadmin
pgadmin: pgadmin:
image: dpage/pgadmin4 image: dpage/pgadmin4
container_name: ptitspas-pgadmin container_name: ptitspas-pgadmin
profiles: ["tools"]
restart: unless-stopped restart: unless-stopped
environment: environment:
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL} PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}