From 0bdc639f0194ace61e3776d0063e0b9a150cb6f4 Mon Sep 17 00:00:00 2001 From: tristan Date: Wed, 24 Jun 2026 15:08:38 +0200 Subject: [PATCH 01/10] docs : design notification fin de contrat (veille du dernier jour) Co-Authored-By: Claude Opus 4.8 (1M context) --- ...-06-24-contract-end-notification-design.md | 142 ++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 docs/superpowers/specs/2026-06-24-contract-end-notification-design.md diff --git a/docs/superpowers/specs/2026-06-24-contract-end-notification-design.md b/docs/superpowers/specs/2026-06-24-contract-end-notification-design.md new file mode 100644 index 0000000..a05b368 --- /dev/null +++ b/docs/superpowers/specs/2026-06-24-contract-end-notification-design.md @@ -0,0 +1,142 @@ +# Notification de fin de contrat (veille du dernier jour) — Design + +**Date :** 2026-06-24 +**Branche :** feature/SIRH-43-ajouter-une-notif-la-veille-d-un-contrat-qui-se-te +**Statut :** Validé (brainstorming) + +## Objectif + +Prévenir automatiquement **les administrateurs**, sur le **dernier jour ouvré précédant la fin +d'un contrat**, qu'un salarié arrive au terme de son emploi — afin qu'ils puissent anticiper +(solde de tout compte, désactivation des accès, etc.). + +La notification réutilise le **système de notification existant** (entité `Notification`, cloche +admin dans `AppTopNav.vue`). Aucune migration de base de données. + +## Décisions de cadrage + +| Sujet | Décision | +|---|---| +| **Déclencheur** | Vraie fin d'emploi uniquement : la période qui se termine est la **dernière** période de contrat du salarié (aucune période ne lui succède). Un changement de contrat enchaîné (ex. CDD 35h → CDI 39h) ne notifie pas. | +| **Timing** | Le **dernier jour ouvré strictement avant** `endDate`, en sautant **week-ends ET jours fériés**. | +| **Message** | « Fin de {nature} de {Prénom Nom} le {dd/mm/yyyy} » — nature = libellé FR (CDI / CDD / Intérim). | +| **Catégorie** | `Contrat` | +| **Cible du clic** | `/employees/{id}` (fiche employé). | +| **Destinataires** | Tous les `ROLE_ADMIN` (`UserRepository::findAllAdmins()`). | +| **Acteur** | `null` (notif générée par un job automatique, pas par un utilisateur). | +| **Déclenchement** | Commande console quotidienne via crontab prod (~6h du matin). | + +## Rappels sur l'existant + +- `Notification` (table `notifications`) : `recipient` (NOT NULL), `actor` (nullable), + `message`, `category`, `target`, `isRead`, `createdAt`. Exposé via `getActorName()`. +- `endDate` d'une `EmployeeContractPeriod` est **inclusif** : c'est le dernier jour couvert + par le contrat (`findOneCoveringDate` : `endDate >= :date`). +- Pattern de notif existant : `WorkHourSiteValidationProcessor` crée une `Notification` par + admin (`findAllAdmins`) avec `new Notification()` + persist + flush. Pas de service factory. +- Pattern cron existant : `RttRolloverCommand` / `LeaveRolloverCommand` (`#[AsCommand]`, + logger `monolog.logger.cron`, options `--force`/`--recompute`). Déclenchées par le crontab + système (pas de Symfony Scheduler dans le projet). +- `PublicHolidayService` : source des fériés (cache 30j), déjà en place. + +## Approche retenue + +**Commande cron quotidienne + service métier dédié et testable.** + +Alternatives écartées : +- **Symfony Scheduler (Messenger)** : brique non utilisée dans le projet, inutile ici. +- **Calcul à la volée dans le provider** : casse `isRead`/historique, recalcul à chaque + ouverture de la cloche, mélange notifs persistées et virtuelles. + +## Conception détaillée + +### 1. Détection (cœur métier) + +Nouveau service `App\Service\Notification\ContractEndNotificationService`. + +Algorithme (date du jour `T` injectable pour les tests) : + +1. Si `T` est un week-end ou un férié → **sortie** (aucun jour chômé ne génère de notif). +2. Calculer `N` = **prochain jour ouvré strictement après `T`** (saute week-ends + fériés via + `PublicHolidayService`). +3. Charger en **une seule requête** la dernière période de chaque employé + (`EmployeeContractPeriodRepository::findLatestPeriodsForAllEmployees()`). +4. Candidat = dernière période dont `endDate` est non nul et vérifie `T < endDate <= N`. + - Le test « dernière période » assure nativement la règle « vraie fin d'emploi » : un + changement de contrat enchaîné a une période suivante, donc n'est jamais la dernière. + - `endDate = null` (CDI ouvert) → jamais candidat. + +**Exemples :** +- Mardi (`T`), `N` = mercredi → notifie les contrats finissant mercredi (J-1 classique). +- Vendredi (`T`), `N` = lundi → notifie les contrats finissant samedi, dimanche **ou** lundi. +- Vendredi (`T`), lundi férié → `N` = mardi → notifie samedi…mardi. +- Week-end (`T`) → rien. + +### 2. Création des notifications & idempotence + +Pour chaque candidat : +- Message : `Fin de {nature} de {Prénom Nom} le {endDate->format('d/m/Y')}`. +- Une `Notification` par admin : `recipient=admin`, `actor=null`, `category='Contrat'`, + `target='/employees/{id}'`. Persist groupé, un seul `flush()` final. + +**Idempotence** (le job peut être relancé le même jour) : avant création, vérifier qu'il +n'existe pas déjà une notif identique pour ce destinataire via +`(recipient, category='Contrat', target='/employees/{id}', message)` **exact**. Le message +étant unique par (employé + date + nature), cela empêche tout doublon — y compris après que +l'admin a lu la notif (`isRead=true`). Nouvelle méthode +`NotificationRepository::existsForRecipientTargetMessage(...)` (ou `findOneBy`). Pas de +migration : on ne stocke pas de FK « période » sur `Notification`. + +### 3. Affichage front (cloche) + +`AppTopNav.vue` rend aujourd'hui `**{actorName}** {message}`. Pour `actorName` vide : +- N'afficher que `{message}` (pas de span gras vide ni `capitalize` orphelin). +- Le reste est inchangé : avatar/pastille, `formatTimeAgo` + catégorie « Contrat », point + non-lu, lien `target`. + +Aucune route ni service front nouveau : `category` et `target` passent par le DTO existant. +Cloche déjà admin-only → rien d'autre côté visibilité. + +### 4. Commande console + +`App\Command\ContractEndNotificationCommand` — `app:contract:end-notifications`. +- Délègue tout au service. +- Option `--date=YYYY-MM-DD` : forcer la date du jour (tests / rattrapage manuel). +- Logger `monolog.logger.cron`. Sortie `SymfonyStyle` (nb de notifs créées / employés concernés). +- **Idempotente** par construction (cf. §2) → relançable sans risque. +- Crontab prod (infra) : `0 6 * * *` (tous les jours, 6h). Pas de restriction jour de semaine + (la commande s'auto-neutralise week-ends/fériés). + +## Fichiers + +**Backend — nouveaux** +- `src/Service/Notification/ContractEndNotificationService.php` +- `src/Command/ContractEndNotificationCommand.php` +- `tests/...` (tests du service) + +**Backend — modifiés** +- `src/Repository/EmployeeContractPeriodRepository.php` — `findLatestPeriodsForAllEmployees()` +- `src/Repository/NotificationRepository.php` — existence anti-doublon +- Helper « jour ouvré » (week-end + férié) — dans le service ou petit util réutilisable + +**Frontend — modifié** +- `frontend/components/AppTopNav.vue` — gérer `actorName` vide + +**Docs** +- `doc/functional-rules.md` — compléter la section 15) Notifications +- `doc/contract-end-notifications.md` — nouveau (règle complète) +- `frontend/data/documentation-content.ts` — entrée admin +- `CLAUDE.md` — note du nouveau pattern (commande cron de notification) + +Pas de migration DB. + +## Tests (PHPUnit) + +Cœur isolé dans `ContractEndNotificationService` (date `T` fixe + `PublicHolidayService` mocké) : +- Fin mercredi, `T`=mardi → 1 notif/admin. +- Fin lundi, `T`=vendredi → notifié vendredi ; rien samedi/dimanche. +- Lundi férié + fin mardi, `T`=vendredi → notifié vendredi (`N` saute le lundi férié). +- Période suivante existante (changement enchaîné) → pas de notif. +- `endDate=null` → pas de notif. +- Idempotence : 2ᵉ exécution même jour → aucun doublon. +- `T` = week-end → aucune création. -- 2.39.5 From 7e943a44e6977fc4ab3e3f22c1c549076a477bbd Mon Sep 17 00:00:00 2001 From: tristan Date: Wed, 24 Jun 2026 15:18:04 +0200 Subject: [PATCH 02/10] =?UTF-8?q?docs=20:=20plan=20d'impl=C3=A9mentation?= =?UTF-8?q?=20notification=20fin=20de=20contrat?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.8 (1M context) --- .../2026-06-24-contract-end-notification.md | 974 ++++++++++++++++++ 1 file changed, 974 insertions(+) create mode 100644 docs/superpowers/plans/2026-06-24-contract-end-notification.md diff --git a/docs/superpowers/plans/2026-06-24-contract-end-notification.md b/docs/superpowers/plans/2026-06-24-contract-end-notification.md new file mode 100644 index 0000000..9322e8f --- /dev/null +++ b/docs/superpowers/plans/2026-06-24-contract-end-notification.md @@ -0,0 +1,974 @@ +# Notification de fin de contrat (veille du dernier jour) — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Prévenir automatiquement les administrateurs, sur le dernier jour ouvré précédant la fin d'un contrat, qu'un salarié arrive au terme de son emploi. + +**Architecture:** Une commande console quotidienne (`app:contract:end-notifications`, déclenchée par le crontab prod) délègue à un service. La logique « dure » (saut des week-ends/fériés, fenêtre de détection, libellé du message) vit dans deux collaborateurs purs et testés en isolation (`WorkingDayCalculator`, `ContractEndNotificationPlanner`). Le service oriente le résultat vers la création de `Notification` (une par admin), avec déduplication par message exact. Aucune migration : on réutilise la table `notifications` existante. + +**Tech Stack:** Symfony 7 + API Platform + Doctrine ORM (backend), PHPUnit (tests), Nuxt 4 / Vue 3 (front). Conteneur de test Docker `php-sirh-fpm`. + +## Global Constraints + +- **PHP** : `declare(strict_types=1);` en tête de chaque fichier ; classes services en `final readonly` quand sans état mutable (suivre `RttRolloverCommand`, `HolidayVirtualHoursResolver`). +- **Commit message** : format ` : ` — **espace obligatoire avant les deux-points** (hook pre-commit), types autorisés : `feat, fix, docs, refactor, test, chore`, etc. Exemple : `feat : add working day calculator`. +- **Pre-commit hook** : lance php-cs-fixer + **toute** la suite PHPUnit. Tout commit échoue si un test casse → garder la suite verte à chaque commit. +- **Lancer les tests** : `make test` (suite complète) ou ciblé `make test FILES="--filter NomDuTest"` (= `docker exec -u www-data php-sirh-fpm php vendor/bin/phpunit ...`). +- **Fériés** : zone `'metropole'`, via `PublicHolidayServiceInterface::getHolidaysDayByYears('metropole', $year)` → tableau `['Y-m-d' => 'libellé']` (suivre `HolidayVirtualHoursResolver::isPublicHoliday`). +- **Catégorie** notif = `'Contrat'` ; **target** = `'/employees/{id}'` ; **acteur** = `null` ; destinataires = `UserRepository::findAllAdmins()`. +- **Règles projet (CLAUDE.md)** : toute évolution fonctionnelle MET À JOUR `doc/` ET `frontend/data/documentation-content.ts` dans la même intervention ; mettre à jour `CLAUDE.md` à la fin. + +--- + +## File Structure + +**Backend — nouveaux** +- `src/Service/Notification/WorkingDayCalculator.php` — jour ouvré (week-end + férié), prochain jour ouvré. Pur (dépend de `PublicHolidayServiceInterface`). +- `src/Service/Notification/ContractEndNotice.php` — DTO immuable `{ ?int employeeId, string message }`. +- `src/Service/Notification/ContractEndNotificationPlanner.php` — sélection des candidats + construction du message. Pur (dépend de `WorkingDayCalculator`). +- `src/Service/Notification/ContractEndNotificationResult.php` — DTO résultat `{ int notificationsCreated, int contractsMatched }`. +- `src/Service/Notification/ContractEndNotificationService.php` — orchestration (repos + EntityManager). +- `src/Command/ContractEndNotificationCommand.php` — commande `app:contract:end-notifications`. + +**Backend — modifiés** +- `src/Repository/EmployeeContractPeriodRepository.php` — `findLatestPeriodsForAllEmployees()`. +- `src/Repository/NotificationRepository.php` — `existsForRecipientCategoryTargetMessage()`. + +**Tests — nouveaux** +- `tests/Service/Notification/WorkingDayCalculatorTest.php` +- `tests/Service/Notification/ContractEndNotificationPlannerTest.php` + +**Frontend — modifié** +- `frontend/components/AppTopNav.vue` — gérer `actorName` vide (ligne 65). + +**Docs — modifiés/nouveaux** +- `doc/functional-rules.md` (section 15), `doc/contract-end-notifications.md` (nouveau), `frontend/data/documentation-content.ts`, `CLAUDE.md`. + +--- + +## Task 1 : WorkingDayCalculator (jour ouvré : week-end + férié) + +**Files:** +- Create: `src/Service/Notification/WorkingDayCalculator.php` +- Test: `tests/Service/Notification/WorkingDayCalculatorTest.php` + +**Interfaces:** +- Consumes: `App\Service\PublicHolidayServiceInterface::getHolidaysDayByYears(string $zone, string $year): array` +- Produces: + - `WorkingDayCalculator::__construct(PublicHolidayServiceInterface $holidays)` + - `WorkingDayCalculator::isWorkingDay(DateTimeImmutable $date): bool` + - `WorkingDayCalculator::nextWorkingDay(DateTimeImmutable $date): DateTimeImmutable` — premier jour ouvré **strictement après** `$date` (heure remise à 00:00:00). + +- [ ] **Step 1: Write the failing test** + +`tests/Service/Notification/WorkingDayCalculatorTest.php` : + +```php +createStub(PublicHolidayServiceInterface::class); + $holidays->method('getHolidaysDayByYears')->willReturn([ + // Lundi 14/07/2025 férié + '2025-07-14' => 'Fête nationale', + ]); + + return new WorkingDayCalculator($holidays); + } + + public function testWeekdayIsWorkingDay(): void + { + // Mardi 08/07/2025 + self::assertTrue($this->calculator()->isWorkingDay(new DateTimeImmutable('2025-07-08'))); + } + + public function testSaturdayAndSundayAreNotWorkingDays(): void + { + self::assertFalse($this->calculator()->isWorkingDay(new DateTimeImmutable('2025-07-12'))); // samedi + self::assertFalse($this->calculator()->isWorkingDay(new DateTimeImmutable('2025-07-13'))); // dimanche + } + + public function testPublicHolidayIsNotWorkingDay(): void + { + self::assertFalse($this->calculator()->isWorkingDay(new DateTimeImmutable('2025-07-14'))); // lundi férié + } + + public function testNextWorkingDayFromWeekdayIsTomorrow(): void + { + // Mardi 08/07 -> Mercredi 09/07 + self::assertSame( + '2025-07-09', + $this->calculator()->nextWorkingDay(new DateTimeImmutable('2025-07-08'))->format('Y-m-d') + ); + } + + public function testNextWorkingDayFromFridaySkipsWeekend(): void + { + // Vendredi 11/07 -> lundi 14/07 est férié -> mardi 15/07 + self::assertSame( + '2025-07-15', + $this->calculator()->nextWorkingDay(new DateTimeImmutable('2025-07-11'))->format('Y-m-d') + ); + } +} +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `make test FILES="--filter WorkingDayCalculatorTest"` +Expected: FAIL — `Class "App\Service\Notification\WorkingDayCalculator" not found`. + +- [ ] **Step 3: Write minimal implementation** + +`src/Service/Notification/WorkingDayCalculator.php` : + +```php +format('N'); // 1 (lundi) .. 7 (dimanche) + if ($dayOfWeek >= 6) { + return false; + } + + return !$this->isPublicHoliday($date); + } + + public function nextWorkingDay(DateTimeImmutable $date): DateTimeImmutable + { + $candidate = $date->modify('+1 day')->setTime(0, 0, 0); + while (!$this->isWorkingDay($candidate)) { + $candidate = $candidate->modify('+1 day'); + } + + return $candidate; + } + + private function isPublicHoliday(DateTimeImmutable $date): bool + { + try { + $holidays = $this->holidays->getHolidaysDayByYears('metropole', $date->format('Y')); + } catch (Throwable) { + return false; + } + + return isset($holidays[$date->format('Y-m-d')]); + } +} +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `make test FILES="--filter WorkingDayCalculatorTest"` +Expected: PASS (5 tests). + +- [ ] **Step 5: Commit** + +```bash +git add src/Service/Notification/WorkingDayCalculator.php tests/Service/Notification/WorkingDayCalculatorTest.php +git commit -m "feat : add working day calculator (weekend + holiday aware)" +``` + +--- + +## Task 2 : ContractEndNotice DTO + +**Files:** +- Create: `src/Service/Notification/ContractEndNotice.php` + +**Interfaces:** +- Produces: `ContractEndNotice::__construct(public ?int $employeeId, public string $message)` (lecture seule). + +Pas de test dédié (DTO sans logique) — sera couvert par le test du planner (Task 3). + +- [ ] **Step 1: Create the DTO** + +`src/Service/Notification/ContractEndNotice.php` : + +```php +createStub(PublicHolidayServiceInterface::class); + $holidays->method('getHolidaysDayByYears')->willReturn([ + '2025-07-14' => 'Fête nationale', // lundi 14/07 férié + ]); + + return new ContractEndNotificationPlanner(new WorkingDayCalculator($holidays)); + } + + private function period( + string $firstName, + string $lastName, + ?string $endDate, + ContractNature $nature = ContractNature::CDD, + ): EmployeeContractPeriod { + $employee = new Employee(); + $employee->setFirstName($firstName)->setLastName($lastName); + + $period = new EmployeeContractPeriod(); + $period->setEmployee($employee) + ->setContractNature($nature) + ->setEndDate($endDate === null ? null : new DateTimeImmutable($endDate)) + ; + + return $period; + } + + public function testNotifiesContractEndingTomorrowOnAWeekday(): void + { + // Mardi 08/07 -> fin mercredi 09/07 + $notices = $this->planner()->plan( + [$this->period('Jean', 'Dupont', '2025-07-09')], + new DateTimeImmutable('2025-07-08'), + ); + + self::assertCount(1, $notices); + self::assertSame('Fin de CDD de Jean Dupont le 09/07/2025', $notices[0]->message); + } + + public function testFridayNotifiesContractsEndingOverTheWeekendAndMonday(): void + { + // Vendredi 11/07 ; lundi 14/07 férié -> prochain ouvré = mardi 15/07. + // Fenêtre ]11/07 ; 15/07] -> samedi 12, dimanche 13, lundi 14, mardi 15. + $notices = $this->planner()->plan( + [ + $this->period('A', 'Sat', '2025-07-12'), // samedi -> inclus + $this->period('B', 'Mon', '2025-07-14'), // lundi férié -> inclus + $this->period('C', 'Tue', '2025-07-15'), // mardi (= borne haute) -> inclus + $this->period('D', 'Wed', '2025-07-16'), // mercredi -> hors fenêtre + ], + new DateTimeImmutable('2025-07-11'), + ); + + self::assertCount(3, $notices); + } + + public function testIgnoresOpenEndedContract(): void + { + $notices = $this->planner()->plan( + [$this->period('Jean', 'Dupont', null, ContractNature::CDI)], + new DateTimeImmutable('2025-07-08'), + ); + + self::assertSame([], $notices); + } + + public function testIgnoresContractEndingToday(): void + { + // fin = today -> trop tard, pas de notif (on notifie la veille) + $notices = $this->planner()->plan( + [$this->period('Jean', 'Dupont', '2025-07-08')], + new DateTimeImmutable('2025-07-08'), + ); + + self::assertSame([], $notices); + } + + public function testReturnsNothingWhenTodayIsNotAWorkingDay(): void + { + // Samedi 12/07 -> aucun jour chômé ne génère de notif + $notices = $this->planner()->plan( + [$this->period('Jean', 'Dupont', '2025-07-14')], + new DateTimeImmutable('2025-07-12'), + ); + + self::assertSame([], $notices); + } + + public function testInterimNatureLabel(): void + { + $notices = $this->planner()->plan( + [$this->period('Marie', 'Martin', '2025-07-09', ContractNature::INTERIM)], + new DateTimeImmutable('2025-07-08'), + ); + + self::assertSame('Fin de Intérim de Marie Martin le 09/07/2025', $notices[0]->message); + } +} +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `make test FILES="--filter ContractEndNotificationPlannerTest"` +Expected: FAIL — `Class "App\Service\Notification\ContractEndNotificationPlanner" not found`. + +- [ ] **Step 3: Write minimal implementation** + +`src/Service/Notification/ContractEndNotificationPlanner.php` : + +```php +setTime(0, 0, 0); + if (!$this->calculator->isWorkingDay($today)) { + return []; + } + + $upperBound = $this->calculator->nextWorkingDay($today); + + $notices = []; + foreach ($latestPeriods as $period) { + $endDate = $period->getEndDate(); + if (null === $endDate) { + continue; + } + + $endDate = $endDate->setTime(0, 0, 0); + if ($endDate <= $today || $endDate > $upperBound) { + continue; + } + + $employee = $period->getEmployee(); + if (null === $employee) { + continue; + } + + $message = sprintf( + 'Fin de %s de %s %s le %s', + $this->natureLabel($period->getContractNatureEnum()), + $employee->getFirstName(), + $employee->getLastName(), + $endDate->format('d/m/Y'), + ); + + $notices[] = new ContractEndNotice($employee->getId(), $message); + } + + return $notices; + } + + private function natureLabel(ContractNature $nature): string + { + return match ($nature) { + ContractNature::CDI => 'CDI', + ContractNature::CDD => 'CDD', + ContractNature::INTERIM => 'Intérim', + }; + } +} +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `make test FILES="--filter ContractEndNotificationPlannerTest"` +Expected: PASS (6 tests). + +- [ ] **Step 5: Commit** + +```bash +git add src/Service/Notification/ContractEndNotificationPlanner.php tests/Service/Notification/ContractEndNotificationPlannerTest.php +git commit -m "feat : add contract end notification planner" +``` + +--- + +## Task 4 : Méthodes de repository + +Deux requêtes : la dernière période par employé, et le test d'existence anti-doublon. + +**Files:** +- Modify: `src/Repository/EmployeeContractPeriodRepository.php` +- Modify: `src/Repository/NotificationRepository.php` + +**Interfaces:** +- Produces: + - `EmployeeContractPeriodRepository::findLatestPeriodsForAllEmployees(): array` (`@return EmployeeContractPeriod[]` — une période par employé, celle de `startDate` max). + - `NotificationRepository::existsForRecipientCategoryTargetMessage(User $recipient, string $category, string $target, string $message): bool`. + +> Pas de test unitaire (accès Doctrine, pas de tests d'intégration DB dans ce projet) — vérifié manuellement en Task 6. + +- [ ] **Step 1: Add `findLatestPeriodsForAllEmployees` to EmployeeContractPeriodRepository** + +Ajouter cette méthode dans `src/Repository/EmployeeContractPeriodRepository.php` (après `findLatestPeriod`) : + +```php + /** + * Latest contract period (max startDate) for every employee that has at least one. + * + * @return EmployeeContractPeriod[] + */ + public function findLatestPeriodsForAllEmployees(): array + { + return $this->createQueryBuilder('p') + ->andWhere('p.startDate = ( + SELECT MAX(p2.startDate) + FROM App\Entity\EmployeeContractPeriod p2 + WHERE p2.employee = p.employee + )') + ->getQuery() + ->getResult() + ; + } +``` + +- [ ] **Step 2: Add `existsForRecipientCategoryTargetMessage` to NotificationRepository** + +Ajouter dans `src/Repository/NotificationRepository.php` (après `markAllReadByRecipient`) : + +```php + public function existsForRecipientCategoryTargetMessage( + User $recipient, + string $category, + string $target, + string $message, + ): bool { + $id = $this->createQueryBuilder('n') + ->select('n.id') + ->andWhere('n.recipient = :recipient') + ->andWhere('n.category = :category') + ->andWhere('n.target = :target') + ->andWhere('n.message = :message') + ->setParameter('recipient', $recipient) + ->setParameter('category', $category) + ->setParameter('target', $target) + ->setParameter('message', $message) + ->setMaxResults(1) + ->getQuery() + ->getOneOrNullResult() + ; + + return null !== $id; + } +``` + +> `User` est déjà importé dans `NotificationRepository` (`use App\Entity\User;`). Si l'import manquait, l'ajouter. + +- [ ] **Step 3: Verify the suite still passes** + +Run: `make test` +Expected: PASS (suite complète, aucun test cassé). + +- [ ] **Step 4: Commit** + +```bash +git add src/Repository/EmployeeContractPeriodRepository.php src/Repository/NotificationRepository.php +git commit -m "feat : add repository queries for contract end notifications" +``` + +--- + +## Task 5 : Service + Result DTO + Command + +Assemble la détection (planner) et la persistance (Notification par admin, dédupliquée), exposée par une commande console. + +**Files:** +- Create: `src/Service/Notification/ContractEndNotificationResult.php` +- Create: `src/Service/Notification/ContractEndNotificationService.php` +- Create: `src/Command/ContractEndNotificationCommand.php` + +**Interfaces:** +- Consumes: + - `EmployeeContractPeriodRepository::findLatestPeriodsForAllEmployees()` (Task 4) + - `NotificationRepository::existsForRecipientCategoryTargetMessage(...)` (Task 4) + - `App\Repository\UserRepository::findAllAdmins(): array` (existant) + - `ContractEndNotificationPlanner::plan(...)` (Task 3) renvoyant `ContractEndNotice[]` + - `App\Entity\Notification` setters `setRecipient/setMessage/setCategory/setTarget` + - `Doctrine\ORM\EntityManagerInterface` +- Produces: + - `ContractEndNotificationResult::__construct(public int $notificationsCreated, public int $contractsMatched)` + - `ContractEndNotificationService::run(DateTimeImmutable $today): ContractEndNotificationResult` + - Commande `app:contract:end-notifications` avec option `--date=YYYY-MM-DD`. + +- [ ] **Step 1: Create the Result DTO** + +`src/Service/Notification/ContractEndNotificationResult.php` : + +```php +periodRepository->findLatestPeriodsForAllEmployees(); + $notices = $this->planner->plan($latestPeriods, $today); + + if ([] === $notices) { + return new ContractEndNotificationResult(0, 0); + } + + $admins = $this->userRepository->findAllAdmins(); + $created = 0; + + foreach ($notices as $notice) { + if (null === $notice->employeeId) { + continue; + } + + $target = '/employees/'.$notice->employeeId; + + foreach ($admins as $admin) { + if ($this->notificationRepository->existsForRecipientCategoryTargetMessage( + $admin, + self::CATEGORY, + $target, + $notice->message, + )) { + continue; + } + + $notification = new Notification(); + $notification->setRecipient($admin) + ->setMessage($notice->message) + ->setCategory(self::CATEGORY) + ->setTarget($target) + ; + + $this->entityManager->persist($notification); + ++$created; + } + } + + $this->entityManager->flush(); + + return new ContractEndNotificationResult($created, \count($notices)); + } +} +``` + +- [ ] **Step 3: Create the command** + +`src/Command/ContractEndNotificationCommand.php` : + +```php +addOption( + 'date', + null, + InputOption::VALUE_REQUIRED, + 'Override the reference day (YYYY-MM-DD) for testing or manual catch-up.' + ); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + + $dateOption = $input->getOption('date'); + + try { + $today = \is_string($dateOption) && '' !== $dateOption + ? new DateTimeImmutable($dateOption) + : new DateTimeImmutable('today'); + } catch (Throwable $exception) { + $io->error(sprintf('Invalid --date value: %s', $exception->getMessage())); + + return Command::INVALID; + } + + $result = $this->service->run($today); + + $this->logger->info('Contract end notifications generated.', [ + 'date' => $today->format('Y-m-d'), + 'contractsMatched' => $result->contractsMatched, + 'notificationsCreated' => $result->notificationsCreated, + ]); + + $io->success(sprintf( + '%d notification(s) créée(s) pour %d fin(s) de contrat (%s).', + $result->notificationsCreated, + $result->contractsMatched, + $today->format('Y-m-d'), + )); + + return Command::SUCCESS; + } +} +``` + +- [ ] **Step 4: Verify the suite still passes and the command is registered** + +Run: `make test` +Expected: PASS (suite complète). + +Run: `docker exec -t -u www-data php-sirh-fpm php bin/console list app:contract` +Expected: la commande `app:contract:end-notifications` apparaît dans la liste. + +- [ ] **Step 5: Commit** + +```bash +git add src/Service/Notification/ContractEndNotificationResult.php src/Service/Notification/ContractEndNotificationService.php src/Command/ContractEndNotificationCommand.php +git commit -m "feat : add contract end notification service and command" +``` + +--- + +## Task 6 : Vérification manuelle de bout en bout (commande) + +Confirme que la commande crée bien des notifications sur des données réelles, et qu'elle est idempotente. + +**Files:** aucun (vérification). + +- [ ] **Step 1: Repérer un employé dont la dernière période finit bientôt** + +Run (adapter la date au besoin) : +```bash +docker exec -t -u www-data php-sirh-fpm php bin/console dbal:run-sql \ + "SELECT employee_id, MAX(start_date) AS s, end_date FROM employee_contract_periods GROUP BY employee_id HAVING end_date IS NOT NULL ORDER BY end_date DESC LIMIT 10" +``` +Expected: liste d'employés avec leur dernière `end_date`. Choisir une `end_date` E pour viser un jour ouvré juste avant. + +- [ ] **Step 2: Lancer la commande sur la veille ouvrée de E** + +Run (remplacer `YYYY-MM-DD` par le dernier jour ouvré avant E) : +```bash +docker exec -t -u www-data php-sirh-fpm php bin/console app:contract:end-notifications --date=YYYY-MM-DD +``` +Expected: `N notification(s) créée(s) pour M fin(s) de contrat...` avec M ≥ 1. + +- [ ] **Step 3: Vérifier l'idempotence (relancer la même commande)** + +Run: même commande qu'au Step 2. +Expected: `0 notification(s) créée(s) pour M fin(s) de contrat...` (aucun doublon). + +- [ ] **Step 4: Vérifier le contenu en base** + +Run: +```bash +docker exec -t -u www-data php-sirh-fpm php bin/console dbal:run-sql \ + "SELECT message, category, target, actor_id, is_read FROM notifications WHERE category='Contrat' ORDER BY id DESC LIMIT 5" +``` +Expected: lignes `Fin de … de … le dd/mm/yyyy`, `category=Contrat`, `target=/employees/{id}`, `actor_id=NULL`, `is_read=0`. + +> Aucune commande de commit ici — étape de vérification uniquement. Si un comportement diffère, revenir aux tasks concernées avant de continuer. + +--- + +## Task 7 : Front — afficher le message sans acteur + +La notif fin de contrat a `actorName` vide ; supprimer le span gras vide. + +**Files:** +- Modify: `frontend/components/AppTopNav.vue` (ligne 65) + +- [ ] **Step 1: Remplacer la ligne de rendu du message** + +Remplacer exactement (ligne 65) : + +```html +

