Compare commits

..
Author SHA1 Message Date
jmartinandCursor 8f8974d65e chore: pgAdmin derrière profile tools (éteint par défaut)
Évite de le relancer à chaque docker compose up / deploy.
Relance manuelle : docker compose --profile tools up -d pgadmin

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 12:32:07 +01:00
jmartin df130aedd9 feat(#216): Agenda B2 — soft-cancel + matrice + cron
Closes #216

Co-authored-by: Julien Martin <julien.martin@ptits-pas.fr>
2026-10-16 15:07:14 +00:00
jmartin 0ac8526053 fix(#217): TS2367 narrowing ANNULE — build Docker
Co-authored-by: Julien Martin <julien.martin@ptits-pas.fr>
2026-10-16 14:52:13 +00:00
jmartin 6419f4e8d3 feat(#217): Agenda B3 — filtres from/to + historique
Closes #217

Co-authored-by: Julien Martin <julien.martin@ptits-pas.fr>
2026-10-16 14:50:31 +00:00
jmartin af7d1b4da4 feat(#215): Agenda B1 — GET :id + DTO enrichi
Closes #215

Co-authored-by: Julien Martin <julien.martin@ptits-pas.fr>
2026-10-16 14:45:05 +00:00
jmartinandCursor 25d030601d merge master into develop: B0 + fix build + docs Agenda
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 16:37:33 +02:00
jmartin a972285787 Merge pull request 'feat(#214): Agenda B0' (#228) from feature/214-agenda-b0-migration into develop
feat(#214): Agenda B0 — migration BDD lots / soft-cancel / prefs

Merged via API.
2026-10-16 14:27:50 +00:00
jmartinandCursor d84cc7e13e feat(#214): migration Agenda B0 — lots, soft-cancel, prefs
Ajoute agenda_lots versionnés, colonnes soft-cancel / heure / id_lot
sur evenements_agenda, soft-cancel + remonte_le sur card_instances,
revision_lot sur card_responses, preferences JSONB utilisateurs.
Met à jour BDD.sql, ENUMS, verify.sql et entités TypeORM.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 16:16:34 +02:00
jmartinandCursor 38af471054 feat(#212): état vide Cartes — ours endormi + message
Remplace le texte sec par l’illustration aquarelle et le message soft ; CTA Ajouter une carte inchangé.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 11:00:26 +02:00
jmartinandCursor 7f554e2ba3 fix(#211): overflow pastilles bandeau + couple plus centré
Les pastilles se réduisent si la fenêtre est étroite ; le sélecteur couple est poussé vers le centre.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 10:44:04 +02:00
jmartinandCursor d05a5e22b2 feat(#211): sélecteur couple compact dans le bandeau
Déplace le contexte de garde (parent/AM) à côté du logo et retire le gros bandeau de la colonne Cartes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 10:37:04 +02:00
jmartinandCursor e6be1dffc4 feat(#207): polish affichage bulles soin + icônes sous-types
Layout type congés (date/heure puis détail italique), assets flacon/pansement/thermo_verre.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-09 16:46:29 +02:00
jmartinandCursor cec1fc2ba7 feat(front): alignement avec la spec backend soins enfant
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-09 16:46:29 +02:00
jmartinandCursor 1c0ff71f26 feat(front): implémentation UI soins enfant (#207)
- Ajout des formulaires spécifiques (fièvre, bobo, médicament) dans la modale d'ajout
- Formatage personnalisé du résumé des soins dans le feed
- Boutons supprimer / corriger (24h) pour l'AM
- Icônes contextuelles selon le sous-type de soin

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-09 16:46:29 +02:00
jmartinandCursor a5d1616a17 fix(cards): resolve typescript errors with payload typing
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 18:09:15 +02:00
jmartinandCursor 1e4e2d5198 fix(cards): allow payload object in DTOs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 18:03:24 +02:00
jmartinandCursor 8af579be53 feat(#206): backend cartes rose soin_enfant (3 sous-types, instant T, correction 24h)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 16:46:54 +02:00
jmartinandCursor a36e9ef176 feat(#175,#176): modale générique Ajouter une carte + CTA pilule
Creation absence (parent) et conge/arret (AM) via une seule modale
Material, catalogue UI extensible, calendrier de periode compact.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 22:36:29 +02:00
jmartin 5d36b0f4c1 Merge branch 'feature/174-feed-bulles-am' into develop
#174 feed bulles AM (widget partagé + polish UX).
2026-10-05 16:16:41 +02:00
jmartinandCursor ad48ab28cc feat(#174): feed bulles AM + libellés statut / tri stable
Branche CartesFeed sur le TdB AM ; Vu / En attente de validation ;
préserve is_creator SSE et tri par cree_le pour limiter les écarts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 16:16:36 +02:00
jmartin 342686f4e0 Merge branch 'feature/173-feed-bulles-parent' into develop
#173 feed bulles parent : UI, ack/SSE, correctifs cards.
2026-10-05 15:41:46 +02:00
jmartinandCursor d42927297d feat(#173): SSE live des bulles + ack sans modale
Abonnement /cards/stream pour sync co-parent en temps réel ;
acquittement (arrêt maladie) en un clic, sans confirmation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 15:41:34 +02:00
jmartinandCursor 1d3ec0b759 fix(cards): FK card_responses via relation JoinColumn + save(create)
Double mapping @Column/@JoinColumn sur id_card ; persist response via
card/user relations. Garde update() sur l’instance (évite save parent
qui nullifiait les FK enfants).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 15:18:43 +02:00
jmartinandCursor 608e62d662 fix(cards): éviter save() qui nullifie id_card des responses
TypeORM resynchronisait les relations au save(card) après accept/refuse
et faisait UPDATE card_responses SET id_card=null → 500.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 15:17:08 +02:00
jmartinandCursor dc491470db docs(#173): contrat API id_evenement (ex-id_absence) dans mini-spec bulles
Alignement post-#205 ; note front pour parser id_evenement.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 12:30:56 +02:00
jmartinandCursor 5a73da898b fix(#173): tri stable des bulles entre parents
Même ordre API (statut puis modifie_le) avec départage par id,
appliqué au chargement et après chaque réponse.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 12:21:25 +02:00
jmartinandCursor 0c736f5605 fix(cards): audience absence_enfant = AM + co-parents du foyer
Le resolver couple_am n’incluait que le créateur et l’AM ; le co-parent
ne voyait pas la notification. Docs : V1 réponses + modifs via agenda.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 12:19:30 +02:00
jmartinandCursor 6c8ef32a11 fix(#173): motif de refus plus visible sur les congés refusés
Affiche « Motif : … » pour les co-parents (réponse API ou payload),
et retire la capture flutter_01.png locale.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 12:03:54 +02:00
jmartinandCursor f3b2da4b4d feat(#173): icône arrêt maladie thermo_croix + Validée/Refusée
Remplace l’ancienne icône maladie ; statut féminin réservé aux
demandes de congés (pas d’absence ni d’arrêt maladie).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 11:34:36 +02:00
jmartinandCursor edab253296 feat(#173): layout bulles unifié, sac_lapin, statut Validé/Refusé
Icône absence aquarelle, calendrier teinté à la volée, encres par
famille de couleur, modales congés clarifiées, et libellé Validé/Refusé
dans la barre d’actions une fois la demande traitée.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 11:13:28 +02:00
jmartinandCursor d61e34a1e6 feat(#173): mapping type_code → teinte UI (sans couleur API)
Aqua/bleu/pêche/rose/lavande dérivés du type ; retrait du champ couleur.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:37:40 +02:00
jmartinandCursor 484fb9a3e5 chore: retire couleur des fixtures tests cards
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:11:56 +02:00
jmartinandCursor 72982f792b docs+fix(#173): API cards sans couleur ; alignement evenements_agenda
Couleur = mapping front (type_code). Spec §32 / mini-spec bulles.
Rebase sur develop (#205).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:11:39 +02:00
jmartinandCursor 32f6eeeeed feat(#173): carte congés maquette + mini-spec bulles pour alignement back
Layout aqua (valise, période une ligne, pilules peintes, lien agenda),
encre pétrole, et docs/32 pour palette sémantique + demandes API couleur.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 8b1c4555ad fix(#173): bulles congé AM en aqua (plus de lavande)
Override front tant que le back renvoie encore couleur=lavender.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor f978e65dfd chore: retirer l’import inutilisé de card_assets.dart
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 6683139429 feat(#173): ajouter la teinte aqua aux cartes (V + H)
Enums, mappings formulaires / bulles / enfants, assets inclus.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor da12418aa0 fix(#173): icône maladie style précédent, 1 boule, sur square
Conserve le look crayon + croix rose, thermomètre corrigé.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 8c778d1a6d fix(#173): thermomètre maladie à une seule boule sur square
Icône collée sur square.png comme les congés.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 1d68f86b3e fix(#173): icône arrêt maladie (1 boule + square.png)
Thermomètre corrigé (boule uniquement en bas), collé sur square.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 2a24c0a061 feat(#173): dégradés haut/bas sur la liste de bulles scrollable
Même logique que le slider enfants : fondu aux bords sauf au
premier et au dernier élément.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 07d3160bff fix(#173): icône en colonne à droite, texte (titre+dates) regroupé
Les 3 lignes restent ensemble à gauche face à l’icône.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor bace0edd96 fix(#173): restaurer icon_carte_conges2 avec fond carré opaque
Sans détourage — le fond crème fait partie du dessin.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor e267cdf8bc fix(#173): icône congés v2 (icon_carte_conges2)
Branche Demande de congés sur la version 2 détourée.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 9c021c56b3 fix(#173): détourage propre des icônes cartes + taille 80px
Fond blanc découpé (flood-fill), crop serré, affichage plus grand.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor c922421919 fix(#173): déclarer assets/images/cartes dans pubspec
Les nouvelles icônes n’étaient pas dans le build (hot restart
insuffisant pour les assets ajoutés).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor e91468616b feat(#173): icône dessin en haut à droite selon le type de bulle
Congés / arrêt maladie / absence — assets remplaçables dans
assets/images/cartes/.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 1f985f5b37 fix(#173): dates en Merienda, plus grandes, indentées ; sans motif
Retire l’affichage du commentaire / motif sur la bulle.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 7705a14bb5 fix(#173): layout bulle selon maquette (Du/Au + pilules larges)
Titre, dates en français sur deux lignes, actions coche/croix
en pilules pleine largeur côte à côte.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 535af3b146 fix(#173): actions en pilules + modales, fin des libellés À traiter
Arrêt maladie reste visible jusqu’à la date de fin ; accepter /
refuser / ack passent par une confirmation modale.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 2832499d3e fix(#173): libellés sémantiques des bulles (congés, arrêt, absence)
Demande de congés / Arrêt maladie / Notification d’absence.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 676e22665a docs(#173): schéma d’extension des cartes (extensible.png)
Référence visuelle des zones fixes / extensibles pour Carte.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 5eb0f13e75 refactor(#173): widget Carte (extensible par défaut) + fix bandeau
Renomme NineSlice* en Carte. Le bandeau couple s’étire en
horizontal seulement pour garder les bouts demi-cercle.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 2c461abc82 refactor(#173): widget NineSliceAsset réutilisable (cartes + bandeau)
Presets cards/bandeau, cache images, appliqué au sélecteur couple.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:41 +02:00
jmartinandCursor 42163826fe fix(#173): 9-slice manuel avec coins à taille logique fixe
Remplace DecorationImage.centerSlice (inopérant si bulle trop
basse) par un peintre 9 zones : coins fixes, centre extensible.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:40 +02:00
jmartinandCursor 7ff169d4c9 fix(#173): ExactAssetImage pour le scale 9-slice
AssetImage n’accepte pas scale ; ExactAssetImage oui.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:40 +02:00
jmartinandCursor ebf77b1ebb fix(#173): 9-slice dynamique sur les bulles (centerSlice)
Coins fixes, bords et centre extensibles selon la taille réelle
de la bulle — sans assets .9.png Android.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:40 +02:00
jmartinandCursor d53682110d feat(#173): feed bulles parent branché sur GET /cards
Affiche la file d’attention pastel (assets card_*_h) filtrée
par couple courant, avec accept / refus motivé / ack.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 17:10:40 +02:00
jmartin 290d442123 Merge branch 'feature/205-evenements-agenda' into develop
Renommage absences_garde → evenements_agenda (#205).
2026-10-01 17:08:01 +02:00
jmartinandCursor 2114748d44 feat(#205): renommer absences_garde → evenements_agenda
Migration live + BDD.sql from-scratch, module Nest / API
/evenements-agenda, FK cartes id_evenement. Front stub path aligné.

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

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

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

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 12:14:16 +02:00
jmartin 2380aa9826 Merge branch 'develop' of https://git.ptits-pas.fr/jmartin/petitspas into develop 2026-09-24 11:58:52 +02:00
jmartin c952113099 Merge branch 'feature/187-agenda-absences-stub' into develop 2026-09-24 11:58:38 +02:00
jmartinandCursor 8204669ec9 fix(ui): use TokenService to fix 401 Unauthorized when calling absences API
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 11:57:03 +02:00
jmartin 76ab0f340a Merge branch 'feature/195-realtime-cartes' into develop
Realtime SSE Cartes (#195).
2026-09-24 11:55:17 +02:00
jmartinandCursor a0a5e15b04 feat(front): add app icon for android, web and windows + agenda stub
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 11:53:43 +02:00
jmartinandCursor 823ea6cd22 feat(#195): SSE realtime Cartes (stream + emit audience)
GET /api/v1/cards/stream (Bearer ou ?access_token=).
Events card.created|updated|deleted, response.added + heartbeat.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 11:50:30 +02:00
jmartin dfac075a74 fix: JwtModule AbsencesGarde + Cards (AuthGuard DI)
Corrige crash-loop Nest AuthGuard DI.

Co-authored-by: Julien Martin <julien.martin@ptits-pas.fr>
2026-09-24 09:44:00 +00:00
jmartin 2d8b857a84 feat(#194): module Cartes SYSTEM
Closes #194

Co-authored-by: Julien Martin <julien.martin@ptits-pas.fr>
2026-09-24 09:38:39 +00:00
jmartin 147051821a feat(#172): API absences-garde (liste, CRUD, droits parent/AM)
Closes #172

Co-authored-by: Julien Martin <julien.martin@ptits-pas.fr>
2026-09-24 09:18:52 +00:00
15 changed files with 1521 additions and 85 deletions
+49
View File
@@ -15,6 +15,7 @@
"@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",
@@ -2544,6 +2545,22 @@
"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",
@@ -3767,6 +3784,12 @@
"@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",
@@ -5856,6 +5879,23 @@
"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",
@@ -8786,6 +8826,15 @@
"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,6 +29,7 @@
"@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,5 +1,6 @@
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';
@@ -58,6 +59,7 @@ import { SuppressionsModule } from './routes/suppressions/suppressions.module';
AuthModule, AuthModule,
AppConfigModule, AppConfigModule,
DocumentsLegauxModule, DocumentsLegauxModule,
ScheduleModule.forRoot(),
EvenementsAgendaModule, EvenementsAgendaModule,
CardsModule, CardsModule,
RelaisModule, RelaisModule,
+31
View File
@@ -0,0 +1,31 @@
/** 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,4 +373,80 @@ 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),
);
});
});
}); });
+26 -22
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()')
.orderBy( .andWhere('c.statut != :annulee', {
`CASE c.statut WHEN 'refusee' THEN 0 WHEN 'ouverte' THEN 1 ELSE 2 END`, annulee: CardInstanceStatutType.ANNULEE,
'ASC', })
) // Tri fil : COALESCE(remonte_le, cree_le) DESC (mini-spec §10)
.addOrderBy('c.modifie_le', 'DESC'); .orderBy('COALESCE(c.remonte_le, c.cree_le)', 'DESC');
if (placementId) { if (placementId) {
await this.assertPlacementAccess(userId, role, placementId); await this.assertPlacementAccess(userId, role, placementId);
@@ -251,6 +251,10 @@ 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');
} }
@@ -285,8 +289,11 @@ export class CardsService {
}), }),
); );
if (card.id_evenement) { // ACK informatif (arrêt / soin) : n’écrit plus sur l’événement (#216)
if (dto.action === CardResponseActionType.ACCEPT || dto.action === CardResponseActionType.ACK) { if (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,
}); });
@@ -298,8 +305,6 @@ 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);
@@ -456,22 +461,21 @@ 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);
} }
void absStatut; // Soft-cancel carte — aucun DELETE physique applicatif (#216)
} const now = new Date();
await this.cardsRepo.delete({ id: cardId }); await this.cardsRepo.update(
{ 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,
}); });
@@ -0,0 +1,50 @@
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);
});
});
@@ -0,0 +1,38 @@
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;
}
}
}
@@ -12,6 +12,7 @@ import {
StatutEvenementAgendaType, StatutEvenementAgendaType,
TypeEvenementAgendaType, TypeEvenementAgendaType,
} from 'src/entities/evenements_agenda.entity'; } from 'src/entities/evenements_agenda.entity';
import { AgendaLotStatutType } from 'src/entities/agenda_lots.entity';
export class CreerEvenementAgendaDto { export class CreerEvenementAgendaDto {
@ApiProperty({ description: 'Placement AM↔enfant (couple)' }) @ApiProperty({ description: 'Placement AM↔enfant (couple)' })
@@ -63,6 +64,25 @@ export class MajEvenementAgendaDto {
motif?: string; motif?: string;
} }
/** Droits calculés pour l’utilisateur courant — #215 */
export class EvenementAgendaActionsDto {
@ApiProperty({ description: 'Peut modifier dates / resoumettre (créateur)' })
peut_modifier: boolean;
@ApiProperty({ description: 'Peut annuler / soft-cancel (créateur)' })
peut_supprimer: boolean;
@ApiProperty({
description: 'Peut accept/refuse (parent habilité, congé en attente)',
})
peut_accepter_refuser: boolean;
@ApiProperty({
description: 'Peut ack informatif (ex. arrêt maladie)',
})
peut_ack: boolean;
}
export class EvenementAgendaDto { export class EvenementAgendaDto {
@ApiProperty() @ApiProperty()
id: string; id: string;
@@ -70,27 +90,82 @@ export class EvenementAgendaDto {
@ApiProperty() @ApiProperty()
id_placement: string; id_placement: string;
@ApiPropertyOptional({
description: 'Lot collectif (congé/arrêt/absence groupés)',
nullable: true,
})
id_lot?: string | null;
@ApiPropertyOptional({
description: 'Carte de collecte liée',
nullable: true,
})
id_card_instance?: string | null;
@ApiProperty({ enum: TypeEvenementAgendaType }) @ApiProperty({ enum: TypeEvenementAgendaType })
type: TypeEvenementAgendaType; type: TypeEvenementAgendaType;
@ApiProperty() @ApiProperty({ example: '2026-10-01' })
date_debut: string; date_debut: string;
@ApiProperty() @ApiProperty({ example: '2026-10-05' })
date_fin: string; date_fin: string;
@ApiProperty({ enum: StatutEvenementAgendaType }) @ApiPropertyOptional({
example: '18:19',
description: 'Heure métier (soin), HH:mm',
nullable: true,
})
heure?: string | null;
@ApiProperty({
enum: StatutEvenementAgendaType,
description: 'Statut de cet événement (membre du lot si lot)',
})
statut: StatutEvenementAgendaType; statut: StatutEvenementAgendaType;
@ApiPropertyOptional({
enum: AgendaLotStatutType,
description: 'Statut global du lot ; null si hors lot',
nullable: true,
})
statut_lot?: AgendaLotStatutType | null;
@ApiProperty({
enum: StatutEvenementAgendaType,
description:
'Statut à afficher pour l’utilisateur courant (peut différer du membre si lot refusé / nouvel accueil)',
})
statut_effectif: StatutEvenementAgendaType;
@ApiProperty() @ApiProperty()
expire_at: string; expire_at: string;
@ApiPropertyOptional({ nullable: true })
verrouille_le?: string | null;
@ApiPropertyOptional({ nullable: true })
refuse_le?: string | null;
@ApiPropertyOptional({ nullable: true })
annule_le?: string | null;
@ApiPropertyOptional() @ApiPropertyOptional()
cree_par?: string | null; cree_par?: string | null;
@ApiPropertyOptional() @ApiPropertyOptional({
description: 'Motif créateur ou texte de refus (sans nommer la famille)',
nullable: true,
})
motif?: string | null; motif?: string | null;
@ApiPropertyOptional({
description:
'Libellé de refus anonymisé : « Refusé par une autre famille » / « Refusé par l\'autre parent »',
nullable: true,
})
libelle_refus?: string | null;
@ApiPropertyOptional() @ApiPropertyOptional()
id_enfant?: string | null; id_enfant?: string | null;
@@ -106,6 +181,9 @@ export class EvenementAgendaDto {
@ApiPropertyOptional() @ApiPropertyOptional()
nom_am?: string | null; nom_am?: string | null;
@ApiProperty({ type: EvenementAgendaActionsDto })
actions: EvenementAgendaActionsDto;
@ApiProperty() @ApiProperty()
cree_le: string; cree_le: string;
@@ -10,6 +10,7 @@ describe('EvenementsAgendaController (#172)', () => {
let controller: EvenementsAgendaController; let controller: EvenementsAgendaController;
const serviceMock = { const serviceMock = {
lister: jest.fn(), lister: jest.fn(),
getById: jest.fn(),
creer: jest.fn(), creer: jest.fn(),
maj: jest.fn(), maj: jest.fn(),
supprimer: jest.fn(), supprimer: jest.fn(),
@@ -70,4 +71,14 @@ describe('EvenementsAgendaController (#172)', () => {
dto, dto,
); );
}); });
it('getById délègue au service — #215', async () => {
serviceMock.getById.mockResolvedValue({ id: 'ev-1', actions: {} });
await controller.getById('u1', RoleType.PARENT, 'ev-1');
expect(serviceMock.getById).toHaveBeenCalledWith(
'ev-1',
'u1',
RoleType.PARENT,
);
});
}); });
@@ -47,16 +47,18 @@ export class EvenementsAgendaController {
@Get() @Get()
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE) @Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
@ApiOperation({ @ApiOperation({
summary: 'Lister les absences / congés / arrêts — ticket #205 / ex-#172', summary: 'Lister les événements agenda — #217 / #205',
description: description:
'Sans placementId : tous les placements du user (parent = famille multi-AM ; AM = tous accueils). ' + 'Sans placementId : tous les placements du user (actifs **et** terminés — historique). ' +
'Avec placementId : un couple enfant–AM.', 'Avec placementId : un couple enfant–AM (terminé OK). ' +
'Filtres from/to inclusifs (chevauchement). Annulés exclus sauf si statut=annule. ' +
'Dates YYYY-MM-DD calendaires (DST-safe).',
}) })
@ApiQuery({ name: 'placementId', required: false }) @ApiQuery({ name: 'placementId', required: false })
@ApiQuery({ name: 'type', required: false, enum: TypeEvenementAgendaType }) @ApiQuery({ name: 'type', required: false, enum: TypeEvenementAgendaType })
@ApiQuery({ name: 'statut', required: false, enum: StatutEvenementAgendaType }) @ApiQuery({ name: 'statut', required: false, enum: StatutEvenementAgendaType })
@ApiQuery({ name: 'from', required: false, description: 'YYYY-MM-DD' }) @ApiQuery({ name: 'from', required: false, description: 'YYYY-MM-DD (inclus)' })
@ApiQuery({ name: 'to', required: false, description: 'YYYY-MM-DD' }) @ApiQuery({ name: 'to', required: false, description: 'YYYY-MM-DD (inclus)' })
@ApiResponse({ status: 200, type: ListeEvenementsAgendaDto }) @ApiResponse({ status: 200, type: ListeEvenementsAgendaDto })
lister( lister(
@User('id') userId: string, @User('id') userId: string,
@@ -76,6 +78,24 @@ export class EvenementsAgendaController {
}); });
} }
@Get(':id')
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
@ApiOperation({
summary: 'Détail d’un événement agenda — #215',
description:
'DTO enrichi : id_lot, heure, statut_lot, statut_effectif, actions. ' +
'Lecture autorisée sur placement terminé (historique). ' +
'Aucun secret sur l’auteur d’un refus d’une autre famille.',
})
@ApiResponse({ status: 200, type: EvenementAgendaDto })
getById(
@User('id') userId: string,
@User('role') role: RoleType,
@Param('id', ParseUUIDPipe) id: string,
): Promise<EvenementAgendaDto> {
return this.evenementsAgendaService.getById(id, userId, role);
}
@Post() @Post()
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE) @Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
@ApiOperation({ summary: 'Créer une période d’absence / congé / arrêt — #172' }) @ApiOperation({ summary: 'Créer une période d’absence / congé / arrêt — #172' })
@@ -3,14 +3,23 @@ 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([EvenementsAgenda, AmChildren, ParentsChildren]), TypeOrmModule.forFeature([
EvenementsAgenda,
AgendaLots,
CardInstance,
AmChildren,
ParentsChildren,
]),
JwtModule.registerAsync({ JwtModule.registerAsync({
imports: [ConfigModule], imports: [ConfigModule],
useFactory: (config: ConfigService) => ({ useFactory: (config: ConfigService) => ({
@@ -21,7 +30,7 @@ import { EvenementsAgendaService } from './evenements-agenda.service';
}), }),
], ],
controllers: [EvenementsAgendaController], controllers: [EvenementsAgendaController],
providers: [EvenementsAgendaService], providers: [EvenementsAgendaService, AgendaExpirationCron],
exports: [EvenementsAgendaService], exports: [EvenementsAgendaService],
}) })
export class EvenementsAgendaModule {} export class EvenementsAgendaModule {}
@@ -7,9 +7,22 @@ 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;
@@ -22,9 +35,19 @@ 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(),
@@ -39,6 +62,8 @@ 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),
@@ -48,6 +73,8 @@ 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', () => {
@@ -165,4 +192,477 @@ describe('EvenementsAgendaService (#172)', () => {
}), }),
).rejects.toBeInstanceOf(BadRequestException); ).rejects.toBeInstanceOf(BadRequestException);
}); });
it('getById enrichit le DTO — #215', async () => {
absencesRepo.findOne.mockResolvedValue({
id: 'ev-1',
id_placement: 'pl-1',
id_lot: 'lot-1',
id_card_instance: 'card-1',
type: TypeEvenementAgendaType.SOIN_ENFANT,
date_debut: '2026-10-16',
date_fin: '2026-10-16',
heure: '18:19:00',
statut: StatutEvenementAgendaType.ACCEPTE,
expire_at: new Date('9999-12-31'),
cree_par: 'am-1',
motif: 'Piqûre',
cree_le: new Date(),
modifie_le: new Date(),
lot: null,
placement: {
enfantId: 'e-1',
amId: 'am-1',
child: { id: 'e-1', first_name: 'Léo' },
am: { user: { prenom: 'Marie', nom: 'AM' } },
},
});
amChildrenRepo.findOne.mockResolvedValue({
id: 'pl-1',
amId: 'am-1',
enfantId: 'e-1',
date_fin: '2026-12-01',
});
parentsChildrenRepo.findOne.mockResolvedValue({
parentId: 'p-1',
enfantId: 'e-1',
});
const res = await service.getById('ev-1', 'p-1', RoleType.PARENT);
expect(res.id_lot).toBe('lot-1');
expect(res.id_card_instance).toBe('card-1');
expect(res.heure).toBe('18:19');
expect(res.statut_effectif).toBe(StatutEvenementAgendaType.ACCEPTE);
expect(res.actions.peut_ack).toBe(true);
expect(res.actions.peut_accepter_refuser).toBe(false);
});
it('getById autorise placement terminé (historique) — #215', async () => {
absencesRepo.findOne.mockResolvedValue({
id: 'ev-old',
id_placement: 'pl-ended',
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
date_debut: '2026-01-01',
date_fin: '2026-01-05',
statut: StatutEvenementAgendaType.ACCEPTE,
expire_at: new Date('9999-12-31'),
cree_par: 'p-1',
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' } },
},
});
amChildrenRepo.findOne.mockResolvedValue({
id: 'pl-ended',
amId: 'am-1',
enfantId: 'e-1',
date_fin: '2026-06-01',
});
parentsChildrenRepo.findOne.mockResolvedValue({
parentId: 'p-1',
enfantId: 'e-1',
});
const res = await service.getById('ev-old', 'p-1', RoleType.PARENT);
expect(res.id).toBe('ev-old');
expect(res.actions.peut_modifier).toBe(true);
});
describe('lister — #217', () => {
const andWhere = jest.fn().mockReturnThis();
const qb = {
leftJoinAndSelect: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
andWhere,
orderBy: jest.fn().mockReturnThis(),
getMany: jest.fn().mockResolvedValue([]),
};
beforeEach(() => {
andWhere.mockClear();
absencesRepo.createQueryBuilder.mockReturnValue(qb);
amChildrenRepo.find.mockResolvedValue([{ id: 'pl-1' }, { id: 'pl-ended' }]);
});
it('from > to → BadRequest', async () => {
await expect(
service.lister('am-1', RoleType.ASSISTANTE_MATERNELLE, {
from: '2026-10-31',
to: '2026-10-01',
}),
).rejects.toBeInstanceOf(BadRequestException);
});
it('date invalide (31 nov) → BadRequest', async () => {
await expect(
service.lister('am-1', RoleType.ASSISTANTE_MATERNELLE, {
from: '2026-11-31',
to: '2026-12-01',
}),
).rejects.toBeInstanceOf(BadRequestException);
});
it('exclut les annulés par défaut + bornes inclusives', async () => {
await service.lister('am-1', RoleType.ASSISTANTE_MATERNELLE, {
from: '2026-10-01',
to: '2026-10-31',
});
expect(amChildrenRepo.find).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ amId: 'am-1' }),
}),
);
// pas de date_fin: IsNull() → historique inclus
const whereArg = amChildrenRepo.find.mock.calls[0][0].where;
expect(whereArg.date_fin).toBeUndefined();
expect(andWhere).toHaveBeenCalledWith('ag.statut != :annule', {
annule: StatutEvenementAgendaType.ANNULE,
});
expect(andWhere).toHaveBeenCalledWith('ag.date_fin >= :from', {
from: '2026-10-01',
});
expect(andWhere).toHaveBeenCalledWith('ag.date_debut <= :to', {
to: '2026-10-31',
});
});
it('DST octobre : bornes calendaires acceptées (2026-10-25)', async () => {
// dernier dimanche d’octobre 2026 = 25 oct. — strings YYYY-MM-DD, pas Date UTC
await expect(
service.lister('am-1', RoleType.ASSISTANTE_MATERNELLE, {
from: '2026-10-25',
to: '2026-10-26',
}),
).resolves.toEqual({ items: [] });
expect(andWhere).toHaveBeenCalledWith('ag.date_fin >= :from', {
from: '2026-10-25',
});
});
it('année bissextile : 2024-02-29 valide', async () => {
await expect(
service.lister('am-1', RoleType.ASSISTANTE_MATERNELLE, {
from: '2024-02-29',
to: '2024-03-01',
}),
).resolves.toEqual({ items: [] });
});
it('2025-02-29 invalide (non bissextile)', async () => {
await expect(
service.lister('am-1', RoleType.ASSISTANTE_MATERNELLE, {
from: '2025-02-29',
to: '2025-03-01',
}),
).rejects.toBeInstanceOf(BadRequestException);
});
});
it('libelle_refus n’expose pas l’auteur — #215', async () => {
absencesRepo.findOne.mockResolvedValue({
id: 'ev-ref',
id_placement: 'pl-1',
type: TypeEvenementAgendaType.CONGE_AM,
date_debut: '2026-11-01',
date_fin: '2026-11-10',
statut: StatutEvenementAgendaType.REFUSE,
expire_at: new Date(),
cree_par: 'am-1',
motif: 'Vacances scolaires',
cree_le: new Date(),
modifie_le: new Date(),
lot: { statut: 'refuse' },
placement: {
enfantId: 'e-1',
amId: 'am-1',
child: { id: 'e-1', first_name: 'Léo' },
am: { user: { prenom: 'Marie', nom: 'AM' } },
},
});
amChildrenRepo.findOne.mockResolvedValue({
id: 'pl-1',
amId: 'am-1',
enfantId: 'e-1',
date_fin: null,
});
parentsChildrenRepo.findOne.mockResolvedValue({
parentId: 'p-1',
enfantId: 'e-1',
});
const res = await service.getById('ev-ref', 'p-1', RoleType.PARENT);
expect(res.libelle_refus).toBe('Refusé par une autre famille');
expect(res.statut_effectif).toBe(StatutEvenementAgendaType.REFUSE);
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,35 +2,58 @@ 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, Repository } from 'typeorm'; import { In, IsNull, LessThanOrEqual, Repository } from 'typeorm';
import { import {
EvenementsAgenda, EvenementsAgenda,
StatutEvenementAgendaType, StatutEvenementAgendaType,
TypeEvenementAgendaType, TypeEvenementAgendaType,
} from 'src/entities/evenements_agenda.entity'; } from 'src/entities/evenements_agenda.entity';
import {
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';
import { import {
EvenementAgendaDto, EvenementAgendaDto,
EvenementAgendaActionsDto,
CreerEvenementAgendaDto, CreerEvenementAgendaDto,
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';
const TTL_EN_ATTENTE_MS = 15 * 24 * 60 * 60 * 1000; /** Auto-valid / soft-cancel refusés = 7×24 h (mini-spec §5). */
const TTL_REFUSE_MS = 7 * 24 * 60 * 60 * 1000; const TTL_EN_ATTENTE_MS = MS_7X24H;
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)
@@ -48,10 +71,14 @@ export class EvenementsAgendaService {
to?: string; to?: string;
}, },
): Promise<ListeEvenementsAgendaDto> { ): Promise<ListeEvenementsAgendaDto> {
this.assertDateRange(opts.from, opts.to);
// Agenda : historique inclus (placements terminés) — #217
const placementIds = await this.resolvePlacementIds( const placementIds = await this.resolvePlacementIds(
userId, userId,
role, role,
opts.placementId, opts.placementId,
{ includeEnded: true },
); );
if (placementIds.length === 0) { if (placementIds.length === 0) {
return { items: [] }; return { items: [] };
@@ -63,15 +90,22 @@ export class EvenementsAgendaService {
.leftJoinAndSelect('placement.child', 'child') .leftJoinAndSelect('placement.child', 'child')
.leftJoinAndSelect('placement.am', 'am') .leftJoinAndSelect('placement.am', 'am')
.leftJoinAndSelect('am.user', 'amUser') .leftJoinAndSelect('am.user', 'amUser')
.leftJoinAndSelect('ag.lot', 'lot')
.where('ag.id_placement IN (:...placementIds)', { placementIds }) .where('ag.id_placement IN (:...placementIds)', { placementIds })
.orderBy('ag.date_debut', 'DESC'); .orderBy('ag.date_debut', 'DESC');
if (opts.type) { if (opts.type) {
qb.andWhere('ag.type = :type', { type: opts.type }); qb.andWhere('ag.type = :type', { type: opts.type });
} }
// Exclusion des annulés par défaut ; statut=annule demande explicitement les annulés
if (opts.statut) { if (opts.statut) {
qb.andWhere('ag.statut = :statut', { statut: opts.statut }); qb.andWhere('ag.statut = :statut', { statut: opts.statut });
} else {
qb.andWhere('ag.statut != :annule', {
annule: StatutEvenementAgendaType.ANNULE,
});
} }
// Chevauchement inclusif : date_debut <= to AND date_fin >= from
if (opts.from) { if (opts.from) {
qb.andWhere('ag.date_fin >= :from', { from: opts.from }); qb.andWhere('ag.date_fin >= :from', { from: opts.from });
} }
@@ -80,7 +114,18 @@ export class EvenementsAgendaService {
} }
const rows = await qb.getMany(); const rows = await qb.getMany();
return { items: rows.map((r) => this.toDto(r)) }; return {
items: rows.map((r) => this.toDto(r, userId, role)),
};
}
/** GET :id — #215 */
async getById(
id: string,
userId: string,
role: RoleType,
): Promise<EvenementAgendaDto> {
return this.getByIdForUser(id, userId, role);
} }
async creer( async creer(
@@ -89,17 +134,23 @@ 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), expire_at: this.expireAtFor(statut, now),
// 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,
}); });
@@ -117,23 +168,48 @@ 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);
// Parent : peut modifier ses absences enfant this.assertCalendarDate(debut, 'date_debut');
// AM : peut modifier congé/arrêt en_attente (avant accept) ou dates si créateur this.assertCalendarDate(fin, 'date_fin');
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) {
row.expire_at = this.expireAtFor(StatutEvenementAgendaType.EN_ATTENTE); // Toute modif de dates d’un événement soumis à validation → nouvelle revision
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 && dto.statut !== row.statut) { if (dto.statut !== undefined) {
// 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 &&
@@ -143,12 +219,25 @@ 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); row.expire_at = this.expireAtFor(dto.statut, now);
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;
} }
@@ -156,6 +245,10 @@ 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,
@@ -176,7 +269,140 @@ export class EvenementsAgendaService {
); );
} }
await this.absencesRepo.delete({ id }); this.assertCanSoftCancel(role, row);
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(
@@ -186,31 +412,171 @@ export class EvenementsAgendaService {
): Promise<EvenementAgendaDto> { ): Promise<EvenementAgendaDto> {
const row = await this.absencesRepo.findOne({ const row = await this.absencesRepo.findOne({
where: { id }, where: { id },
relations: ['placement', 'placement.child', 'placement.am', 'placement.am.user'], relations: [
'placement',
'placement.child',
'placement.am',
'placement.am.user',
'lot',
],
}); });
if (!row) { if (!row) {
throw new NotFoundException('Absence introuvable'); throw new NotFoundException('Événement introuvable');
} }
await this.assertCanAccessPlacement(userId, role, row.id_placement); // Lecture : historique autorisé même si placement terminé (B1 / prépare B3)
return this.toDto(row); await this.assertCanAccessPlacement(userId, role, row.id_placement, {
allowEnded: true,
});
return this.toDto(row, userId, role);
} }
private statutInitial(type: TypeEvenementAgendaType): StatutEvenementAgendaType { private statutInitial(type: TypeEvenementAgendaType): StatutEvenementAgendaType {
if (type === TypeEvenementAgendaType.ABSENCE_ENFANT || type === TypeEvenementAgendaType.SOIN_ENFANT) { // Arrêt maladie : accepté dès soumission (ack parent informatif seulement) — #216
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(statut: StatutEvenementAgendaType): Date { private expireAtFor(
const now = Date.now(); statut: StatutEvenementAgendaType,
if (statut === StatutEvenementAgendaType.ACCEPTE) { from: Date = new Date(),
return EXPIRE_ACCEPTE; ): Date {
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(now + TTL_REFUSE_MS); return new Date(t + 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 {
@@ -221,6 +587,33 @@ export class EvenementsAgendaService {
} }
} }
/** Bornes calendaires YYYY-MM-DD (comparaison lexicographique = calendaire, DST-safe). #217 */
private assertDateRange(from?: string, to?: string): void {
if (from) this.assertCalendarDate(from, 'from');
if (to) this.assertCalendarDate(to, 'to');
if (from && to && from > to) {
throw new BadRequestException('from doit être inférieure ou égale à to');
}
}
private assertCalendarDate(value: string, field: string): void {
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) {
throw new BadRequestException(
`${field} doit être une date YYYY-MM-DD`,
);
}
const [y, m, d] = value.split('-').map(Number);
// UTC : évite qu’un parse local fasse glisser le jour à l’heure d’hiver
const dt = new Date(Date.UTC(y, m - 1, d));
if (
dt.getUTCFullYear() !== y ||
dt.getUTCMonth() !== m - 1 ||
dt.getUTCDate() !== d
) {
throw new BadRequestException(`${field} n’est pas une date calendaire valide`);
}
}
private assertCanCreateType(role: RoleType, type: TypeEvenementAgendaType): void { private assertCanCreateType(role: RoleType, type: TypeEvenementAgendaType): void {
if (role === RoleType.PARENT) { if (role === RoleType.PARENT) {
if (type !== TypeEvenementAgendaType.ABSENCE_ENFANT) { if (type !== TypeEvenementAgendaType.ABSENCE_ENFANT) {
@@ -258,6 +651,9 @@ 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
@@ -269,7 +665,6 @@ 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');
@@ -284,25 +679,20 @@ export class EvenementsAgendaService {
_motif?: string, _motif?: string,
): void { ): void {
if (role === RoleType.PARENT) { if (role === RoleType.PARENT) {
// Accept / refuse congé ; ack arrêt (accepte) // Arrêt : déjà accepté à la soumission — ack carte n’écrit plus ici (#216)
if ( if (row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM) {
row.type === TypeEvenementAgendaType.CONGE_AM || throw new BadRequestException(
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM 'L’accusé de réception d’un arrêt maladie n’écrit pas sur l’événement',
) { );
}
// 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');
} }
@@ -332,9 +722,12 @@ export class EvenementsAgendaService {
userId: string, userId: string,
role: RoleType, role: RoleType,
placementId?: string, placementId?: string,
opts?: { includeEnded?: boolean },
): Promise<string[]> { ): Promise<string[]> {
if (placementId) { if (placementId) {
await this.assertCanAccessPlacement(userId, role, placementId); await this.assertCanAccessPlacement(userId, role, placementId, {
allowEnded: opts?.includeEnded === true,
});
return [placementId]; return [placementId];
} }
@@ -346,7 +739,9 @@ export class EvenementsAgendaService {
const enfantIds = liens.map((l) => l.enfantId); const enfantIds = liens.map((l) => l.enfantId);
if (enfantIds.length === 0) return []; if (enfantIds.length === 0) return [];
const placements = await this.amChildrenRepo.find({ const placements = await this.amChildrenRepo.find({
where: { enfantId: In(enfantIds), date_fin: IsNull() }, where: opts?.includeEnded
? { enfantId: In(enfantIds) }
: { enfantId: In(enfantIds), date_fin: IsNull() },
select: ['id'], select: ['id'],
}); });
return placements.map((p) => p.id); return placements.map((p) => p.id);
@@ -354,7 +749,9 @@ export class EvenementsAgendaService {
if (role === RoleType.ASSISTANTE_MATERNELLE) { if (role === RoleType.ASSISTANTE_MATERNELLE) {
const placements = await this.amChildrenRepo.find({ const placements = await this.amChildrenRepo.find({
where: { amId: userId, date_fin: IsNull() }, where: opts?.includeEnded
? { amId: userId }
: { amId: userId, date_fin: IsNull() },
select: ['id'], select: ['id'],
}); });
return placements.map((p) => p.id); return placements.map((p) => p.id);
@@ -367,12 +764,19 @@ export class EvenementsAgendaService {
userId: string, userId: string,
role: RoleType, role: RoleType,
placementId: string, placementId: string,
opts?: { allowEnded?: boolean },
): Promise<AmChildren> { ): Promise<AmChildren> {
const placement = await this.amChildrenRepo.findOne({ const placement = await this.amChildrenRepo.findOne({
where: { id: placementId, date_fin: IsNull() }, where: opts?.allowEnded
? { id: placementId }
: { id: placementId, date_fin: IsNull() },
}); });
if (!placement) { if (!placement) {
throw new NotFoundException('Placement / couple introuvable ou inactif'); throw new NotFoundException(
opts?.allowEnded
? 'Placement / couple introuvable'
: 'Placement / couple introuvable ou inactif',
);
} }
if (role === RoleType.ASSISTANTE_MATERNELLE) { if (role === RoleType.ASSISTANTE_MATERNELLE) {
@@ -397,26 +801,187 @@ export class EvenementsAgendaService {
throw new ForbiddenException('Rôle non autorisé'); throw new ForbiddenException('Rôle non autorisé');
} }
private toDto(row: EvenementsAgenda): EvenementAgendaDto { private toDto(
row: EvenementsAgenda,
userId?: string,
role?: RoleType,
): EvenementAgendaDto {
const child = row.placement?.child; const child = row.placement?.child;
const amUser = row.placement?.am?.user; const amUser = row.placement?.am?.user;
const statutLot = (row.lot?.statut as AgendaLotStatutType | undefined) ?? null;
const statutEffectif = this.statutEffectif(row, statutLot);
return { return {
id: row.id, id: row.id,
id_placement: row.id_placement, id_placement: row.id_placement,
id_lot: row.id_lot ?? null,
id_card_instance: row.id_card_instance ?? null,
type: row.type, type: row.type,
date_debut: row.date_debut, date_debut: row.date_debut,
date_fin: row.date_fin, date_fin: row.date_fin,
heure: this.formatHeure(row.heure),
statut: row.statut, statut: row.statut,
statut_lot: statutLot,
statut_effectif: statutEffectif,
expire_at: row.expire_at?.toISOString?.() ?? String(row.expire_at), expire_at: row.expire_at?.toISOString?.() ?? String(row.expire_at),
verrouille_le: row.verrouille_le
? row.verrouille_le.toISOString?.() ?? String(row.verrouille_le)
: null,
refuse_le: row.refuse_le
? row.refuse_le.toISOString?.() ?? String(row.refuse_le)
: null,
annule_le: row.annule_le
? row.annule_le.toISOString?.() ?? String(row.annule_le)
: null,
cree_par: row.cree_par ?? null, cree_par: row.cree_par ?? null,
motif: row.motif ?? null, motif: row.motif ?? null,
libelle_refus: this.libelleRefus(row, statutLot, userId, role),
id_enfant: child?.id ?? row.placement?.enfantId ?? null, id_enfant: child?.id ?? row.placement?.enfantId ?? null,
prenom_enfant: child?.first_name ?? null, prenom_enfant: child?.first_name ?? null,
id_am: row.placement?.amId ?? null, id_am: row.placement?.amId ?? null,
prenom_am: amUser?.prenom ?? null, prenom_am: amUser?.prenom ?? null,
nom_am: amUser?.nom ?? null, nom_am: amUser?.nom ?? null,
actions: this.actionsPour(row, statutLot, userId, role),
cree_le: row.cree_le?.toISOString?.() ?? String(row.cree_le), cree_le: row.cree_le?.toISOString?.() ?? String(row.cree_le),
modifie_le: row.modifie_le?.toISOString?.() ?? String(row.modifie_le), modifie_le: row.modifie_le?.toISOString?.() ?? String(row.modifie_le),
}; };
} }
private formatHeure(heure?: string | null): string | null {
if (!heure) return null;
const s = String(heure);
return s.length >= 5 ? s.slice(0, 5) : s;
}
private statutEffectif(
row: EvenementsAgenda,
statutLot: AgendaLotStatutType | null,
): StatutEvenementAgendaType {
if (row.statut === StatutEvenementAgendaType.ANNULE) {
return StatutEvenementAgendaType.ANNULE;
}
if (statutLot === AgendaLotStatutType.ANNULE) {
return StatutEvenementAgendaType.ANNULE;
}
if (statutLot === AgendaLotStatutType.REFUSE) {
return StatutEvenementAgendaType.REFUSE;
}
return row.statut;
}
/**
* Anonymise l’auteur du refus : jamais le nom d’une autre famille.
* B1 : si refusé et viewer ≠ créateur → « autre famille » ;
* si viewer est parent créateur/foyer et motif présent → « autre parent » pour co-parent
* (sans id répondant en B1 : défaut « autre famille » pour parent destinataire).
*/
private libelleRefus(
row: EvenementsAgenda,
statutLot: AgendaLotStatutType | null,
userId?: string,
role?: RoleType,
): string | null {
const refuse =
row.statut === StatutEvenementAgendaType.REFUSE ||
statutLot === AgendaLotStatutType.REFUSE;
if (!refuse) return null;
if (!userId || !role) return 'Refusé';
if (role === RoleType.ASSISTANTE_MATERNELLE) {
return 'Refusé par une famille';
}
// Parent : ne jamais citer quelle famille. Si ce n’est pas le créateur AM, message générique.
if (row.cree_par && row.cree_par === userId) {
return null;
}
return 'Refusé par une autre famille';
}
private actionsPour(
row: EvenementsAgenda,
statutLot: AgendaLotStatutType | null,
userId?: string,
role?: RoleType,
): EvenementAgendaActionsDto {
const none: EvenementAgendaActionsDto = {
peut_modifier: false,
peut_supprimer: false,
peut_accepter_refuser: false,
peut_ack: false,
};
if (!userId || !role) return none;
if (
row.statut === StatutEvenementAgendaType.ANNULE ||
statutLot === AgendaLotStatutType.ANNULE
) {
return none;
}
const isCreator = row.cree_par === userId;
const today = new Date().toISOString().slice(0, 10);
const notStarted = row.date_debut > today;
const enAttente =
row.statut === StatutEvenementAgendaType.EN_ATTENTE ||
statutLot === AgendaLotStatutType.EN_ATTENTE;
const refuse =
row.statut === StatutEvenementAgendaType.REFUSE ||
statutLot === AgendaLotStatutType.REFUSE;
const accepte =
row.statut === StatutEvenementAgendaType.ACCEPTE ||
statutLot === AgendaLotStatutType.ACCEPTE;
if (role === RoleType.ASSISTANTE_MATERNELLE && isCreator) {
const congeFuturModifiable =
row.type === TypeEvenementAgendaType.CONGE_AM &&
accepte &&
notStarted;
return {
peut_modifier:
enAttente || refuse || congeFuturModifiable ||
(row.type !== TypeEvenementAgendaType.CONGE_AM &&
row.type !== TypeEvenementAgendaType.SOIN_ENFANT &&
accepte),
peut_supprimer:
enAttente ||
refuse ||
(row.type === TypeEvenementAgendaType.CONGE_AM &&
accepte &&
notStarted) ||
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM ||
row.type === TypeEvenementAgendaType.SOIN_ENFANT,
peut_accepter_refuser: false,
peut_ack: false,
};
}
if (role === RoleType.PARENT && !isCreator) {
// ANNULE déjà exclu en tête de actionsPour (narrowing TS)
const congeEnAttente =
row.type === TypeEvenementAgendaType.CONGE_AM &&
row.statut === StatutEvenementAgendaType.EN_ATTENTE &&
statutLot !== AgendaLotStatutType.REFUSE;
const arretAck =
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM;
const soinAck = row.type === TypeEvenementAgendaType.SOIN_ENFANT;
return {
peut_modifier: false,
peut_supprimer: false,
peut_accepter_refuser: congeEnAttente,
peut_ack: arretAck || soinAck,
};
}
if (
role === RoleType.PARENT &&
isCreator &&
row.type === TypeEvenementAgendaType.ABSENCE_ENFANT
) {
return {
peut_modifier: true,
peut_supprimer: true,
peut_accepter_refuser: false,
peut_ack: false,
};
}
return none;
}
} }
+3 -1
View File
@@ -14,10 +14,12 @@ services:
networks: networks:
- ptitspas_network - ptitspas_network
# Interface d'administration DB # Interface d'administration DB (optionnel — pas démarré par défaut)
# 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}