{{ notification.actorName }} {{ notification.message }}

+``` + +par : + +```html +

{{ notification.actorName }} {{ notification.message }}

+``` + +> Avec acteur : `**Jean** a validé les heures` (l'espace est dans le span). Sans acteur : `Fin de CDD de … le …` (pas de span, pas d'espace en tête). + +- [ ] **Step 2: Vérifier le typecheck front** + +Run: `cd frontend && npx vue-tsc --noEmit -p tsconfig.json 2>&1 | head -20` +Expected: aucune nouvelle erreur liée à `AppTopNav.vue`. (Ne PAS lancer `npm run build`.) + +> Si `vue-tsc` n'est pas disponible / trop lent, vérification visuelle suffisante : la modification est un simple `v-if` sur un span existant. + +- [ ] **Step 3: Commit** + +```bash +git add frontend/components/AppTopNav.vue +git commit -m "feat : render actorless notifications without empty bold span" +``` + +--- + +## Task 8 : Documentation + +Mise à jour obligatoire (règles CLAUDE.md) : `doc/`, doc in-app, `CLAUDE.md`. + +**Files:** +- Create: `doc/contract-end-notifications.md` +- Modify: `doc/functional-rules.md` (section 15) Notifications) +- Modify: `frontend/data/documentation-content.ts` +- Modify: `CLAUDE.md` + +- [ ] **Step 1: Créer `doc/contract-end-notifications.md`** + +```markdown +# Notification de fin de contrat (veille du dernier jour) + +## Objectif +Prévenir les administrateurs, sur le dernier jour ouvré précédant la fin d'un contrat, qu'un +salarié arrive au terme de son emploi. + +## Déclenchement +Commande `app:contract:end-notifications`, lancée chaque jour par le crontab de production +(ex. `0 6 * * *`). Option `--date=YYYY-MM-DD` pour test/rattrapage. Logger `cron`. + +## Règle métier +- **Cible** : la **dernière** période de contrat d'un employé (aucune période ne lui succède). + Un changement de contrat enchaîné (ex. CDD → CDI) ne notifie pas. +- **Quand** : sur le **dernier jour ouvré strictement avant** `endDate` (`endDate` est inclusif + = dernier jour travaillé). Les week-ends ET jours fériés (`PublicHolidayService`, zone + `metropole`) sont sautés. Concrètement, le jour J ouvré couvre les fins de contrat dans + l'intervalle `]J ; prochain_jour_ouvré(J)]` — un vendredi notifie ainsi les fins du + samedi, dimanche et lundi (mardi si lundi férié). +- **Destinataires** : tous les `ROLE_ADMIN`. +- **Message** : `Fin de {CDI|CDD|Intérim} de {Prénom Nom} le {dd/mm/yyyy}`, catégorie + `Contrat`, cible `/employees/{id}`, sans acteur. + +## Idempotence +Avant création, on vérifie l'absence d'une notif identique +`(recipient, category='Contrat', target, message)`. Le message étant unique par +(employé + date + nature), relancer la commande le même jour ne crée aucun doublon. + +## Implémentation +- `App\Service\Notification\WorkingDayCalculator` — jour ouvré / prochain jour ouvré. +- `App\Service\Notification\ContractEndNotificationPlanner` — sélection + message (pur, testé). +- `App\Service\Notification\ContractEndNotificationService` — persistance (1 notif/admin). +- `App\Command\ContractEndNotificationCommand` — `app:contract:end-notifications`. +- `EmployeeContractPeriodRepository::findLatestPeriodsForAllEmployees`, + `NotificationRepository::existsForRecipientCategoryTargetMessage`. +- Pas de migration : réutilise la table `notifications`. +``` + +- [ ] **Step 2: Compléter `doc/functional-rules.md` section 15) Notifications** + +Repérer la section `15) Notifications` (vers ligne 475). Ajouter, à la fin de la section, ce paragraphe : + +```markdown +- **Fin de contrat (J-1 ouvré)** : une commande quotidienne (`app:contract:end-notifications`) + notifie tous les admins, sur le dernier jour ouvré précédant la fin d'un contrat, qu'un + salarié arrive au terme de son emploi. Cible = **dernière** période de l'employé (un + changement de contrat enchaîné ne notifie pas). Week-ends et fériés sautés. Message + « Fin de {nature} de {Nom} le {date} », catégorie `Contrat`, lien vers la fiche employé, + sans acteur. Idempotente. Détail : `doc/contract-end-notifications.md`. +``` + +- [ ] **Step 3: Ajouter une entrée dans la doc in-app `frontend/data/documentation-content.ts`** + +Localiser la section/article traitant des notifications (rechercher `Notification` dans le +fichier) au niveau d'accès `admin`. Y ajouter un bloc décrivant la notif fin de contrat. Si +aucun article notifications n'existe au niveau admin, ajouter un article dans la section la +plus proche (gestion employés / administration) avec `requiredLevel: 'admin'`. Exemple de bloc +à insérer dans le tableau `blocks` de l'article : + +```typescript +{ + type: 'paragraph', + text: "Chaque jour ouvré, l'application prévient les administrateurs (cloche en haut à droite) lorsqu'un salarié atteint le dernier jour ouvré avant la fin de son contrat. Le message indique la nature du contrat, le nom du salarié et la date de fin, et renvoie vers sa fiche. Les week-ends et jours fériés sont pris en compte : une fin de contrat le lundi est signalée dès le vendredi.", +}, +``` + +> Respecter les types `DocBlock` de `frontend/types/documentation.ts` (vérifier le champ exact : +> `text` vs `content`) en s'alignant sur les blocs voisins existants du fichier. + +- [ ] **Step 4: Mettre à jour `CLAUDE.md`** + +Sous la section `## Audit Logging` ou à la suite des sections « Notifications » existantes (il +n'y a pas encore de section Notifications dédiée dans CLAUDE.md — l'ajouter), insérer : + +```markdown +## Notifications +- Système : entité `Notification` (table `notifications`, `recipient`/`actor`/`message`/`category`/`target`/`isRead`), cloche **admin-only** dans `AppTopNav.vue`, providers `/notifications/{unread,today,history}` + `POST /notifications/mark-all-read`. Création historique : `WorkHourSiteValidationProcessor` (1 notif/admin via `UserRepository::findAllAdmins`). +- **Fin de contrat (J-1 ouvré)** : commande cron quotidienne `app:contract:end-notifications` (crontab prod, ~6h ; option `--date`). Notifie les admins sur le **dernier jour ouvré avant** `endDate` (inclusif) de la **dernière** période d'un employé (changement de contrat enchaîné exclu). Week-ends + fériés sautés (`WorkingDayCalculator`). Fenêtre couverte un jour J = `]J ; prochain_jour_ouvré(J)]`. Message « Fin de {nature} de {Nom} le {date} », catégorie `Contrat`, target `/employees/{id}`, acteur null. Idempotent (`NotificationRepository::existsForRecipientCategoryTargetMessage`). Logique pure testée : `ContractEndNotificationPlanner` + `WorkingDayCalculator`. Front : `AppTopNav.vue` masque le span acteur si `actorName` vide. Doc : `doc/contract-end-notifications.md`. +``` + +- [ ] **Step 5: Commit** + +```bash +git add doc/contract-end-notifications.md doc/functional-rules.md frontend/data/documentation-content.ts CLAUDE.md +git commit -m "docs : document contract end notification feature" +``` + +--- + +## Self-Review (effectuée à la rédaction) + +- **Couverture du spec** : détection (Task 1+3), idempotence (Task 4+5), création/destinataires (Task 5), commande cron (Task 5), front acteur vide (Task 7), tests (Task 1, 3), docs 4 fichiers (Task 8), vérif e2e (Task 6). ✅ +- **Pas de placeholder** : tout le code est fourni ; les seules zones « à adapter » sont des valeurs runtime (dates réelles en Task 6) et l'emplacement exact de l'article doc in-app (Task 8 Step 3), explicitement cadrées. ✅ +- **Cohérence des types** : `WorkingDayCalculator::{isWorkingDay,nextWorkingDay}`, `ContractEndNotificationPlanner::plan(array, DateTimeImmutable): ContractEndNotice[]`, `ContractEndNotice{employeeId,message}`, `ContractEndNotificationResult{notificationsCreated,contractsMatched}`, `findLatestPeriodsForAllEmployees()`, `existsForRecipientCategoryTargetMessage()` — noms identiques entre définition et usage. ✅ +- **Note** : `findLatestPeriodsForAllEmployees` renvoie la période de `startDate` max par employé ; en cas d'égalité exacte de `startDate` (anomalie de données) plusieurs lignes peuvent remonter pour un même employé — sans impact fonctionnel (la dédup par message évite les doublons de notif). -- 2.39.5 From a4792364896b6ae51b4196ff203d24ea7fbbebd8 Mon Sep 17 00:00:00 2001 From: tristan Date: Wed, 24 Jun 2026 15:21:13 +0200 Subject: [PATCH 03/10] feat : add working day calculator (weekend + holiday aware) --- .../Notification/WorkingDayCalculator.php | 47 ++++++++++++++ .../Notification/WorkingDayCalculatorTest.php | 62 +++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 src/Service/Notification/WorkingDayCalculator.php create mode 100644 tests/Service/Notification/WorkingDayCalculatorTest.php diff --git a/src/Service/Notification/WorkingDayCalculator.php b/src/Service/Notification/WorkingDayCalculator.php new file mode 100644 index 0000000..314546f --- /dev/null +++ b/src/Service/Notification/WorkingDayCalculator.php @@ -0,0 +1,47 @@ +format('N'); // 1 (lundi) .. 7 (dimanche) + if ($dayOfWeek >= 6) { + return false; + } + + return !$this->isPublicHoliday($date); + } + + public function nextWorkingDay(DateTimeImmutable $date): DateTimeImmutable + { + $candidate = $date->modify('+1 day')->setTime(0, 0, 0); + while (!$this->isWorkingDay($candidate)) { + $candidate = $candidate->modify('+1 day'); + } + + return $candidate; + } + + private function isPublicHoliday(DateTimeImmutable $date): bool + { + try { + $holidays = $this->holidays->getHolidaysDayByYears('metropole', $date->format('Y')); + } catch (Throwable) { + return false; + } + + return isset($holidays[$date->format('Y-m-d')]); + } +} diff --git a/tests/Service/Notification/WorkingDayCalculatorTest.php b/tests/Service/Notification/WorkingDayCalculatorTest.php new file mode 100644 index 0000000..5d98dba --- /dev/null +++ b/tests/Service/Notification/WorkingDayCalculatorTest.php @@ -0,0 +1,62 @@ +calculator()->isWorkingDay(new DateTimeImmutable('2025-07-08'))); + } + + public function testSaturdayAndSundayAreNotWorkingDays(): void + { + self::assertFalse($this->calculator()->isWorkingDay(new DateTimeImmutable('2025-07-12'))); // samedi + self::assertFalse($this->calculator()->isWorkingDay(new DateTimeImmutable('2025-07-13'))); // dimanche + } + + public function testPublicHolidayIsNotWorkingDay(): void + { + self::assertFalse($this->calculator()->isWorkingDay(new DateTimeImmutable('2025-07-14'))); // lundi férié + } + + public function testNextWorkingDayFromWeekdayIsTomorrow(): void + { + // Mardi 08/07 -> Mercredi 09/07 + self::assertSame( + '2025-07-09', + $this->calculator()->nextWorkingDay(new DateTimeImmutable('2025-07-08'))->format('Y-m-d') + ); + } + + public function testNextWorkingDayFromFridaySkipsWeekend(): void + { + // Vendredi 11/07 -> lundi 14/07 est férié -> mardi 15/07 + self::assertSame( + '2025-07-15', + $this->calculator()->nextWorkingDay(new DateTimeImmutable('2025-07-11'))->format('Y-m-d') + ); + } + + private function calculator(): WorkingDayCalculator + { + $holidays = $this->createStub(PublicHolidayServiceInterface::class); + $holidays->method('getHolidaysDayByYears')->willReturn([ + // Lundi 14/07/2025 férié + '2025-07-14' => 'Fête nationale', + ]); + + return new WorkingDayCalculator($holidays); + } +} -- 2.39.5 From 3b63817348db09ae806e2d9494254d70b2842ed3 Mon Sep 17 00:00:00 2001 From: tristan Date: Wed, 24 Jun 2026 15:24:22 +0200 Subject: [PATCH 04/10] feat : add contract end notice DTO --- src/Service/Notification/ContractEndNotice.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 src/Service/Notification/ContractEndNotice.php diff --git a/src/Service/Notification/ContractEndNotice.php b/src/Service/Notification/ContractEndNotice.php new file mode 100644 index 0000000..0ef6594 --- /dev/null +++ b/src/Service/Notification/ContractEndNotice.php @@ -0,0 +1,13 @@ + Date: Wed, 24 Jun 2026 15:25:09 +0200 Subject: [PATCH 05/10] feat : add contract end notification planner --- .../ContractEndNotificationPlanner.php | 70 +++++++++++ .../ContractEndNotificationPlannerTest.php | 119 ++++++++++++++++++ 2 files changed, 189 insertions(+) create mode 100644 src/Service/Notification/ContractEndNotificationPlanner.php create mode 100644 tests/Service/Notification/ContractEndNotificationPlannerTest.php diff --git a/src/Service/Notification/ContractEndNotificationPlanner.php b/src/Service/Notification/ContractEndNotificationPlanner.php new file mode 100644 index 0000000..39a237c --- /dev/null +++ b/src/Service/Notification/ContractEndNotificationPlanner.php @@ -0,0 +1,70 @@ +setTime(0, 0, 0); + if (!$this->calculator->isWorkingDay($today)) { + return []; + } + + $upperBound = $this->calculator->nextWorkingDay($today); + + $notices = []; + foreach ($latestPeriods as $period) { + $endDate = $period->getEndDate(); + if (null === $endDate) { + continue; + } + + $endDate = $endDate->setTime(0, 0, 0); + if ($endDate <= $today || $endDate > $upperBound) { + continue; + } + + $employee = $period->getEmployee(); + if (null === $employee) { + continue; + } + + $message = sprintf( + 'Fin de %s de %s %s le %s', + $this->natureLabel($period->getContractNatureEnum()), + $employee->getFirstName(), + $employee->getLastName(), + $endDate->format('d/m/Y'), + ); + + $notices[] = new ContractEndNotice($employee->getId(), $message); + } + + return $notices; + } + + private function natureLabel(ContractNature $nature): string + { + return match ($nature) { + ContractNature::CDI => 'CDI', + ContractNature::CDD => 'CDD', + ContractNature::INTERIM => 'Intérim', + }; + } +} diff --git a/tests/Service/Notification/ContractEndNotificationPlannerTest.php b/tests/Service/Notification/ContractEndNotificationPlannerTest.php new file mode 100644 index 0000000..250266c --- /dev/null +++ b/tests/Service/Notification/ContractEndNotificationPlannerTest.php @@ -0,0 +1,119 @@ + fin mercredi 09/07 + $notices = $this->planner()->plan( + [$this->period('Jean', 'Dupont', '2025-07-09')], + new DateTimeImmutable('2025-07-08'), + ); + + self::assertCount(1, $notices); + self::assertSame('Fin de CDD de Jean Dupont le 09/07/2025', $notices[0]->message); + } + + public function testFridayNotifiesContractsEndingOverTheWeekendAndMonday(): void + { + // Vendredi 11/07 ; lundi 14/07 férié -> prochain ouvré = mardi 15/07. + // Fenêtre ]11/07 ; 15/07] -> samedi 12, dimanche 13, lundi 14, mardi 15. + $notices = $this->planner()->plan( + [ + $this->period('A', 'Sat', '2025-07-12'), // samedi -> inclus + $this->period('B', 'Mon', '2025-07-14'), // lundi férié -> inclus + $this->period('C', 'Tue', '2025-07-15'), // mardi (= borne haute) -> inclus + $this->period('D', 'Wed', '2025-07-16'), // mercredi -> hors fenêtre + ], + new DateTimeImmutable('2025-07-11'), + ); + + self::assertCount(3, $notices); + } + + public function testIgnoresOpenEndedContract(): void + { + $notices = $this->planner()->plan( + [$this->period('Jean', 'Dupont', null, ContractNature::CDI)], + new DateTimeImmutable('2025-07-08'), + ); + + self::assertSame([], $notices); + } + + public function testIgnoresContractEndingToday(): void + { + // fin = today -> trop tard, pas de notif (on notifie la veille) + $notices = $this->planner()->plan( + [$this->period('Jean', 'Dupont', '2025-07-08')], + new DateTimeImmutable('2025-07-08'), + ); + + self::assertSame([], $notices); + } + + public function testReturnsNothingWhenTodayIsNotAWorkingDay(): void + { + // Samedi 12/07 -> aucun jour chômé ne génère de notif + $notices = $this->planner()->plan( + [$this->period('Jean', 'Dupont', '2025-07-14')], + new DateTimeImmutable('2025-07-12'), + ); + + self::assertSame([], $notices); + } + + public function testInterimNatureLabel(): void + { + $notices = $this->planner()->plan( + [$this->period('Marie', 'Martin', '2025-07-09', ContractNature::INTERIM)], + new DateTimeImmutable('2025-07-08'), + ); + + self::assertSame('Fin de Intérim de Marie Martin le 09/07/2025', $notices[0]->message); + } + + private function planner(): ContractEndNotificationPlanner + { + $holidays = $this->createStub(PublicHolidayServiceInterface::class); + $holidays->method('getHolidaysDayByYears')->willReturn([ + '2025-07-14' => 'Fête nationale', // lundi 14/07 férié + ]); + + return new ContractEndNotificationPlanner(new WorkingDayCalculator($holidays)); + } + + private function period( + string $firstName, + string $lastName, + ?string $endDate, + ContractNature $nature = ContractNature::CDD, + ): EmployeeContractPeriod { + $employee = new Employee(); + $employee->setFirstName($firstName)->setLastName($lastName); + + $period = new EmployeeContractPeriod(); + $period->setEmployee($employee) + ->setContractNature($nature) + ->setEndDate(null === $endDate ? null : new DateTimeImmutable($endDate)) + ; + + return $period; + } +} -- 2.39.5 From d5cf7c705878cf573865d04403bc6a6d07d34d1e Mon Sep 17 00:00:00 2001 From: tristan Date: Wed, 24 Jun 2026 15:28:53 +0200 Subject: [PATCH 06/10] feat : add repository queries for contract end notifications --- .../EmployeeContractPeriodRepository.php | 18 ++++++++++++++ src/Repository/NotificationRepository.php | 24 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/Repository/EmployeeContractPeriodRepository.php b/src/Repository/EmployeeContractPeriodRepository.php index ba9cc9d..a6ef760 100644 --- a/src/Repository/EmployeeContractPeriodRepository.php +++ b/src/Repository/EmployeeContractPeriodRepository.php @@ -72,6 +72,24 @@ final class EmployeeContractPeriodRepository extends ServiceEntityRepository imp ; } + /** + * Latest contract period (max startDate) for every employee that has at least one. + * + * @return EmployeeContractPeriod[] + */ + public function findLatestPeriodsForAllEmployees(): array + { + return $this->createQueryBuilder('p') + ->andWhere('p.startDate = ( + SELECT MAX(p2.startDate) + FROM App\Entity\EmployeeContractPeriod p2 + WHERE p2.employee = p.employee + )') + ->getQuery() + ->getResult() + ; + } + public function closeOpenPeriods(Employee $employee, DateTimeImmutable $endDate): int { return $this->createQueryBuilder('p') diff --git a/src/Repository/NotificationRepository.php b/src/Repository/NotificationRepository.php index 9136aac..ca681e6 100644 --- a/src/Repository/NotificationRepository.php +++ b/src/Repository/NotificationRepository.php @@ -84,4 +84,28 @@ final class NotificationRepository extends ServiceEntityRepository ->execute() ; } + + public function existsForRecipientCategoryTargetMessage( + User $recipient, + string $category, + string $target, + string $message, + ): bool { + $id = $this->createQueryBuilder('n') + ->select('n.id') + ->andWhere('n.recipient = :recipient') + ->andWhere('n.category = :category') + ->andWhere('n.target = :target') + ->andWhere('n.message = :message') + ->setParameter('recipient', $recipient) + ->setParameter('category', $category) + ->setParameter('target', $target) + ->setParameter('message', $message) + ->setMaxResults(1) + ->getQuery() + ->getOneOrNullResult() + ; + + return null !== $id; + } } -- 2.39.5 From baa824d2d2935d810473169ac508ec64c1efd1e1 Mon Sep 17 00:00:00 2001 From: tristan Date: Wed, 24 Jun 2026 15:32:14 +0200 Subject: [PATCH 07/10] feat : add contract end notification service and command --- .../ContractEndNotificationCommand.php | 78 +++++++++++++++++++ .../ContractEndNotificationResult.php | 13 ++++ .../ContractEndNotificationService.php | 73 +++++++++++++++++ 3 files changed, 164 insertions(+) create mode 100644 src/Command/ContractEndNotificationCommand.php create mode 100644 src/Service/Notification/ContractEndNotificationResult.php create mode 100644 src/Service/Notification/ContractEndNotificationService.php diff --git a/src/Command/ContractEndNotificationCommand.php b/src/Command/ContractEndNotificationCommand.php new file mode 100644 index 0000000..d52d8a3 --- /dev/null +++ b/src/Command/ContractEndNotificationCommand.php @@ -0,0 +1,78 @@ +addOption( + 'date', + null, + InputOption::VALUE_REQUIRED, + 'Override the reference day (YYYY-MM-DD) for testing or manual catch-up.' + ); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + + $dateOption = $input->getOption('date'); + + try { + $today = is_string($dateOption) && '' !== $dateOption + ? new DateTimeImmutable($dateOption) + : new DateTimeImmutable('today'); + } catch (Throwable $exception) { + $io->error(sprintf('Invalid --date value: %s', $exception->getMessage())); + + return Command::INVALID; + } + + $result = $this->service->run($today); + + $this->logger->info('Contract end notifications generated.', [ + 'date' => $today->format('Y-m-d'), + 'contractsMatched' => $result->contractsMatched, + 'notificationsCreated' => $result->notificationsCreated, + ]); + + $io->success(sprintf( + '%d notification(s) créée(s) pour %d fin(s) de contrat (%s).', + $result->notificationsCreated, + $result->contractsMatched, + $today->format('Y-m-d'), + )); + + return Command::SUCCESS; + } +} diff --git a/src/Service/Notification/ContractEndNotificationResult.php b/src/Service/Notification/ContractEndNotificationResult.php new file mode 100644 index 0000000..cf0464e --- /dev/null +++ b/src/Service/Notification/ContractEndNotificationResult.php @@ -0,0 +1,13 @@ +periodRepository->findLatestPeriodsForAllEmployees(); + $notices = $this->planner->plan($latestPeriods, $today); + + if ([] === $notices) { + return new ContractEndNotificationResult(0, 0); + } + + $admins = $this->userRepository->findAllAdmins(); + $created = 0; + + foreach ($notices as $notice) { + if (null === $notice->employeeId) { + continue; + } + + $target = '/employees/'.$notice->employeeId; + + foreach ($admins as $admin) { + if ($this->notificationRepository->existsForRecipientCategoryTargetMessage( + $admin, + self::CATEGORY, + $target, + $notice->message, + )) { + continue; + } + + $notification = new Notification(); + $notification->setRecipient($admin) + ->setMessage($notice->message) + ->setCategory(self::CATEGORY) + ->setTarget($target) + ; + + $this->entityManager->persist($notification); + ++$created; + } + } + + $this->entityManager->flush(); + + return new ContractEndNotificationResult($created, count($notices)); + } +} -- 2.39.5 From 87444965be5586a2b2b30cb6037bcdf3968726c6 Mon Sep 17 00:00:00 2001 From: tristan Date: Wed, 24 Jun 2026 15:36:59 +0200 Subject: [PATCH 08/10] feat : render actorless notifications without empty bold span --- frontend/components/AppTopNav.vue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/components/AppTopNav.vue b/frontend/components/AppTopNav.vue index 1f2b7e3..5cead14 100644 --- a/frontend/components/AppTopNav.vue +++ b/frontend/components/AppTopNav.vue @@ -62,7 +62,7 @@ >
-

{{ notification.actorName }} {{ notification.message }}

+

{{ notification.actorName }} {{ notification.message }}

{{ formatTimeAgo(notification.createdAt) }} - {{ notification.category }}

-- 2.39.5 From 5e2c6c219bd8eca42d3b631af223f0c732075b29 Mon Sep 17 00:00:00 2001 From: tristan Date: Wed, 24 Jun 2026 15:41:24 +0200 Subject: [PATCH 09/10] docs : document contract end notification feature --- CLAUDE.md | 4 +++ doc/contract-end-notifications.md | 35 ++++++++++++++++++++++++++ doc/functional-rules.md | 7 ++++++ frontend/data/documentation-content.ts | 1 + 4 files changed, 47 insertions(+) create mode 100644 doc/contract-end-notifications.md diff --git a/CLAUDE.md b/CLAUDE.md index 7a7ca49..dad7bff 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -212,6 +212,10 @@ - **Écran Journal refondu** (`frontend/pages/audit-logs.vue` + `useAuditLogsList`) : tableau en `MalioDataTable` (1er usage SIRH), **drawer de filtre** façon STARSEED (`MalioDrawer` + `MalioAccordion`, état brouillon/appliqué, badge compteur, Réinitialiser/Appliquer), **drawer de détail** au clic ligne. Filtres backend : `employee` (LIKE nom/prénom de l'employé affecté, via join), `username`/`ip`/`device` (LIKE insensible casse), `entityType[]`/`action[]` (IN), `perPage` (10/25/50/100, défaut 10). Filtres du drawer = champs texte (recherche libre), période en `MalioDateRange`, type/action en cases à cocher. Logique dans `useAuditLogsList` ; libellés FR en dur ; filtres hors URL. Provider/`AuditLogReadRepositoryInterface`/repository portent les nouveaux critères. - Documentation: `doc/audit-logging.md` +## Notifications +- Système : entité `Notification` (table `notifications`, `recipient`/`actor`/`message`/`category`/`target`/`isRead`), cloche **admin-only** dans `AppTopNav.vue`, providers `/notifications/{unread,today,history}` + `POST /notifications/mark-all-read`. Création historique : `WorkHourSiteValidationProcessor` (1 notif/admin via `UserRepository::findAllAdmins`). +- **Fin de contrat (J-1 ouvré)** : commande cron quotidienne `app:contract:end-notifications` (crontab prod, ~6h ; option `--date`). Notifie les admins sur le **dernier jour ouvré avant** `endDate` (inclusif) de la **dernière** période d'un employé (changement de contrat enchaîné exclu). Week-ends + fériés sautés (`WorkingDayCalculator`). Fenêtre couverte un jour J = `]J ; prochain_jour_ouvré(J)]`. Message « Fin de {nature} de {Nom} le {date} », catégorie `Contrat`, target `/employees/{id}`, acteur null. Idempotent (`NotificationRepository::existsForRecipientCategoryTargetMessage`). Logique pure testée : `ContractEndNotificationPlanner` + `WorkingDayCalculator`. Front : `AppTopNav.vue` masque le span acteur si `actorName` vide. Doc : `doc/contract-end-notifications.md`. + ## Backend Conventions - Prefer explicit DTOs over associative arrays - Business rules in backend (providers/processors/services), frontend is display/interaction only diff --git a/doc/contract-end-notifications.md b/doc/contract-end-notifications.md new file mode 100644 index 0000000..1dfa67a --- /dev/null +++ b/doc/contract-end-notifications.md @@ -0,0 +1,35 @@ +# Notification de fin de contrat (veille du dernier jour) + +## Objectif +Prévenir les administrateurs, sur le dernier jour ouvré précédant la fin d'un contrat, qu'un +salarié arrive au terme de son emploi. + +## Déclenchement +Commande `app:contract:end-notifications`, lancée chaque jour par le crontab de production +(ex. `0 6 * * *`). Option `--date=YYYY-MM-DD` pour test/rattrapage. Logger `cron`. + +## Règle métier +- **Cible** : la **dernière** période de contrat d'un employé (aucune période ne lui succède). + Un changement de contrat enchaîné (ex. CDD → CDI) ne notifie pas. +- **Quand** : sur le **dernier jour ouvré strictement avant** `endDate` (`endDate` est inclusif + = dernier jour travaillé). Les week-ends ET jours fériés (`PublicHolidayService`, zone + `metropole`) sont sautés. Concrètement, le jour J ouvré couvre les fins de contrat dans + l'intervalle `]J ; prochain_jour_ouvré(J)]` — un vendredi notifie ainsi les fins du + samedi, dimanche et lundi (mardi si lundi férié). +- **Destinataires** : tous les `ROLE_ADMIN`. +- **Message** : `Fin de {CDI|CDD|Intérim} de {Prénom Nom} le {dd/mm/yyyy}`, catégorie + `Contrat`, cible `/employees/{id}`, sans acteur. + +## Idempotence +Avant création, on vérifie l'absence d'une notif identique +`(recipient, category='Contrat', target, message)`. Le message étant unique par +(employé + date + nature), relancer la commande le même jour ne crée aucun doublon. + +## Implémentation +- `App\Service\Notification\WorkingDayCalculator` — jour ouvré / prochain jour ouvré. +- `App\Service\Notification\ContractEndNotificationPlanner` — sélection + message (pur, testé). +- `App\Service\Notification\ContractEndNotificationService` — persistance (1 notif/admin). +- `App\Command\ContractEndNotificationCommand` — `app:contract:end-notifications`. +- `EmployeeContractPeriodRepository::findLatestPeriodsForAllEmployees`, + `NotificationRepository::existsForRecipientCategoryTargetMessage`. +- Pas de migration : réutilise la table `notifications`. diff --git a/doc/functional-rules.md b/doc/functional-rules.md index 25d4be6..7e8ae6e 100644 --- a/doc/functional-rules.md +++ b/doc/functional-rules.md @@ -486,6 +486,13 @@ Seuls les employés dont au moins une période de contrat intersecte la période - condition: plus aucune ligne `work_hours` du site à la date concernée avec `isSiteValid = false` - destinataires: utilisateurs `ROLE_ADMIN` +- **Fin de contrat (J-1 ouvré)** : une commande quotidienne (`app:contract:end-notifications`) + notifie tous les admins, sur le dernier jour ouvré précédant la fin d'un contrat, qu'un + salarié arrive au terme de son emploi. Cible = **dernière** période de l'employé (un + changement de contrat enchaîné ne notifie pas). Week-ends et fériés sautés. Message + « Fin de {nature} de {Nom} le {date} », catégorie `Contrat`, lien vers la fiche employé, + sans acteur. Idempotente. Détail : `doc/contract-end-notifications.md`. + ## 16) Export PDF des heures annuelles - Accessible depuis la fiche employé (bouton imprimante à droite du nom) diff --git a/frontend/data/documentation-content.ts b/frontend/data/documentation-content.ts index d42404a..92ac7a2 100644 --- a/frontend/data/documentation-content.ts +++ b/frontend/data/documentation-content.ts @@ -268,6 +268,7 @@ export const documentationSections: DocSection[] = [ { type: 'paragraph', content: 'Deux tâches automatiques s\'exécutent quotidiennement pour gérer le report des compteurs.' }, { type: 'list', content: 'Report congés (02h10) : déclenche le report des congés payés le 1er juin (CDI/CDD) et le 1er janvier (forfait)\nReport RTT (02h15) : déclenche le report du solde RTT le 1er juin' }, { type: 'note', content: 'Ces tâches sont idempotentes : si elles s\'exécutent plusieurs fois, aucun doublon n\'est créé.' }, + { type: 'paragraph', content: 'Notification fin de contrat : chaque jour ouvré, les administrateurs sont prévenus (cloche en haut à droite) lorsqu\'un salarié atteint le dernier jour ouvré avant la fin de son contrat. Le message indique la nature du contrat, le nom du salarié et la date de fin, et renvoie vers sa fiche. Les week-ends et jours fériés sont pris en compte : une fin de contrat le lundi est signalée dès le vendredi.' }, ], }, ], -- 2.39.5 From d201489bcbf5764958f9bec8546fc57f0142a619 Mon Sep 17 00:00:00 2001 From: tristan Date: Wed, 24 Jun 2026 15:48:04 +0200 Subject: [PATCH 10/10] =?UTF-8?q?docs=20:=20note=20Lundi=20de=20Pentec?= =?UTF-8?q?=C3=B4te=20trait=C3=A9=20comme=20jour=20ouvr=C3=A9=20(choix=20d?= =?UTF-8?q?=C3=A9lib=C3=A9r=C3=A9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.8 (1M context) --- CLAUDE.md | 2 +- doc/contract-end-notifications.md | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index dad7bff..b035a86 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -214,7 +214,7 @@ ## Notifications - Système : entité `Notification` (table `notifications`, `recipient`/`actor`/`message`/`category`/`target`/`isRead`), cloche **admin-only** dans `AppTopNav.vue`, providers `/notifications/{unread,today,history}` + `POST /notifications/mark-all-read`. Création historique : `WorkHourSiteValidationProcessor` (1 notif/admin via `UserRepository::findAllAdmins`). -- **Fin de contrat (J-1 ouvré)** : commande cron quotidienne `app:contract:end-notifications` (crontab prod, ~6h ; option `--date`). Notifie les admins sur le **dernier jour ouvré avant** `endDate` (inclusif) de la **dernière** période d'un employé (changement de contrat enchaîné exclu). Week-ends + fériés sautés (`WorkingDayCalculator`). Fenêtre couverte un jour J = `]J ; prochain_jour_ouvré(J)]`. Message « Fin de {nature} de {Nom} le {date} », catégorie `Contrat`, target `/employees/{id}`, acteur null. Idempotent (`NotificationRepository::existsForRecipientCategoryTargetMessage`). Logique pure testée : `ContractEndNotificationPlanner` + `WorkingDayCalculator`. Front : `AppTopNav.vue` masque le span acteur si `actorName` vide. Doc : `doc/contract-end-notifications.md`. +- **Fin de contrat (J-1 ouvré)** : commande cron quotidienne `app:contract:end-notifications` (crontab prod, ~6h ; option `--date`). Notifie les admins sur le **dernier jour ouvré avant** `endDate` (inclusif) de la **dernière** période d'un employé (changement de contrat enchaîné exclu). Week-ends + fériés sautés (`WorkingDayCalculator`, via `getHolidaysDayByYears` → applique `EXCLUDED_PUBLIC_HOLIDAYS`, donc **Lundi de Pentecôte traité comme jour ouvré**, cohérent avec le reste de l'app). Fenêtre couverte un jour J = `]J ; prochain_jour_ouvré(J)]`. Message « Fin de {nature} de {Nom} le {date} », catégorie `Contrat`, target `/employees/{id}`, acteur null. Idempotent (`NotificationRepository::existsForRecipientCategoryTargetMessage`). Logique pure testée : `ContractEndNotificationPlanner` + `WorkingDayCalculator`. Front : `AppTopNav.vue` masque le span acteur si `actorName` vide. Doc : `doc/contract-end-notifications.md`. ## Backend Conventions - Prefer explicit DTOs over associative arrays diff --git a/doc/contract-end-notifications.md b/doc/contract-end-notifications.md index 1dfa67a..77752df 100644 --- a/doc/contract-end-notifications.md +++ b/doc/contract-end-notifications.md @@ -16,6 +16,13 @@ Commande `app:contract:end-notifications`, lancée chaque jour par le crontab de `metropole`) sont sautés. Concrètement, le jour J ouvré couvre les fins de contrat dans l'intervalle `]J ; prochain_jour_ouvré(J)]` — un vendredi notifie ainsi les fins du samedi, dimanche et lundi (mardi si lundi férié). +- **Jour de solidarité (Lundi de Pentecôte)** : traité comme un **jour ouvré** (choix + délibéré). Le calcul s'appuie sur `getHolidaysDayByYears`, qui applique + `EXCLUDED_PUBLIC_HOLIDAYS` (défaut = `"Lundi de Pentecôte"`) — la même liste de fériés que + le reste de l'app (heures, congés, RTT). On évite ainsi une définition de « férié » + divergente pour ce seul calcul ; et le jour de solidarité est, par nature, un jour travaillé + (admins présents → la cloche est vue). Une fin de contrat le mardi après Pentecôte est donc + notifiée le Lundi de Pentecôte, pas le vendredi précédent. - **Destinataires** : tous les `ROLE_ADMIN`. - **Message** : `Fin de {CDI|CDD|Intérim} de {Prénom Nom} le {dd/mm/yyyy}`, catégorie `Contrat`, cible `/employees/{id}`, sans acteur. -- 2.39.5