Compare commits
155
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da71803852 | ||
|
|
2380aa9826 | ||
|
|
c952113099 | ||
|
|
8204669ec9 | ||
|
|
76ab0f340a | ||
|
|
a0a5e15b04 | ||
|
|
823ea6cd22 | ||
|
|
dfac075a74 | ||
|
|
2d8b857a84 | ||
|
|
147051821a | ||
|
|
41f7006073 | ||
|
|
8d8627cf38 | ||
|
|
6a586110e7 | ||
|
|
f9fd8d73a8 | ||
|
|
93ee3a5549 | ||
|
|
db08aca714 | ||
|
|
494f0e4c19 | ||
|
|
9a4664a8ea | ||
|
|
bf00933f65 | ||
|
|
7b4650b81b | ||
|
|
b7ae07f5aa | ||
|
|
a88f791317 | ||
|
|
138398a4a0 | ||
|
|
7cf30643aa | ||
|
|
5eb3468fe0 | ||
|
|
df4f48e864 | ||
|
|
6f9136aae5 | ||
|
|
461c70df05 | ||
|
|
fa88d00657 | ||
|
|
6e18956a63 | ||
|
|
745349bc83 | ||
|
|
89f65356d1 | ||
|
|
71b1897678 | ||
|
|
3218daa12e | ||
|
|
1d6261b312 | ||
|
|
9557cf9947 | ||
|
|
939e7777ac | ||
|
|
b474842e19 | ||
|
|
a312d9c0fa | ||
|
|
b5b32062b3 | ||
|
|
946d8edcd2 | ||
|
|
c8cb82dd24 | ||
|
|
9cd180bf6a | ||
|
|
ca07d2e111 | ||
|
|
67336c64fe | ||
|
|
97afbbcf9a | ||
|
|
e235b30140 | ||
|
|
7f23356273 | ||
|
|
c8c9cfbc4d | ||
|
|
530e896b66 | ||
|
|
0029c5ab86 | ||
|
|
2ce9e9215f | ||
|
|
3fdd913367 | ||
|
|
6708f73b06 | ||
|
|
f596f062a6 | ||
|
|
86701731e3 | ||
|
|
b4abb7d6de | ||
|
|
cb5c1a5518 | ||
|
|
30ca99fb65 | ||
|
|
8ee2ca8ea6 | ||
|
|
e3552667bc | ||
|
|
4ae334b247 | ||
|
|
471a62ddb7 | ||
|
|
59afeb0a8d | ||
|
|
d2172eafdb | ||
|
|
d247867fa0 | ||
|
|
93912d1374 | ||
|
|
925b6d5cd4 | ||
|
|
b0dddd6695 | ||
|
|
ef7512dc1e | ||
|
|
2ececa711b | ||
|
|
7a3d997ff9 | ||
|
|
6b89d7b405 | ||
|
|
f7ac628445 | ||
|
|
26e9738ec7 | ||
|
|
0ec3410457 | ||
|
|
c3acf1970d | ||
|
|
6fe2b89a61 | ||
|
|
d6a9b3fd66 | ||
|
|
134b9781c8 | ||
|
|
b936d27445 | ||
|
|
18c1d1eba7 | ||
|
|
f74b14c203 | ||
|
|
f194b5f9e8 | ||
|
|
5ab8ae3423 | ||
|
|
3277f77846 | ||
|
|
2d80ad0d7e | ||
|
|
09386f8aa6 | ||
|
|
faa50f637c | ||
|
|
267fe63aec | ||
|
|
90b185740c | ||
|
|
b903dbf60b | ||
|
|
291ea26b34 | ||
|
|
59919834b9 | ||
|
|
cf6acbae7c | ||
|
|
7951c38d4d | ||
|
|
77d952a6f7 | ||
|
|
b4b546044d | ||
|
|
6788351070 | ||
|
|
d6dac181d2 | ||
|
|
7b69f27ca5 | ||
|
|
003fe6b762 | ||
|
|
8ed68797aa | ||
|
|
9ad371a342 | ||
|
|
18718670e9 | ||
|
|
fbf22f2540 | ||
|
|
43a2cd213b | ||
|
|
c865d11dc3 | ||
|
|
d03a8e6c8b | ||
|
|
66c7f22280 | ||
|
|
53721ffbb3 | ||
|
|
52e40d0001 | ||
|
|
4985726bc6 | ||
|
|
479a32b4bf | ||
|
|
2fd97ddecb | ||
|
|
ce474797c4 | ||
|
|
ebf794e1ac | ||
|
|
d55f240f56 | ||
|
|
966f4a9c9c | ||
|
|
8494341b56 | ||
|
|
1dddc67933 | ||
|
|
b99745e0fe | ||
|
|
df776d8200 | ||
|
|
c26ed00374 | ||
|
|
9d54d9b19b | ||
|
|
c438009286 | ||
|
|
9b7231f1da | ||
|
|
f300505225 | ||
|
|
25c10c885a | ||
|
|
d70577b1c3 | ||
|
|
671da71752 | ||
|
|
c226c2fcdf | ||
|
|
e1684676a7 | ||
|
|
f71943fa79 | ||
|
|
65f10e9ca6 | ||
|
|
9eb62ddd13 | ||
|
|
b6e83bf9ef | ||
|
|
919148fa75 | ||
|
|
7ba8d51668 | ||
|
|
43dabd1885 | ||
|
|
a4eee819cd | ||
|
|
3fd4812a07 | ||
|
|
6f39813bb4 | ||
|
|
18f3a7f276 | ||
|
|
e6a087147a | ||
|
|
ca88710e49 | ||
|
|
644ba6c9c9 | ||
|
|
15123f691c | ||
|
|
e51e625d93 | ||
|
|
7765350d9a | ||
|
|
46d0f82f54 | ||
|
|
dff108c7d5 | ||
|
|
4723c78bbb | ||
|
|
699d163c6a | ||
|
|
d91caef0c5 |
@@ -89,6 +89,9 @@
|
|||||||
"transform": {
|
"transform": {
|
||||||
"^.+\\.(t|j)s$": "ts-jest"
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
},
|
},
|
||||||
|
"moduleNameMapper": {
|
||||||
|
"^src/(.*)$": "<rootDir>/$1"
|
||||||
|
},
|
||||||
"collectCoverageFrom": [
|
"collectCoverageFrom": [
|
||||||
"**/*.(t|j)s"
|
"**/*.(t|j)s"
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -33,7 +33,6 @@ model Child {
|
|||||||
dateOfBirth DateTime
|
dateOfBirth DateTime
|
||||||
photoUrl String?
|
photoUrl String?
|
||||||
photoConsent Boolean @default(false)
|
photoConsent Boolean @default(false)
|
||||||
isMultiple Boolean @default(false)
|
|
||||||
isUnborn Boolean @default(false)
|
isUnborn Boolean @default(false)
|
||||||
parentId String
|
parentId String
|
||||||
parent Parent @relation(fields: [parentId], references: [id])
|
parent Parent @relation(fields: [parentId], references: [id])
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
/**
|
||||||
|
* Commentaire de clôture + fermeture issue Gitea #131.
|
||||||
|
* Usage: node backend/scripts/close-gitea-issue-131.js
|
||||||
|
*/
|
||||||
|
const https = require('https');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const repoRoot = path.join(__dirname, '../..');
|
||||||
|
const ISSUE = 131;
|
||||||
|
const REPO = 'jmartin/petitspas';
|
||||||
|
|
||||||
|
const body = `## Fermeture ticket #131 — livré sur \`develop\` et \`master\`
|
||||||
|
|
||||||
|
Branche **\`feature/131\`** mergée dans **\`develop\`**, puis squash merge **\`develop\` → \`master\`** (déploiement production).
|
||||||
|
|
||||||
|
### Fiche parent (dashboard admin)
|
||||||
|
- Modale **\`AdminParentEditModal\`** éditable dès l'ouverture
|
||||||
|
- En-tête dynamique : **nom/prénom** + sous-titre **co-parent** (si connu)
|
||||||
|
- Gélule **statut** modifiable
|
||||||
|
- **\`PATCH /api/v1/parents/:id/fiche\`** — identité + statut
|
||||||
|
- **\`GET /api/v1/parents\`** — liste parents (fix décorateur \`@Get()\` manquant)
|
||||||
|
- Réponses API : \`co_parent\` peuplé, secrets user masqués (\`sanitizeUserForApi\`)
|
||||||
|
- Liste enfants en bas de fiche + rattachement/détachement
|
||||||
|
|
||||||
|
### Fiche AM (dashboard admin)
|
||||||
|
- Modale **\`AdminAmEditModal\`** — 3 onglets : Identité | Fiche pro | Enfants accueillis
|
||||||
|
- **\`PATCH /api/v1/assistantes-maternelles/:id/fiche\`** — identité + champs pro (NIR, date/lieu naissance, date agrément, places, disponibilité)
|
||||||
|
- **\`POST/DELETE …/enfants/:enfantId\`** — rattacher / détacher un enfant
|
||||||
|
- Grille capacité **\`AdminAmChildrenCapacityGrid\`** (2×2)
|
||||||
|
- Rattachement enfants **différé jusqu'à Sauvegarder** (pas d'appel API immédiat)
|
||||||
|
|
||||||
|
### Back — placement AM ↔ enfant
|
||||||
|
- Table **\`enfants_assistantes_maternelles\`** (placement temporel, 1 garde active/enfant)
|
||||||
|
- Enum enfant : \`a_naitre\`, \`garde\`, \`sans_garde\`, \`scolarise\` — **plus \`actif\`**
|
||||||
|
- Rattachement → statut enfant \`garde\` ; détachement → \`sans_garde\`
|
||||||
|
- Migration : \`database/migrations/2026_enfants_assistantes_maternelles.sql\`
|
||||||
|
- Schéma canonique : \`database/BDD.sql\`
|
||||||
|
|
||||||
|
### Front — statuts & polish
|
||||||
|
- **\`enfant_status_utils.dart\`** — libellés/couleurs \`garde\`/\`sans_garde\`
|
||||||
|
- Mise à jour cartes enfants, modale détail, filtres dashboard
|
||||||
|
|
||||||
|
### Correctifs recette
|
||||||
|
- \`GET /parents\` 404 → ajout \`@Get()\` sur \`getAll()\`
|
||||||
|
- Sauvegarde AM 400 → alignement DTO \`UpdateAmFicheAdminDto\` sur payload front
|
||||||
|
- Crash NIR → fix \`toISOString\` + pas d'effacement NIR (colonne NOT NULL)
|
||||||
|
|
||||||
|
### Hors périmètre #131 (tickets voisins)
|
||||||
|
- **#137** onglet Enfants global · **#138** fiche enfant complète · **#115/#116** affiliation avancée
|
||||||
|
|
||||||
|
---
|
||||||
|
*Issue fermée après merge sur \`develop\` + \`master\` et déploiement production.*`;
|
||||||
|
|
||||||
|
let token = process.env.GITEA_TOKEN;
|
||||||
|
if (!token) {
|
||||||
|
try {
|
||||||
|
const tokenFile = path.join(repoRoot, '.gitea-token');
|
||||||
|
if (fs.existsSync(tokenFile)) token = fs.readFileSync(tokenFile, 'utf8').trim();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
if (!token) {
|
||||||
|
try {
|
||||||
|
const briefing = fs.readFileSync(
|
||||||
|
path.join(repoRoot, 'docs/27_BRIEFING-FRONTEND.md'),
|
||||||
|
'utf8',
|
||||||
|
);
|
||||||
|
const m = briefing.match(/Token:\s*(giteabu_[a-f0-9]+)/);
|
||||||
|
if (m) token = m[1].trim();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
if (!token) {
|
||||||
|
console.error('Token non trouvé : .gitea-token ou GITEA_TOKEN');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function request(method, apiPath, payloadObj) {
|
||||||
|
const payload = payloadObj ? JSON.stringify(payloadObj) : null;
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const opts = {
|
||||||
|
hostname: 'git.ptits-pas.fr',
|
||||||
|
path: `/api/v1/repos/${REPO}${apiPath}`,
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
Authorization: 'token ' + token,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const req = https.request(opts, (res) => {
|
||||||
|
let d = '';
|
||||||
|
res.on('data', (c) => (d += c));
|
||||||
|
res.on('end', () => {
|
||||||
|
if (res.statusCode !== 200 && res.statusCode !== 201) {
|
||||||
|
reject(new Error(`HTTP ${res.statusCode}: ${d}`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
resolve(d ? JSON.parse(d) : {});
|
||||||
|
} catch (_) {
|
||||||
|
resolve({});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
req.on('error', reject);
|
||||||
|
if (payload) req.write(payload);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
console.log(`POST commentaire issue #${ISSUE}...`);
|
||||||
|
await request('POST', `/issues/${ISSUE}/comments`, { body });
|
||||||
|
console.log('Commentaire publié.');
|
||||||
|
console.log(`PATCH fermeture issue #${ISSUE}...`);
|
||||||
|
await request('PATCH', `/issues/${ISSUE}`, { state: 'closed' });
|
||||||
|
console.log(`Issue #${ISSUE} fermée.`);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e.message || e);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
})();
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
/**
|
||||||
|
* Crée l'issue Gitea — gestionnaire ne doit pas pouvoir se supprimer.
|
||||||
|
* Usage: node backend/scripts/create-gitea-issue-gestionnaire-self-delete.js
|
||||||
|
*/
|
||||||
|
const https = require('https');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const repoRoot = path.join(__dirname, '../..');
|
||||||
|
const MILESTONE_0_1_0 = 10;
|
||||||
|
|
||||||
|
let token = process.env.GITEA_TOKEN;
|
||||||
|
if (!token) {
|
||||||
|
try {
|
||||||
|
const tokenFile = path.join(repoRoot, '.gitea-token');
|
||||||
|
if (fs.existsSync(tokenFile)) token = fs.readFileSync(tokenFile, 'utf8').trim();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
if (!token) {
|
||||||
|
try {
|
||||||
|
const briefing = fs.readFileSync(
|
||||||
|
path.join(repoRoot, 'docs/27_BRIEFING-FRONTEND.md'),
|
||||||
|
'utf8',
|
||||||
|
);
|
||||||
|
const m = briefing.match(/Token:\s*(gitebu_[a-f0-9]+)/);
|
||||||
|
if (m) token = m[1].trim();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
if (!token) {
|
||||||
|
console.error('Token non trouvé : .gitea-token ou GITEA_TOKEN');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = `## Contexte
|
||||||
|
|
||||||
|
Quand un **gestionnaire** connecté ouvre sa propre fiche dans l'onglet **Gestionnaires** (Gestion des utilisateurs), la modale **Modifier un "Gestionnaire"** affiche le bouton **Supprimer**.
|
||||||
|
|
||||||
|
Comportement actuel : le gestionnaire voit et peut tenter de supprimer son propre compte.
|
||||||
|
|
||||||
|
## Comportement attendu
|
||||||
|
|
||||||
|
Comme pour le **super administrateur** (bouton Supprimer masqué sur la fiche super admin) :
|
||||||
|
|
||||||
|
- **Pas de bouton Supprimer** quand l'utilisateur édite **sa propre fiche**
|
||||||
|
- **Modification** des informations (prénom, nom, email, téléphone, relais, mot de passe) **toujours autorisée**
|
||||||
|
|
||||||
|
## Périmètre
|
||||||
|
|
||||||
|
- Frontend : \`AdminUserFormDialog\` (\`gestionnaires_create.dart\`)
|
||||||
|
- Comparer \`initialUser.id\` avec l'utilisateur connecté (\`AuthService.getCurrentUser\`)
|
||||||
|
- Masquer Supprimer si édition de soi-même ; conserver garde existante super admin
|
||||||
|
|
||||||
|
## Critères d'acceptation
|
||||||
|
|
||||||
|
- [ ] Gestionnaire connecté → ouvre sa fiche → **pas** de bouton Supprimer
|
||||||
|
- [ ] Gestionnaire connecté → peut **Modifier** ses informations
|
||||||
|
- [ ] Super admin / admin → peut toujours supprimer **un autre** gestionnaire (si droits API)
|
||||||
|
- [ ] Pas de régression sur fiche super administrateur (Supprimer toujours masqué)
|
||||||
|
|
||||||
|
## Fichiers clés
|
||||||
|
|
||||||
|
- \`frontend/lib/screens/administrateurs/creation/gestionnaires_create.dart\`
|
||||||
|
- \`frontend/lib/widgets/admin/gestionnaire_management_widget.dart\`
|
||||||
|
|
||||||
|
## Milestone
|
||||||
|
|
||||||
|
**0.1.0** — correction UX / sécurité gestion utilisateurs.`;
|
||||||
|
|
||||||
|
const payloadClean = JSON.stringify({
|
||||||
|
title: '[Bug] Gestionnaire peut voir Supprimer sur sa propre fiche',
|
||||||
|
body,
|
||||||
|
milestone: MILESTONE_0_1_0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const opts = {
|
||||||
|
hostname: 'git.ptits-pas.fr',
|
||||||
|
path: '/api/v1/repos/jmartin/petitspas/issues',
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
Authorization: 'token ' + token,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Content-Length': Buffer.byteLength(payloadClean),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const req = https.request(opts, (res) => {
|
||||||
|
let d = '';
|
||||||
|
res.on('data', (c) => (d += c));
|
||||||
|
res.on('end', () => {
|
||||||
|
try {
|
||||||
|
const o = JSON.parse(d);
|
||||||
|
if (o.number) {
|
||||||
|
console.log('NUMBER:', o.number);
|
||||||
|
console.log('URL:', o.html_url);
|
||||||
|
console.log('MILESTONE:', o.milestone?.title ?? '(aucun)');
|
||||||
|
} else {
|
||||||
|
console.error('Réponse:', d);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(d);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
req.on('error', (e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
req.write(payloadClean);
|
||||||
|
req.end();
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
/**
|
||||||
|
* Met à jour l'issue Gitea #140 — epic dashboard admin ch.6 famille.
|
||||||
|
* Usage: node backend/scripts/update-gitea-issue-140-ch6-famille.js
|
||||||
|
* Token : .gitea-token (racine), GITEA_TOKEN, ou docs/27_BRIEFING-FRONTEND.md
|
||||||
|
*/
|
||||||
|
const https = require('https');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const repoRoot = path.join(__dirname, '../..');
|
||||||
|
let token = process.env.GITEA_TOKEN;
|
||||||
|
if (!token) {
|
||||||
|
try {
|
||||||
|
const tokenFile = path.join(repoRoot, '.gitea-token');
|
||||||
|
if (fs.existsSync(tokenFile)) token = fs.readFileSync(tokenFile, 'utf8').trim();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
if (!token) {
|
||||||
|
try {
|
||||||
|
const briefing = fs.readFileSync(
|
||||||
|
path.join(repoRoot, 'docs/27_BRIEFING-FRONTEND.md'),
|
||||||
|
'utf8',
|
||||||
|
);
|
||||||
|
const m = briefing.match(/Token:\s*(giteabu_[a-f0-9]+)/);
|
||||||
|
if (m) token = m[1].trim();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
if (!token) {
|
||||||
|
console.error('Token non trouvé : .gitea-token ou GITEA_TOKEN (voir docs/26_GITEA-API.md)');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = `## Rôle de ce ticket
|
||||||
|
|
||||||
|
**#140 est un ticket epic / livraison** : il regroupe la mise en œuvre du **chapitre 6** du doc [28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md](../docs/28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md) (§6.1 et §6.2) sur la branche \`feature/140-dashboard-admin-ch6-famille\`.
|
||||||
|
|
||||||
|
Il **ne remplace pas** les tickets détaillés ci-dessous : il sert de **fil de livraison** (PR, recette, fermeture coordonnée). Chaque sous-ticket garde son périmètre propre ; #140 est clos quand l'ensemble est **fonctionnel et homogène en UI**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tickets couverts (périmètres embarqués)
|
||||||
|
|
||||||
|
| Ticket | Sujet | Rôle dans #140 |
|
||||||
|
|--------|--------|----------------|
|
||||||
|
| **#115** | Rattachement parent — **backend** | API \`POST/DELETE …/enfants/:enfantId\` |
|
||||||
|
| **#116** | Rattachement parent — **frontend** | UI rattacher / détacher depuis la fiche parent |
|
||||||
|
| **#130** | \`UserService\` — APIs admin | Appels \`getParents\`, \`getParent\`, \`getEnfants\`, \`updateParentFiche\`, etc. |
|
||||||
|
| **#131** | Fiche parent éditable | Modale parent (dashboard) — *hors fiche AM* |
|
||||||
|
| **#137** | Onglet **Enfants** | Liste globale admin + accès fiche enfant |
|
||||||
|
| **#138** | Fiche enfant + liste dans fiche parent | \`AdminChildDetailModal\` + liste enfants en bas de fiche parent |
|
||||||
|
|
||||||
|
> **Note :** fermer #140 peut entraîner la fermeture **partielle ou totale** de ces tickets selon ce qui est réellement livré et recetté dans la PR.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hors scope #140
|
||||||
|
|
||||||
|
- **§6.3** — Création dossier admin sans numéro → **#129**
|
||||||
|
- Fiche **AM** éditable (dashboard) → reste **#131** (partie AM)
|
||||||
|
- Parcours gestionnaire « famille complexe » → **#139**
|
||||||
|
- Qualification responsable légal (combobox sur lien) → ticket à créer
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Backend (attendu / livré)
|
||||||
|
|
||||||
|
- [x] \`PATCH /parents/:id/fiche\` — édition fiche parent (admin/gestionnaire)
|
||||||
|
- [x] \`POST /parents/:id/enfants/:enfantId\` — rattacher un enfant existant
|
||||||
|
- [x] \`DELETE /parents/:id/enfants/:enfantId\` — détacher (garde-fou : ≥1 responsable / enfant)
|
||||||
|
- [x] \`GET /enfants\` enrichi ; \`PATCH /enfants/:id\` pour gestionnaire
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Frontend — fait
|
||||||
|
|
||||||
|
- [x] Modale **fiche parent** éditable (shell aligné validation, statut gélule, téléphone formaté, \`IdentityBlock\`)
|
||||||
|
- [x] Onglet **Enfants** — liste globale (\`EnfantManagementWidget\`)
|
||||||
|
- [x] Liste enfants dans fiche parent — cartes (photo, nom, âge ans/mois, statut), cadre blanc, scroll 2,5 lignes
|
||||||
|
- [x] Rattacher / détacher un enfant **existant** (API branchée)
|
||||||
|
- [x] Parsing robuste \`parentChildren\` + URLs médias \`/uploads\` en Flutter web
|
||||||
|
- [x] \`UserService\` — APIs parents / enfants / affiliation
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Frontend — reste à faire (bloquant clôture)
|
||||||
|
|
||||||
|
### Fiche enfant — #138 (UI)
|
||||||
|
- [ ] Reprendre \`AdminChildDetailModal\` : même **look & feel** que fiche parent / modales validation (largeur ~930 px, grille champs, photo enfant)
|
||||||
|
- [ ] Aligner dates, genre, statut sur les wizards validation famille
|
||||||
|
|
||||||
|
### Modale **rattacher** un enfant — #116 (UI)
|
||||||
|
- [ ] Remplacer le \`SimpleDialog\` actuel par une modale cohérente : liste type \`AdminEnfantUserCard\` (photo, nom, âge), recherche éventuelle
|
||||||
|
|
||||||
|
### Création d'un **nouvel** enfant depuis la fiche parent — doc §6.2
|
||||||
|
- [ ] **Non implémenté** aujourd'hui (seul le rattachement d'un enfant déjà en base existe)
|
||||||
|
- [ ] À trancher : inclus dans #140 si le back expose un \`POST\` admin depuis le contexte parent, sinon ticket dédié / extension #129
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Recette avant merge
|
||||||
|
|
||||||
|
1. Parent avec 0 / 1 / 3+ enfants — liste, scroll, compteur
|
||||||
|
2. Rattacher puis détacher (message si dernier responsable)
|
||||||
|
3. Clic enfant → fiche enfant (après refonte UI)
|
||||||
|
4. Onglet Enfants — même rendu cartes
|
||||||
|
5. Avatars photos (URLs absolues web)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Branche
|
||||||
|
|
||||||
|
\`feature/140-dashboard-admin-ch6-famille\`
|
||||||
|
|
||||||
|
## Références
|
||||||
|
|
||||||
|
- Doc produit : \`docs/28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md\` §6.1, §6.2`;
|
||||||
|
|
||||||
|
const payload = JSON.stringify({ body });
|
||||||
|
|
||||||
|
const req = https.request(
|
||||||
|
{
|
||||||
|
hostname: 'git.ptits-pas.fr',
|
||||||
|
path: '/api/v1/repos/jmartin/petitspas/issues/140',
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: {
|
||||||
|
Authorization: `token ${token}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Content-Length': Buffer.byteLength(payload),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
(res) => {
|
||||||
|
let data = '';
|
||||||
|
res.on('data', (chunk) => {
|
||||||
|
data += chunk;
|
||||||
|
});
|
||||||
|
res.on('end', () => {
|
||||||
|
if (res.statusCode >= 200 && res.statusCode < 300) {
|
||||||
|
const json = JSON.parse(data);
|
||||||
|
console.log('Issue #140 mise à jour :', json.html_url);
|
||||||
|
console.log('updated_at:', json.updated_at);
|
||||||
|
} else {
|
||||||
|
console.error('Erreur', res.statusCode, data);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
req.on('error', (err) => {
|
||||||
|
console.error(err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
req.write(payload);
|
||||||
|
req.end();
|
||||||
@@ -16,8 +16,11 @@ import { AllExceptionsFilter } from './common/filters/all_exceptions.filters';
|
|||||||
import { EnfantsModule } from './routes/enfants/enfants.module';
|
import { EnfantsModule } from './routes/enfants/enfants.module';
|
||||||
import { AppConfigModule } from './modules/config/config.module';
|
import { AppConfigModule } from './modules/config/config.module';
|
||||||
import { DocumentsLegauxModule } from './modules/documents-legaux';
|
import { DocumentsLegauxModule } from './modules/documents-legaux';
|
||||||
|
import { AbsencesGardeModule } from './modules/absences-garde';
|
||||||
|
import { CardsModule } from './modules/cards';
|
||||||
import { RelaisModule } from './routes/relais/relais.module';
|
import { RelaisModule } from './routes/relais/relais.module';
|
||||||
import { DossiersModule } from './routes/dossiers/dossiers.module';
|
import { DossiersModule } from './routes/dossiers/dossiers.module';
|
||||||
|
import { SuppressionsModule } from './routes/suppressions/suppressions.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -55,8 +58,11 @@ import { DossiersModule } from './routes/dossiers/dossiers.module';
|
|||||||
AuthModule,
|
AuthModule,
|
||||||
AppConfigModule,
|
AppConfigModule,
|
||||||
DocumentsLegauxModule,
|
DocumentsLegauxModule,
|
||||||
|
AbsencesGardeModule,
|
||||||
|
CardsModule,
|
||||||
RelaisModule,
|
RelaisModule,
|
||||||
DossiersModule,
|
DossiersModule,
|
||||||
|
SuppressionsModule,
|
||||||
],
|
],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { sanitizeUserForApi } from './sanitize-user-for-api';
|
||||||
|
import { RoleType, StatutUtilisateurType, Users } from '../../entities/users.entity';
|
||||||
|
|
||||||
|
describe('sanitizeUserForApi', () => {
|
||||||
|
const base: Users = {
|
||||||
|
id: 'u1',
|
||||||
|
email: 'a@b.fr',
|
||||||
|
prenom: 'Paul',
|
||||||
|
nom: 'Parent',
|
||||||
|
role: RoleType.PARENT,
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
password: 'hash',
|
||||||
|
token_creation_mdp: 'tok',
|
||||||
|
token_creation_mdp_expire_le: new Date(),
|
||||||
|
password_reset_token: 'rst',
|
||||||
|
password_reset_expires: new Date(),
|
||||||
|
} as Users;
|
||||||
|
|
||||||
|
it('retire password et tokens', () => {
|
||||||
|
const out = sanitizeUserForApi(base)!;
|
||||||
|
expect(out.prenom).toBe('Paul');
|
||||||
|
expect(out.nom).toBe('Parent');
|
||||||
|
expect(out.password).toBeUndefined();
|
||||||
|
expect(out.token_creation_mdp).toBeUndefined();
|
||||||
|
expect(out.password_reset_token).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retourne undefined si user absent', () => {
|
||||||
|
expect(sanitizeUserForApi(null)).toBeUndefined();
|
||||||
|
expect(sanitizeUserForApi(undefined)).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { Users } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
/** Champs sensibles exclus des réponses API (ticket #131 — user / co_parent). */
|
||||||
|
const SENSITIVE_USER_KEYS: (keyof Users)[] = [
|
||||||
|
'password',
|
||||||
|
'token_creation_mdp',
|
||||||
|
'token_creation_mdp_expire_le',
|
||||||
|
'password_reset_token',
|
||||||
|
'password_reset_expires',
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retourne une copie utilisateur sans secrets (hash MDP, tokens).
|
||||||
|
* Utilisé pour `user` et `co_parent` dans les réponses Parents.
|
||||||
|
*/
|
||||||
|
export function sanitizeUserForApi(user?: Users | null): Users | undefined {
|
||||||
|
if (!user) return undefined;
|
||||||
|
const safe = { ...user } as Users;
|
||||||
|
for (const key of SENSITIVE_USER_KEYS) {
|
||||||
|
delete safe[key];
|
||||||
|
}
|
||||||
|
return safe;
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
ManyToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { AmChildren } from './am_children.entity';
|
||||||
|
import { Users } from './users.entity';
|
||||||
|
|
||||||
|
export enum TypeAbsenceGardeType {
|
||||||
|
ABSENCE_ENFANT = 'absence_enfant',
|
||||||
|
CONGE_AM = 'conge_am',
|
||||||
|
ARRET_MALADIE_AM = 'arret_maladie_am',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum StatutAbsenceGardeType {
|
||||||
|
EN_ATTENTE = 'en_attente',
|
||||||
|
ACCEPTE = 'accepte',
|
||||||
|
REFUSE = 'refuse',
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vérité métier des absences / congés / arrêts par couple AM↔enfant.
|
||||||
|
* Les cartes (module ultérieur) collectent ; cette table stocke.
|
||||||
|
* Ticket #193.
|
||||||
|
*/
|
||||||
|
@Entity('absences_garde', { schema: 'public' })
|
||||||
|
export class AbsencesGarde {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ name: 'id_placement', type: 'uuid' })
|
||||||
|
id_placement: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => AmChildren, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'id_placement', referencedColumnName: 'id' })
|
||||||
|
placement: AmChildren;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'enum',
|
||||||
|
enum: TypeAbsenceGardeType,
|
||||||
|
enumName: 'type_absence_garde_type',
|
||||||
|
name: 'type',
|
||||||
|
})
|
||||||
|
type: TypeAbsenceGardeType;
|
||||||
|
|
||||||
|
@Column({ name: 'date_debut', type: 'date' })
|
||||||
|
date_debut: string;
|
||||||
|
|
||||||
|
@Column({ name: 'date_fin', type: 'date' })
|
||||||
|
date_fin: string;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'enum',
|
||||||
|
enum: StatutAbsenceGardeType,
|
||||||
|
enumName: 'statut_absence_garde_type',
|
||||||
|
name: 'statut',
|
||||||
|
default: StatutAbsenceGardeType.EN_ATTENTE,
|
||||||
|
})
|
||||||
|
statut: StatutAbsenceGardeType;
|
||||||
|
|
||||||
|
/** Purge auto pour en_attente/refuse ; accepte → infinity. */
|
||||||
|
@Column({ name: 'expire_at', type: 'timestamptz' })
|
||||||
|
expire_at: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'cree_par', type: 'uuid', nullable: true })
|
||||||
|
cree_par?: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => Users, { nullable: true, onDelete: 'SET NULL' })
|
||||||
|
@JoinColumn({ name: 'cree_par', referencedColumnName: 'id' })
|
||||||
|
createdBy?: Users;
|
||||||
|
|
||||||
|
/** Réf. carte de collecte (FK quand module Cartes existera). */
|
||||||
|
@Column({ name: 'id_card_instance', type: 'uuid', nullable: true })
|
||||||
|
id_card_instance?: string;
|
||||||
|
|
||||||
|
@Column({ name: 'motif', type: 'text', nullable: true })
|
||||||
|
motif?: string;
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||||
|
cree_le: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
|
||||||
|
modifie_le: Date;
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import {
|
||||||
|
Entity,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
Column,
|
||||||
|
ManyToOne,
|
||||||
|
JoinColumn,
|
||||||
|
CreateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { AssistanteMaternelle } from './assistantes_maternelles.entity';
|
||||||
|
import { Children } from './children.entity';
|
||||||
|
import { Users } from './users.entity';
|
||||||
|
|
||||||
|
@Entity('enfants_assistantes_maternelles', { schema: 'public' })
|
||||||
|
export class AmChildren {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ name: 'id_am', type: 'uuid' })
|
||||||
|
amId: string;
|
||||||
|
|
||||||
|
@Column({ name: 'id_enfant', type: 'uuid' })
|
||||||
|
enfantId: string;
|
||||||
|
|
||||||
|
@Column({ name: 'date_debut', type: 'date' })
|
||||||
|
date_debut: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'date_fin', type: 'date', nullable: true })
|
||||||
|
date_fin?: Date;
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||||
|
cree_le: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'cree_par', type: 'uuid', nullable: true })
|
||||||
|
cree_par?: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => AssistanteMaternelle, (am) => am.amChildren, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'id_am', referencedColumnName: 'user_id' })
|
||||||
|
am: AssistanteMaternelle;
|
||||||
|
|
||||||
|
@ManyToOne(() => Children, (c) => c.amLinks, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'id_enfant', referencedColumnName: 'id' })
|
||||||
|
child: Children;
|
||||||
|
|
||||||
|
@ManyToOne(() => Users, { nullable: true, onDelete: 'SET NULL' })
|
||||||
|
@JoinColumn({ name: 'cree_par', referencedColumnName: 'id' })
|
||||||
|
createdBy?: Users;
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Entity, PrimaryColumn, Column, OneToOne, JoinColumn } from 'typeorm';
|
import { Entity, PrimaryColumn, Column, OneToOne, OneToMany, JoinColumn, ManyToOne } from 'typeorm';
|
||||||
import { Users } from './users.entity';
|
import { Users } from './users.entity';
|
||||||
|
import { AmChildren } from './am_children.entity';
|
||||||
|
|
||||||
@Entity('assistantes_maternelles')
|
@Entity('assistantes_maternelles')
|
||||||
export class AssistanteMaternelle {
|
export class AssistanteMaternelle {
|
||||||
@@ -51,4 +52,17 @@ export class AssistanteMaternelle {
|
|||||||
/** Numéro de dossier (format AAAA-NNNNNN), même valeur que sur utilisateurs (ticket #103) */
|
/** Numéro de dossier (format AAAA-NNNNNN), même valeur que sur utilisateurs (ticket #103) */
|
||||||
@Column({ name: 'numero_dossier', length: 20, nullable: true })
|
@Column({ name: 'numero_dossier', length: 20, nullable: true })
|
||||||
numero_dossier?: string;
|
numero_dossier?: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placement AM↔enfant sélectionné sur le TdB AM (couple actif) — ticket #171.
|
||||||
|
*/
|
||||||
|
@Column({ name: 'id_placement_garde_courant', type: 'uuid', nullable: true })
|
||||||
|
id_placement_garde_courant?: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => AmChildren, { nullable: true, onDelete: 'SET NULL' })
|
||||||
|
@JoinColumn({ name: 'id_placement_garde_courant', referencedColumnName: 'id' })
|
||||||
|
placement_garde_courant?: AmChildren;
|
||||||
|
|
||||||
|
@OneToMany(() => AmChildren, (ac) => ac.am)
|
||||||
|
amChildren: AmChildren[];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
ManyToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { CardInstance } from './card_instances.entity';
|
||||||
|
import { Users } from './users.entity';
|
||||||
|
|
||||||
|
@Entity('card_audience_members', { schema: 'public' })
|
||||||
|
export class CardAudienceMember {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ name: 'id_card', type: 'uuid' })
|
||||||
|
id_card: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => CardInstance, (c) => c.audience, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'id_card', referencedColumnName: 'id' })
|
||||||
|
card: CardInstance;
|
||||||
|
|
||||||
|
@Column({ name: 'id_utilisateur', type: 'uuid' })
|
||||||
|
id_utilisateur: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => Users, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'id_utilisateur', referencedColumnName: 'id' })
|
||||||
|
user: Users;
|
||||||
|
|
||||||
|
@Column({ name: 'role_snapshot', type: 'varchar', length: 64 })
|
||||||
|
role_snapshot: string;
|
||||||
|
|
||||||
|
@Column({ name: 'is_creator', type: 'boolean', default: false })
|
||||||
|
is_creator: boolean;
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
ManyToOne,
|
||||||
|
OneToMany,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { AmChildren } from './am_children.entity';
|
||||||
|
import { AbsencesGarde } from './absences_garde.entity';
|
||||||
|
import { Users } from './users.entity';
|
||||||
|
import { CardType } from './card_types.entity';
|
||||||
|
import { CardAudienceMember } from './card_audience_members.entity';
|
||||||
|
import { CardResponse } from './card_responses.entity';
|
||||||
|
|
||||||
|
export enum CardInstanceStatutType {
|
||||||
|
OUVERTE = 'ouverte',
|
||||||
|
REFUSEE = 'refusee',
|
||||||
|
TRAITEE = 'traitee',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum CardOperationType {
|
||||||
|
CREATE = 'create',
|
||||||
|
UPDATE = 'update',
|
||||||
|
}
|
||||||
|
|
||||||
|
@Entity('card_instances', { schema: 'public' })
|
||||||
|
export class CardInstance {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ name: 'type_code', type: 'varchar', length: 64 })
|
||||||
|
type_code: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => CardType, { onDelete: 'RESTRICT' })
|
||||||
|
@JoinColumn({ name: 'type_code', referencedColumnName: 'code' })
|
||||||
|
type: CardType;
|
||||||
|
|
||||||
|
@Column({ name: 'id_placement', type: 'uuid' })
|
||||||
|
id_placement: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => AmChildren, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'id_placement', referencedColumnName: 'id' })
|
||||||
|
placement: AmChildren;
|
||||||
|
|
||||||
|
@Column({ name: 'id_absence', type: 'uuid', nullable: true })
|
||||||
|
id_absence?: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => AbsencesGarde, { nullable: true, onDelete: 'SET NULL' })
|
||||||
|
@JoinColumn({ name: 'id_absence', referencedColumnName: 'id' })
|
||||||
|
absence?: AbsencesGarde;
|
||||||
|
|
||||||
|
@Column({ name: 'cree_par', type: 'uuid', nullable: true })
|
||||||
|
cree_par?: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => Users, { nullable: true, onDelete: 'SET NULL' })
|
||||||
|
@JoinColumn({ name: 'cree_par', referencedColumnName: 'id' })
|
||||||
|
createdBy?: Users;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'enum',
|
||||||
|
enum: CardOperationType,
|
||||||
|
enumName: 'card_operation_type',
|
||||||
|
name: 'operation',
|
||||||
|
default: CardOperationType.CREATE,
|
||||||
|
})
|
||||||
|
operation: CardOperationType;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'enum',
|
||||||
|
enum: CardInstanceStatutType,
|
||||||
|
enumName: 'card_instance_statut_type',
|
||||||
|
name: 'statut',
|
||||||
|
default: CardInstanceStatutType.OUVERTE,
|
||||||
|
})
|
||||||
|
statut: CardInstanceStatutType;
|
||||||
|
|
||||||
|
@Column({ name: 'payload', type: 'jsonb', default: {} })
|
||||||
|
payload: Record<string, unknown>;
|
||||||
|
|
||||||
|
@Column({ name: 'purge_at', type: 'timestamptz' })
|
||||||
|
purge_at: Date;
|
||||||
|
|
||||||
|
@OneToMany(() => CardAudienceMember, (m) => m.card)
|
||||||
|
audience: CardAudienceMember[];
|
||||||
|
|
||||||
|
@OneToMany(() => CardResponse, (r) => r.card)
|
||||||
|
responses: CardResponse[];
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||||
|
cree_le: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
|
||||||
|
modifie_le: Date;
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
ManyToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { CardInstance } from './card_instances.entity';
|
||||||
|
import { Users } from './users.entity';
|
||||||
|
|
||||||
|
export enum CardResponseActionType {
|
||||||
|
ACCEPT = 'accept',
|
||||||
|
REFUSE = 'refuse',
|
||||||
|
ACK = 'ack',
|
||||||
|
}
|
||||||
|
|
||||||
|
@Entity('card_responses', { schema: 'public' })
|
||||||
|
export class CardResponse {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ name: 'id_card', type: 'uuid' })
|
||||||
|
id_card: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => CardInstance, (c) => c.responses, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'id_card', referencedColumnName: 'id' })
|
||||||
|
card: CardInstance;
|
||||||
|
|
||||||
|
@Column({ name: 'id_utilisateur', type: 'uuid' })
|
||||||
|
id_utilisateur: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => Users, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'id_utilisateur', referencedColumnName: 'id' })
|
||||||
|
user: Users;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'enum',
|
||||||
|
enum: CardResponseActionType,
|
||||||
|
enumName: 'card_response_action_type',
|
||||||
|
name: 'action',
|
||||||
|
})
|
||||||
|
action: CardResponseActionType;
|
||||||
|
|
||||||
|
@Column({ name: 'comment', type: 'text', nullable: true })
|
||||||
|
comment?: string;
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||||
|
cree_le: Date;
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
PrimaryColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
|
export enum CardResponseModeType {
|
||||||
|
NONE = 'none',
|
||||||
|
ACK = 'ack',
|
||||||
|
ACCEPT_REFUSE = 'accept_refuse',
|
||||||
|
}
|
||||||
|
|
||||||
|
@Entity('card_types', { schema: 'public' })
|
||||||
|
export class CardType {
|
||||||
|
@PrimaryColumn({ name: 'code', type: 'varchar', length: 64 })
|
||||||
|
code: string;
|
||||||
|
|
||||||
|
@Column({ name: 'system', type: 'boolean', default: true })
|
||||||
|
system: boolean;
|
||||||
|
|
||||||
|
@Column({ name: 'titre', type: 'varchar', length: 120 })
|
||||||
|
titre: string;
|
||||||
|
|
||||||
|
@Column({ name: 'emitter_roles', type: 'text', array: true })
|
||||||
|
emitter_roles: string[];
|
||||||
|
|
||||||
|
@Column({ name: 'recipient_roles', type: 'text', array: true })
|
||||||
|
recipient_roles: string[];
|
||||||
|
|
||||||
|
@Column({ name: 'audience_resolver', type: 'varchar', length: 64 })
|
||||||
|
audience_resolver: string;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'enum',
|
||||||
|
enum: CardResponseModeType,
|
||||||
|
enumName: 'card_response_mode_type',
|
||||||
|
name: 'response_mode',
|
||||||
|
})
|
||||||
|
response_mode: CardResponseModeType;
|
||||||
|
|
||||||
|
@Column({ name: 'retention_days', type: 'int', default: 14 })
|
||||||
|
retention_days: number;
|
||||||
|
|
||||||
|
@Column({ name: 'couleur', type: 'varchar', length: 32, nullable: true })
|
||||||
|
couleur?: string;
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||||
|
cree_le: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
|
||||||
|
modifie_le: Date;
|
||||||
|
}
|
||||||
@@ -4,12 +4,14 @@ import {
|
|||||||
} from 'typeorm';
|
} from 'typeorm';
|
||||||
import { Parents } from './parents.entity';
|
import { Parents } from './parents.entity';
|
||||||
import { ParentsChildren } from './parents_children.entity';
|
import { ParentsChildren } from './parents_children.entity';
|
||||||
|
import { AmChildren } from './am_children.entity';
|
||||||
import { Dossier } from './dossiers.entity';
|
import { Dossier } from './dossiers.entity';
|
||||||
|
|
||||||
export enum StatutEnfantType {
|
export enum StatutEnfantType {
|
||||||
A_NAITRE = 'a_naitre',
|
A_NAITRE = 'a_naitre',
|
||||||
ACTIF = 'actif',
|
|
||||||
SCOLARISE = 'scolarise',
|
SCOLARISE = 'scolarise',
|
||||||
|
GARDE = 'garde',
|
||||||
|
SANS_GARDE = 'sans_garde',
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum GenreType {
|
export enum GenreType {
|
||||||
@@ -61,13 +63,13 @@ export class Children {
|
|||||||
@Column({ type: 'timestamptz', nullable: true, name: 'date_consentement_photo' })
|
@Column({ type: 'timestamptz', nullable: true, name: 'date_consentement_photo' })
|
||||||
consent_photo_at?: Date;
|
consent_photo_at?: Date;
|
||||||
|
|
||||||
@Column({ default: false, name: 'est_multiple', type: 'boolean' })
|
|
||||||
is_multiple: boolean;
|
|
||||||
|
|
||||||
// Lien via table de jointure enfants_parents
|
// Lien via table de jointure enfants_parents
|
||||||
@OneToMany(() => ParentsChildren, pc => pc.child)
|
@OneToMany(() => ParentsChildren, pc => pc.child)
|
||||||
parentLinks: ParentsChildren[];
|
parentLinks: ParentsChildren[];
|
||||||
|
|
||||||
|
@OneToMany(() => AmChildren, (ac) => ac.child)
|
||||||
|
amLinks: AmChildren[];
|
||||||
|
|
||||||
// Relation avec Dossier
|
// Relation avec Dossier
|
||||||
@OneToMany(() => Dossier, d => d.child)
|
@OneToMany(() => Dossier, d => d.child)
|
||||||
dossiers: Dossier[];
|
dossiers: Dossier[];
|
||||||
|
|||||||
@@ -1,79 +0,0 @@
|
|||||||
import { Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
|
|
||||||
import { Children } from "./children.entity";
|
|
||||||
import { Users } from "./users.entity";
|
|
||||||
import { Parents } from "./parents.entity";
|
|
||||||
|
|
||||||
export enum TypeEvenementType {
|
|
||||||
ABSENCE_ENFANT = 'absence_enfant',
|
|
||||||
CONGE_AM = 'conge_am',
|
|
||||||
CONGE_PARENT = 'conge_parent',
|
|
||||||
ARRET_MALADIE_AM = 'arret_maladie_am',
|
|
||||||
EVENEMENT_RPE = 'evenement_rpe',
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum StatutEvenementType {
|
|
||||||
PROPOSE = 'propose',
|
|
||||||
VALIDE = 'valide',
|
|
||||||
REFUSE = 'refuse',
|
|
||||||
}
|
|
||||||
|
|
||||||
@Entity('evenements')
|
|
||||||
export class Evenement {
|
|
||||||
// Define your columns and relationships here
|
|
||||||
@PrimaryGeneratedColumn('uuid')
|
|
||||||
id: string;
|
|
||||||
|
|
||||||
@Column({
|
|
||||||
type: 'enum',
|
|
||||||
enum: TypeEvenementType,
|
|
||||||
enumName: 'type_evenement_type',
|
|
||||||
name: 'type'
|
|
||||||
})
|
|
||||||
type: TypeEvenementType;
|
|
||||||
|
|
||||||
@ManyToOne(() => Children, { onDelete: 'CASCADE', nullable: true })
|
|
||||||
@JoinColumn({ name: 'id_enfant', referencedColumnName: 'id' })
|
|
||||||
child?: Children;
|
|
||||||
|
|
||||||
@ManyToOne(() => Users, { nullable: true })
|
|
||||||
@JoinColumn({ name: 'id_am', referencedColumnName: 'id' })
|
|
||||||
assistanteMaternelle?: Users;
|
|
||||||
|
|
||||||
@ManyToOne(() => Parents, { nullable: true })
|
|
||||||
@JoinColumn({ name: 'id_parent', referencedColumnName: 'user_id' })
|
|
||||||
parent?: Parents;
|
|
||||||
|
|
||||||
@ManyToOne(() => Users, { nullable: true })
|
|
||||||
@JoinColumn({ name: 'cree_par', referencedColumnName: 'id' })
|
|
||||||
created_by?: Users;
|
|
||||||
|
|
||||||
@Column({ type: 'timestamptz', nullable: true, name: 'date_debut' })
|
|
||||||
start_date?: Date;
|
|
||||||
|
|
||||||
@Column({ type: 'timestamptz', nullable: true, name: 'date_fin' })
|
|
||||||
end_date?: Date;
|
|
||||||
|
|
||||||
@Column({ type: 'text', nullable: true, name: 'commentaires' })
|
|
||||||
comments?: string;
|
|
||||||
|
|
||||||
@Column({
|
|
||||||
type: 'enum',
|
|
||||||
enum: StatutEvenementType,
|
|
||||||
enumName: 'statut_evenement_type',
|
|
||||||
name: 'statut',
|
|
||||||
default: StatutEvenementType.PROPOSE
|
|
||||||
})
|
|
||||||
status: StatutEvenementType;
|
|
||||||
|
|
||||||
@Column({type: 'timestamptz', nullable: true, name: 'delai_grace'})
|
|
||||||
grace_deadline?: Date;
|
|
||||||
|
|
||||||
@Column({type: 'boolean', default: false, name: 'urgent'})
|
|
||||||
urgent: boolean;
|
|
||||||
|
|
||||||
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
|
||||||
created_at: Date;
|
|
||||||
|
|
||||||
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
|
|
||||||
updated_at: Date;
|
|
||||||
}
|
|
||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
import { Users } from './users.entity';
|
import { Users } from './users.entity';
|
||||||
import { ParentsChildren } from './parents_children.entity';
|
import { ParentsChildren } from './parents_children.entity';
|
||||||
import { Dossier } from './dossiers.entity';
|
import { Dossier } from './dossiers.entity';
|
||||||
|
import { AmChildren } from './am_children.entity';
|
||||||
|
|
||||||
@Entity('parents', { schema: 'public' })
|
@Entity('parents', { schema: 'public' })
|
||||||
export class Parents {
|
export class Parents {
|
||||||
@@ -25,6 +26,17 @@ export class Parents {
|
|||||||
@Column({ name: 'numero_dossier', length: 20, nullable: true })
|
@Column({ name: 'numero_dossier', length: 20, nullable: true })
|
||||||
numero_dossier?: string;
|
numero_dossier?: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placement AM↔enfant sélectionné sur le TdB parent (couple actif) — ticket #168.
|
||||||
|
* Null / absent = le front prend le premier couple actif retourné par l’API.
|
||||||
|
*/
|
||||||
|
@Column({ name: 'id_placement_garde_courant', type: 'uuid', nullable: true })
|
||||||
|
id_placement_garde_courant?: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => AmChildren, { nullable: true, onDelete: 'SET NULL' })
|
||||||
|
@JoinColumn({ name: 'id_placement_garde_courant', referencedColumnName: 'id' })
|
||||||
|
placement_garde_courant?: AmChildren;
|
||||||
|
|
||||||
// Lien vers enfants via la table enfants_parents
|
// Lien vers enfants via la table enfants_parents
|
||||||
@OneToMany(() => ParentsChildren, pc => pc.parent)
|
@OneToMany(() => ParentsChildren, pc => pc.parent)
|
||||||
parentChildren: ParentsChildren[];
|
parentChildren: ParentsChildren[];
|
||||||
|
|||||||
@@ -119,6 +119,13 @@ export class Users {
|
|||||||
@Column({ type: 'timestamptz', nullable: true, name: 'token_creation_mdp_expire_le' })
|
@Column({ type: 'timestamptz', nullable: true, name: 'token_creation_mdp_expire_le' })
|
||||||
token_creation_mdp_expire_le?: Date;
|
token_creation_mdp_expire_le?: Date;
|
||||||
|
|
||||||
|
/** Ticket #127 — réinitialisation mot de passe oublié (distinct de token_creation_mdp / inscription) */
|
||||||
|
@Column({ nullable: true, name: 'password_reset_token', length: 255 })
|
||||||
|
password_reset_token?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'timestamptz', nullable: true, name: 'password_reset_expires' })
|
||||||
|
password_reset_expires?: Date;
|
||||||
|
|
||||||
/** Token pour reprise après refus (lien email), ticket #110 */
|
/** Token pour reprise après refus (lien email), ticket #110 */
|
||||||
@Column({ nullable: true, name: 'token_reprise', length: 255 })
|
@Column({ nullable: true, name: 'token_reprise', length: 255 })
|
||||||
token_reprise?: string;
|
token_reprise?: string;
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { AbsencesGardeController } from './absences-garde.controller';
|
||||||
|
import { AbsencesGardeService } from './absences-garde.service';
|
||||||
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
import { TypeAbsenceGardeType } from 'src/entities/absences_garde.entity';
|
||||||
|
|
||||||
|
describe('AbsencesGardeController (#172)', () => {
|
||||||
|
let controller: AbsencesGardeController;
|
||||||
|
const serviceMock = {
|
||||||
|
lister: jest.fn(),
|
||||||
|
creer: jest.fn(),
|
||||||
|
maj: jest.fn(),
|
||||||
|
supprimer: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
controllers: [AbsencesGardeController],
|
||||||
|
providers: [{ provide: AbsencesGardeService, useValue: serviceMock }],
|
||||||
|
})
|
||||||
|
.overrideGuard(AuthGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.overrideGuard(RolesGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.compile();
|
||||||
|
|
||||||
|
controller = module.get(AbsencesGardeController);
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(controller).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lister délègue au service', async () => {
|
||||||
|
serviceMock.lister.mockResolvedValue({ items: [] });
|
||||||
|
const res = await controller.lister(
|
||||||
|
'u1',
|
||||||
|
RoleType.PARENT,
|
||||||
|
'pl-1',
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
'2026-01-01',
|
||||||
|
'2026-12-31',
|
||||||
|
);
|
||||||
|
expect(serviceMock.lister).toHaveBeenCalledWith('u1', RoleType.PARENT, {
|
||||||
|
placementId: 'pl-1',
|
||||||
|
type: undefined,
|
||||||
|
statut: undefined,
|
||||||
|
from: '2026-01-01',
|
||||||
|
to: '2026-12-31',
|
||||||
|
});
|
||||||
|
expect(res.items).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creer délègue au service', async () => {
|
||||||
|
serviceMock.creer.mockResolvedValue({ id: 'a1' });
|
||||||
|
const dto = {
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeAbsenceGardeType.ABSENCE_ENFANT,
|
||||||
|
date_debut: '2026-10-01',
|
||||||
|
date_fin: '2026-10-02',
|
||||||
|
};
|
||||||
|
await controller.creer('u1', RoleType.PARENT, dto);
|
||||||
|
expect(serviceMock.creer).toHaveBeenCalledWith(
|
||||||
|
'u1',
|
||||||
|
RoleType.PARENT,
|
||||||
|
dto,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
|
Param,
|
||||||
|
ParseUUIDPipe,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiBody,
|
||||||
|
ApiOperation,
|
||||||
|
ApiQuery,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from '@nestjs/swagger';
|
||||||
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||||
|
import { User } from 'src/common/decorators/user.decorator';
|
||||||
|
import {
|
||||||
|
StatutAbsenceGardeType,
|
||||||
|
TypeAbsenceGardeType,
|
||||||
|
} from 'src/entities/absences_garde.entity';
|
||||||
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
import { AbsencesGardeService } from './absences-garde.service';
|
||||||
|
import {
|
||||||
|
AbsenceGardeDto,
|
||||||
|
CreerAbsenceGardeDto,
|
||||||
|
ListeAbsencesGardeDto,
|
||||||
|
MajAbsenceGardeDto,
|
||||||
|
} from './dto/absences-garde.dto';
|
||||||
|
|
||||||
|
@ApiTags('Absences garde')
|
||||||
|
@ApiBearerAuth('access-token')
|
||||||
|
@Controller('absences-garde')
|
||||||
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
|
export class AbsencesGardeController {
|
||||||
|
constructor(private readonly absencesGardeService: AbsencesGardeService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Lister les absences / congés / arrêts — ticket #172',
|
||||||
|
description:
|
||||||
|
'Sans placementId : tous les placements du user (parent = famille multi-AM ; AM = tous accueils). ' +
|
||||||
|
'Avec placementId : un couple enfant–AM.',
|
||||||
|
})
|
||||||
|
@ApiQuery({ name: 'placementId', required: false })
|
||||||
|
@ApiQuery({ name: 'type', required: false, enum: TypeAbsenceGardeType })
|
||||||
|
@ApiQuery({ name: 'statut', required: false, enum: StatutAbsenceGardeType })
|
||||||
|
@ApiQuery({ name: 'from', required: false, description: 'YYYY-MM-DD' })
|
||||||
|
@ApiQuery({ name: 'to', required: false, description: 'YYYY-MM-DD' })
|
||||||
|
@ApiResponse({ status: 200, type: ListeAbsencesGardeDto })
|
||||||
|
lister(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Query('placementId') placementId?: string,
|
||||||
|
@Query('type') type?: TypeAbsenceGardeType,
|
||||||
|
@Query('statut') statut?: StatutAbsenceGardeType,
|
||||||
|
@Query('from') from?: string,
|
||||||
|
@Query('to') to?: string,
|
||||||
|
): Promise<ListeAbsencesGardeDto> {
|
||||||
|
return this.absencesGardeService.lister(userId, role, {
|
||||||
|
placementId,
|
||||||
|
type,
|
||||||
|
statut,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiOperation({ summary: 'Créer une période d’absence / congé / arrêt — #172' })
|
||||||
|
@ApiBody({ type: CreerAbsenceGardeDto })
|
||||||
|
@ApiResponse({ status: 201, type: AbsenceGardeDto })
|
||||||
|
@HttpCode(HttpStatus.CREATED)
|
||||||
|
creer(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Body() dto: CreerAbsenceGardeDto,
|
||||||
|
): Promise<AbsenceGardeDto> {
|
||||||
|
return this.absencesGardeService.creer(userId, role, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':id')
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Mettre à jour dates / statut / motif — #172',
|
||||||
|
description:
|
||||||
|
'Parent : accept/refuse congé (motivation si refus), ack arrêt. ' +
|
||||||
|
'AM : modifier dates (en attente / refuse / accepté), republication après refus.',
|
||||||
|
})
|
||||||
|
@ApiBody({ type: MajAbsenceGardeDto })
|
||||||
|
@ApiResponse({ status: 200, type: AbsenceGardeDto })
|
||||||
|
maj(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
@Body() dto: MajAbsenceGardeDto,
|
||||||
|
): Promise<AbsenceGardeDto> {
|
||||||
|
return this.absencesGardeService.maj(userId, role, id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':id')
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
|
@ApiOperation({ summary: 'Supprimer une absence (hard delete) — #172' })
|
||||||
|
@ApiResponse({ status: 204 })
|
||||||
|
async supprimer(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
): Promise<void> {
|
||||||
|
await this.absencesGardeService.supprimer(userId, role, id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { AbsencesGarde } from 'src/entities/absences_garde.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { AbsencesGardeController } from './absences-garde.controller';
|
||||||
|
import { AbsencesGardeService } from './absences-garde.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
TypeOrmModule.forFeature([AbsencesGarde, AmChildren, ParentsChildren]),
|
||||||
|
JwtModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: (config: ConfigService) => ({
|
||||||
|
secret: config.get('jwt.accessSecret'),
|
||||||
|
signOptions: { expiresIn: config.get('jwt.accessExpiresIn') },
|
||||||
|
}),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
controllers: [AbsencesGardeController],
|
||||||
|
providers: [AbsencesGardeService],
|
||||||
|
exports: [AbsencesGardeService],
|
||||||
|
})
|
||||||
|
export class AbsencesGardeModule {}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
|
import { ForbiddenException, BadRequestException } from '@nestjs/common';
|
||||||
|
import { AbsencesGardeService } from './absences-garde.service';
|
||||||
|
import {
|
||||||
|
AbsencesGarde,
|
||||||
|
StatutAbsenceGardeType,
|
||||||
|
TypeAbsenceGardeType,
|
||||||
|
} from 'src/entities/absences_garde.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
describe('AbsencesGardeService (#172)', () => {
|
||||||
|
let service: AbsencesGardeService;
|
||||||
|
const absencesRepo = {
|
||||||
|
create: jest.fn((x) => x),
|
||||||
|
save: jest.fn(async (x) => ({
|
||||||
|
...x,
|
||||||
|
id: x.id ?? 'abs-1',
|
||||||
|
cree_le: new Date(),
|
||||||
|
modifie_le: new Date(),
|
||||||
|
})),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
createQueryBuilder: jest.fn(),
|
||||||
|
};
|
||||||
|
const amChildrenRepo = {
|
||||||
|
find: jest.fn(),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
const parentsChildrenRepo = {
|
||||||
|
find: jest.fn(),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
AbsencesGardeService,
|
||||||
|
{ provide: getRepositoryToken(AbsencesGarde), useValue: absencesRepo },
|
||||||
|
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo },
|
||||||
|
{
|
||||||
|
provide: getRepositoryToken(ParentsChildren),
|
||||||
|
useValue: parentsChildrenRepo,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
service = module.get(AbsencesGardeService);
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(service).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parent crée absence_enfant → statut accepte', async () => {
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
parentsChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
parentId: 'p-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
});
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'abs-1',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeAbsenceGardeType.ABSENCE_ENFANT,
|
||||||
|
date_debut: '2026-10-01',
|
||||||
|
date_fin: '2026-10-02',
|
||||||
|
statut: StatutAbsenceGardeType.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' } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await service.creer('p-1', RoleType.PARENT, {
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeAbsenceGardeType.ABSENCE_ENFANT,
|
||||||
|
date_debut: '2026-10-01',
|
||||||
|
date_fin: '2026-10-02',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(absencesRepo.save).toHaveBeenCalled();
|
||||||
|
const savedArg = absencesRepo.save.mock.calls[0][0];
|
||||||
|
expect(savedArg.statut).toBe(StatutAbsenceGardeType.ACCEPTE);
|
||||||
|
expect(res.type).toBe(TypeAbsenceGardeType.ABSENCE_ENFANT);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parent ne peut pas créer un congé AM', async () => {
|
||||||
|
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.creer('p-1', RoleType.PARENT, {
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeAbsenceGardeType.CONGE_AM,
|
||||||
|
date_debut: '2026-10-01',
|
||||||
|
date_fin: '2026-10-05',
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(ForbiddenException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refus congé sans motif → BadRequest', async () => {
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'abs-1',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeAbsenceGardeType.CONGE_AM,
|
||||||
|
date_debut: '2026-10-01',
|
||||||
|
date_fin: '2026-10-05',
|
||||||
|
statut: StatutAbsenceGardeType.EN_ATTENTE,
|
||||||
|
expire_at: 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: StatutAbsenceGardeType.REFUSE,
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dates invalides → BadRequest', async () => {
|
||||||
|
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.creer('p-1', RoleType.PARENT, {
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeAbsenceGardeType.ABSENCE_ENFANT,
|
||||||
|
date_debut: '2026-10-10',
|
||||||
|
date_fin: '2026-10-01',
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,421 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
ForbiddenException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { In, IsNull, Repository } from 'typeorm';
|
||||||
|
import {
|
||||||
|
AbsencesGarde,
|
||||||
|
StatutAbsenceGardeType,
|
||||||
|
TypeAbsenceGardeType,
|
||||||
|
} from 'src/entities/absences_garde.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
import {
|
||||||
|
AbsenceGardeDto,
|
||||||
|
CreerAbsenceGardeDto,
|
||||||
|
ListeAbsencesGardeDto,
|
||||||
|
MajAbsenceGardeDto,
|
||||||
|
} from './dto/absences-garde.dto';
|
||||||
|
|
||||||
|
const TTL_EN_ATTENTE_MS = 15 * 24 * 60 * 60 * 1000;
|
||||||
|
const TTL_REFUSE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||||
|
/** Sentinel « pas de purge » pour les périodes acceptées */
|
||||||
|
const EXPIRE_ACCEPTE = new Date('9999-12-31T23:59:59.999Z');
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AbsencesGardeService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(AbsencesGarde)
|
||||||
|
private readonly absencesRepo: Repository<AbsencesGarde>,
|
||||||
|
@InjectRepository(AmChildren)
|
||||||
|
private readonly amChildrenRepo: Repository<AmChildren>,
|
||||||
|
@InjectRepository(ParentsChildren)
|
||||||
|
private readonly parentsChildrenRepo: Repository<ParentsChildren>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async lister(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
opts: {
|
||||||
|
placementId?: string;
|
||||||
|
type?: TypeAbsenceGardeType;
|
||||||
|
statut?: StatutAbsenceGardeType;
|
||||||
|
from?: string;
|
||||||
|
to?: string;
|
||||||
|
},
|
||||||
|
): Promise<ListeAbsencesGardeDto> {
|
||||||
|
const placementIds = await this.resolvePlacementIds(
|
||||||
|
userId,
|
||||||
|
role,
|
||||||
|
opts.placementId,
|
||||||
|
);
|
||||||
|
if (placementIds.length === 0) {
|
||||||
|
return { items: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const qb = this.absencesRepo
|
||||||
|
.createQueryBuilder('ag')
|
||||||
|
.leftJoinAndSelect('ag.placement', 'placement')
|
||||||
|
.leftJoinAndSelect('placement.child', 'child')
|
||||||
|
.leftJoinAndSelect('placement.am', 'am')
|
||||||
|
.leftJoinAndSelect('am.user', 'amUser')
|
||||||
|
.where('ag.id_placement IN (:...placementIds)', { placementIds })
|
||||||
|
.orderBy('ag.date_debut', 'DESC');
|
||||||
|
|
||||||
|
if (opts.type) {
|
||||||
|
qb.andWhere('ag.type = :type', { type: opts.type });
|
||||||
|
}
|
||||||
|
if (opts.statut) {
|
||||||
|
qb.andWhere('ag.statut = :statut', { statut: opts.statut });
|
||||||
|
}
|
||||||
|
if (opts.from) {
|
||||||
|
qb.andWhere('ag.date_fin >= :from', { from: opts.from });
|
||||||
|
}
|
||||||
|
if (opts.to) {
|
||||||
|
qb.andWhere('ag.date_debut <= :to', { to: opts.to });
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await qb.getMany();
|
||||||
|
return { items: rows.map((r) => this.toDto(r)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
async creer(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
dto: CreerAbsenceGardeDto,
|
||||||
|
): Promise<AbsenceGardeDto> {
|
||||||
|
this.assertDates(dto.date_debut, dto.date_fin);
|
||||||
|
await this.assertCanAccessPlacement(userId, role, dto.id_placement);
|
||||||
|
this.assertCanCreateType(role, dto.type);
|
||||||
|
|
||||||
|
const statut = this.statutInitial(dto.type);
|
||||||
|
const entity = this.absencesRepo.create({
|
||||||
|
id_placement: dto.id_placement,
|
||||||
|
type: dto.type,
|
||||||
|
date_debut: dto.date_debut,
|
||||||
|
date_fin: dto.date_fin,
|
||||||
|
statut,
|
||||||
|
expire_at: this.expireAtFor(statut),
|
||||||
|
cree_par: userId,
|
||||||
|
motif: dto.motif?.trim() || undefined,
|
||||||
|
});
|
||||||
|
const saved = await this.absencesRepo.save(entity);
|
||||||
|
return this.getByIdForUser(saved.id, userId, role);
|
||||||
|
}
|
||||||
|
|
||||||
|
async maj(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
id: string,
|
||||||
|
dto: MajAbsenceGardeDto,
|
||||||
|
): Promise<AbsenceGardeDto> {
|
||||||
|
const row = await this.absencesRepo.findOne({ where: { id } });
|
||||||
|
if (!row) {
|
||||||
|
throw new NotFoundException('Absence introuvable');
|
||||||
|
}
|
||||||
|
await this.assertCanAccessPlacement(userId, role, row.id_placement);
|
||||||
|
|
||||||
|
if (dto.date_debut !== undefined || dto.date_fin !== undefined) {
|
||||||
|
const debut = dto.date_debut ?? row.date_debut;
|
||||||
|
const fin = dto.date_fin ?? row.date_fin;
|
||||||
|
this.assertDates(debut, fin);
|
||||||
|
// Parent : peut modifier ses absences enfant
|
||||||
|
// AM : peut modifier congé/arrêt en_attente (avant accept) ou dates si créateur
|
||||||
|
this.assertCanEditDates(role, row);
|
||||||
|
row.date_debut = debut;
|
||||||
|
row.date_fin = fin;
|
||||||
|
if (row.statut === StatutAbsenceGardeType.EN_ATTENTE) {
|
||||||
|
row.expire_at = this.expireAtFor(StatutAbsenceGardeType.EN_ATTENTE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dto.statut !== undefined && dto.statut !== row.statut) {
|
||||||
|
this.assertCanChangeStatut(role, row, dto.statut, dto.motif);
|
||||||
|
if (
|
||||||
|
dto.statut === StatutAbsenceGardeType.REFUSE &&
|
||||||
|
(!dto.motif || !dto.motif.trim())
|
||||||
|
) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Une motivation est obligatoire en cas de refus',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
row.statut = dto.statut;
|
||||||
|
row.expire_at = this.expireAtFor(dto.statut);
|
||||||
|
if (dto.motif?.trim()) {
|
||||||
|
row.motif = dto.motif.trim();
|
||||||
|
}
|
||||||
|
} else if (dto.motif !== undefined) {
|
||||||
|
row.motif = dto.motif.trim() || undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.absencesRepo.save(row);
|
||||||
|
return this.getByIdForUser(id, userId, role);
|
||||||
|
}
|
||||||
|
|
||||||
|
async supprimer(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
id: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const row = await this.absencesRepo.findOne({ where: { id } });
|
||||||
|
if (!row) {
|
||||||
|
throw new NotFoundException('Absence introuvable');
|
||||||
|
}
|
||||||
|
await this.assertCanAccessPlacement(userId, role, row.id_placement);
|
||||||
|
|
||||||
|
if (
|
||||||
|
role === RoleType.PARENT &&
|
||||||
|
row.type !== TypeAbsenceGardeType.ABSENCE_ENFANT
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Un parent ne peut supprimer que les absences enfant',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.absencesRepo.delete({ id });
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getByIdForUser(
|
||||||
|
id: string,
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
): Promise<AbsenceGardeDto> {
|
||||||
|
const row = await this.absencesRepo.findOne({
|
||||||
|
where: { id },
|
||||||
|
relations: ['placement', 'placement.child', 'placement.am', 'placement.am.user'],
|
||||||
|
});
|
||||||
|
if (!row) {
|
||||||
|
throw new NotFoundException('Absence introuvable');
|
||||||
|
}
|
||||||
|
await this.assertCanAccessPlacement(userId, role, row.id_placement);
|
||||||
|
return this.toDto(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
private statutInitial(type: TypeAbsenceGardeType): StatutAbsenceGardeType {
|
||||||
|
if (type === TypeAbsenceGardeType.ABSENCE_ENFANT) {
|
||||||
|
return StatutAbsenceGardeType.ACCEPTE;
|
||||||
|
}
|
||||||
|
return StatutAbsenceGardeType.EN_ATTENTE;
|
||||||
|
}
|
||||||
|
|
||||||
|
private expireAtFor(statut: StatutAbsenceGardeType): Date {
|
||||||
|
const now = Date.now();
|
||||||
|
if (statut === StatutAbsenceGardeType.ACCEPTE) {
|
||||||
|
return EXPIRE_ACCEPTE;
|
||||||
|
}
|
||||||
|
if (statut === StatutAbsenceGardeType.REFUSE) {
|
||||||
|
return new Date(now + TTL_REFUSE_MS);
|
||||||
|
}
|
||||||
|
return new Date(now + TTL_EN_ATTENTE_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertDates(debut: string, fin: string): void {
|
||||||
|
if (fin < debut) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'date_fin doit être supérieure ou égale à date_debut',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertCanCreateType(role: RoleType, type: TypeAbsenceGardeType): void {
|
||||||
|
if (role === RoleType.PARENT) {
|
||||||
|
if (type !== TypeAbsenceGardeType.ABSENCE_ENFANT) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Un parent ne peut créer que des absences enfant',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
if (
|
||||||
|
type !== TypeAbsenceGardeType.CONGE_AM &&
|
||||||
|
type !== TypeAbsenceGardeType.ARRET_MALADIE_AM
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Une AM ne peut créer que congé ou arrêt maladie',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new ForbiddenException('Rôle non autorisé à créer une absence');
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertCanEditDates(
|
||||||
|
role: RoleType,
|
||||||
|
row: AbsencesGarde,
|
||||||
|
): void {
|
||||||
|
if (role === RoleType.PARENT) {
|
||||||
|
if (row.type !== TypeAbsenceGardeType.ABSENCE_ENFANT) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Un parent ne peut modifier que les absences enfant',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
if (
|
||||||
|
row.type === TypeAbsenceGardeType.CONGE_AM ||
|
||||||
|
row.type === TypeAbsenceGardeType.ARRET_MALADIE_AM
|
||||||
|
) {
|
||||||
|
if (
|
||||||
|
row.statut !== StatutAbsenceGardeType.EN_ATTENTE &&
|
||||||
|
row.statut !== StatutAbsenceGardeType.REFUSE &&
|
||||||
|
row.statut !== StatutAbsenceGardeType.ACCEPTE
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException('Statut incompatible avec une modification');
|
||||||
|
}
|
||||||
|
// Accepté : autorisé (S2b — re-validation via cartes plus tard ; API permet update dates)
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new ForbiddenException('Type non modifiable par l’AM');
|
||||||
|
}
|
||||||
|
throw new ForbiddenException('Modification non autorisée');
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertCanChangeStatut(
|
||||||
|
role: RoleType,
|
||||||
|
row: AbsencesGarde,
|
||||||
|
next: StatutAbsenceGardeType,
|
||||||
|
_motif?: string,
|
||||||
|
): void {
|
||||||
|
if (role === RoleType.PARENT) {
|
||||||
|
// Accept / refuse congé ; ack arrêt (accepte)
|
||||||
|
if (
|
||||||
|
row.type === TypeAbsenceGardeType.CONGE_AM ||
|
||||||
|
row.type === TypeAbsenceGardeType.ARRET_MALADIE_AM
|
||||||
|
) {
|
||||||
|
if (
|
||||||
|
next !== StatutAbsenceGardeType.ACCEPTE &&
|
||||||
|
next !== StatutAbsenceGardeType.REFUSE
|
||||||
|
) {
|
||||||
|
throw new BadRequestException('Transition de statut invalide');
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
row.type === TypeAbsenceGardeType.ARRET_MALADIE_AM &&
|
||||||
|
next === StatutAbsenceGardeType.REFUSE
|
||||||
|
) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Un arrêt maladie ne se refuse pas (accusé seulement)',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (row.statut !== StatutAbsenceGardeType.EN_ATTENTE) {
|
||||||
|
throw new BadRequestException('Cette demande n’est plus en attente');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Pas de changement de statut sur ce type pour un parent',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
// Remise en attente après refus OU modification d’un congé déjà accepté (S2b)
|
||||||
|
if (
|
||||||
|
next === StatutAbsenceGardeType.EN_ATTENTE &&
|
||||||
|
(row.statut === StatutAbsenceGardeType.REFUSE ||
|
||||||
|
row.statut === StatutAbsenceGardeType.ACCEPTE)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'L’AM ne valide pas elle-même (sauf republication / modification)',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw new ForbiddenException('Changement de statut non autorisé');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolvePlacementIds(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
placementId?: string,
|
||||||
|
): Promise<string[]> {
|
||||||
|
if (placementId) {
|
||||||
|
await this.assertCanAccessPlacement(userId, role, placementId);
|
||||||
|
return [placementId];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (role === RoleType.PARENT) {
|
||||||
|
const liens = await this.parentsChildrenRepo.find({
|
||||||
|
where: { parentId: userId },
|
||||||
|
select: ['enfantId'],
|
||||||
|
});
|
||||||
|
const enfantIds = liens.map((l) => l.enfantId);
|
||||||
|
if (enfantIds.length === 0) return [];
|
||||||
|
const placements = await this.amChildrenRepo.find({
|
||||||
|
where: { enfantId: In(enfantIds), date_fin: IsNull() },
|
||||||
|
select: ['id'],
|
||||||
|
});
|
||||||
|
return placements.map((p) => p.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
const placements = await this.amChildrenRepo.find({
|
||||||
|
where: { amId: userId, date_fin: IsNull() },
|
||||||
|
select: ['id'],
|
||||||
|
});
|
||||||
|
return placements.map((p) => p.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new ForbiddenException('Rôle non autorisé');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertCanAccessPlacement(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
placementId: string,
|
||||||
|
): Promise<AmChildren> {
|
||||||
|
const placement = await this.amChildrenRepo.findOne({
|
||||||
|
where: { id: placementId, date_fin: IsNull() },
|
||||||
|
});
|
||||||
|
if (!placement) {
|
||||||
|
throw new NotFoundException('Placement / couple introuvable ou inactif');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
if (placement.amId !== userId) {
|
||||||
|
throw new ForbiddenException('Ce placement ne vous appartient pas');
|
||||||
|
}
|
||||||
|
return placement;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (role === RoleType.PARENT) {
|
||||||
|
const lien = await this.parentsChildrenRepo.findOne({
|
||||||
|
where: { parentId: userId, enfantId: placement.enfantId },
|
||||||
|
});
|
||||||
|
if (!lien) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Ce placement ne concerne pas un de vos enfants',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return placement;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new ForbiddenException('Rôle non autorisé');
|
||||||
|
}
|
||||||
|
|
||||||
|
private toDto(row: AbsencesGarde): AbsenceGardeDto {
|
||||||
|
const child = row.placement?.child;
|
||||||
|
const amUser = row.placement?.am?.user;
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
id_placement: row.id_placement,
|
||||||
|
type: row.type,
|
||||||
|
date_debut: row.date_debut,
|
||||||
|
date_fin: row.date_fin,
|
||||||
|
statut: row.statut,
|
||||||
|
expire_at: row.expire_at?.toISOString?.() ?? String(row.expire_at),
|
||||||
|
cree_par: row.cree_par ?? null,
|
||||||
|
motif: row.motif ?? null,
|
||||||
|
id_enfant: child?.id ?? row.placement?.enfantId ?? null,
|
||||||
|
prenom_enfant: child?.first_name ?? null,
|
||||||
|
id_am: row.placement?.amId ?? null,
|
||||||
|
prenom_am: amUser?.prenom ?? null,
|
||||||
|
nom_am: amUser?.nom ?? null,
|
||||||
|
cree_le: row.cree_le?.toISOString?.() ?? String(row.cree_le),
|
||||||
|
modifie_le: row.modifie_le?.toISOString?.() ?? String(row.modifie_le),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import {
|
||||||
|
IsDateString,
|
||||||
|
IsEnum,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
IsUUID,
|
||||||
|
MaxLength,
|
||||||
|
MinLength,
|
||||||
|
} from 'class-validator';
|
||||||
|
import {
|
||||||
|
StatutAbsenceGardeType,
|
||||||
|
TypeAbsenceGardeType,
|
||||||
|
} from 'src/entities/absences_garde.entity';
|
||||||
|
|
||||||
|
export class CreerAbsenceGardeDto {
|
||||||
|
@ApiProperty({ description: 'Placement AM↔enfant (couple)' })
|
||||||
|
@IsUUID()
|
||||||
|
id_placement: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: TypeAbsenceGardeType })
|
||||||
|
@IsEnum(TypeAbsenceGardeType)
|
||||||
|
type: TypeAbsenceGardeType;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2026-10-01' })
|
||||||
|
@IsDateString()
|
||||||
|
date_debut: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2026-10-05' })
|
||||||
|
@IsDateString()
|
||||||
|
date_fin: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(2000)
|
||||||
|
motif?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MajAbsenceGardeDto {
|
||||||
|
@ApiPropertyOptional({ example: '2026-10-02' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
date_debut?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: '2026-10-06' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
date_fin?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ enum: StatutAbsenceGardeType })
|
||||||
|
@IsOptional()
|
||||||
|
@IsEnum(StatutAbsenceGardeType)
|
||||||
|
statut?: StatutAbsenceGardeType;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Motivation de refus (parent) ou motif créateur',
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(2000)
|
||||||
|
motif?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class AbsenceGardeDto {
|
||||||
|
@ApiProperty()
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
id_placement: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: TypeAbsenceGardeType })
|
||||||
|
type: TypeAbsenceGardeType;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
date_debut: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
date_fin: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: StatutAbsenceGardeType })
|
||||||
|
statut: StatutAbsenceGardeType;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
expire_at: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
cree_par?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
motif?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
id_enfant?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
prenom_enfant?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
id_am?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
prenom_am?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
nom_am?: string | null;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
cree_le: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
modifie_le: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ListeAbsencesGardeDto {
|
||||||
|
@ApiProperty({ type: [AbsenceGardeDto] })
|
||||||
|
items: AbsenceGardeDto[];
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export { AbsencesGardeModule } from './absences-garde.module';
|
||||||
|
export { AbsencesGardeService } from './absences-garde.service';
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Headers,
|
||||||
|
MessageEvent,
|
||||||
|
Query,
|
||||||
|
Sse,
|
||||||
|
UnauthorizedException,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiOperation,
|
||||||
|
ApiQuery,
|
||||||
|
ApiTags,
|
||||||
|
} from '@nestjs/swagger';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||||
|
import { Public } from 'src/common/decorators/public.decorator';
|
||||||
|
import { User } from 'src/common/decorators/user.decorator';
|
||||||
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
import { CardsRealtimeService } from './cards-realtime.service';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SSE Cartes — #195
|
||||||
|
* Auth : Bearer (recommandé) ou `?access_token=` (EventSource navigateur).
|
||||||
|
*/
|
||||||
|
@ApiTags('Cartes')
|
||||||
|
@Controller('cards')
|
||||||
|
export class CardsRealtimeController {
|
||||||
|
constructor(
|
||||||
|
private readonly realtime: CardsRealtimeService,
|
||||||
|
private readonly jwtService: JwtService,
|
||||||
|
private readonly configService: ConfigService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Sse('stream')
|
||||||
|
@Public()
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Flux SSE bulles (card.created|updated|deleted, response.added) — #195',
|
||||||
|
})
|
||||||
|
@ApiQuery({
|
||||||
|
name: 'access_token',
|
||||||
|
required: false,
|
||||||
|
description: 'JWT si pas de header Authorization (EventSource)',
|
||||||
|
})
|
||||||
|
@ApiBearerAuth('access-token')
|
||||||
|
async stream(
|
||||||
|
@Headers('authorization') authorization?: string,
|
||||||
|
@Query('access_token') accessToken?: string,
|
||||||
|
): Promise<Observable<MessageEvent>> {
|
||||||
|
const userId = await this.resolveUserId(authorization, accessToken);
|
||||||
|
return this.realtime.streamFor(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Variante gardée (clients qui envoient Bearer correctement). */
|
||||||
|
@Get('stream/info')
|
||||||
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiBearerAuth('access-token')
|
||||||
|
@ApiOperation({ summary: 'Debug : abonnés SSE pour mon user — #195' })
|
||||||
|
info(@User('id') userId: string) {
|
||||||
|
return {
|
||||||
|
user_id: userId,
|
||||||
|
subscribers: this.realtime.subscriberCount(userId),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolveUserId(
|
||||||
|
authorization?: string,
|
||||||
|
accessToken?: string,
|
||||||
|
): Promise<string> {
|
||||||
|
let token = accessToken?.trim();
|
||||||
|
if (!token && authorization?.startsWith('Bearer ')) {
|
||||||
|
token = authorization.slice(7).trim();
|
||||||
|
}
|
||||||
|
if (!token) {
|
||||||
|
throw new UnauthorizedException('Token manquant (Bearer ou access_token)');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const payload = await this.jwtService.verifyAsync<{ sub: string }>(token, {
|
||||||
|
secret: this.configService.get<string>('jwt.accessSecret'),
|
||||||
|
});
|
||||||
|
if (!payload?.sub) throw new UnauthorizedException('Token invalide');
|
||||||
|
return payload.sub;
|
||||||
|
} catch {
|
||||||
|
throw new UnauthorizedException('Token invalide ou expiré');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { MessageEvent } from '@nestjs/common';
|
||||||
|
import { CardsRealtimeService } from './cards-realtime.service';
|
||||||
|
|
||||||
|
describe('CardsRealtimeService (#195)', () => {
|
||||||
|
let service: CardsRealtimeService;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
service = new CardsRealtimeService();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
service.onModuleDestroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('émet card.created aux abonnés du user', async () => {
|
||||||
|
const events: MessageEvent[] = [];
|
||||||
|
const sub = service.streamFor('user-a').subscribe((e) => events.push(e));
|
||||||
|
|
||||||
|
await new Promise((r) => setTimeout(r, 20));
|
||||||
|
expect(events[0]?.type).toBe('heartbeat');
|
||||||
|
expect(service.subscriberCount('user-a')).toBe(1);
|
||||||
|
|
||||||
|
service.emitToUsers(['user-a', 'user-b'], 'card.created', 'card-1', {
|
||||||
|
id: 'card-1',
|
||||||
|
});
|
||||||
|
await new Promise((r) => setTimeout(r, 20));
|
||||||
|
|
||||||
|
const created = events.find((e) => e.type === 'card.created');
|
||||||
|
expect(created).toBeDefined();
|
||||||
|
expect((created!.data as { card_id: string }).card_id).toBe('card-1');
|
||||||
|
expect(service.subscriberCount('user-b')).toBe(0);
|
||||||
|
|
||||||
|
sub.unsubscribe();
|
||||||
|
expect(service.subscriberCount('user-a')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ne diffuse pas aux users non abonnés', async () => {
|
||||||
|
const events: MessageEvent[] = [];
|
||||||
|
const sub = service.streamFor('user-a').subscribe((e) => events.push(e));
|
||||||
|
await new Promise((r) => setTimeout(r, 20));
|
||||||
|
const before = events.length;
|
||||||
|
service.emitToUsers(['user-b'], 'card.updated', 'x');
|
||||||
|
await new Promise((r) => setTimeout(r, 20));
|
||||||
|
expect(events.length).toBe(before);
|
||||||
|
sub.unsubscribe();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { Injectable, MessageEvent, OnModuleDestroy } from '@nestjs/common';
|
||||||
|
import { Observable, Subject, interval, merge, takeUntil } from 'rxjs';
|
||||||
|
import { map } from 'rxjs/operators';
|
||||||
|
|
||||||
|
export type CardRealtimeEventType =
|
||||||
|
| 'card.created'
|
||||||
|
| 'card.updated'
|
||||||
|
| 'card.deleted'
|
||||||
|
| 'response.added'
|
||||||
|
| 'heartbeat';
|
||||||
|
|
||||||
|
export interface CardRealtimePayload {
|
||||||
|
event: CardRealtimeEventType;
|
||||||
|
card_id?: string;
|
||||||
|
data?: unknown;
|
||||||
|
at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bus SSE in-memory par utilisateur (V1 mono-instance).
|
||||||
|
* Rooms = userId (audience carte).
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class CardsRealtimeService implements OnModuleDestroy {
|
||||||
|
private readonly byUser = new Map<string, Set<Subject<CardRealtimePayload>>>();
|
||||||
|
private readonly destroy$ = new Subject<void>();
|
||||||
|
|
||||||
|
onModuleDestroy(): void {
|
||||||
|
this.destroy$.next();
|
||||||
|
this.destroy$.complete();
|
||||||
|
for (const set of this.byUser.values()) {
|
||||||
|
for (const s of set) s.complete();
|
||||||
|
}
|
||||||
|
this.byUser.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Flux SSE pour un utilisateur authentifié. */
|
||||||
|
streamFor(userId: string): Observable<MessageEvent> {
|
||||||
|
const subject = new Subject<CardRealtimePayload>();
|
||||||
|
let set = this.byUser.get(userId);
|
||||||
|
if (!set) {
|
||||||
|
set = new Set();
|
||||||
|
this.byUser.set(userId, set);
|
||||||
|
}
|
||||||
|
set.add(subject);
|
||||||
|
|
||||||
|
const heartbeat$ = interval(25_000).pipe(
|
||||||
|
map(
|
||||||
|
(): CardRealtimePayload => ({
|
||||||
|
event: 'heartbeat',
|
||||||
|
at: new Date().toISOString(),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return new Observable<MessageEvent>((observer) => {
|
||||||
|
const sub = merge(subject, heartbeat$)
|
||||||
|
.pipe(takeUntil(this.destroy$))
|
||||||
|
.subscribe({
|
||||||
|
next: (payload) =>
|
||||||
|
observer.next({
|
||||||
|
type: payload.event,
|
||||||
|
data: payload,
|
||||||
|
} as MessageEvent),
|
||||||
|
error: (err) => observer.error(err),
|
||||||
|
complete: () => observer.complete(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// ping initial
|
||||||
|
subject.next({
|
||||||
|
event: 'heartbeat',
|
||||||
|
at: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
sub.unsubscribe();
|
||||||
|
set!.delete(subject);
|
||||||
|
subject.complete();
|
||||||
|
if (set!.size === 0) this.byUser.delete(userId);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
emitToUsers(
|
||||||
|
userIds: string[],
|
||||||
|
event: Exclude<CardRealtimeEventType, 'heartbeat'>,
|
||||||
|
cardId: string | undefined,
|
||||||
|
data?: unknown,
|
||||||
|
): void {
|
||||||
|
const unique = [...new Set(userIds.filter(Boolean))];
|
||||||
|
const payload: CardRealtimePayload = {
|
||||||
|
event,
|
||||||
|
card_id: cardId,
|
||||||
|
data,
|
||||||
|
at: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
for (const uid of unique) {
|
||||||
|
const set = this.byUser.get(uid);
|
||||||
|
if (!set) continue;
|
||||||
|
for (const s of set) s.next(payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Test / debug : nombre d’abonnés actifs. */
|
||||||
|
subscriberCount(userId?: string): number {
|
||||||
|
if (userId) return this.byUser.get(userId)?.size ?? 0;
|
||||||
|
let n = 0;
|
||||||
|
for (const s of this.byUser.values()) n += s.size;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
|
Param,
|
||||||
|
ParseUUIDPipe,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiBody,
|
||||||
|
ApiOperation,
|
||||||
|
ApiQuery,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from '@nestjs/swagger';
|
||||||
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||||
|
import { User } from 'src/common/decorators/user.decorator';
|
||||||
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
import { CardsService } from './cards.service';
|
||||||
|
import {
|
||||||
|
CarteDto,
|
||||||
|
CreerCarteDto,
|
||||||
|
ListeCartesDto,
|
||||||
|
MajCarteDto,
|
||||||
|
RepondreCarteDto,
|
||||||
|
} from './dto/cards.dto';
|
||||||
|
|
||||||
|
@ApiTags('Cartes')
|
||||||
|
@ApiBearerAuth('access-token')
|
||||||
|
@Controller('cards')
|
||||||
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
|
export class CardsController {
|
||||||
|
constructor(private readonly cardsService: CardsService) {}
|
||||||
|
|
||||||
|
@Get('types')
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiOperation({ summary: 'Types SYSTEM émissibles pour mon rôle — #194' })
|
||||||
|
listerTypes(@User('role') role: RoleType) {
|
||||||
|
return this.cardsService.listerTypes(role);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiOperation({ summary: 'Feed bulles de l’utilisateur — #194' })
|
||||||
|
@ApiQuery({ name: 'placementId', required: false })
|
||||||
|
@ApiResponse({ status: 200, type: ListeCartesDto })
|
||||||
|
lister(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Query('placementId') placementId?: string,
|
||||||
|
): Promise<ListeCartesDto> {
|
||||||
|
return this.cardsService.lister(userId, role, placementId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@HttpCode(HttpStatus.CREATED)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Créer une bulle (+ hook absences_garde) — #194',
|
||||||
|
})
|
||||||
|
@ApiBody({ type: CreerCarteDto })
|
||||||
|
@ApiResponse({ status: 201, type: CarteDto })
|
||||||
|
creer(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Body() dto: CreerCarteDto,
|
||||||
|
): Promise<CarteDto> {
|
||||||
|
return this.cardsService.creer(userId, role, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post(':id/respond')
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiOperation({ summary: 'Répondre (accept / refuse / ack) — #194' })
|
||||||
|
@ApiBody({ type: RepondreCarteDto })
|
||||||
|
repondre(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
@Body() dto: RepondreCarteDto,
|
||||||
|
): Promise<CarteDto> {
|
||||||
|
return this.cardsService.repondre(userId, role, id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':id')
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Modifier dates (créateur, ouverte/refusée) — #194',
|
||||||
|
})
|
||||||
|
@ApiBody({ type: MajCarteDto })
|
||||||
|
maj(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
@Body() dto: MajCarteDto,
|
||||||
|
): Promise<CarteDto> {
|
||||||
|
return this.cardsService.majEnAttente(userId, role, id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':id')
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
|
@ApiOperation({ summary: 'Supprimer bulle (+ absence si non traitée) — #194' })
|
||||||
|
async supprimer(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
): Promise<void> {
|
||||||
|
await this.cardsService.supprimer(userId, role, id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { AbsencesGardeModule } from '../absences-garde';
|
||||||
|
import { CardType } from 'src/entities/card_types.entity';
|
||||||
|
import { CardInstance } from 'src/entities/card_instances.entity';
|
||||||
|
import { CardAudienceMember } from 'src/entities/card_audience_members.entity';
|
||||||
|
import { CardResponse } from 'src/entities/card_responses.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { CardsController } from './cards.controller';
|
||||||
|
import { CardsRealtimeController } from './cards-realtime.controller';
|
||||||
|
import { CardsService } from './cards.service';
|
||||||
|
import { CardsRealtimeService } from './cards-realtime.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
AbsencesGardeModule,
|
||||||
|
TypeOrmModule.forFeature([
|
||||||
|
CardType,
|
||||||
|
CardInstance,
|
||||||
|
CardAudienceMember,
|
||||||
|
CardResponse,
|
||||||
|
AmChildren,
|
||||||
|
ParentsChildren,
|
||||||
|
]),
|
||||||
|
JwtModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: (config: ConfigService) => ({
|
||||||
|
secret: config.get('jwt.accessSecret'),
|
||||||
|
signOptions: { expiresIn: config.get('jwt.accessExpiresIn') },
|
||||||
|
}),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
controllers: [CardsController, CardsRealtimeController],
|
||||||
|
providers: [CardsService, CardsRealtimeService],
|
||||||
|
exports: [CardsService, CardsRealtimeService],
|
||||||
|
})
|
||||||
|
export class CardsModule {}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
|
import { ForbiddenException } from '@nestjs/common';
|
||||||
|
import { CardsService } from './cards.service';
|
||||||
|
import { CardsRealtimeService } from './cards-realtime.service';
|
||||||
|
import { AbsencesGardeService } from '../absences-garde/absences-garde.service';
|
||||||
|
import { CardType, CardResponseModeType } from 'src/entities/card_types.entity';
|
||||||
|
import {
|
||||||
|
CardInstance,
|
||||||
|
CardInstanceStatutType,
|
||||||
|
CardOperationType,
|
||||||
|
} from 'src/entities/card_instances.entity';
|
||||||
|
import { CardAudienceMember } from 'src/entities/card_audience_members.entity';
|
||||||
|
import { CardResponse } from 'src/entities/card_responses.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
import { StatutAbsenceGardeType, TypeAbsenceGardeType } from 'src/entities/absences_garde.entity';
|
||||||
|
|
||||||
|
describe('CardsService (#194)', () => {
|
||||||
|
let service: CardsService;
|
||||||
|
|
||||||
|
const typesRepo = { find: jest.fn(), findOne: jest.fn() };
|
||||||
|
const cardsRepo = {
|
||||||
|
create: jest.fn((x) => x),
|
||||||
|
save: jest.fn(async (x) => ({ ...x, id: x.id ?? 'card-1', cree_le: new Date(), modifie_le: new Date() })),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
createQueryBuilder: jest.fn(),
|
||||||
|
manager: { query: jest.fn() },
|
||||||
|
};
|
||||||
|
const audienceRepo = {
|
||||||
|
create: jest.fn((x) => x),
|
||||||
|
save: jest.fn(),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
find: jest.fn(),
|
||||||
|
};
|
||||||
|
const responsesRepo = {
|
||||||
|
create: jest.fn((x) => x),
|
||||||
|
save: jest.fn(),
|
||||||
|
};
|
||||||
|
const amChildrenRepo = { findOne: jest.fn() };
|
||||||
|
const parentsChildrenRepo = { find: jest.fn(), findOne: jest.fn() };
|
||||||
|
const absencesService = {
|
||||||
|
creer: jest.fn(),
|
||||||
|
maj: jest.fn(),
|
||||||
|
supprimer: jest.fn(),
|
||||||
|
};
|
||||||
|
const realtime = { emitToUsers: jest.fn() };
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
CardsService,
|
||||||
|
{ provide: getRepositoryToken(CardType), useValue: typesRepo },
|
||||||
|
{ provide: getRepositoryToken(CardInstance), useValue: cardsRepo },
|
||||||
|
{ provide: getRepositoryToken(CardAudienceMember), useValue: audienceRepo },
|
||||||
|
{ provide: getRepositoryToken(CardResponse), useValue: responsesRepo },
|
||||||
|
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo },
|
||||||
|
{ provide: getRepositoryToken(ParentsChildren), useValue: parentsChildrenRepo },
|
||||||
|
{ provide: AbsencesGardeService, useValue: absencesService },
|
||||||
|
{ provide: CardsRealtimeService, useValue: realtime },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
service = module.get(CardsService);
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(service).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('AM crée congé → absence + carte ouverte + audience parents', async () => {
|
||||||
|
typesRepo.findOne.mockResolvedValue({
|
||||||
|
code: 'conge_am',
|
||||||
|
system: true,
|
||||||
|
titre: 'Congé AM',
|
||||||
|
emitter_roles: [RoleType.ASSISTANTE_MATERNELLE],
|
||||||
|
recipient_roles: [RoleType.PARENT],
|
||||||
|
audience_resolver: 'couple_parents',
|
||||||
|
response_mode: CardResponseModeType.ACCEPT_REFUSE,
|
||||||
|
retention_days: 14,
|
||||||
|
couleur: 'lavender',
|
||||||
|
});
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
absencesService.creer.mockResolvedValue({
|
||||||
|
id: 'abs-1',
|
||||||
|
type: TypeAbsenceGardeType.CONGE_AM,
|
||||||
|
statut: StatutAbsenceGardeType.EN_ATTENTE,
|
||||||
|
});
|
||||||
|
parentsChildrenRepo.find.mockResolvedValue([
|
||||||
|
{ parentId: 'p-1', enfantId: 'e-1' },
|
||||||
|
{ parentId: 'p-2', enfantId: 'e-1' },
|
||||||
|
]);
|
||||||
|
cardsRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'card-1',
|
||||||
|
type_code: 'conge_am',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
id_absence: 'abs-1',
|
||||||
|
cree_par: 'am-1',
|
||||||
|
operation: CardOperationType.CREATE,
|
||||||
|
statut: CardInstanceStatutType.OUVERTE,
|
||||||
|
payload: { date_debut: '2026-11-01', date_fin: '2026-11-07' },
|
||||||
|
purge_at: new Date(),
|
||||||
|
cree_le: new Date(),
|
||||||
|
modifie_le: new Date(),
|
||||||
|
type: {
|
||||||
|
titre: 'Congé AM',
|
||||||
|
couleur: 'lavender',
|
||||||
|
response_mode: CardResponseModeType.ACCEPT_REFUSE,
|
||||||
|
retention_days: 14,
|
||||||
|
},
|
||||||
|
responses: [],
|
||||||
|
audience: [
|
||||||
|
{ id_utilisateur: 'am-1' },
|
||||||
|
{ id_utilisateur: 'p-1' },
|
||||||
|
{ id_utilisateur: 'p-2' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await service.creer('am-1', RoleType.ASSISTANTE_MATERNELLE, {
|
||||||
|
type_code: 'conge_am',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
date_debut: '2026-11-01',
|
||||||
|
date_fin: '2026-11-07',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(absencesService.creer).toHaveBeenCalled();
|
||||||
|
expect(audienceRepo.save).toHaveBeenCalled();
|
||||||
|
expect(realtime.emitToUsers).toHaveBeenCalledWith(
|
||||||
|
['am-1', 'p-1', 'p-2'],
|
||||||
|
'card.created',
|
||||||
|
'card-1',
|
||||||
|
expect.any(Object),
|
||||||
|
);
|
||||||
|
expect(res.type_code).toBe('conge_am');
|
||||||
|
expect(res.statut).toBe(CardInstanceStatutType.OUVERTE);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parent ne peut pas émettre conge_am', async () => {
|
||||||
|
typesRepo.findOne.mockResolvedValue({
|
||||||
|
code: 'conge_am',
|
||||||
|
system: true,
|
||||||
|
emitter_roles: [RoleType.ASSISTANTE_MATERNELLE],
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
service.creer('p-1', RoleType.PARENT, {
|
||||||
|
type_code: 'conge_am',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
date_debut: '2026-11-01',
|
||||||
|
date_fin: '2026-11-07',
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(ForbiddenException);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,489 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
ForbiddenException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { IsNull, Repository } from 'typeorm';
|
||||||
|
import { AbsencesGardeService } from '../absences-garde/absences-garde.service';
|
||||||
|
import {
|
||||||
|
StatutAbsenceGardeType,
|
||||||
|
TypeAbsenceGardeType,
|
||||||
|
} from 'src/entities/absences_garde.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
import { CardType, CardResponseModeType } from 'src/entities/card_types.entity';
|
||||||
|
import {
|
||||||
|
CardInstance,
|
||||||
|
CardInstanceStatutType,
|
||||||
|
CardOperationType,
|
||||||
|
} from 'src/entities/card_instances.entity';
|
||||||
|
import { CardAudienceMember } from 'src/entities/card_audience_members.entity';
|
||||||
|
import {
|
||||||
|
CardResponse,
|
||||||
|
CardResponseActionType,
|
||||||
|
} from 'src/entities/card_responses.entity';
|
||||||
|
import {
|
||||||
|
CarteDto,
|
||||||
|
CreerCarteDto,
|
||||||
|
ListeCartesDto,
|
||||||
|
MajCarteDto,
|
||||||
|
RepondreCarteDto,
|
||||||
|
} from './dto/cards.dto';
|
||||||
|
import { CardsRealtimeService } from './cards-realtime.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CardsService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(CardType)
|
||||||
|
private readonly typesRepo: Repository<CardType>,
|
||||||
|
@InjectRepository(CardInstance)
|
||||||
|
private readonly cardsRepo: Repository<CardInstance>,
|
||||||
|
@InjectRepository(CardAudienceMember)
|
||||||
|
private readonly audienceRepo: Repository<CardAudienceMember>,
|
||||||
|
@InjectRepository(CardResponse)
|
||||||
|
private readonly responsesRepo: Repository<CardResponse>,
|
||||||
|
@InjectRepository(AmChildren)
|
||||||
|
private readonly amChildrenRepo: Repository<AmChildren>,
|
||||||
|
@InjectRepository(ParentsChildren)
|
||||||
|
private readonly parentsChildrenRepo: Repository<ParentsChildren>,
|
||||||
|
private readonly absencesService: AbsencesGardeService,
|
||||||
|
private readonly realtime: CardsRealtimeService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async listerTypes(role: RoleType): Promise<CardType[]> {
|
||||||
|
const all = await this.typesRepo.find({ where: { system: true } });
|
||||||
|
return all.filter((t) => t.emitter_roles.includes(role));
|
||||||
|
}
|
||||||
|
|
||||||
|
async lister(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
placementId?: string,
|
||||||
|
): Promise<ListeCartesDto> {
|
||||||
|
const qb = this.cardsRepo
|
||||||
|
.createQueryBuilder('c')
|
||||||
|
.innerJoin('c.audience', 'aud', 'aud.id_utilisateur = :userId', { userId })
|
||||||
|
.leftJoinAndSelect('c.type', 'type')
|
||||||
|
.leftJoinAndSelect('c.responses', 'responses')
|
||||||
|
.where('c.purge_at > now()')
|
||||||
|
.orderBy(
|
||||||
|
`CASE c.statut WHEN 'refusee' THEN 0 WHEN 'ouverte' THEN 1 ELSE 2 END`,
|
||||||
|
'ASC',
|
||||||
|
)
|
||||||
|
.addOrderBy('c.modifie_le', 'DESC');
|
||||||
|
|
||||||
|
if (placementId) {
|
||||||
|
await this.assertPlacementAccess(userId, role, placementId);
|
||||||
|
qb.andWhere('c.id_placement = :placementId', { placementId });
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await qb.getMany();
|
||||||
|
return {
|
||||||
|
items: rows.map((c) => this.toDto(c, userId)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async creer(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
dto: CreerCarteDto,
|
||||||
|
): Promise<CarteDto> {
|
||||||
|
if (dto.date_fin < dto.date_debut) {
|
||||||
|
throw new BadRequestException('date_fin < date_debut');
|
||||||
|
}
|
||||||
|
|
||||||
|
const type = await this.typesRepo.findOne({ where: { code: dto.type_code } });
|
||||||
|
if (!type || !type.system) {
|
||||||
|
throw new NotFoundException('Type de carte inconnu');
|
||||||
|
}
|
||||||
|
if (!type.emitter_roles.includes(role)) {
|
||||||
|
throw new ForbiddenException('Vous ne pouvez pas émettre ce type de carte');
|
||||||
|
}
|
||||||
|
|
||||||
|
const placement = await this.assertPlacementAccess(
|
||||||
|
userId,
|
||||||
|
role,
|
||||||
|
dto.id_placement,
|
||||||
|
);
|
||||||
|
const operation = dto.operation ?? CardOperationType.CREATE;
|
||||||
|
|
||||||
|
let absenceId = dto.id_absence;
|
||||||
|
const absenceType = this.mapAbsenceType(dto.type_code);
|
||||||
|
|
||||||
|
if (operation === CardOperationType.CREATE) {
|
||||||
|
const absence = await this.absencesService.creer(userId, role, {
|
||||||
|
id_placement: dto.id_placement,
|
||||||
|
type: absenceType,
|
||||||
|
date_debut: dto.date_debut,
|
||||||
|
date_fin: dto.date_fin,
|
||||||
|
motif: dto.motif,
|
||||||
|
});
|
||||||
|
absenceId = absence.id;
|
||||||
|
} else {
|
||||||
|
if (!absenceId) {
|
||||||
|
throw new BadRequestException('id_absence requis pour operation=update');
|
||||||
|
}
|
||||||
|
await this.absencesService.maj(userId, role, absenceId, {
|
||||||
|
date_debut: dto.date_debut,
|
||||||
|
date_fin: dto.date_fin,
|
||||||
|
motif: dto.motif,
|
||||||
|
// Congé accepté modifié → repasse en attente via cartes respond flow;
|
||||||
|
// pour absence enfant update immédiat déjà fait.
|
||||||
|
...(dto.type_code === 'conge_am'
|
||||||
|
? { statut: StatutAbsenceGardeType.EN_ATTENTE }
|
||||||
|
: {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const statutInitial =
|
||||||
|
type.response_mode === CardResponseModeType.NONE
|
||||||
|
? CardInstanceStatutType.TRAITEE
|
||||||
|
: CardInstanceStatutType.OUVERTE;
|
||||||
|
|
||||||
|
const card = this.cardsRepo.create({
|
||||||
|
type_code: type.code,
|
||||||
|
id_placement: dto.id_placement,
|
||||||
|
id_absence: absenceId,
|
||||||
|
cree_par: userId,
|
||||||
|
operation,
|
||||||
|
statut: statutInitial,
|
||||||
|
payload: {
|
||||||
|
date_debut: dto.date_debut,
|
||||||
|
date_fin: dto.date_fin,
|
||||||
|
motif: dto.motif ?? null,
|
||||||
|
},
|
||||||
|
purge_at: this.purgeAt(type.retention_days, statutInitial),
|
||||||
|
});
|
||||||
|
const saved = await this.cardsRepo.save(card);
|
||||||
|
|
||||||
|
if (absenceId) {
|
||||||
|
await this.linkAbsenceCard(absenceId, saved.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.buildAudience(saved, type, placement, userId, role);
|
||||||
|
|
||||||
|
const full = await this.loadCard(saved.id);
|
||||||
|
const dtoOut = this.toDto(full, userId);
|
||||||
|
this.emitAudience(full, 'card.created', dtoOut);
|
||||||
|
return dtoOut;
|
||||||
|
}
|
||||||
|
|
||||||
|
async repondre(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
cardId: string,
|
||||||
|
dto: RepondreCarteDto,
|
||||||
|
): Promise<CarteDto> {
|
||||||
|
const card = await this.loadCard(cardId);
|
||||||
|
await this.assertInAudience(card, userId);
|
||||||
|
if (card.statut !== CardInstanceStatutType.OUVERTE) {
|
||||||
|
throw new BadRequestException('Cette carte n’est plus ouverte');
|
||||||
|
}
|
||||||
|
if (card.cree_par === userId) {
|
||||||
|
throw new ForbiddenException('Le créateur ne répond pas à sa propre carte');
|
||||||
|
}
|
||||||
|
|
||||||
|
const mode = card.type.response_mode;
|
||||||
|
if (mode === CardResponseModeType.NONE) {
|
||||||
|
throw new BadRequestException('Ce type de carte ne demande pas de réponse');
|
||||||
|
}
|
||||||
|
if (mode === CardResponseModeType.ACK && dto.action !== CardResponseActionType.ACK) {
|
||||||
|
throw new BadRequestException('Action attendue : ack');
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
mode === CardResponseModeType.ACCEPT_REFUSE &&
|
||||||
|
dto.action !== CardResponseActionType.ACCEPT &&
|
||||||
|
dto.action !== CardResponseActionType.REFUSE
|
||||||
|
) {
|
||||||
|
throw new BadRequestException('Action attendue : accept ou refuse');
|
||||||
|
}
|
||||||
|
if (dto.action === CardResponseActionType.REFUSE && !dto.comment?.trim()) {
|
||||||
|
throw new BadRequestException('Motivation obligatoire en cas de refus');
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.responsesRepo.save(
|
||||||
|
this.responsesRepo.create({
|
||||||
|
id_card: card.id,
|
||||||
|
id_utilisateur: userId,
|
||||||
|
action: dto.action,
|
||||||
|
comment: dto.comment?.trim(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (card.id_absence) {
|
||||||
|
if (dto.action === CardResponseActionType.ACCEPT || dto.action === CardResponseActionType.ACK) {
|
||||||
|
await this.absencesService.maj(userId, role, card.id_absence, {
|
||||||
|
statut: StatutAbsenceGardeType.ACCEPTE,
|
||||||
|
});
|
||||||
|
card.statut = CardInstanceStatutType.TRAITEE;
|
||||||
|
} else if (dto.action === CardResponseActionType.REFUSE) {
|
||||||
|
await this.absencesService.maj(userId, role, card.id_absence, {
|
||||||
|
statut: StatutAbsenceGardeType.REFUSE,
|
||||||
|
motif: dto.comment!.trim(),
|
||||||
|
});
|
||||||
|
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);
|
||||||
|
await this.cardsRepo.save(card);
|
||||||
|
const full = await this.loadCard(cardId);
|
||||||
|
const dtoOut = this.toDto(full, userId);
|
||||||
|
this.emitAudience(full, 'response.added', {
|
||||||
|
action: dto.action,
|
||||||
|
card: dtoOut,
|
||||||
|
});
|
||||||
|
this.emitAudience(full, 'card.updated', dtoOut);
|
||||||
|
return dtoOut;
|
||||||
|
}
|
||||||
|
|
||||||
|
async majEnAttente(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
cardId: string,
|
||||||
|
dto: MajCarteDto,
|
||||||
|
): Promise<CarteDto> {
|
||||||
|
const card = await this.loadCard(cardId);
|
||||||
|
if (card.cree_par !== userId) {
|
||||||
|
throw new ForbiddenException('Seul le créateur peut modifier cette carte');
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
card.statut !== CardInstanceStatutType.OUVERTE &&
|
||||||
|
card.statut !== CardInstanceStatutType.REFUSEE
|
||||||
|
) {
|
||||||
|
throw new BadRequestException('Carte non modifiable dans cet état');
|
||||||
|
}
|
||||||
|
|
||||||
|
const debut =
|
||||||
|
dto.date_debut ?? String(card.payload?.['date_debut'] ?? '');
|
||||||
|
const fin = dto.date_fin ?? String(card.payload?.['date_fin'] ?? '');
|
||||||
|
if (!debut || !fin || fin < debut) {
|
||||||
|
throw new BadRequestException('Dates invalides');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (card.id_absence) {
|
||||||
|
await this.absencesService.maj(userId, role, card.id_absence, {
|
||||||
|
date_debut: debut,
|
||||||
|
date_fin: fin,
|
||||||
|
motif: dto.motif,
|
||||||
|
statut: StatutAbsenceGardeType.EN_ATTENTE,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
card.payload = {
|
||||||
|
...card.payload,
|
||||||
|
date_debut: debut,
|
||||||
|
date_fin: fin,
|
||||||
|
motif: dto.motif ?? card.payload?.['motif'] ?? null,
|
||||||
|
};
|
||||||
|
card.statut = CardInstanceStatutType.OUVERTE;
|
||||||
|
card.purge_at = this.purgeAt(card.type.retention_days, card.statut);
|
||||||
|
await this.cardsRepo.save(card);
|
||||||
|
const full = await this.loadCard(cardId);
|
||||||
|
const dtoOut = this.toDto(full, userId);
|
||||||
|
this.emitAudience(full, 'card.updated', dtoOut);
|
||||||
|
return dtoOut;
|
||||||
|
}
|
||||||
|
|
||||||
|
async supprimer(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
cardId: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const card = await this.loadCard(cardId);
|
||||||
|
if (card.cree_par !== userId) {
|
||||||
|
throw new ForbiddenException('Seul le créateur peut supprimer cette carte');
|
||||||
|
}
|
||||||
|
const audienceIds = await this.audienceUserIds(card);
|
||||||
|
if (card.id_absence) {
|
||||||
|
const absStatut =
|
||||||
|
card.statut === CardInstanceStatutType.TRAITEE
|
||||||
|
? null
|
||||||
|
: card.id_absence;
|
||||||
|
// Supprime l’absence liée si pas encore acceptée définitivement
|
||||||
|
if (
|
||||||
|
card.statut === CardInstanceStatutType.OUVERTE ||
|
||||||
|
card.statut === CardInstanceStatutType.REFUSEE
|
||||||
|
) {
|
||||||
|
await this.absencesService.supprimer(userId, role, card.id_absence);
|
||||||
|
}
|
||||||
|
void absStatut;
|
||||||
|
}
|
||||||
|
await this.cardsRepo.delete({ id: cardId });
|
||||||
|
this.realtime.emitToUsers(audienceIds, 'card.deleted', cardId, {
|
||||||
|
id: cardId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private emitAudience(
|
||||||
|
card: CardInstance,
|
||||||
|
event: 'card.created' | 'card.updated' | 'response.added',
|
||||||
|
data: unknown,
|
||||||
|
): void {
|
||||||
|
const ids = (card.audience ?? []).map((a) => a.id_utilisateur);
|
||||||
|
if (ids.length === 0) return;
|
||||||
|
this.realtime.emitToUsers(ids, event, card.id, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async audienceUserIds(card: CardInstance): Promise<string[]> {
|
||||||
|
if (card.audience?.length) {
|
||||||
|
return card.audience.map((a) => a.id_utilisateur);
|
||||||
|
}
|
||||||
|
const rows = await this.audienceRepo.find({ where: { id_card: card.id } });
|
||||||
|
return rows.map((r) => r.id_utilisateur);
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapAbsenceType(typeCode: string): TypeAbsenceGardeType {
|
||||||
|
if (typeCode === 'absence_enfant' || typeCode === 'absence_enfant_modif') {
|
||||||
|
return TypeAbsenceGardeType.ABSENCE_ENFANT;
|
||||||
|
}
|
||||||
|
if (typeCode === 'conge_am') return TypeAbsenceGardeType.CONGE_AM;
|
||||||
|
if (typeCode === 'arret_maladie_am') {
|
||||||
|
return TypeAbsenceGardeType.ARRET_MALADIE_AM;
|
||||||
|
}
|
||||||
|
throw new BadRequestException(`Type non mappé à une absence: ${typeCode}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async linkAbsenceCard(absenceId: string, cardId: string): Promise<void> {
|
||||||
|
// Update direct pour éviter droits maj vides
|
||||||
|
await this.cardsRepo.manager.query(
|
||||||
|
`UPDATE absences_garde SET id_card_instance = $1, modifie_le = now() WHERE id = $2`,
|
||||||
|
[cardId, absenceId],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async buildAudience(
|
||||||
|
card: CardInstance,
|
||||||
|
type: CardType,
|
||||||
|
placement: AmChildren,
|
||||||
|
creatorId: string,
|
||||||
|
creatorRole: RoleType,
|
||||||
|
): Promise<void> {
|
||||||
|
const members: Partial<CardAudienceMember>[] = [
|
||||||
|
{
|
||||||
|
id_card: card.id,
|
||||||
|
id_utilisateur: creatorId,
|
||||||
|
role_snapshot: creatorRole,
|
||||||
|
is_creator: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
if (type.audience_resolver === 'couple_am') {
|
||||||
|
members.push({
|
||||||
|
id_card: card.id,
|
||||||
|
id_utilisateur: placement.amId,
|
||||||
|
role_snapshot: RoleType.ASSISTANTE_MATERNELLE,
|
||||||
|
is_creator: false,
|
||||||
|
});
|
||||||
|
} else if (type.audience_resolver === 'couple_parents') {
|
||||||
|
const liens = await this.parentsChildrenRepo.find({
|
||||||
|
where: { enfantId: placement.enfantId },
|
||||||
|
});
|
||||||
|
for (const l of liens) {
|
||||||
|
if (l.parentId === creatorId) continue;
|
||||||
|
members.push({
|
||||||
|
id_card: card.id,
|
||||||
|
id_utilisateur: l.parentId,
|
||||||
|
role_snapshot: RoleType.PARENT,
|
||||||
|
is_creator: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// dédup
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const unique = members.filter((m) => {
|
||||||
|
const k = m.id_utilisateur!;
|
||||||
|
if (seen.has(k)) return false;
|
||||||
|
seen.add(k);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
await this.audienceRepo.save(this.audienceRepo.create(unique));
|
||||||
|
}
|
||||||
|
|
||||||
|
private purgeAt(
|
||||||
|
retentionDays: number,
|
||||||
|
statut: CardInstanceStatutType,
|
||||||
|
): Date {
|
||||||
|
const days =
|
||||||
|
statut === CardInstanceStatutType.OUVERTE
|
||||||
|
? Math.max(retentionDays, 15)
|
||||||
|
: retentionDays;
|
||||||
|
return new Date(Date.now() + days * 24 * 60 * 60 * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadCard(id: string): Promise<CardInstance> {
|
||||||
|
const card = await this.cardsRepo.findOne({
|
||||||
|
where: { id },
|
||||||
|
relations: ['type', 'responses', 'audience'],
|
||||||
|
});
|
||||||
|
if (!card) throw new NotFoundException('Carte introuvable');
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertInAudience(card: CardInstance, userId: string): Promise<void> {
|
||||||
|
const ok = (card.audience ?? []).some((a) => a.id_utilisateur === userId);
|
||||||
|
if (!ok) {
|
||||||
|
const row = await this.audienceRepo.findOne({
|
||||||
|
where: { id_card: card.id, id_utilisateur: userId },
|
||||||
|
});
|
||||||
|
if (!row) throw new ForbiddenException('Carte hors de votre audience');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertPlacementAccess(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
placementId: string,
|
||||||
|
): Promise<AmChildren> {
|
||||||
|
const placement = await this.amChildrenRepo.findOne({
|
||||||
|
where: { id: placementId, date_fin: IsNull() },
|
||||||
|
});
|
||||||
|
if (!placement) {
|
||||||
|
throw new NotFoundException('Placement introuvable ou inactif');
|
||||||
|
}
|
||||||
|
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
if (placement.amId !== userId) {
|
||||||
|
throw new ForbiddenException('Placement non autorisé');
|
||||||
|
}
|
||||||
|
return placement;
|
||||||
|
}
|
||||||
|
if (role === RoleType.PARENT) {
|
||||||
|
const lien = await this.parentsChildrenRepo.findOne({
|
||||||
|
where: { parentId: userId, enfantId: placement.enfantId },
|
||||||
|
});
|
||||||
|
if (!lien) throw new ForbiddenException('Placement non autorisé');
|
||||||
|
return placement;
|
||||||
|
}
|
||||||
|
throw new ForbiddenException('Rôle non autorisé');
|
||||||
|
}
|
||||||
|
|
||||||
|
private toDto(card: CardInstance, userId: string): CarteDto {
|
||||||
|
const lastRefuse = [...(card.responses ?? [])]
|
||||||
|
.reverse()
|
||||||
|
.find((r) => r.action === CardResponseActionType.REFUSE);
|
||||||
|
return {
|
||||||
|
id: card.id,
|
||||||
|
type_code: card.type_code,
|
||||||
|
titre: card.type?.titre ?? card.type_code,
|
||||||
|
couleur: card.type?.couleur ?? null,
|
||||||
|
id_placement: card.id_placement,
|
||||||
|
id_absence: card.id_absence ?? null,
|
||||||
|
operation: card.operation,
|
||||||
|
statut: card.statut,
|
||||||
|
payload: card.payload ?? {},
|
||||||
|
purge_at: card.purge_at?.toISOString?.() ?? String(card.purge_at),
|
||||||
|
cree_par: card.cree_par ?? null,
|
||||||
|
is_creator: card.cree_par === userId,
|
||||||
|
response_mode: card.type?.response_mode,
|
||||||
|
last_refuse_comment: lastRefuse?.comment ?? null,
|
||||||
|
cree_le: card.cree_le?.toISOString?.() ?? String(card.cree_le),
|
||||||
|
modifie_le: card.modifie_le?.toISOString?.() ?? String(card.modifie_le),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import {
|
||||||
|
IsDateString,
|
||||||
|
IsEnum,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
IsUUID,
|
||||||
|
MaxLength,
|
||||||
|
MinLength,
|
||||||
|
ValidateIf,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { CardInstanceStatutType, CardOperationType } from 'src/entities/card_instances.entity';
|
||||||
|
import { CardResponseActionType } from 'src/entities/card_responses.entity';
|
||||||
|
|
||||||
|
export class CreerCarteDto {
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'absence_enfant | absence_enfant_modif | conge_am | arret_maladie_am',
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
type_code: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsUUID()
|
||||||
|
id_placement: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2026-10-01' })
|
||||||
|
@IsDateString()
|
||||||
|
date_debut: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2026-10-05' })
|
||||||
|
@IsDateString()
|
||||||
|
date_fin: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(2000)
|
||||||
|
motif?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Requis pour operation=update (même id absences_garde)',
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsUUID()
|
||||||
|
id_absence?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ enum: CardOperationType, default: CardOperationType.CREATE })
|
||||||
|
@IsOptional()
|
||||||
|
@IsEnum(CardOperationType)
|
||||||
|
operation?: CardOperationType;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RepondreCarteDto {
|
||||||
|
@ApiProperty({ enum: CardResponseActionType })
|
||||||
|
@IsEnum(CardResponseActionType)
|
||||||
|
action: CardResponseActionType;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ description: 'Obligatoire si action=refuse' })
|
||||||
|
@ValidateIf((o) => o.action === CardResponseActionType.REFUSE)
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(2000)
|
||||||
|
comment?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MajCarteDto {
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
date_debut?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
date_fin?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(2000)
|
||||||
|
motif?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CarteDto {
|
||||||
|
@ApiProperty()
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
type_code: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
titre: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
couleur?: string | null;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
id_placement: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
id_absence?: string | null;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: CardOperationType })
|
||||||
|
operation: CardOperationType;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: CardInstanceStatutType })
|
||||||
|
statut: CardInstanceStatutType;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
payload: Record<string, unknown>;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
purge_at: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
cree_par?: string | null;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
is_creator: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
response_mode?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
last_refuse_comment?: string | null;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
cree_le: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
modifie_le: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ListeCartesDto {
|
||||||
|
@ApiProperty({ type: [CarteDto] })
|
||||||
|
items: CarteDto[];
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export { CardsModule } from './cards.module';
|
||||||
|
export { CardsService } from './cards.service';
|
||||||
|
export { CardsRealtimeService } from './cards-realtime.service';
|
||||||
@@ -1,7 +1,21 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { MailService, ValidationAccountEmailKind } from './mail.service';
|
import { MailService, ValidationAccountEmailKind, isTransientSmtpError } from './mail.service';
|
||||||
import { AppConfigService } from '../config/config.service';
|
import { AppConfigService } from '../config/config.service';
|
||||||
|
|
||||||
|
describe('isTransientSmtpError', () => {
|
||||||
|
it('détecte les erreurs SMTP temporaires (454, coupure auth, timeout)', () => {
|
||||||
|
expect(isTransientSmtpError(new Error('Invalid login: 454 4.7.0 Temporary authentication failure'))).toBe(true);
|
||||||
|
expect(isTransientSmtpError(new Error('Connection lost to authentication server'))).toBe(true);
|
||||||
|
expect(isTransientSmtpError(Object.assign(new Error('timeout'), { code: 'ETIMEDOUT' }))).toBe(true);
|
||||||
|
expect(isTransientSmtpError(Object.assign(new Error('auth failed'), { responseCode: 454 }))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignore les erreurs permanentes (mauvaise adresse, refus définitif)', () => {
|
||||||
|
expect(isTransientSmtpError(new Error('Invalid login: 535 Authentication failed'))).toBe(false);
|
||||||
|
expect(isTransientSmtpError(new Error('Mailbox unavailable'))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('MailService (ticket #28)', () => {
|
describe('MailService (ticket #28)', () => {
|
||||||
let service: MailService;
|
let service: MailService;
|
||||||
let sendEmailSpy: jest.SpyInstance;
|
let sendEmailSpy: jest.SpyInstance;
|
||||||
@@ -68,4 +82,37 @@ describe('MailService (ticket #28)', () => {
|
|||||||
expect(html).toContain('2025-000001');
|
expect(html).toContain('2025-000001');
|
||||||
expect(html).toContain(`https://app.test/create-password?token=${encodeURIComponent(token)}`);
|
expect(html).toContain(`https://app.test/create-password?token=${encodeURIComponent(token)}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('sendPasswordResetEmail utilise Handlebars + lien /reset-password', async () => {
|
||||||
|
const token = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
|
||||||
|
await service.sendPasswordResetEmail({
|
||||||
|
email: 'u@test.fr',
|
||||||
|
prenom: 'Marie',
|
||||||
|
nom: 'Curie',
|
||||||
|
token,
|
||||||
|
});
|
||||||
|
expect(sendEmailSpy).toHaveBeenCalledTimes(1);
|
||||||
|
const [, subject, html] = sendEmailSpy.mock.calls[0];
|
||||||
|
expect(subject).toContain('Réinitialisation');
|
||||||
|
expect(html).toContain('Marie');
|
||||||
|
expect(html).toContain(`https://app.test/reset-password?token=${encodeURIComponent(token)}`);
|
||||||
|
expect(html).not.toContain('create-password');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sendResoumissionPendingEmail — accusé resoumission avec n° dossier', async () => {
|
||||||
|
await service.sendResoumissionPendingEmail(
|
||||||
|
'parent@test.fr',
|
||||||
|
'Claire',
|
||||||
|
'MARTIN',
|
||||||
|
'2026-000024',
|
||||||
|
);
|
||||||
|
expect(sendEmailSpy).toHaveBeenCalledTimes(1);
|
||||||
|
const [to, subject, html] = sendEmailSpy.mock.calls[0];
|
||||||
|
expect(to).toBe('parent@test.fr');
|
||||||
|
expect(subject).toContain('resoumis');
|
||||||
|
expect(subject).toContain('2026-000024');
|
||||||
|
expect(html).toContain('Claire');
|
||||||
|
expect(html).toContain('2026-000024');
|
||||||
|
expect(html).toContain('en attente de validation');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,20 +2,121 @@ import { Injectable, Logger } from '@nestjs/common';
|
|||||||
import { readFileSync } from 'fs';
|
import { readFileSync } from 'fs';
|
||||||
import { join } from 'path';
|
import { join } from 'path';
|
||||||
import * as Handlebars from 'handlebars';
|
import * as Handlebars from 'handlebars';
|
||||||
|
import type SMTPTransport from 'nodemailer/lib/smtp-transport';
|
||||||
import { AppConfigService } from '../config/config.service';
|
import { AppConfigService } from '../config/config.service';
|
||||||
|
|
||||||
/** Ticket #28 — quel template d'email envoyer après validation de compte */
|
/** Ticket #28 — quel template d'email envoyer après validation de compte */
|
||||||
export type ValidationAccountEmailKind = 'parent' | 'am';
|
export type ValidationAccountEmailKind = 'parent' | 'am';
|
||||||
|
|
||||||
|
type MailTransporter = {
|
||||||
|
sendMail: (options: Record<string, unknown>) => Promise<unknown>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Erreurs SMTP temporaires (surcharge auth, coupure réseau…) — retentables. */
|
||||||
|
export function isTransientSmtpError(error: unknown): boolean {
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
const code = typeof error === 'object' && error !== null && 'code' in error
|
||||||
|
? String((error as { code?: unknown }).code ?? '')
|
||||||
|
: '';
|
||||||
|
const responseCode =
|
||||||
|
typeof error === 'object' && error !== null && 'responseCode' in error
|
||||||
|
? Number((error as { responseCode?: unknown }).responseCode)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
if (responseCode === 454 || responseCode === 421 || responseCode === 450 || responseCode === 451) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const transientCodes = new Set(['ECONNRESET', 'ETIMEDOUT', 'ESOCKET', 'ECONNREFUSED', 'EPIPE']);
|
||||||
|
if (transientCodes.has(code)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const transientPatterns = [
|
||||||
|
/temporary authentication failure/i,
|
||||||
|
/connection lost to authentication server/i,
|
||||||
|
/connection reset/i,
|
||||||
|
/timeout/i,
|
||||||
|
/try again later/i,
|
||||||
|
];
|
||||||
|
return transientPatterns.some((pattern) => pattern.test(message));
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class MailService {
|
export class MailService {
|
||||||
private readonly logger = new Logger(MailService.name);
|
private readonly logger = new Logger(MailService.name);
|
||||||
|
private readonly smtpMaxAttempts = 3;
|
||||||
|
private readonly smtpRetryBaseDelayMs = 1000;
|
||||||
|
|
||||||
/** Cache des templates Handlebars compilés (fichiers .hbs) */
|
/** Cache des templates Handlebars compilés (fichiers .hbs) */
|
||||||
private readonly compiledTemplates = new Map<ValidationAccountEmailKind, Handlebars.TemplateDelegate>();
|
private readonly compiledTemplates = new Map<ValidationAccountEmailKind, Handlebars.TemplateDelegate>();
|
||||||
|
|
||||||
|
/** Transporteur SMTP réutilisé (évite une auth TCP/SASL par email). */
|
||||||
|
private transporter: MailTransporter | null = null;
|
||||||
|
private transporterConfigKey: string | null = null;
|
||||||
|
|
||||||
constructor(private readonly configService: AppConfigService) {}
|
constructor(private readonly configService: AppConfigService) {}
|
||||||
|
|
||||||
|
private sleep(ms: number): Promise<void> {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildSmtpTransportConfig(): SMTPTransport.Options {
|
||||||
|
const smtpHost = this.configService.get<string>('smtp_host');
|
||||||
|
const smtpPort = this.configService.get<number>('smtp_port');
|
||||||
|
const smtpSecure = this.configService.get<boolean>('smtp_secure');
|
||||||
|
const smtpAuthRequired = this.configService.get<boolean>('smtp_auth_required');
|
||||||
|
const smtpUser = this.configService.get<string>('smtp_user');
|
||||||
|
const smtpPassword = this.configService.get<string>('smtp_password');
|
||||||
|
|
||||||
|
const transportConfig = {
|
||||||
|
host: smtpHost,
|
||||||
|
port: smtpPort,
|
||||||
|
secure: smtpSecure,
|
||||||
|
pool: true,
|
||||||
|
maxConnections: 1,
|
||||||
|
maxMessages: 100,
|
||||||
|
...(smtpAuthRequired && smtpUser && smtpPassword
|
||||||
|
? { auth: { user: smtpUser, pass: smtpPassword } }
|
||||||
|
: {}),
|
||||||
|
} as SMTPTransport.Options;
|
||||||
|
|
||||||
|
return transportConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
private getSmtpConfigKey(config: SMTPTransport.Options): string {
|
||||||
|
const auth = config.auth as { user?: string; pass?: string } | undefined;
|
||||||
|
return JSON.stringify({
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
secure: config.secure,
|
||||||
|
user: auth?.user ?? '',
|
||||||
|
pass: auth?.pass ?? '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private resetTransporter(): void {
|
||||||
|
const current = this.transporter as { close?: () => void } | null;
|
||||||
|
current?.close?.();
|
||||||
|
this.transporter = null;
|
||||||
|
this.transporterConfigKey = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getTransporter(): Promise<MailTransporter> {
|
||||||
|
const transportConfig = this.buildSmtpTransportConfig();
|
||||||
|
const configKey = this.getSmtpConfigKey(transportConfig);
|
||||||
|
|
||||||
|
if (this.transporter && this.transporterConfigKey === configKey) {
|
||||||
|
return this.transporter;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.resetTransporter();
|
||||||
|
const nodemailer = await import('nodemailer');
|
||||||
|
this.transporter = nodemailer.createTransport(transportConfig) as MailTransporter;
|
||||||
|
this.transporterConfigKey = configKey;
|
||||||
|
return this.transporter;
|
||||||
|
}
|
||||||
|
|
||||||
private templateBasename(kind: ValidationAccountEmailKind): string {
|
private templateBasename(kind: ValidationAccountEmailKind): string {
|
||||||
const map: Record<ValidationAccountEmailKind, string> = {
|
const map: Record<ValidationAccountEmailKind, string> = {
|
||||||
parent: 'account-validated-parent',
|
parent: 'account-validated-parent',
|
||||||
@@ -81,52 +182,50 @@ export class MailService {
|
|||||||
* @param text Contenu texte (optionnel)
|
* @param text Contenu texte (optionnel)
|
||||||
*/
|
*/
|
||||||
async sendEmail(to: string, subject: string, html: string, text?: string): Promise<void> {
|
async sendEmail(to: string, subject: string, html: string, text?: string): Promise<void> {
|
||||||
try {
|
|
||||||
// Récupération de la configuration SMTP
|
|
||||||
const smtpHost = this.configService.get<string>('smtp_host');
|
|
||||||
const smtpPort = this.configService.get<number>('smtp_port');
|
|
||||||
const smtpSecure = this.configService.get<boolean>('smtp_secure');
|
|
||||||
const smtpAuthRequired = this.configService.get<boolean>('smtp_auth_required');
|
|
||||||
const smtpUser = this.configService.get<string>('smtp_user');
|
|
||||||
const smtpPassword = this.configService.get<string>('smtp_password');
|
|
||||||
const emailFromName = this.configService.get<string>('email_from_name');
|
const emailFromName = this.configService.get<string>('email_from_name');
|
||||||
const emailFromAddress = this.configService.get<string>('email_from_address');
|
const emailFromAddress = this.configService.get<string>('email_from_address');
|
||||||
|
const mailOptions = {
|
||||||
// Import dynamique de nodemailer
|
|
||||||
const nodemailer = await import('nodemailer');
|
|
||||||
|
|
||||||
// Configuration du transporteur
|
|
||||||
const transportConfig: any = {
|
|
||||||
host: smtpHost,
|
|
||||||
port: smtpPort,
|
|
||||||
secure: smtpSecure,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (smtpAuthRequired && smtpUser && smtpPassword) {
|
|
||||||
transportConfig.auth = {
|
|
||||||
user: smtpUser,
|
|
||||||
pass: smtpPassword,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const transporter = nodemailer.createTransport(transportConfig);
|
|
||||||
|
|
||||||
// Envoi de l'email
|
|
||||||
await transporter.sendMail({
|
|
||||||
from: `"${emailFromName}" <${emailFromAddress}>`,
|
from: `"${emailFromName}" <${emailFromAddress}>`,
|
||||||
to,
|
to,
|
||||||
subject,
|
subject,
|
||||||
text: text || html.replace(/<[^>]*>?/gm, ''), // Fallback texte simple
|
text: text || html.replace(/<[^>]*>?/gm, ''),
|
||||||
html,
|
html,
|
||||||
});
|
};
|
||||||
|
|
||||||
|
let lastError: unknown;
|
||||||
|
|
||||||
|
for (let attempt = 1; attempt <= this.smtpMaxAttempts; attempt++) {
|
||||||
|
try {
|
||||||
|
const transporter = await this.getTransporter();
|
||||||
|
await transporter.sendMail(mailOptions);
|
||||||
this.logger.log(`📧 Email envoyé à ${to} : ${subject}`);
|
this.logger.log(`📧 Email envoyé à ${to} : ${subject}`);
|
||||||
|
return;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
lastError = error;
|
||||||
|
const canRetry = attempt < this.smtpMaxAttempts && isTransientSmtpError(error);
|
||||||
|
|
||||||
|
if (canRetry) {
|
||||||
|
const delayMs = this.smtpRetryBaseDelayMs * 2 ** (attempt - 1);
|
||||||
|
this.logger.warn(
|
||||||
|
`SMTP temporairement indisponible pour ${to} (tentative ${attempt}/${this.smtpMaxAttempts}), nouvel essai dans ${delayMs}ms`,
|
||||||
|
error instanceof Error ? error.message : error,
|
||||||
|
);
|
||||||
|
this.resetTransporter();
|
||||||
|
await this.sleep(delayMs);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
this.logger.error(`❌ Erreur lors de l'envoi de l'email à ${to}`, error);
|
this.logger.error(`❌ Erreur lors de l'envoi de l'email à ${to}`, error);
|
||||||
|
this.resetTransporter();
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.logger.error(`❌ Erreur lors de l'envoi de l'email à ${to}`, lastError);
|
||||||
|
this.resetTransporter();
|
||||||
|
throw lastError;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Envoi de l'email de bienvenue pour un gestionnaire
|
* Envoi de l'email de bienvenue pour un gestionnaire
|
||||||
* @param to Email du gestionnaire
|
* @param to Email du gestionnaire
|
||||||
@@ -202,6 +301,43 @@ export class MailService {
|
|||||||
await this.sendEmail(to, subject, html);
|
await this.sendEmail(to, subject, html);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Accusé de resoumission après refus (reprise #112) : dossier à nouveau en attente de validation.
|
||||||
|
*/
|
||||||
|
async sendResoumissionPendingEmail(
|
||||||
|
to: string,
|
||||||
|
prenom: string,
|
||||||
|
nom: string,
|
||||||
|
numeroDossier: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const appName = this.configService.get<string>('app_name', "P'titsPas");
|
||||||
|
const appUrl = this.configService.get<string>('app_url', 'https://app.ptits-pas.fr');
|
||||||
|
|
||||||
|
const safe = (s: string) =>
|
||||||
|
(s || '')
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"');
|
||||||
|
|
||||||
|
const subject = `Votre dossier a été resoumis — ${safe(numeroDossier)}`;
|
||||||
|
const html = `
|
||||||
|
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
||||||
|
<h2 style="color: #4CAF50;">Bonjour ${safe(prenom)} ${safe(nom)},</h2>
|
||||||
|
<p>Nous avons bien reçu la <strong>resoumission</strong> de votre dossier sur <strong>${safe(appName)}</strong>.</p>
|
||||||
|
<p><strong>Numéro de dossier :</strong> ${safe(numeroDossier)}</p>
|
||||||
|
<p>Votre dossier est de nouveau <strong>en attente de validation</strong> par notre équipe. Vous recevrez un email lorsqu'il aura été traité.</p>
|
||||||
|
<div style="text-align: center; margin: 30px 0;">
|
||||||
|
<a href="${appUrl}" style="background-color: #4CAF50; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; font-weight: bold;">Accéder au site</a>
|
||||||
|
</div>
|
||||||
|
<hr style="border: 1px solid #eee; margin: 20px 0;">
|
||||||
|
<p style="color: #666; font-size: 12px;">Cet email a été envoyé automatiquement. Merci de ne pas y répondre.</p>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
await this.sendEmail(to, subject, html);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Email de refus de dossier avec lien reprise (token).
|
* Email de refus de dossier avec lien reprise (token).
|
||||||
* Ticket #110 – Refus sans suppression
|
* Ticket #110 – Refus sans suppression
|
||||||
@@ -214,21 +350,29 @@ export class MailService {
|
|||||||
token: string,
|
token: string,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const appName = this.configService.get<string>('app_name', "P'titsPas");
|
const appName = this.configService.get<string>('app_name', "P'titsPas");
|
||||||
const appUrl = this.configService.get<string>('app_url', 'https://app.ptits-pas.fr');
|
const appUrl = (this.configService.get<string>('app_url', 'https://app.ptits-pas.fr') || '').replace(/\/+$/, '');
|
||||||
const repriseLink = `${appUrl}/reprise?token=${encodeURIComponent(token)}`;
|
const repriseLink = `${appUrl}/reprise?token=${encodeURIComponent(token)}`;
|
||||||
|
|
||||||
|
const safe = (s: string) =>
|
||||||
|
(s || '')
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"');
|
||||||
|
|
||||||
const subject = `Votre dossier – compléments demandés`;
|
const subject = `Votre dossier – compléments demandés`;
|
||||||
const commentBlock = comment
|
const commentText = safe(comment || 'Le gestionnaire vous demande de compléter votre dossier avant une nouvelle validation.');
|
||||||
? `<p><strong>Message du gestionnaire :</strong></p><p>${comment.replace(/</g, '<').replace(/>/g, '>')}</p>`
|
|
||||||
: '';
|
|
||||||
const html = `
|
const html = `
|
||||||
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
||||||
<h2 style="color: #333;">Bonjour ${prenom} ${nom},</h2>
|
<h2 style="color: #4CAF50;">Bonjour ${safe(prenom)} ${safe(nom)},</h2>
|
||||||
<p>Votre dossier d'inscription sur <strong>${appName}</strong> n'a pas pu être validé en l'état.</p>
|
<p>Votre dossier d'inscription sur <strong>${safe(appName)}</strong> n'a pas pu être validé en l'état.</p>
|
||||||
${commentBlock}
|
<div style="background-color: #F4FBF5; border-left: 4px solid #4CAF50; padding: 12px 16px; margin: 20px 0;">
|
||||||
|
<p style="margin: 0 0 8px 0;"><strong>Message du gestionnaire :</strong></p>
|
||||||
|
<p style="margin: 0;">${commentText}</p>
|
||||||
|
</div>
|
||||||
<p>Vous pouvez corriger les éléments indiqués et soumettre à nouveau votre dossier en cliquant sur le lien ci-dessous.</p>
|
<p>Vous pouvez corriger les éléments indiqués et soumettre à nouveau votre dossier en cliquant sur le lien ci-dessous.</p>
|
||||||
<div style="text-align: center; margin: 30px 0;">
|
<div style="text-align: center; margin: 30px 0;">
|
||||||
<a href="${repriseLink}" style="background-color: #2196F3; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; font-weight: bold;">Reprendre mon dossier</a>
|
<a href="${repriseLink}" style="background-color: #4CAF50; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; font-weight: bold;">Reprendre mon dossier</a>
|
||||||
</div>
|
</div>
|
||||||
<p style="color: #666; font-size: 12px;">Ce lien est valable 7 jours. Si vous n'avez pas demandé cette reprise, vous pouvez ignorer cet email.</p>
|
<p style="color: #666; font-size: 12px;">Ce lien est valable 7 jours. Si vous n'avez pas demandé cette reprise, vous pouvez ignorer cet email.</p>
|
||||||
<hr style="border: 1px solid #eee; margin: 20px 0;">
|
<hr style="border: 1px solid #eee; margin: 20px 0;">
|
||||||
@@ -238,4 +382,31 @@ export class MailService {
|
|||||||
|
|
||||||
await this.sendEmail(to, subject, html);
|
await this.sendEmail(to, subject, html);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ticket #127 — lien application `/reset-password?token=` (pas create-password).
|
||||||
|
*/
|
||||||
|
async sendPasswordResetEmail(recipient: {
|
||||||
|
email: string;
|
||||||
|
prenom: string;
|
||||||
|
nom: string;
|
||||||
|
token: string;
|
||||||
|
}): Promise<void> {
|
||||||
|
const appName = this.configService.get<string>('app_name', "P'titsPas");
|
||||||
|
const appUrl = (this.configService.get<string>('app_url', 'https://app.ptits-pas.fr') || '').replace(/\/+$/, '');
|
||||||
|
const resetPasswordUrl = `${appUrl}/reset-password?token=${encodeURIComponent(recipient.token)}`;
|
||||||
|
|
||||||
|
const filePath = join(__dirname, 'templates', 'password-reset.hbs');
|
||||||
|
const source = readFileSync(filePath, 'utf8');
|
||||||
|
const compiled = Handlebars.compile(source);
|
||||||
|
const html = compiled({
|
||||||
|
prenom: recipient.prenom || '',
|
||||||
|
nom: recipient.nom || '',
|
||||||
|
appName,
|
||||||
|
resetPasswordUrl,
|
||||||
|
}) as string;
|
||||||
|
|
||||||
|
const subject = `${appName} — Réinitialisation de votre mot de passe`;
|
||||||
|
await this.sendEmail(recipient.email, subject, html);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
||||||
|
<h2 style="color: #4CAF50;">Bonjour {{prenom}} {{nom}},</h2>
|
||||||
|
<p>Vous avez demandé à <strong>réinitialiser votre mot de passe</strong> sur <strong>{{appName}}</strong>.</p>
|
||||||
|
<p>Cliquez sur le bouton ci-dessous pour en choisir un nouveau. Ce lien est valable une durée limitée.</p>
|
||||||
|
<div style="text-align: center; margin: 30px 0;">
|
||||||
|
<a href="{{{resetPasswordUrl}}}" style="background-color: #4CAF50; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; font-weight: bold;">Réinitialiser mon mot de passe</a>
|
||||||
|
</div>
|
||||||
|
<p style="color: #666; font-size: 13px;">Si le bouton ne fonctionne pas, copiez ce lien dans votre navigateur :<br /><span style="word-break: break-all;">{{{resetPasswordUrl}}}</span></p>
|
||||||
|
<p style="color: #666; font-size: 12px;">Si vous n'êtes pas à l'origine de cette demande, vous pouvez ignorer cet e-mail.</p>
|
||||||
|
<hr style="border: 1px solid #eee; margin: 20px 0;" />
|
||||||
|
<p style="color: #666; font-size: 12px;">Cet email a été envoyé automatiquement par {{appName}}. Merci de ne pas y répondre.</p>
|
||||||
|
</div>
|
||||||
+79
-2
@@ -1,20 +1,97 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { AssistantesMaternellesController } from './assistantes_maternelles.controller';
|
import { AssistantesMaternellesController } from './assistantes_maternelles.controller';
|
||||||
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
||||||
|
import { AuthService } from '../auth/auth.service';
|
||||||
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
|
||||||
describe('AssistantesMaternellesController', () => {
|
describe('AssistantesMaternellesController', () => {
|
||||||
let controller: AssistantesMaternellesController;
|
let controller: AssistantesMaternellesController;
|
||||||
|
const authServiceMock = {
|
||||||
|
createAmDossierStaff: jest.fn(),
|
||||||
|
};
|
||||||
|
const amServiceMock = {
|
||||||
|
listerCouplesGarde: jest.fn(),
|
||||||
|
definirCoupleGardeCourant: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
controllers: [AssistantesMaternellesController],
|
controllers: [AssistantesMaternellesController],
|
||||||
providers: [AssistantesMaternellesService],
|
providers: [
|
||||||
}).compile();
|
{ provide: AssistantesMaternellesService, useValue: amServiceMock },
|
||||||
|
{ provide: AuthService, useValue: authServiceMock },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.overrideGuard(AuthGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.overrideGuard(RolesGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.compile();
|
||||||
|
|
||||||
controller = module.get<AssistantesMaternellesController>(AssistantesMaternellesController);
|
controller = module.get<AssistantesMaternellesController>(AssistantesMaternellesController);
|
||||||
|
jest.clearAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('should be defined', () => {
|
||||||
expect(controller).toBeDefined();
|
expect(controller).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('createDossier delegates to authService.createAmDossierStaff with CGU accepted', async () => {
|
||||||
|
authServiceMock.createAmDossierStaff.mockResolvedValue({
|
||||||
|
message: 'ok',
|
||||||
|
user_id: 'u1',
|
||||||
|
statut: 'actif',
|
||||||
|
numero_dossier: '2026-000001',
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = {
|
||||||
|
email: 'am.staff@test.fr',
|
||||||
|
prenom: 'Marie',
|
||||||
|
nom: 'TEST',
|
||||||
|
telephone: '0689567890',
|
||||||
|
consentement_photo: false,
|
||||||
|
lieu_naissance_ville: 'Paris',
|
||||||
|
lieu_naissance_pays: 'France',
|
||||||
|
nir: '285017512345678',
|
||||||
|
numero_agrement: 'AGR-TEST-001',
|
||||||
|
capacite_accueil: 3,
|
||||||
|
places_disponibles: 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
const res = await controller.createDossier(body as any);
|
||||||
|
expect(authServiceMock.createAmDossierStaff).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
email: body.email,
|
||||||
|
acceptation_cgu: true,
|
||||||
|
acceptation_privacy: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(res.numero_dossier).toBe('2026-000001');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('listerCouplesGarde délègue au service (#171)', async () => {
|
||||||
|
amServiceMock.listerCouplesGarde.mockResolvedValue({
|
||||||
|
couples: [],
|
||||||
|
couple_courant_id: null,
|
||||||
|
});
|
||||||
|
const res = await controller.listerCouplesGarde('am-uuid');
|
||||||
|
expect(amServiceMock.listerCouplesGarde).toHaveBeenCalledWith('am-uuid');
|
||||||
|
expect(res.couple_courant_id).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('definirCoupleGardeCourant délègue au service (#171)', async () => {
|
||||||
|
amServiceMock.definirCoupleGardeCourant.mockResolvedValue({
|
||||||
|
couples: [{ id: 'pl-1', courant: true }],
|
||||||
|
couple_courant_id: 'pl-1',
|
||||||
|
});
|
||||||
|
const res = await controller.definirCoupleGardeCourant('am-uuid', {
|
||||||
|
couple_id: 'pl-1',
|
||||||
|
});
|
||||||
|
expect(amServiceMock.definirCoupleGardeCourant).toHaveBeenCalledWith(
|
||||||
|
'am-uuid',
|
||||||
|
'pl-1',
|
||||||
|
);
|
||||||
|
expect(res.couple_courant_id).toBe('pl-1');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,28 +2,68 @@ import {
|
|||||||
Controller,
|
Controller,
|
||||||
Get,
|
Get,
|
||||||
Post,
|
Post,
|
||||||
|
Put,
|
||||||
Body,
|
Body,
|
||||||
Patch,
|
Patch,
|
||||||
Param,
|
Param,
|
||||||
Delete,
|
Delete,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
||||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||||
import { RoleType } from 'src/entities/users.entity';
|
import { RoleType, Users } from 'src/entities/users.entity';
|
||||||
import { CreateAssistanteDto } from '../user/dto/create_assistante.dto';
|
import { CreateAssistanteDto } from '../user/dto/create_assistante.dto';
|
||||||
import { UpdateAssistanteDto } from '../user/dto/update_assistante.dto';
|
import { UpdateAssistanteDto } from '../user/dto/update_assistante.dto';
|
||||||
|
import { UpdateAmFicheAdminDto } from './dto/update-am-fiche-admin.dto';
|
||||||
|
import { StaffCreateAmDossierDto } from './dto/staff-create-am-dossier.dto';
|
||||||
|
import { StaffCreateAmDossierResponseDto } from './dto/staff-create-am-dossier-response.dto';
|
||||||
|
import { CouplesGardeAmResponseDto } from './dto/couples-garde-am.dto';
|
||||||
|
import { DefinirCoupleGardeCourantAmDto } from './dto/definir-couple-garde-courant-am.dto';
|
||||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
|
import { User } from 'src/common/decorators/user.decorator';
|
||||||
|
import { mapAmForApi, mapAmsForApi } from './assistantes_maternelles.mapper';
|
||||||
|
import { AuthService } from '../auth/auth.service';
|
||||||
|
import { RegisterAMCompletDto } from '../auth/dto/register-am-complet.dto';
|
||||||
|
|
||||||
@ApiTags("Assistantes Maternelles")
|
@ApiTags("Assistantes Maternelles")
|
||||||
@ApiBearerAuth('access-token')
|
@ApiBearerAuth('access-token')
|
||||||
@UseGuards(AuthGuard, RolesGuard)
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
@Controller('assistantes-maternelles')
|
@Controller('assistantes-maternelles')
|
||||||
export class AssistantesMaternellesController {
|
export class AssistantesMaternellesController {
|
||||||
constructor(private readonly assistantesMaternellesService: AssistantesMaternellesService) { }
|
constructor(
|
||||||
|
private readonly assistantesMaternellesService: AssistantesMaternellesService,
|
||||||
|
private readonly authService: AuthService,
|
||||||
|
) { }
|
||||||
|
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
|
@Post('dossier')
|
||||||
|
@HttpCode(HttpStatus.CREATED)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Créer un dossier AM complet (staff) — ticket #156',
|
||||||
|
description:
|
||||||
|
'Crée user + fiche AM avec statut actif, n° dossier, et envoie l’e-mail de création de mot de passe. ' +
|
||||||
|
'Ne pas utiliser POST /auth/register/am depuis le dashboard.',
|
||||||
|
})
|
||||||
|
@ApiBody({ type: StaffCreateAmDossierDto })
|
||||||
|
@ApiResponse({ status: 201, type: StaffCreateAmDossierResponseDto })
|
||||||
|
@ApiResponse({ status: 400, description: 'Validation métier / NIR' })
|
||||||
|
@ApiResponse({ status: 403, description: 'Rôle non autorisé' })
|
||||||
|
@ApiResponse({ status: 409, description: 'Email / NIR / agrément déjà pris' })
|
||||||
|
async createDossier(
|
||||||
|
@Body() dto: StaffCreateAmDossierDto,
|
||||||
|
): Promise<StaffCreateAmDossierResponseDto> {
|
||||||
|
const registerDto = {
|
||||||
|
...dto,
|
||||||
|
acceptation_cgu: true,
|
||||||
|
acceptation_privacy: true,
|
||||||
|
} as RegisterAMCompletDto;
|
||||||
|
return this.authService.createAmDossierStaff(registerDto);
|
||||||
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||||
@ApiOperation({ summary: 'Créer nounou' })
|
@ApiOperation({ summary: 'Créer nounou' })
|
||||||
@@ -31,28 +71,104 @@ export class AssistantesMaternellesController {
|
|||||||
@ApiResponse({ status: 403, description: 'Accès refusé : Réservé aux super_admins et gestionnaires' })
|
@ApiResponse({ status: 403, description: 'Accès refusé : Réservé aux super_admins et gestionnaires' })
|
||||||
@ApiBody({ type: CreateAssistanteDto })
|
@ApiBody({ type: CreateAssistanteDto })
|
||||||
@Post()
|
@Post()
|
||||||
create(@Body() dto: CreateAssistanteDto): Promise<AssistanteMaternelle> {
|
async create(@Body() dto: CreateAssistanteDto): Promise<AssistanteMaternelle> {
|
||||||
return this.assistantesMaternellesService.create(dto);
|
const am = await this.assistantesMaternellesService.create(dto);
|
||||||
|
return mapAmForApi(am);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
@Get()
|
@Get()
|
||||||
@ApiOperation({ summary: 'Récupérer la liste des nounous' })
|
@ApiOperation({ summary: 'Récupérer la liste des nounous (inclut amChildren actifs) — ticket #131' })
|
||||||
@ApiResponse({ status: 200, description: 'Liste des nounous' })
|
@ApiResponse({ status: 200, description: 'Liste des nounous' })
|
||||||
@ApiResponse({ status: 403, description: 'Accès refusé : Réservé aux super_admins et gestionnaires' })
|
@ApiResponse({ status: 403, description: 'Accès refusé : Réservé aux super_admins et gestionnaires' })
|
||||||
getAll(): Promise<AssistanteMaternelle[]> {
|
async getAll(): Promise<AssistanteMaternelle[]> {
|
||||||
return this.assistantesMaternellesService.findAll();
|
const ams = await this.assistantesMaternellesService.findAll();
|
||||||
|
return mapAmsForApi(ams);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
@Get('me/couples-garde')
|
||||||
|
@Roles(RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Couples de garde de l’AM connectée — ticket #171',
|
||||||
|
description:
|
||||||
|
'Placements actifs (enfant + parents) pour peupler le bandeau couple TdB AM, ' +
|
||||||
|
'avec indication du couple courant.',
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: 200, type: CouplesGardeAmResponseDto })
|
||||||
|
listerCouplesGarde(
|
||||||
|
@User('id') userId: string,
|
||||||
|
): Promise<CouplesGardeAmResponseDto> {
|
||||||
|
return this.assistantesMaternellesService.listerCouplesGarde(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('me/couples-garde/courant')
|
||||||
|
@Roles(RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiOperation({ summary: 'Définir le couple de garde courant (AM) — ticket #171' })
|
||||||
|
@ApiBody({ type: DefinirCoupleGardeCourantAmDto })
|
||||||
|
@ApiResponse({ status: 200, type: CouplesGardeAmResponseDto })
|
||||||
|
definirCoupleGardeCourant(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@Body() dto: DefinirCoupleGardeCourantAmDto,
|
||||||
|
): Promise<CouplesGardeAmResponseDto> {
|
||||||
|
return this.assistantesMaternellesService.definirCoupleGardeCourant(
|
||||||
|
userId,
|
||||||
|
dto.couple_id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
@Get(':id')
|
@Get(':id')
|
||||||
@ApiParam({ name: 'id', description: "UUID de la nounou" })
|
@ApiParam({ name: 'id', description: "UUID de la nounou" })
|
||||||
@ApiOperation({ summary: 'Récupérer une nounou par id' })
|
@ApiOperation({ summary: 'Récupérer une nounou par id (inclut amChildren) — ticket #131' })
|
||||||
@ApiResponse({ status: 200, description: 'Détails de la nounou' })
|
@ApiResponse({ status: 200, description: 'Détails de la nounou' })
|
||||||
@ApiResponse({ status: 404, description: 'Nounou non trouvée' })
|
@ApiResponse({ status: 404, description: 'Nounou non trouvée' })
|
||||||
@ApiResponse({ status: 403, description: 'Accès refusé : Réservé aux super_admins et gestionnaires' })
|
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||||
getOne(@Param('id') user_id: string): Promise<AssistanteMaternelle> {
|
async getOne(@Param('id') user_id: string): Promise<AssistanteMaternelle> {
|
||||||
return this.assistantesMaternellesService.findOne(user_id);
|
const am = await this.assistantesMaternellesService.findOne(user_id);
|
||||||
|
return mapAmForApi(am);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
|
@Patch(':id/fiche')
|
||||||
|
@ApiBody({ type: UpdateAmFicheAdminDto })
|
||||||
|
@ApiOperation({ summary: 'Mettre à jour la fiche AM (identité + pro) — ticket #131' })
|
||||||
|
@ApiParam({ name: 'id', description: "UUID utilisateur de l'AM" })
|
||||||
|
@ApiResponse({ status: 200, description: 'Fiche AM mise à jour' })
|
||||||
|
async updateFicheAdmin(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() dto: UpdateAmFicheAdminDto,
|
||||||
|
): Promise<AssistanteMaternelle> {
|
||||||
|
const am = await this.assistantesMaternellesService.updateFicheAdmin(id, dto);
|
||||||
|
return mapAmForApi(am);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
|
@Post(':id/enfants/:enfantId')
|
||||||
|
@ApiOperation({ summary: 'Rattacher un enfant à une AM (statut enfant → garde) — ticket #131' })
|
||||||
|
@ApiParam({ name: 'id', description: "UUID utilisateur de l'AM" })
|
||||||
|
@ApiParam({ name: 'enfantId', description: "UUID de l'enfant" })
|
||||||
|
@ApiResponse({ status: 200, description: 'AM avec enfants mis à jour' })
|
||||||
|
async attachEnfant(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Param('enfantId') enfantId: string,
|
||||||
|
@User() currentUser: Users,
|
||||||
|
): Promise<AssistanteMaternelle> {
|
||||||
|
const am = await this.assistantesMaternellesService.attachEnfant(id, enfantId, currentUser);
|
||||||
|
return mapAmForApi(am);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
|
@Delete(':id/enfants/:enfantId')
|
||||||
|
@ApiOperation({ summary: "Clôturer le placement d'un enfant chez une AM — ticket #131" })
|
||||||
|
@ApiParam({ name: 'id', description: "UUID utilisateur de l'AM" })
|
||||||
|
@ApiParam({ name: 'enfantId', description: "UUID de l'enfant" })
|
||||||
|
@ApiResponse({ status: 200, description: 'AM avec enfants mis à jour' })
|
||||||
|
async detachEnfant(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Param('enfantId') enfantId: string,
|
||||||
|
): Promise<AssistanteMaternelle> {
|
||||||
|
const am = await this.assistantesMaternellesService.detachEnfant(id, enfantId);
|
||||||
|
return mapAmForApi(am);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||||
@@ -63,14 +179,15 @@ export class AssistantesMaternellesController {
|
|||||||
@ApiResponse({ status: 404, description: 'Nounou non trouvée' })
|
@ApiResponse({ status: 404, description: 'Nounou non trouvée' })
|
||||||
@ApiParam({ name: 'id', description: "UUID de la nounou" })
|
@ApiParam({ name: 'id', description: "UUID de la nounou" })
|
||||||
@Patch(':id')
|
@Patch(':id')
|
||||||
update(@Param('id') id: string, @Body() dto: UpdateAssistanteDto): Promise<AssistanteMaternelle> {
|
async update(@Param('id') id: string, @Body() dto: UpdateAssistanteDto): Promise<AssistanteMaternelle> {
|
||||||
return this.assistantesMaternellesService.update(id, dto);
|
const am = await this.assistantesMaternellesService.update(id, dto);
|
||||||
|
return mapAmForApi(am);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
@ApiOperation({ summary: 'Supprimer une nounou' })
|
@ApiOperation({ summary: 'Supprimer une nounou' })
|
||||||
@ApiResponse({ status: 200, description: 'Nounou supprimée avec succès' })
|
@ApiResponse({ status: 200, description: 'Nounou supprimée avec succès' })
|
||||||
@ApiResponse({ status: 403, description: 'Accès refusé : Réservé aux super_admins, gestionnaires et administrateurs' })
|
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||||
@ApiResponse({ status: 404, description: 'Nounou non trouvée' })
|
@ApiResponse({ status: 404, description: 'Nounou non trouvée' })
|
||||||
@ApiParam({ name: 'id', description: "UUID de la nounou" })
|
@ApiParam({ name: 'id', description: "UUID de la nounou" })
|
||||||
@Delete(':id')
|
@Delete(':id')
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { sanitizeUserForApi } from '../../common/utils/sanitize-user-for-api';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sérialisation API fiche AM — ticket #131.
|
||||||
|
* Expose `amChildren` actifs (date_fin null) avec enfant imbriqué, sans secrets user.
|
||||||
|
*/
|
||||||
|
export function mapAmForApi(am: AssistanteMaternelle): AssistanteMaternelle {
|
||||||
|
const activeChildren = (am.amChildren ?? []).filter((link) => !link.date_fin);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...am,
|
||||||
|
user: sanitizeUserForApi(am.user)!,
|
||||||
|
amChildren: activeChildren.map((link) => ({
|
||||||
|
...link,
|
||||||
|
child: link.child,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapAmsForApi(ams: AssistanteMaternelle[]): AssistanteMaternelle[] {
|
||||||
|
return ams.map(mapAmForApi);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function filterActiveAmChildren(links: AmChildren[] | undefined): AmChildren[] {
|
||||||
|
return (links ?? []).filter((link) => !link.date_fin);
|
||||||
|
}
|
||||||
@@ -2,13 +2,23 @@ import { Module } from '@nestjs/common';
|
|||||||
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
||||||
import { AssistantesMaternellesController } from './assistantes_maternelles.controller';
|
import { AssistantesMaternellesController } from './assistantes_maternelles.controller';
|
||||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { Children } from 'src/entities/children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { Users } from 'src/entities/users.entity';
|
import { Users } from 'src/entities/users.entity';
|
||||||
import { AuthModule } from '../auth/auth.module';
|
import { AuthModule } from '../auth/auth.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([AssistanteMaternelle, Users]),
|
imports: [
|
||||||
AuthModule
|
TypeOrmModule.forFeature([
|
||||||
|
AssistanteMaternelle,
|
||||||
|
AmChildren,
|
||||||
|
Children,
|
||||||
|
Users,
|
||||||
|
ParentsChildren,
|
||||||
|
]),
|
||||||
|
AuthModule,
|
||||||
],
|
],
|
||||||
controllers: [AssistantesMaternellesController],
|
controllers: [AssistantesMaternellesController],
|
||||||
providers: [AssistantesMaternellesService],
|
providers: [AssistantesMaternellesService],
|
||||||
|
|||||||
+138
-6
@@ -1,18 +1,150 @@
|
|||||||
|
import { NotFoundException } from '@nestjs/common';
|
||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
||||||
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
|
import { Users } from 'src/entities/users.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { Children } from 'src/entities/children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
|
||||||
describe('AssistantesMaternellesService', () => {
|
describe('AssistantesMaternellesService — couples de garde (#171)', () => {
|
||||||
let service: AssistantesMaternellesService;
|
let service: AssistantesMaternellesService;
|
||||||
|
|
||||||
beforeEach(async () => {
|
const amRepo = { findOne: jest.fn(), update: jest.fn() };
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const usersRepo = {};
|
||||||
providers: [AssistantesMaternellesService],
|
const amChildrenRepo = { find: jest.fn(), findOne: jest.fn() };
|
||||||
}).compile();
|
const childrenRepo = {};
|
||||||
|
const parentsChildrenRepo = { find: jest.fn() };
|
||||||
|
|
||||||
service = module.get<AssistantesMaternellesService>(AssistantesMaternellesService);
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
AssistantesMaternellesService,
|
||||||
|
{ provide: getRepositoryToken(AssistanteMaternelle), useValue: amRepo },
|
||||||
|
{ provide: getRepositoryToken(Users), useValue: usersRepo },
|
||||||
|
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo },
|
||||||
|
{ provide: getRepositoryToken(Children), useValue: childrenRepo },
|
||||||
|
{
|
||||||
|
provide: getRepositoryToken(ParentsChildren),
|
||||||
|
useValue: parentsChildrenRepo,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
service = module.get(AssistantesMaternellesService);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('should be defined', () => {
|
||||||
expect(service).toBeDefined();
|
expect(service).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('listerCouplesGarde', () => {
|
||||||
|
it('retourne vide si aucun placement', async () => {
|
||||||
|
amRepo.findOne.mockResolvedValue({
|
||||||
|
user_id: 'am-1',
|
||||||
|
id_placement_garde_courant: null,
|
||||||
|
});
|
||||||
|
amChildrenRepo.find.mockResolvedValue([]);
|
||||||
|
const res = await service.listerCouplesGarde('am-1');
|
||||||
|
expect(res).toEqual({ couples: [], couple_courant_id: null });
|
||||||
|
expect(parentsChildrenRepo.find).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('mappe placements + parents et marque le courant', async () => {
|
||||||
|
amRepo.findOne.mockResolvedValue({
|
||||||
|
user_id: 'am-1',
|
||||||
|
id_placement_garde_courant: 'pl-2',
|
||||||
|
});
|
||||||
|
amChildrenRepo.find.mockResolvedValue([
|
||||||
|
{
|
||||||
|
id: 'pl-1',
|
||||||
|
enfantId: 'e1',
|
||||||
|
child: { id: 'e1', first_name: 'Léa', last_name: 'M', photo_url: null },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'pl-2',
|
||||||
|
enfantId: 'e2',
|
||||||
|
child: { id: 'e2', first_name: 'Emma', last_name: 'M', photo_url: null },
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
parentsChildrenRepo.find.mockResolvedValue([
|
||||||
|
{
|
||||||
|
parentId: 'p1',
|
||||||
|
enfantId: 'e1',
|
||||||
|
parent: { user: { prenom: 'Claire', nom: 'Martin', photo_url: null } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
parentId: 'p2',
|
||||||
|
enfantId: 'e1',
|
||||||
|
parent: { user: { prenom: 'Thomas', nom: 'Martin', photo_url: null } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
parentId: 'p1',
|
||||||
|
enfantId: 'e2',
|
||||||
|
parent: { user: { prenom: 'Claire', nom: 'Martin', photo_url: null } },
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const res = await service.listerCouplesGarde('am-1');
|
||||||
|
expect(res.couples).toHaveLength(2);
|
||||||
|
expect(res.couple_courant_id).toBe('pl-2');
|
||||||
|
expect(res.couples[1].courant).toBe(true);
|
||||||
|
expect(res.couples[0].parents).toHaveLength(2);
|
||||||
|
expect(res.couples[0].parents[0].prenom).toBe('Claire');
|
||||||
|
expect(res.couples[0].enfant.prenom).toBe('Léa');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('404 si AM inconnue', async () => {
|
||||||
|
amRepo.findOne.mockResolvedValue(null);
|
||||||
|
await expect(service.listerCouplesGarde('x')).rejects.toBeInstanceOf(
|
||||||
|
NotFoundException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('definirCoupleGardeCourant', () => {
|
||||||
|
it('persiste si le placement appartient à l’AM', async () => {
|
||||||
|
amRepo.findOne.mockResolvedValue({
|
||||||
|
user_id: 'am-1',
|
||||||
|
id_placement_garde_courant: null,
|
||||||
|
});
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e1',
|
||||||
|
});
|
||||||
|
amRepo.update.mockResolvedValue({ affected: 1 });
|
||||||
|
amChildrenRepo.find.mockResolvedValue([
|
||||||
|
{
|
||||||
|
id: 'pl-1',
|
||||||
|
enfantId: 'e1',
|
||||||
|
child: { id: 'e1', first_name: 'Léa', last_name: null, photo_url: null },
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
parentsChildrenRepo.find.mockResolvedValue([
|
||||||
|
{
|
||||||
|
parentId: 'p1',
|
||||||
|
enfantId: 'e1',
|
||||||
|
parent: { user: { prenom: 'Claire', nom: 'M', photo_url: null } },
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const res = await service.definirCoupleGardeCourant('am-1', 'pl-1');
|
||||||
|
expect(amRepo.update).toHaveBeenCalledWith(
|
||||||
|
{ user_id: 'am-1' },
|
||||||
|
{ id_placement_garde_courant: 'pl-1' },
|
||||||
|
);
|
||||||
|
expect(res.couple_courant_id).toBe('pl-1');
|
||||||
|
expect(res.couples[0].courant).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('404 si placement d’une autre AM', async () => {
|
||||||
|
amRepo.findOne.mockResolvedValue({ user_id: 'am-1' });
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue(null);
|
||||||
|
await expect(
|
||||||
|
service.definirCoupleGardeCourant('am-1', 'pl-x'),
|
||||||
|
).rejects.toBeInstanceOf(NotFoundException);
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,11 +5,19 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { Repository } from 'typeorm';
|
import { In, IsNull, Repository } from 'typeorm';
|
||||||
import { RoleType, Users } from 'src/entities/users.entity';
|
import { RoleType, Users } from 'src/entities/users.entity';
|
||||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { Children, StatutEnfantType } from 'src/entities/children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
import { CreateAssistanteDto } from '../user/dto/create_assistante.dto';
|
import { CreateAssistanteDto } from '../user/dto/create_assistante.dto';
|
||||||
import { UpdateAssistanteDto } from '../user/dto/update_assistante.dto';
|
import { UpdateAssistanteDto } from '../user/dto/update_assistante.dto';
|
||||||
|
import { UpdateAmFicheAdminDto } from './dto/update-am-fiche-admin.dto';
|
||||||
|
import { CouplesGardeAmResponseDto } from './dto/couples-garde-am.dto';
|
||||||
|
import { validateNir } from 'src/common/utils/nir.util';
|
||||||
|
|
||||||
|
const AM_CHILDREN_RELATIONS = ['user', 'amChildren', 'amChildren.child'] as const;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AssistantesMaternellesService {
|
export class AssistantesMaternellesService {
|
||||||
@@ -17,10 +25,15 @@ export class AssistantesMaternellesService {
|
|||||||
@InjectRepository(AssistanteMaternelle)
|
@InjectRepository(AssistanteMaternelle)
|
||||||
private readonly assistantesMaternelleRepository: Repository<AssistanteMaternelle>,
|
private readonly assistantesMaternelleRepository: Repository<AssistanteMaternelle>,
|
||||||
@InjectRepository(Users)
|
@InjectRepository(Users)
|
||||||
private readonly usersRepository: Repository<Users>
|
private readonly usersRepository: Repository<Users>,
|
||||||
|
@InjectRepository(AmChildren)
|
||||||
|
private readonly amChildrenRepository: Repository<AmChildren>,
|
||||||
|
@InjectRepository(Children)
|
||||||
|
private readonly childrenRepository: Repository<Children>,
|
||||||
|
@InjectRepository(ParentsChildren)
|
||||||
|
private readonly parentsChildrenRepository: Repository<ParentsChildren>,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
// Création d’une assistante maternelle
|
|
||||||
async create(dto: CreateAssistanteDto): Promise<AssistanteMaternelle> {
|
async create(dto: CreateAssistanteDto): Promise<AssistanteMaternelle> {
|
||||||
const user = await this.usersRepository.findOneBy({ id: dto.user_id });
|
const user = await this.usersRepository.findOneBy({ id: dto.user_id });
|
||||||
if (!user) throw new NotFoundException('Utilisateur introuvable');
|
if (!user) throw new NotFoundException('Utilisateur introuvable');
|
||||||
@@ -49,32 +62,313 @@ export class AssistantesMaternellesService {
|
|||||||
return this.assistantesMaternelleRepository.save(entity);
|
return this.assistantesMaternelleRepository.save(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Liste des assistantes maternelles
|
|
||||||
async findAll(): Promise<AssistanteMaternelle[]> {
|
async findAll(): Promise<AssistanteMaternelle[]> {
|
||||||
return this.assistantesMaternelleRepository.find({
|
return this.assistantesMaternelleRepository.find({
|
||||||
relations: ['user'],
|
relations: [...AM_CHILDREN_RELATIONS],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Récupérer une assistante maternelle par user_id
|
|
||||||
async findOne(user_id: string): Promise<AssistanteMaternelle> {
|
async findOne(user_id: string): Promise<AssistanteMaternelle> {
|
||||||
const assistante = await this.assistantesMaternelleRepository.findOne({
|
const assistante = await this.assistantesMaternelleRepository.findOne({
|
||||||
where: { user_id },
|
where: { user_id },
|
||||||
relations: ['user'],
|
relations: [...AM_CHILDREN_RELATIONS],
|
||||||
});
|
});
|
||||||
if (!assistante) throw new NotFoundException('Assistante maternelle introuvable');
|
if (!assistante) throw new NotFoundException('Assistante maternelle introuvable');
|
||||||
return assistante;
|
return assistante;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mise à jour
|
|
||||||
async update(id: string, dto: UpdateAssistanteDto): Promise<AssistanteMaternelle> {
|
async update(id: string, dto: UpdateAssistanteDto): Promise<AssistanteMaternelle> {
|
||||||
await this.assistantesMaternelleRepository.update(id, dto);
|
await this.assistantesMaternelleRepository.update(id, dto);
|
||||||
return this.findOne(id);
|
return this.findOne(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Suppression d’une assistante maternelle
|
/**
|
||||||
|
* Mise à jour fiche AM (identité + champs pro) par admin/gestionnaire. Ticket #131.
|
||||||
|
*/
|
||||||
|
async updateFicheAdmin(amUserId: string, dto: UpdateAmFicheAdminDto): Promise<AssistanteMaternelle> {
|
||||||
|
const am = await this.findOne(amUserId);
|
||||||
|
const user = am.user;
|
||||||
|
|
||||||
|
if (dto.email && dto.email !== user.email) {
|
||||||
|
const existing = await this.usersRepository.findOne({ where: { email: dto.email } });
|
||||||
|
if (existing && existing.id !== user.id) {
|
||||||
|
throw new ConflictException('Cet email est déjà utilisé');
|
||||||
|
}
|
||||||
|
user.email = dto.email;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dto.nom !== undefined) user.nom = dto.nom;
|
||||||
|
if (dto.prenom !== undefined) user.prenom = dto.prenom;
|
||||||
|
if (dto.telephone !== undefined) user.telephone = dto.telephone;
|
||||||
|
if (dto.adresse !== undefined) user.adresse = dto.adresse;
|
||||||
|
if (dto.ville !== undefined) user.ville = dto.ville;
|
||||||
|
if (dto.code_postal !== undefined) user.code_postal = dto.code_postal;
|
||||||
|
if (dto.statut !== undefined) user.statut = dto.statut;
|
||||||
|
if (dto.date_naissance !== undefined) {
|
||||||
|
user.date_naissance = dto.date_naissance ? new Date(dto.date_naissance) : undefined;
|
||||||
|
}
|
||||||
|
if (dto.lieu_naissance_ville !== undefined) {
|
||||||
|
user.lieu_naissance_ville = dto.lieu_naissance_ville || undefined;
|
||||||
|
}
|
||||||
|
if (dto.lieu_naissance_pays !== undefined) {
|
||||||
|
user.lieu_naissance_pays = dto.lieu_naissance_pays || undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.usersRepository.save(user);
|
||||||
|
|
||||||
|
const amPatch: Partial<AssistanteMaternelle> = {};
|
||||||
|
if (dto.approval_number !== undefined) amPatch.approval_number = dto.approval_number;
|
||||||
|
if (dto.residence_city !== undefined) amPatch.residence_city = dto.residence_city;
|
||||||
|
if (dto.max_children !== undefined) amPatch.max_children = dto.max_children;
|
||||||
|
if (dto.places_available !== undefined) amPatch.places_available = dto.places_available;
|
||||||
|
if (dto.biography !== undefined) amPatch.biography = dto.biography;
|
||||||
|
if (dto.available !== undefined) amPatch.available = dto.available;
|
||||||
|
if (dto.agreement_date !== undefined) {
|
||||||
|
amPatch.agreement_date = dto.agreement_date ? new Date(dto.agreement_date) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dto.nir !== undefined) {
|
||||||
|
const nirNormalized = dto.nir.replace(/\s/g, '').toUpperCase();
|
||||||
|
if (nirNormalized) {
|
||||||
|
const dateNaissanceForNir =
|
||||||
|
dto.date_naissance ??
|
||||||
|
(user.date_naissance instanceof Date
|
||||||
|
? user.date_naissance.toISOString().slice(0, 10)
|
||||||
|
: user.date_naissance
|
||||||
|
? String(user.date_naissance).slice(0, 10)
|
||||||
|
: undefined);
|
||||||
|
const nirValidation = validateNir(nirNormalized, {
|
||||||
|
dateNaissance: dateNaissanceForNir,
|
||||||
|
});
|
||||||
|
if (!nirValidation.valid) {
|
||||||
|
throw new BadRequestException(nirValidation.error || 'NIR invalide');
|
||||||
|
}
|
||||||
|
const nirDejaUtilise = await this.assistantesMaternelleRepository.findOne({
|
||||||
|
where: { nir: nirNormalized },
|
||||||
|
});
|
||||||
|
if (nirDejaUtilise && nirDejaUtilise.user_id !== amUserId) {
|
||||||
|
throw new ConflictException(
|
||||||
|
'Un compte assistante maternelle avec ce numéro NIR existe déjà.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
amPatch.nir = nirNormalized;
|
||||||
|
}
|
||||||
|
// NIR vide : ne pas effacer (colonne NOT NULL en BDD) — le front renvoie toujours la clé.
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(amPatch).length > 0) {
|
||||||
|
await this.assistantesMaternelleRepository.update(amUserId, amPatch);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.findOne(amUserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rattacher un enfant à une AM (placement actif). Ticket #131.
|
||||||
|
* Passe le statut enfant à `garde` (sauf a_naitre / scolarise).
|
||||||
|
*/
|
||||||
|
async attachEnfant(amUserId: string, enfantId: string, createdBy?: Users): Promise<AssistanteMaternelle> {
|
||||||
|
const am = await this.findOne(amUserId);
|
||||||
|
|
||||||
|
const existingForAm = await this.amChildrenRepository.findOne({
|
||||||
|
where: { amId: amUserId, enfantId, date_fin: IsNull() },
|
||||||
|
});
|
||||||
|
if (existingForAm) {
|
||||||
|
throw new ConflictException('Cet enfant est déjà rattaché à cette assistante maternelle');
|
||||||
|
}
|
||||||
|
|
||||||
|
const child = await this.childrenRepository.findOne({ where: { id: enfantId } });
|
||||||
|
if (!child) {
|
||||||
|
throw new NotFoundException('Enfant introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const activeForChild = await this.amChildrenRepository.findOne({
|
||||||
|
where: { enfantId, date_fin: IsNull() },
|
||||||
|
});
|
||||||
|
if (activeForChild && activeForChild.amId !== amUserId) {
|
||||||
|
throw new ConflictException(
|
||||||
|
'Cet enfant est déjà en garde chez une autre assistante maternelle',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const activeCount = await this.amChildrenRepository.count({
|
||||||
|
where: { amId: amUserId, date_fin: IsNull() },
|
||||||
|
});
|
||||||
|
if (am.max_children != null && activeCount >= am.max_children) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
`Capacité maximale atteinte (${am.max_children} enfant(s))`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.amChildrenRepository.save(
|
||||||
|
this.amChildrenRepository.create({
|
||||||
|
amId: amUserId,
|
||||||
|
enfantId,
|
||||||
|
date_debut: new Date(),
|
||||||
|
cree_par: createdBy?.id,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.applyGardeStatusOnAttach(child);
|
||||||
|
|
||||||
|
return this.findOne(amUserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clôturer le placement AM ↔ enfant. Ticket #131.
|
||||||
|
* Repasse l'enfant en `sans_garde` s'il n'a plus de placement actif.
|
||||||
|
*/
|
||||||
|
async detachEnfant(amUserId: string, enfantId: string): Promise<AssistanteMaternelle> {
|
||||||
|
await this.findOne(amUserId);
|
||||||
|
|
||||||
|
const link = await this.amChildrenRepository.findOne({
|
||||||
|
where: { amId: amUserId, enfantId, date_fin: IsNull() },
|
||||||
|
relations: ['child'],
|
||||||
|
});
|
||||||
|
if (!link) {
|
||||||
|
throw new NotFoundException('Lien assistante maternelle-enfant introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
link.date_fin = new Date();
|
||||||
|
await this.amChildrenRepository.save(link);
|
||||||
|
|
||||||
|
const remaining = await this.amChildrenRepository.count({
|
||||||
|
where: { enfantId, date_fin: IsNull() },
|
||||||
|
});
|
||||||
|
if (remaining === 0 && link.child) {
|
||||||
|
await this.applySansGardeStatusOnDetach(link.child);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.findOne(amUserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async applyGardeStatusOnAttach(child: Children): Promise<void> {
|
||||||
|
if (
|
||||||
|
child.status === StatutEnfantType.A_NAITRE ||
|
||||||
|
child.status === StatutEnfantType.SCOLARISE
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
child.status = StatutEnfantType.GARDE;
|
||||||
|
await this.childrenRepository.save(child);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async applySansGardeStatusOnDetach(child: Children): Promise<void> {
|
||||||
|
if (
|
||||||
|
child.status === StatutEnfantType.A_NAITRE ||
|
||||||
|
child.status === StatutEnfantType.SCOLARISE
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
child.status = StatutEnfantType.SANS_GARDE;
|
||||||
|
await this.childrenRepository.save(child);
|
||||||
|
}
|
||||||
|
|
||||||
async remove(id: string): Promise<{ message: string }> {
|
async remove(id: string): Promise<{ message: string }> {
|
||||||
await this.assistantesMaternelleRepository.delete(id);
|
await this.assistantesMaternelleRepository.delete(id);
|
||||||
return { message: 'Assistante maternelle supprimée' };
|
return { message: 'Assistante maternelle supprimée' };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Liste les couples de garde (enfant ↔ parents) de l’AM connectée — ticket #171.
|
||||||
|
* Un couple = un placement actif dans enfants_assistantes_maternelles pour cette AM.
|
||||||
|
*/
|
||||||
|
async listerCouplesGarde(amUserId: string): Promise<CouplesGardeAmResponseDto> {
|
||||||
|
const am = await this.assistantesMaternelleRepository.findOne({
|
||||||
|
where: { user_id: amUserId },
|
||||||
|
});
|
||||||
|
if (!am) {
|
||||||
|
throw new NotFoundException('Assistante maternelle introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const placements = await this.amChildrenRepository.find({
|
||||||
|
where: { amId: amUserId, date_fin: IsNull() },
|
||||||
|
relations: ['child'],
|
||||||
|
order: { date_debut: 'ASC' },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (placements.length === 0) {
|
||||||
|
return { couples: [], couple_courant_id: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const enfantIds = placements.map((p) => p.enfantId);
|
||||||
|
const liens = await this.parentsChildrenRepository.find({
|
||||||
|
where: { enfantId: In(enfantIds) },
|
||||||
|
relations: ['parent', 'parent.user'],
|
||||||
|
});
|
||||||
|
const parentsByEnfant = new Map<
|
||||||
|
string,
|
||||||
|
{ id: string; prenom: string | null; nom: string | null; photo_url: string | null }[]
|
||||||
|
>();
|
||||||
|
for (const l of liens) {
|
||||||
|
const list = parentsByEnfant.get(l.enfantId) ?? [];
|
||||||
|
const u = l.parent?.user;
|
||||||
|
list.push({
|
||||||
|
id: l.parentId,
|
||||||
|
prenom: u?.prenom ?? null,
|
||||||
|
nom: u?.nom ?? null,
|
||||||
|
photo_url: u?.photo_url ?? null,
|
||||||
|
});
|
||||||
|
parentsByEnfant.set(l.enfantId, list);
|
||||||
|
}
|
||||||
|
|
||||||
|
let idCourant = am.id_placement_garde_courant ?? null;
|
||||||
|
const idsValides = new Set(placements.map((p) => p.id));
|
||||||
|
if (idCourant && !idsValides.has(idCourant)) {
|
||||||
|
idCourant = null;
|
||||||
|
await this.assistantesMaternelleRepository.update(
|
||||||
|
{ user_id: amUserId },
|
||||||
|
{ id_placement_garde_courant: () => 'NULL' },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!idCourant && placements.length === 1) {
|
||||||
|
idCourant = placements[0].id;
|
||||||
|
}
|
||||||
|
|
||||||
|
const couples = placements.map((p) => ({
|
||||||
|
id: p.id,
|
||||||
|
enfant: {
|
||||||
|
id: p.child.id,
|
||||||
|
prenom: p.child.first_name ?? null,
|
||||||
|
nom: p.child.last_name ?? null,
|
||||||
|
photo_url: p.child.photo_url ?? null,
|
||||||
|
},
|
||||||
|
parents: parentsByEnfant.get(p.enfantId) ?? [],
|
||||||
|
courant: idCourant != null && p.id === idCourant,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
couples,
|
||||||
|
couple_courant_id: idCourant,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persiste le couple de garde actif pour l’AM — ticket #171.
|
||||||
|
*/
|
||||||
|
async definirCoupleGardeCourant(
|
||||||
|
amUserId: string,
|
||||||
|
coupleId: string,
|
||||||
|
): Promise<CouplesGardeAmResponseDto> {
|
||||||
|
const am = await this.assistantesMaternelleRepository.findOne({
|
||||||
|
where: { user_id: amUserId },
|
||||||
|
});
|
||||||
|
if (!am) {
|
||||||
|
throw new NotFoundException('Assistante maternelle introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const placement = await this.amChildrenRepository.findOne({
|
||||||
|
where: { id: coupleId, amId: amUserId, date_fin: IsNull() },
|
||||||
|
});
|
||||||
|
if (!placement) {
|
||||||
|
throw new NotFoundException('Couple de garde introuvable ou inactif pour cette AM');
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.assistantesMaternelleRepository.update(
|
||||||
|
{ user_id: amUserId },
|
||||||
|
{ id_placement_garde_courant: coupleId },
|
||||||
|
);
|
||||||
|
|
||||||
|
return this.listerCouplesGarde(amUserId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
/** Identité minimale enfant — ticket #171 (miroir #168) */
|
||||||
|
export class CoupleGardeAmEnfantDto {
|
||||||
|
@ApiProperty({ format: 'uuid' })
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
prenom?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
nom?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
photo_url?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Identité minimale parent pour bandeau AM — ticket #171 */
|
||||||
|
export class CoupleGardeAmParentDto {
|
||||||
|
@ApiProperty({ format: 'uuid', description: 'UUID utilisateur du parent' })
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
prenom?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
nom?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
photo_url?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un couple côté AM = placement actif enfant ↔ foyer parents.
|
||||||
|
* `id` = enfants_assistantes_maternelles.id (même clé que #168).
|
||||||
|
*/
|
||||||
|
export class CoupleGardeAmDto {
|
||||||
|
@ApiProperty({
|
||||||
|
format: 'uuid',
|
||||||
|
description: 'Id du placement (enfants_assistantes_maternelles.id)',
|
||||||
|
})
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@ApiProperty({ type: CoupleGardeAmEnfantDto })
|
||||||
|
enfant: CoupleGardeAmEnfantDto;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
type: [CoupleGardeAmParentDto],
|
||||||
|
description: 'Parents rattachés à l’enfant (0–2 typiquement)',
|
||||||
|
})
|
||||||
|
parents: CoupleGardeAmParentDto[];
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'True si c’est le couple actuellement sélectionné' })
|
||||||
|
courant: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CouplesGardeAmResponseDto {
|
||||||
|
@ApiProperty({ type: [CoupleGardeAmDto] })
|
||||||
|
couples: CoupleGardeAmDto[];
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
format: 'uuid',
|
||||||
|
nullable: true,
|
||||||
|
description: 'Id du couple courant (null si aucun)',
|
||||||
|
})
|
||||||
|
couple_courant_id: string | null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsNotEmpty, IsUUID } from 'class-validator';
|
||||||
|
|
||||||
|
/** Corps PUT couple de garde courant AM — ticket #171 */
|
||||||
|
export class DefinirCoupleGardeCourantAmDto {
|
||||||
|
@ApiProperty({
|
||||||
|
format: 'uuid',
|
||||||
|
description: 'Id du placement (enfants_assistantes_maternelles.id) à sélectionner',
|
||||||
|
})
|
||||||
|
@IsUUID()
|
||||||
|
@IsNotEmpty()
|
||||||
|
couple_id: string;
|
||||||
|
}
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
/** Réponse 201 POST /assistantes-maternelles/dossier (#156). */
|
||||||
|
export class StaffCreateAmDossierResponseDto {
|
||||||
|
@ApiProperty()
|
||||||
|
message: string;
|
||||||
|
|
||||||
|
@ApiProperty({ format: 'uuid' })
|
||||||
|
user_id: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
enum: StatutUtilisateurType,
|
||||||
|
example: StatutUtilisateurType.ACTIF,
|
||||||
|
})
|
||||||
|
statut: StatutUtilisateurType;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: '2026-000042',
|
||||||
|
description: 'Numéro de dossier attribué',
|
||||||
|
})
|
||||||
|
numero_dossier: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { ApiPropertyOptional, OmitType } from '@nestjs/swagger';
|
||||||
|
import { IsBoolean, IsOptional } from 'class-validator';
|
||||||
|
import { RegisterAMCompletDto } from 'src/routes/auth/dto/register-am-complet.dto';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Création dossier AM par staff (#156).
|
||||||
|
* Mêmes champs que l'inscription publique, sans CGU/privacy obligatoires
|
||||||
|
* (acceptées côté serveur pour le compte du gestionnaire).
|
||||||
|
*/
|
||||||
|
export class StaffCreateAmDossierDto extends OmitType(RegisterAMCompletDto, [
|
||||||
|
'acceptation_cgu',
|
||||||
|
'acceptation_privacy',
|
||||||
|
] as const) {
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Ignoré côté staff (CGU acceptées serveur). Conservé pour compat éventuelle.',
|
||||||
|
default: true,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
acceptation_cgu?: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Ignoré côté staff (privacy acceptée serveur).',
|
||||||
|
default: true,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
acceptation_privacy?: boolean;
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import {
|
||||||
|
IsBoolean,
|
||||||
|
IsDateString,
|
||||||
|
IsEmail,
|
||||||
|
IsEnum,
|
||||||
|
IsInt,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
Max,
|
||||||
|
MaxLength,
|
||||||
|
Min,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
/** Mise à jour fiche AM par admin/gestionnaire (doc 28 §6.1, ticket #131). */
|
||||||
|
export class UpdateAmFicheAdminDto {
|
||||||
|
@ApiPropertyOptional({ example: 'MARTIN' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(100)
|
||||||
|
nom?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'Claire' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(100)
|
||||||
|
prenom?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'claire@example.com' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsEmail()
|
||||||
|
email?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: '0612345678' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(20)
|
||||||
|
telephone?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: '5 place Bellecour' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
adresse?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'Lyon' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(150)
|
||||||
|
ville?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: '69002' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(10)
|
||||||
|
code_postal?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ enum: StatutUtilisateurType })
|
||||||
|
@IsOptional()
|
||||||
|
@IsEnum(StatutUtilisateurType)
|
||||||
|
statut?: StatutUtilisateurType;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: '123456789012345' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(15)
|
||||||
|
nir?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: '1985-03-12' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
date_naissance?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'Lyon' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(100)
|
||||||
|
lieu_naissance_ville?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'France' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(100)
|
||||||
|
lieu_naissance_pays?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'AGR-2024-12345' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(50)
|
||||||
|
approval_number?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: '2020-01-15' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
agreement_date?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'Lyon' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(100)
|
||||||
|
residence_city?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 4 })
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
@Max(10)
|
||||||
|
max_children?: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 2 })
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(0)
|
||||||
|
@Max(10)
|
||||||
|
places_available?: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
biography?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: true })
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
available?: boolean;
|
||||||
|
}
|
||||||
@@ -9,6 +9,8 @@ describe('AuthController', () => {
|
|||||||
const authServiceMock = {
|
const authServiceMock = {
|
||||||
verifyCreatePasswordToken: jest.fn(),
|
verifyCreatePasswordToken: jest.fn(),
|
||||||
createPasswordWithToken: jest.fn(),
|
createPasswordWithToken: jest.fn(),
|
||||||
|
requestPasswordReset: jest.fn(),
|
||||||
|
resetPasswordWithResetToken: jest.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
@@ -70,4 +72,39 @@ describe('AuthController', () => {
|
|||||||
});
|
});
|
||||||
expect(authServiceMock.createPasswordWithToken).toHaveBeenCalledWith('tok-123', 'Password1');
|
expect(authServiceMock.createPasswordWithToken).toHaveBeenCalledWith('tok-123', 'Password1');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('forgot-password délègue au service et renvoie le message générique', async () => {
|
||||||
|
authServiceMock.requestPasswordReset.mockResolvedValue({
|
||||||
|
message: 'Si cette adresse est associée…',
|
||||||
|
});
|
||||||
|
await expect(controller.forgotPassword({ email: 'user@test.fr' })).resolves.toEqual({
|
||||||
|
message: 'Si cette adresse est associée…',
|
||||||
|
});
|
||||||
|
expect(authServiceMock.requestPasswordReset).toHaveBeenCalledWith('user@test.fr');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects reset-password when confirmation mismatches', async () => {
|
||||||
|
await expect(
|
||||||
|
controller.resetPassword({
|
||||||
|
token: 'tok',
|
||||||
|
password: 'Password1',
|
||||||
|
password_confirmation: 'Password2',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(BadRequestException);
|
||||||
|
expect(authServiceMock.resetPasswordWithResetToken).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calls reset-password when payload is valid', async () => {
|
||||||
|
authServiceMock.resetPasswordWithResetToken.mockResolvedValue({
|
||||||
|
message: 'Mot de passe mis à jour.',
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
controller.resetPassword({
|
||||||
|
token: 'tok-123',
|
||||||
|
password: 'Password1',
|
||||||
|
password_confirmation: 'Password1',
|
||||||
|
}),
|
||||||
|
).resolves.toEqual({ message: 'Mot de passe mis à jour.' });
|
||||||
|
expect(authServiceMock.resetPasswordWithResetToken).toHaveBeenCalledWith('tok-123', 'Password1');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,17 @@
|
|||||||
import { Body, Controller, Get, Patch, Post, Query, Req, UnauthorizedException, BadRequestException, UseGuards } from '@nestjs/common';
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
Req,
|
||||||
|
UnauthorizedException,
|
||||||
|
BadRequestException,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
import { LoginDto } from './dto/login.dto';
|
import { LoginDto } from './dto/login.dto';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
import { Public } from 'src/common/decorators/public.decorator';
|
import { Public } from 'src/common/decorators/public.decorator';
|
||||||
@@ -8,6 +21,8 @@ import { RegisterAMCompletDto } from './dto/register-am-complet.dto';
|
|||||||
import { RegisterAmResponseDto } from './dto/register-am-response.dto';
|
import { RegisterAmResponseDto } from './dto/register-am-response.dto';
|
||||||
import { ChangePasswordRequiredDto } from './dto/change-password.dto';
|
import { ChangePasswordRequiredDto } from './dto/change-password.dto';
|
||||||
import { CreatePasswordDto } from './dto/create-password.dto';
|
import { CreatePasswordDto } from './dto/create-password.dto';
|
||||||
|
import { ForgotPasswordDto } from './dto/forgot-password.dto';
|
||||||
|
import { ResetPasswordDto } from './dto/reset-password.dto';
|
||||||
import { ApiBearerAuth, ApiOperation, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
|
import { ApiBearerAuth, ApiOperation, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
import type { Request } from 'express';
|
import type { Request } from 'express';
|
||||||
@@ -87,8 +102,7 @@ export class AuthController {
|
|||||||
@ApiResponse({ status: 200, description: 'Dossier resoumis' })
|
@ApiResponse({ status: 200, description: 'Dossier resoumis' })
|
||||||
@ApiResponse({ status: 404, description: 'Token invalide ou expiré' })
|
@ApiResponse({ status: 404, description: 'Token invalide ou expiré' })
|
||||||
async resoumettreReprise(@Body() dto: ResoumettreRepriseDto) {
|
async resoumettreReprise(@Body() dto: ResoumettreRepriseDto) {
|
||||||
const { token, ...fields } = dto;
|
return this.authService.resoumettreReprise(dto);
|
||||||
return this.authService.resoumettreReprise(token, fields);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Public()
|
@Public()
|
||||||
@@ -133,6 +147,36 @@ export class AuthController {
|
|||||||
return this.authService.createPasswordWithToken(dto.token, dto.password);
|
return this.authService.createPasswordWithToken(dto.token, dto.password);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post('forgot-password')
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Demande de réinitialisation du mot de passe (ticket #127)',
|
||||||
|
description:
|
||||||
|
'Réponse identique que l’e-mail existe ou non (anti-énumération). Si un compte avec mot de passe existe, un e-mail avec lien /reset-password est envoyé.',
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: 200, description: 'Message générique' })
|
||||||
|
async forgotPassword(@Body() dto: ForgotPasswordDto) {
|
||||||
|
return this.authService.requestPasswordReset(dto.email ?? '');
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post('reset-password')
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Réinitialiser le mot de passe via token e-mail (ticket #127)',
|
||||||
|
description: 'Distinct de POST /auth/create-password (inscription). Utilise password_reset_token.',
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: 200, description: 'Mot de passe mis à jour' })
|
||||||
|
@ApiResponse({ status: 400, description: 'Confirmation ou règles de mot de passe' })
|
||||||
|
@ApiResponse({ status: 404, description: 'Token invalide, expiré, ou déjà utilisé' })
|
||||||
|
async resetPassword(@Body() dto: ResetPasswordDto) {
|
||||||
|
if (dto.password !== dto.password_confirmation) {
|
||||||
|
throw new BadRequestException('Les mots de passe ne correspondent pas');
|
||||||
|
}
|
||||||
|
return this.authService.resetPasswordWithResetToken(dto.token, dto.password);
|
||||||
|
}
|
||||||
|
|
||||||
@Get('me')
|
@Get('me')
|
||||||
@UseGuards(AuthGuard)
|
@UseGuards(AuthGuard)
|
||||||
@ApiBearerAuth('access-token')
|
@ApiBearerAuth('access-token')
|
||||||
|
|||||||
@@ -12,11 +12,25 @@ import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entit
|
|||||||
import { AppConfigModule } from 'src/modules/config';
|
import { AppConfigModule } from 'src/modules/config';
|
||||||
import { NumeroDossierModule } from 'src/modules/numero-dossier/numero-dossier.module';
|
import { NumeroDossierModule } from 'src/modules/numero-dossier/numero-dossier.module';
|
||||||
import { MailModule } from 'src/modules/mail/mail.module';
|
import { MailModule } from 'src/modules/mail/mail.module';
|
||||||
|
import { ParentsModule } from '../parents/parents.module';
|
||||||
|
import { DossiersModule } from '../dossiers/dossiers.module';
|
||||||
|
import { DossierFamille, DossierFamilleEnfant } from 'src/entities/dossier_famille.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
TypeOrmModule.forFeature([Users, Parents, Children, AssistanteMaternelle]),
|
TypeOrmModule.forFeature([
|
||||||
|
Users,
|
||||||
|
Parents,
|
||||||
|
Children,
|
||||||
|
AssistanteMaternelle,
|
||||||
|
DossierFamille,
|
||||||
|
DossierFamilleEnfant,
|
||||||
|
ParentsChildren,
|
||||||
|
]),
|
||||||
forwardRef(() => UserModule),
|
forwardRef(() => UserModule),
|
||||||
|
forwardRef(() => ParentsModule),
|
||||||
|
DossiersModule,
|
||||||
AppConfigModule,
|
AppConfigModule,
|
||||||
MailModule,
|
MailModule,
|
||||||
NumeroDossierModule,
|
NumeroDossierModule,
|
||||||
|
|||||||
@@ -5,11 +5,13 @@ import { getRepositoryToken } from '@nestjs/typeorm';
|
|||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
import { UserService } from '../user/user.service';
|
import { UserService } from '../user/user.service';
|
||||||
|
import { ParentsService } from '../parents/parents.service';
|
||||||
|
import { DossiersService } from '../dossiers/dossiers.service';
|
||||||
import { AppConfigService } from 'src/modules/config/config.service';
|
import { AppConfigService } from 'src/modules/config/config.service';
|
||||||
import { MailService } from 'src/modules/mail/mail.service';
|
import { MailService } from 'src/modules/mail/mail.service';
|
||||||
import { NumeroDossierService } from 'src/modules/numero-dossier/numero-dossier.service';
|
import { NumeroDossierService } from 'src/modules/numero-dossier/numero-dossier.service';
|
||||||
import { Parents } from 'src/entities/parents.entity';
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
import { Users } from 'src/entities/users.entity';
|
import { Users, RoleType, StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
import { Children } from 'src/entities/children.entity';
|
import { Children } from 'src/entities/children.entity';
|
||||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
|
|
||||||
@@ -18,18 +20,54 @@ describe('AuthService (#118 create-password API)', () => {
|
|||||||
const usersRepoMock = {
|
const usersRepoMock = {
|
||||||
findOne: jest.fn(),
|
findOne: jest.fn(),
|
||||||
createQueryBuilder: jest.fn(),
|
createQueryBuilder: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
manager: { transaction: jest.fn() },
|
||||||
|
};
|
||||||
|
|
||||||
|
const userServiceMock = {
|
||||||
|
findByTokenReprise: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const parentsServiceMock = {
|
||||||
|
getDossierFamilleByNumero: jest.fn(),
|
||||||
|
getFamilyUserIds: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const dossiersServiceMock = {
|
||||||
|
getDossierByNumero: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const mailServiceMock = {
|
||||||
|
sendPasswordResetEmail: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
|
||||||
|
const appConfigMock = {
|
||||||
|
get: jest.fn().mockReturnValue(7),
|
||||||
};
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
|
const qbChain: any = {};
|
||||||
|
qbChain.where = jest.fn().mockReturnValue(qbChain);
|
||||||
|
qbChain.select = jest.fn().mockReturnValue(qbChain);
|
||||||
|
qbChain.getOne = jest.fn().mockResolvedValue(null);
|
||||||
|
qbChain.update = jest.fn().mockReturnValue(qbChain);
|
||||||
|
qbChain.set = jest.fn().mockReturnValue(qbChain);
|
||||||
|
qbChain.andWhere = jest.fn().mockReturnValue(qbChain);
|
||||||
|
qbChain.execute = jest.fn().mockResolvedValue({ affected: 0 });
|
||||||
|
usersRepoMock.createQueryBuilder.mockReturnValue(qbChain);
|
||||||
|
usersRepoMock.update.mockResolvedValue({ affected: 1, raw: [] });
|
||||||
|
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
AuthService,
|
AuthService,
|
||||||
{ provide: UserService, useValue: {} },
|
{ provide: UserService, useValue: userServiceMock },
|
||||||
|
{ provide: ParentsService, useValue: parentsServiceMock },
|
||||||
|
{ provide: DossiersService, useValue: dossiersServiceMock },
|
||||||
{ provide: JwtService, useValue: {} },
|
{ provide: JwtService, useValue: {} },
|
||||||
{ provide: ConfigService, useValue: { get: jest.fn() } },
|
{ provide: ConfigService, useValue: { get: jest.fn() } },
|
||||||
{ provide: AppConfigService, useValue: {} },
|
{ provide: AppConfigService, useValue: appConfigMock },
|
||||||
{ provide: MailService, useValue: {} },
|
{ provide: MailService, useValue: mailServiceMock },
|
||||||
{ provide: NumeroDossierService, useValue: {} },
|
{ provide: NumeroDossierService, useValue: {} },
|
||||||
{ provide: getRepositoryToken(Parents), useValue: {} },
|
{ provide: getRepositoryToken(Parents), useValue: {} },
|
||||||
{ provide: getRepositoryToken(Users), useValue: usersRepoMock },
|
{ provide: getRepositoryToken(Users), useValue: usersRepoMock },
|
||||||
@@ -61,4 +99,124 @@ describe('AuthService (#118 create-password API)', () => {
|
|||||||
message: 'Token valide',
|
message: 'Token valide',
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('#127 forgot / reset password', () => {
|
||||||
|
it('requestPasswordReset returns generic message when email unknown', async () => {
|
||||||
|
const r = await service.requestPasswordReset('unknown@test.fr');
|
||||||
|
expect(r.message).toContain('Si cette adresse');
|
||||||
|
expect(mailServiceMock.sendPasswordResetEmail).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requestPasswordReset sends mail when user has password', async () => {
|
||||||
|
usersRepoMock.createQueryBuilder.mockReturnValueOnce({
|
||||||
|
where: jest.fn().mockReturnThis(),
|
||||||
|
select: jest.fn().mockReturnThis(),
|
||||||
|
getOne: jest.fn().mockResolvedValue({
|
||||||
|
id: 'u1',
|
||||||
|
email: 'a@test.fr',
|
||||||
|
prenom: 'A',
|
||||||
|
nom: 'B',
|
||||||
|
password: 'hashed',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const r = await service.requestPasswordReset('a@test.fr');
|
||||||
|
expect(r.message).toContain('Si cette adresse');
|
||||||
|
expect(usersRepoMock.update).toHaveBeenCalled();
|
||||||
|
expect(mailServiceMock.sendPasswordResetEmail).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ email: 'a@test.fr', token: expect.any(String) }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resetPasswordWithResetToken throws when token unknown', async () => {
|
||||||
|
usersRepoMock.findOne.mockResolvedValue(null);
|
||||||
|
await expect(service.resetPasswordWithResetToken('bad', 'Password1')).rejects.toThrow(
|
||||||
|
NotFoundException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resetPasswordWithResetToken succeeds when update affects row', async () => {
|
||||||
|
usersRepoMock.findOne.mockResolvedValue({
|
||||||
|
id: 'u1',
|
||||||
|
password: 'oldhash',
|
||||||
|
password_reset_expires: new Date(Date.now() + 60_000),
|
||||||
|
});
|
||||||
|
const exec = jest.fn().mockResolvedValue({ affected: 1 });
|
||||||
|
const chain: any = {};
|
||||||
|
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 = exec;
|
||||||
|
usersRepoMock.createQueryBuilder.mockReturnValueOnce(chain);
|
||||||
|
|
||||||
|
const r = await service.resetPasswordWithResetToken('good-token', 'Password1');
|
||||||
|
expect(r.message.toLowerCase()).toContain('mis à jour');
|
||||||
|
expect(exec).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Reprise après refus (#112)', () => {
|
||||||
|
const token = '11111111-1111-1111-1111-111111111111';
|
||||||
|
|
||||||
|
it('getRepriseDossier throws when token invalid', async () => {
|
||||||
|
userServiceMock.findByTokenReprise.mockResolvedValue(null);
|
||||||
|
await expect(service.getRepriseDossier(token)).rejects.toThrow(NotFoundException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getRepriseDossier returns famille complète pour parent', async () => {
|
||||||
|
userServiceMock.findByTokenReprise.mockResolvedValue({
|
||||||
|
id: 'p1',
|
||||||
|
email: 'claire@test.fr',
|
||||||
|
prenom: 'Claire',
|
||||||
|
nom: 'MARTIN',
|
||||||
|
role: RoleType.PARENT,
|
||||||
|
numero_dossier: '2026-000021',
|
||||||
|
statut: StatutUtilisateurType.REFUSE,
|
||||||
|
});
|
||||||
|
parentsServiceMock.getDossierFamilleByNumero.mockResolvedValue({
|
||||||
|
numero_dossier: '2026-000021',
|
||||||
|
parents: [{ user_id: 'p1', email: 'claire@test.fr', statut: StatutUtilisateurType.REFUSE }],
|
||||||
|
enfants: [{ id: 'e1', first_name: 'Emma', status: 'sans_garde' }],
|
||||||
|
texte_motivation: 'Motivation test',
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.getRepriseDossier(token);
|
||||||
|
expect(result.parents).toHaveLength(1);
|
||||||
|
expect(result.enfants).toHaveLength(1);
|
||||||
|
expect(result.texte_motivation).toBe('Motivation test');
|
||||||
|
expect(result.numero_dossier).toBe('2026-000021');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getRepriseDossier returns fiche AM complète', async () => {
|
||||||
|
userServiceMock.findByTokenReprise.mockResolvedValue({
|
||||||
|
id: 'am1',
|
||||||
|
email: 'am@test.fr',
|
||||||
|
role: RoleType.ASSISTANTE_MATERNELLE,
|
||||||
|
numero_dossier: '2026-000003',
|
||||||
|
});
|
||||||
|
dossiersServiceMock.getDossierByNumero.mockResolvedValue({
|
||||||
|
type: 'am',
|
||||||
|
dossier: {
|
||||||
|
numero_dossier: '2026-000003',
|
||||||
|
user: {
|
||||||
|
id: 'am1',
|
||||||
|
email: 'am@test.fr',
|
||||||
|
prenom: 'Marie',
|
||||||
|
nom: 'DUPONT',
|
||||||
|
statut: StatutUtilisateurType.REFUSE,
|
||||||
|
},
|
||||||
|
numero_agrement: 'AGR-1',
|
||||||
|
nir: '123456789012345',
|
||||||
|
biographie: 'Bio',
|
||||||
|
nb_max_enfants: 4,
|
||||||
|
place_disponible: 2,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.getRepriseDossier(token);
|
||||||
|
expect(result.numero_agrement).toBe('AGR-1');
|
||||||
|
expect(result.biographie).toBe('Bio');
|
||||||
|
expect(result.nb_max_enfants).toBe(4);
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -55,9 +55,13 @@ export class EnfantInscriptionDto {
|
|||||||
@IsString()
|
@IsString()
|
||||||
photo_filename?: string;
|
photo_filename?: string;
|
||||||
|
|
||||||
@ApiProperty({ example: false, required: false, description: 'Grossesse multiple (jumeaux, triplés, etc.)' })
|
@ApiProperty({
|
||||||
|
example: true,
|
||||||
|
required: false,
|
||||||
|
description: 'Consentement affichage / stockage photo (colonne enfants.consentement_photo)',
|
||||||
|
})
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
grossesse_multiple?: boolean;
|
consent_photo?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsNotEmpty, IsUUID } from 'class-validator';
|
||||||
|
import { EnfantInscriptionDto } from './enfant-inscription.dto';
|
||||||
|
|
||||||
|
/** Enfant existant modifiable lors de la resoumission reprise (#112). */
|
||||||
|
export class EnfantRepriseDto extends EnfantInscriptionDto {
|
||||||
|
@ApiProperty({ description: 'UUID enfant existant (obligatoire en reprise)' })
|
||||||
|
@IsUUID()
|
||||||
|
@IsNotEmpty()
|
||||||
|
id: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { Transform } from 'class-transformer';
|
||||||
|
import { IsOptional, IsString, MaxLength } from 'class-validator';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ticket #127 — pas de @IsEmail / @MinLength stricts : éviter 400 sur saisies vides ou bizarres ;
|
||||||
|
* le service renvoie toujours la même réponse 200 (anti-énumération).
|
||||||
|
*/
|
||||||
|
export class ForgotPasswordDto {
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'parent@example.com',
|
||||||
|
required: false,
|
||||||
|
description: 'E-mail (trim + lowercase via transform). Absent ou vide → même réponse générique.',
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(320)
|
||||||
|
@Transform(({ value }) => (typeof value === 'string' ? value.trim().toLowerCase() : ''))
|
||||||
|
email?: string;
|
||||||
|
}
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import { RoleType } from 'src/entities/users.entity';
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
import {
|
||||||
|
DossierFamilleEnfantDto,
|
||||||
|
DossierFamilleParentDto,
|
||||||
|
} from '../../parents/dto/dossier-famille-complet.dto';
|
||||||
|
|
||||||
/** Réponse GET /auth/reprise-dossier – données dossier pour préremplir le formulaire reprise. Ticket #111 */
|
/** Réponse GET /auth/reprise-dossier – dossier complet pour préremplir le wizard reprise. #111 + #112 */
|
||||||
export class RepriseDossierDto {
|
export class RepriseDossierDto {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
id: string;
|
id: string;
|
||||||
@@ -41,4 +45,47 @@ export class RepriseDossierDto {
|
|||||||
|
|
||||||
@ApiProperty({ required: false })
|
@ApiProperty({ required: false })
|
||||||
situation_familiale?: string;
|
situation_familiale?: string;
|
||||||
|
|
||||||
|
// --- Parent (dossier famille, aligné #119) ---
|
||||||
|
|
||||||
|
@ApiProperty({ type: [DossierFamilleParentDto], required: false })
|
||||||
|
parents?: DossierFamilleParentDto[];
|
||||||
|
|
||||||
|
@ApiProperty({ type: [DossierFamilleEnfantDto], required: false })
|
||||||
|
enfants?: DossierFamilleEnfantDto[];
|
||||||
|
|
||||||
|
@ApiProperty({ required: false, description: 'Motivation / présentation dossier famille' })
|
||||||
|
texte_motivation?: string;
|
||||||
|
|
||||||
|
// --- AM (aligné DossierAmCompletDto) ---
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
consentement_photo?: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
date_naissance?: Date;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
lieu_naissance_ville?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
lieu_naissance_pays?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
numero_agrement?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
nir?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
date_agrement?: Date;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
nb_max_enfants?: number;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
place_disponible?: number;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
biographie?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsString, MinLength, Matches } from 'class-validator';
|
||||||
|
|
||||||
|
/** Ticket #127 — mêmes règles que [CreatePasswordDto] (inscription #118). */
|
||||||
|
export class ResetPasswordDto {
|
||||||
|
@ApiProperty({ description: 'Token UUID reçu par e-mail (lien reset-password)' })
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1, { message: 'Token manquant' })
|
||||||
|
token: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'Nouveau mot de passe (min 8 caractères, 1 majuscule, 1 chiffre)',
|
||||||
|
minLength: 8,
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@MinLength(8, { message: 'Le mot de passe doit contenir au moins 8 caractères' })
|
||||||
|
@Matches(/^(?=.*[A-Z])(?=.*\d)/, {
|
||||||
|
message: 'Le mot de passe doit contenir au moins une majuscule et un chiffre',
|
||||||
|
})
|
||||||
|
password: string;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Confirmation du nouveau mot de passe' })
|
||||||
|
@IsString()
|
||||||
|
password_confirmation: string;
|
||||||
|
}
|
||||||
@@ -1,12 +1,29 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import { IsOptional, IsString, MaxLength, IsUUID } from 'class-validator';
|
import {
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
MaxLength,
|
||||||
|
IsUUID,
|
||||||
|
IsBoolean,
|
||||||
|
IsArray,
|
||||||
|
ValidateNested,
|
||||||
|
IsInt,
|
||||||
|
Min,
|
||||||
|
Max,
|
||||||
|
IsDateString,
|
||||||
|
Matches,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
|
import { EnfantRepriseDto } from './enfant-reprise.dto';
|
||||||
|
|
||||||
/** Body PUT /auth/reprise-resoumettre – token + champs modifiables. Ticket #111 */
|
/** Body PATCH /auth/reprise-resoumettre – token + champs modifiables du wizard. #111 + #112 */
|
||||||
export class ResoumettreRepriseDto {
|
export class ResoumettreRepriseDto {
|
||||||
@ApiProperty({ description: 'Token reprise (reçu par email)' })
|
@ApiProperty({ description: 'Token reprise (reçu par email)' })
|
||||||
@IsUUID()
|
@IsUUID()
|
||||||
token: string;
|
token: string;
|
||||||
|
|
||||||
|
// --- Identité titulaire (parent principal ou AM) ---
|
||||||
|
|
||||||
@ApiProperty({ required: false })
|
@ApiProperty({ required: false })
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@@ -42,8 +59,147 @@ export class ResoumettreRepriseDto {
|
|||||||
@MaxLength(10)
|
@MaxLength(10)
|
||||||
code_postal?: string;
|
code_postal?: string;
|
||||||
|
|
||||||
@ApiProperty({ required: false, description: 'Pour AM' })
|
@ApiProperty({ required: false, description: 'Pour AM (URL photo existante)' })
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
photo_url?: string;
|
photo_url?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false, description: 'Pour AM (nouvelle photo base64)' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
photo_base64?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false, description: 'Pour AM (nom fichier photo)' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
photo_filename?: string;
|
||||||
|
|
||||||
|
// --- Co-parent (reprise parent) ---
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
co_parent_email?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
co_parent_prenom?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
co_parent_nom?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@Matches(/^(\+33|0)[1-9](\d{2}){4}$/, {
|
||||||
|
message: 'Le numéro de téléphone du co-parent doit être valide',
|
||||||
|
})
|
||||||
|
co_parent_telephone?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
co_parent_meme_adresse?: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
co_parent_adresse?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
co_parent_code_postal?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
co_parent_ville?: string;
|
||||||
|
|
||||||
|
// --- Motivation dossier famille ---
|
||||||
|
|
||||||
|
@ApiProperty({ required: false, description: 'Alias texte_motivation' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(2000)
|
||||||
|
texte_motivation?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false, description: 'Alias presentation_dossier (inscription)' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(2000)
|
||||||
|
presentation_dossier?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ type: [EnfantRepriseDto], required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@ValidateNested({ each: true })
|
||||||
|
@Type(() => EnfantRepriseDto)
|
||||||
|
enfants?: EnfantRepriseDto[];
|
||||||
|
|
||||||
|
// --- AM ---
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
consentement_photo?: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
date_naissance?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(100)
|
||||||
|
lieu_naissance_ville?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(100)
|
||||||
|
lieu_naissance_pays?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(50)
|
||||||
|
numero_agrement?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@Matches(/^[1-3]\d{4}(?:2A|2B|\d{2})\d{6}\d{2}$/, {
|
||||||
|
message: 'Le NIR doit contenir 15 caractères (chiffres, ou 2A/2B pour la Corse)',
|
||||||
|
})
|
||||||
|
nir?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
date_agrement?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
@Max(10)
|
||||||
|
capacite_accueil?: number;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(0)
|
||||||
|
@Max(10)
|
||||||
|
places_disponibles?: number;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(2000)
|
||||||
|
biographie?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { DossiersController } from './dossiers.controller';
|
||||||
|
import { DossiersService } from './dossiers.service';
|
||||||
|
import { SuppressionService } from '../suppressions/suppression.service';
|
||||||
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
describe('DossiersController', () => {
|
||||||
|
let controller: DossiersController;
|
||||||
|
const dossiersServiceMock = {
|
||||||
|
listDossiers: jest.fn(),
|
||||||
|
getDossierByNumero: jest.fn(),
|
||||||
|
};
|
||||||
|
const suppressionServiceMock = {
|
||||||
|
deleteDossier: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
controllers: [DossiersController],
|
||||||
|
providers: [
|
||||||
|
{ provide: DossiersService, useValue: dossiersServiceMock },
|
||||||
|
{ provide: SuppressionService, useValue: suppressionServiceMock },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.overrideGuard(AuthGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.overrideGuard(RolesGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.compile();
|
||||||
|
|
||||||
|
controller = module.get<DossiersController>(DossiersController);
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(controller).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('list delegates to dossiersService.listDossiers with q', async () => {
|
||||||
|
dossiersServiceMock.listDossiers.mockResolvedValue([
|
||||||
|
{
|
||||||
|
type: 'famille',
|
||||||
|
numero_dossier: '2026-000043',
|
||||||
|
libelle: 'Claire MARTIN',
|
||||||
|
emails: ['claire@test.fr'],
|
||||||
|
user_ids: ['u1'],
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
a_valider: false,
|
||||||
|
date_reference: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const res = await controller.list('martin');
|
||||||
|
expect(dossiersServiceMock.listDossiers).toHaveBeenCalledWith('martin');
|
||||||
|
expect(res).toHaveLength(1);
|
||||||
|
expect(res[0].numero_dossier).toBe('2026-000043');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getDossier delegates to getDossierByNumero', async () => {
|
||||||
|
dossiersServiceMock.getDossierByNumero.mockResolvedValue({
|
||||||
|
type: 'family',
|
||||||
|
dossier: { numero_dossier: '2026-000001' },
|
||||||
|
});
|
||||||
|
const res = await controller.getDossier('2026-000001');
|
||||||
|
expect(dossiersServiceMock.getDossierByNumero).toHaveBeenCalledWith('2026-000001');
|
||||||
|
expect(res.type).toBe('family');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('remove delegates to suppressionService.deleteDossier', async () => {
|
||||||
|
const user = { id: 'u1', role: 'gestionnaire' } as never;
|
||||||
|
suppressionServiceMock.deleteDossier.mockResolvedValue({
|
||||||
|
type: 'famille',
|
||||||
|
deleted_user_ids: [],
|
||||||
|
deleted_enfant_ids: [],
|
||||||
|
message: 'ok',
|
||||||
|
});
|
||||||
|
await controller.remove('2026-000001', user);
|
||||||
|
expect(suppressionServiceMock.deleteDossier).toHaveBeenCalledWith(
|
||||||
|
'2026-000001',
|
||||||
|
user,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,17 +1,58 @@
|
|||||||
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
|
import {
|
||||||
import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiOperation,
|
||||||
|
ApiParam,
|
||||||
|
ApiQuery,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from '@nestjs/swagger';
|
||||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||||
import { RoleType } from 'src/entities/users.entity';
|
import { RoleType, Users } from 'src/entities/users.entity';
|
||||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
import { User } from 'src/common/decorators/user.decorator';
|
||||||
import { DossiersService } from './dossiers.service';
|
import { DossiersService } from './dossiers.service';
|
||||||
|
import { SuppressionService } from '../suppressions/suppression.service';
|
||||||
import { DossierUnifieDto } from './dto/dossier-unifie.dto';
|
import { DossierUnifieDto } from './dto/dossier-unifie.dto';
|
||||||
|
import { DossierListItemDto } from './dto/dossier-list-item.dto';
|
||||||
|
|
||||||
@ApiTags('Dossiers')
|
@ApiTags('Dossiers')
|
||||||
|
@ApiBearerAuth('access-token')
|
||||||
@Controller('dossiers')
|
@Controller('dossiers')
|
||||||
@UseGuards(AuthGuard, RolesGuard)
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
export class DossiersController {
|
export class DossiersController {
|
||||||
constructor(private readonly dossiersService: DossiersService) {}
|
constructor(
|
||||||
|
private readonly dossiersService: DossiersService,
|
||||||
|
private readonly suppressionService: SuppressionService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Liste unifiée des dossiers (familles + AM) — ticket #153',
|
||||||
|
description:
|
||||||
|
'1 entrée = 1 numero_dossier. Types `famille` | `assistante_maternelle`. ' +
|
||||||
|
'Filtre optionnel `q` (n°, nom, email). Tri : à valider d’abord, puis n° décroissant. ' +
|
||||||
|
'`sans_enfant` (#159) pour dossiers famille sans enfant.',
|
||||||
|
})
|
||||||
|
@ApiQuery({
|
||||||
|
name: 'q',
|
||||||
|
required: false,
|
||||||
|
description: 'Recherche libre : n° dossier, libellé, email…',
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: 200, type: [DossierListItemDto] })
|
||||||
|
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||||
|
list(@Query('q') q?: string): Promise<DossierListItemDto[]> {
|
||||||
|
return this.dossiersService.listDossiers(q);
|
||||||
|
}
|
||||||
|
|
||||||
@Get(':numeroDossier')
|
@Get(':numeroDossier')
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
@@ -23,4 +64,21 @@ export class DossiersController {
|
|||||||
getDossier(@Param('numeroDossier') numeroDossier: string): Promise<DossierUnifieDto> {
|
getDossier(@Param('numeroDossier') numeroDossier: string): Promise<DossierUnifieDto> {
|
||||||
return this.dossiersService.getDossierByNumero(numeroDossier);
|
return this.dossiersService.getDossierByNumero(numeroDossier);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Delete(':numeroDossier')
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Supprimer un dossier (famille ou AM) — #159',
|
||||||
|
description:
|
||||||
|
'Famille : parents + enfants. AM : compte AM + dossier AM (enfants conservés, placements clos).',
|
||||||
|
})
|
||||||
|
@ApiParam({ name: 'numeroDossier', description: 'Numéro de dossier' })
|
||||||
|
@ApiResponse({ status: 200, description: 'Résultat de suppression' })
|
||||||
|
@ApiResponse({ status: 404, description: 'Dossier introuvable' })
|
||||||
|
remove(
|
||||||
|
@Param('numeroDossier') numeroDossier: string,
|
||||||
|
@User() currentUser: Users,
|
||||||
|
) {
|
||||||
|
return this.suppressionService.deleteDossier(numeroDossier, currentUser);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { JwtModule } from '@nestjs/jwt';
|
|||||||
import { Parents } from 'src/entities/parents.entity';
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
import { ParentsModule } from '../parents/parents.module';
|
import { ParentsModule } from '../parents/parents.module';
|
||||||
|
import { SuppressionsModule } from '../suppressions/suppressions.module';
|
||||||
import { DossiersController } from './dossiers.controller';
|
import { DossiersController } from './dossiers.controller';
|
||||||
import { DossiersService } from './dossiers.service';
|
import { DossiersService } from './dossiers.service';
|
||||||
|
|
||||||
@@ -12,6 +13,7 @@ import { DossiersService } from './dossiers.service';
|
|||||||
imports: [
|
imports: [
|
||||||
TypeOrmModule.forFeature([Parents, AssistanteMaternelle]),
|
TypeOrmModule.forFeature([Parents, AssistanteMaternelle]),
|
||||||
ParentsModule,
|
ParentsModule,
|
||||||
|
SuppressionsModule,
|
||||||
JwtModule.registerAsync({
|
JwtModule.registerAsync({
|
||||||
imports: [ConfigModule],
|
imports: [ConfigModule],
|
||||||
useFactory: (config: ConfigService) => ({
|
useFactory: (config: ConfigService) => ({
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
|
import { DossiersService } from './dossiers.service';
|
||||||
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
|
import { ParentsService } from '../parents/parents.service';
|
||||||
|
import { SuppressionService } from '../suppressions/suppression.service';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
describe('DossiersService.listDossiers', () => {
|
||||||
|
let service: DossiersService;
|
||||||
|
const parentsQb = {
|
||||||
|
innerJoinAndSelect: jest.fn().mockReturnThis(),
|
||||||
|
leftJoinAndSelect: jest.fn().mockReturnThis(),
|
||||||
|
where: jest.fn().mockReturnThis(),
|
||||||
|
andWhere: jest.fn().mockReturnThis(),
|
||||||
|
getMany: jest.fn(),
|
||||||
|
};
|
||||||
|
const amQb = {
|
||||||
|
innerJoinAndSelect: jest.fn().mockReturnThis(),
|
||||||
|
where: jest.fn().mockReturnThis(),
|
||||||
|
andWhere: jest.fn().mockReturnThis(),
|
||||||
|
getMany: jest.fn(),
|
||||||
|
};
|
||||||
|
const parentsRepo = {
|
||||||
|
createQueryBuilder: jest.fn(() => parentsQb),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
const amRepo = {
|
||||||
|
createQueryBuilder: jest.fn(() => amQb),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
const parentsService = {
|
||||||
|
getDossierFamilleByNumero: jest.fn(),
|
||||||
|
};
|
||||||
|
const suppressionService = {
|
||||||
|
countEnfantsForNumero: jest.fn().mockResolvedValue(1),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
DossiersService,
|
||||||
|
{ provide: getRepositoryToken(Parents), useValue: parentsRepo },
|
||||||
|
{ provide: getRepositoryToken(AssistanteMaternelle), useValue: amRepo },
|
||||||
|
{ provide: ParentsService, useValue: parentsService },
|
||||||
|
{ provide: SuppressionService, useValue: suppressionService },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get(DossiersService);
|
||||||
|
jest.clearAllMocks();
|
||||||
|
parentsRepo.createQueryBuilder.mockReturnValue(parentsQb);
|
||||||
|
amRepo.createQueryBuilder.mockReturnValue(amQb);
|
||||||
|
suppressionService.countEnfantsForNumero.mockResolvedValue(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('aggregates famille (pivot+co-parent) and AM, sorts a_valider first', async () => {
|
||||||
|
parentsQb.getMany.mockResolvedValue([
|
||||||
|
{
|
||||||
|
user_id: 'p1',
|
||||||
|
numero_dossier: '2026-000010',
|
||||||
|
user: {
|
||||||
|
id: 'p1',
|
||||||
|
email: 'claire@test.fr',
|
||||||
|
prenom: 'Claire',
|
||||||
|
nom: 'Martin',
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
cree_le: new Date('2026-01-01'),
|
||||||
|
},
|
||||||
|
co_parent: {
|
||||||
|
id: 'p2',
|
||||||
|
email: 'thomas@test.fr',
|
||||||
|
prenom: 'Thomas',
|
||||||
|
nom: 'Martin',
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
cree_le: new Date('2026-01-02'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
user_id: 'p3',
|
||||||
|
numero_dossier: '2026-000020',
|
||||||
|
user: {
|
||||||
|
id: 'p3',
|
||||||
|
email: 'pending@test.fr',
|
||||||
|
prenom: 'Paul',
|
||||||
|
nom: 'Pending',
|
||||||
|
statut: StatutUtilisateurType.EN_ATTENTE,
|
||||||
|
cree_le: new Date('2026-02-01'),
|
||||||
|
},
|
||||||
|
co_parent: undefined,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
amQb.getMany.mockResolvedValue([
|
||||||
|
{
|
||||||
|
user_id: 'am1',
|
||||||
|
numero_dossier: '2026-000015',
|
||||||
|
user: {
|
||||||
|
id: 'am1',
|
||||||
|
email: 'am@test.fr',
|
||||||
|
prenom: 'Marie',
|
||||||
|
nom: 'Dupont',
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
cree_le: new Date('2026-01-15'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const list = await service.listDossiers();
|
||||||
|
expect(list).toHaveLength(3);
|
||||||
|
expect(list[0].a_valider).toBe(true);
|
||||||
|
expect(list[0].type).toBe('famille');
|
||||||
|
expect(list[0].numero_dossier).toBe('2026-000020');
|
||||||
|
|
||||||
|
const famille = list.find((i) => i.numero_dossier === '2026-000010')!;
|
||||||
|
expect(famille.type).toBe('famille');
|
||||||
|
expect(famille.user_ids).toEqual(expect.arrayContaining(['p1', 'p2']));
|
||||||
|
expect(famille.emails).toHaveLength(2);
|
||||||
|
expect(famille.libelle).toContain('MARTIN');
|
||||||
|
|
||||||
|
const am = list.find((i) => i.type === 'assistante_maternelle')!;
|
||||||
|
expect(am.numero_dossier).toBe('2026-000015');
|
||||||
|
expect(am.libelle).toContain('Marie');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters with q', async () => {
|
||||||
|
parentsQb.getMany.mockResolvedValue([]);
|
||||||
|
amQb.getMany.mockResolvedValue([
|
||||||
|
{
|
||||||
|
user_id: 'am1',
|
||||||
|
numero_dossier: '2026-000015',
|
||||||
|
user: {
|
||||||
|
id: 'am1',
|
||||||
|
email: 'am@test.fr',
|
||||||
|
prenom: 'Marie',
|
||||||
|
nom: 'Dupont',
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
cree_le: new Date('2026-01-15'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const hit = await service.listDossiers('dupont');
|
||||||
|
expect(hit).toHaveLength(1);
|
||||||
|
const miss = await service.listDossiers('zzz');
|
||||||
|
expect(miss).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -3,12 +3,15 @@ import { InjectRepository } from '@nestjs/typeorm';
|
|||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { Parents } from 'src/entities/parents.entity';
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
|
import { StatutUtilisateurType, Users } from 'src/entities/users.entity';
|
||||||
import { ParentsService } from '../parents/parents.service';
|
import { ParentsService } from '../parents/parents.service';
|
||||||
|
import { SuppressionService } from '../suppressions/suppression.service';
|
||||||
import { DossierUnifieDto } from './dto/dossier-unifie.dto';
|
import { DossierUnifieDto } from './dto/dossier-unifie.dto';
|
||||||
import { DossierAmCompletDto, DossierAmUserDto } from './dto/dossier-am-complet.dto';
|
import { DossierAmCompletDto, DossierAmUserDto } from './dto/dossier-am-complet.dto';
|
||||||
|
import { DossierListItemDto } from './dto/dossier-list-item.dto';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Endpoint unifié GET /dossiers/:numeroDossier – AM ou famille. Ticket #119.
|
* Dossiers unifiés — détail (#119) + liste (#153) + sans_enfant (#159).
|
||||||
*/
|
*/
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class DossiersService {
|
export class DossiersService {
|
||||||
@@ -18,8 +21,173 @@ export class DossiersService {
|
|||||||
@InjectRepository(AssistanteMaternelle)
|
@InjectRepository(AssistanteMaternelle)
|
||||||
private readonly amRepository: Repository<AssistanteMaternelle>,
|
private readonly amRepository: Repository<AssistanteMaternelle>,
|
||||||
private readonly parentsService: ParentsService,
|
private readonly parentsService: ParentsService,
|
||||||
|
private readonly suppressionService: SuppressionService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Liste unifiée tous dossiers (familles + AM) ayant un numero_dossier.
|
||||||
|
* Ticket #153 — optionnel `q` filtre n° / nom / prénom / email (côté serveur).
|
||||||
|
*/
|
||||||
|
async listDossiers(q?: string): Promise<DossierListItemDto[]> {
|
||||||
|
const items: DossierListItemDto[] = [
|
||||||
|
...(await this.listFamilleItems()),
|
||||||
|
...(await this.listAmItems()),
|
||||||
|
];
|
||||||
|
|
||||||
|
const needle = (q ?? '').trim().toLowerCase();
|
||||||
|
const filtered = needle
|
||||||
|
? items.filter((item) => this.matchesQuery(item, needle))
|
||||||
|
: items;
|
||||||
|
|
||||||
|
filtered.sort((a, b) => {
|
||||||
|
// À valider d'abord, puis n° dossier décroissant
|
||||||
|
if (a.a_valider !== b.a_valider) return a.a_valider ? -1 : 1;
|
||||||
|
return b.numero_dossier.localeCompare(a.numero_dossier, 'fr');
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const item of filtered) {
|
||||||
|
if (item.type === 'famille') {
|
||||||
|
const n = await this.suppressionService.countEnfantsForNumero(
|
||||||
|
item.numero_dossier,
|
||||||
|
);
|
||||||
|
item.sans_enfant = n === 0;
|
||||||
|
} else {
|
||||||
|
item.sans_enfant = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return filtered;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async listFamilleItems(): Promise<DossierListItemDto[]> {
|
||||||
|
const parents = await this.parentsRepository
|
||||||
|
.createQueryBuilder('p')
|
||||||
|
.innerJoinAndSelect('p.user', 'u')
|
||||||
|
.leftJoinAndSelect('p.co_parent', 'cp')
|
||||||
|
.where('p.numero_dossier IS NOT NULL')
|
||||||
|
.andWhere("TRIM(p.numero_dossier) <> ''")
|
||||||
|
.getMany();
|
||||||
|
|
||||||
|
const byNum = new Map<string, Parents[]>();
|
||||||
|
for (const p of parents) {
|
||||||
|
const num = (p.numero_dossier ?? '').trim();
|
||||||
|
if (!num) continue;
|
||||||
|
const group = byNum.get(num) ?? [];
|
||||||
|
group.push(p);
|
||||||
|
byNum.set(num, group);
|
||||||
|
}
|
||||||
|
|
||||||
|
const items: DossierListItemDto[] = [];
|
||||||
|
for (const [numero_dossier, group] of byNum) {
|
||||||
|
const usersMap = new Map<string, Users>();
|
||||||
|
for (const p of group) {
|
||||||
|
if (p.user) usersMap.set(p.user.id, p.user);
|
||||||
|
if (p.co_parent) usersMap.set(p.co_parent.id, p.co_parent);
|
||||||
|
}
|
||||||
|
const users = [...usersMap.values()].sort((a, b) => {
|
||||||
|
const an = `${a.nom ?? ''} ${a.prenom ?? ''}`.toLowerCase();
|
||||||
|
const bn = `${b.nom ?? ''} ${b.prenom ?? ''}`.toLowerCase();
|
||||||
|
return an.localeCompare(bn, 'fr') || a.id.localeCompare(b.id);
|
||||||
|
});
|
||||||
|
if (users.length === 0) continue;
|
||||||
|
|
||||||
|
const names = users.map((u) => this.formatPersonName(u)).filter(Boolean);
|
||||||
|
const libelle =
|
||||||
|
names.length === 0
|
||||||
|
? `Dossier ${numero_dossier}`
|
||||||
|
: names.length === 1
|
||||||
|
? names[0]
|
||||||
|
: names.join(' & ');
|
||||||
|
|
||||||
|
const emails = users.map((u) => u.email).filter(Boolean);
|
||||||
|
const user_ids = users.map((u) => u.id);
|
||||||
|
const a_valider = users.some((u) => u.statut === StatutUtilisateurType.EN_ATTENTE);
|
||||||
|
const statut = a_valider
|
||||||
|
? StatutUtilisateurType.EN_ATTENTE
|
||||||
|
: (users[0].statut ?? StatutUtilisateurType.ACTIF);
|
||||||
|
const date_reference = this.minCreeLeIso(users);
|
||||||
|
|
||||||
|
items.push({
|
||||||
|
type: 'famille',
|
||||||
|
numero_dossier,
|
||||||
|
libelle,
|
||||||
|
emails,
|
||||||
|
user_ids,
|
||||||
|
statut,
|
||||||
|
a_valider,
|
||||||
|
date_reference,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async listAmItems(): Promise<DossierListItemDto[]> {
|
||||||
|
const ams = await this.amRepository
|
||||||
|
.createQueryBuilder('am')
|
||||||
|
.innerJoinAndSelect('am.user', 'u')
|
||||||
|
.where('am.numero_dossier IS NOT NULL')
|
||||||
|
.andWhere("TRIM(am.numero_dossier) <> ''")
|
||||||
|
.getMany();
|
||||||
|
|
||||||
|
const byNum = new Map<string, AssistanteMaternelle>();
|
||||||
|
for (const am of ams) {
|
||||||
|
const num = (am.numero_dossier ?? '').trim();
|
||||||
|
if (!num || !am.user) continue;
|
||||||
|
// Un n° = une AM ; garder le premier
|
||||||
|
if (!byNum.has(num)) byNum.set(num, am);
|
||||||
|
}
|
||||||
|
|
||||||
|
const items: DossierListItemDto[] = [];
|
||||||
|
for (const [numero_dossier, am] of byNum) {
|
||||||
|
const u = am.user!;
|
||||||
|
const libelle = this.formatPersonName(u) || `AM ${numero_dossier}`;
|
||||||
|
const a_valider = u.statut === StatutUtilisateurType.EN_ATTENTE;
|
||||||
|
items.push({
|
||||||
|
type: 'assistante_maternelle',
|
||||||
|
numero_dossier,
|
||||||
|
libelle,
|
||||||
|
emails: u.email ? [u.email] : [],
|
||||||
|
user_ids: [u.id],
|
||||||
|
statut: u.statut ?? StatutUtilisateurType.ACTIF,
|
||||||
|
a_valider,
|
||||||
|
date_reference: this.minCreeLeIso([u]),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
private matchesQuery(item: DossierListItemDto, needle: string): boolean {
|
||||||
|
const hay = [
|
||||||
|
item.numero_dossier,
|
||||||
|
item.libelle,
|
||||||
|
...item.emails,
|
||||||
|
item.statut,
|
||||||
|
item.type,
|
||||||
|
]
|
||||||
|
.join(' ')
|
||||||
|
.toLowerCase();
|
||||||
|
return hay.includes(needle);
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatPersonName(u: Users): string {
|
||||||
|
const prenom = (u.prenom ?? '').trim();
|
||||||
|
const nom = (u.nom ?? '').trim();
|
||||||
|
const nomFmt = nom ? nom.toUpperCase() : '';
|
||||||
|
return [prenom, nomFmt].filter(Boolean).join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
private minCreeLeIso(users: Users[]): string | null {
|
||||||
|
let min: Date | null = null;
|
||||||
|
for (const u of users) {
|
||||||
|
const d = u.cree_le;
|
||||||
|
if (!d) continue;
|
||||||
|
const date = d instanceof Date ? d : new Date(d);
|
||||||
|
if (Number.isNaN(date.getTime())) continue;
|
||||||
|
if (!min || date < min) min = date;
|
||||||
|
}
|
||||||
|
return min ? min.toISOString() : null;
|
||||||
|
}
|
||||||
|
|
||||||
async getDossierByNumero(numeroDossier: string): Promise<DossierUnifieDto> {
|
async getDossierByNumero(numeroDossier: string): Promise<DossierUnifieDto> {
|
||||||
const num = numeroDossier?.trim();
|
const num = numeroDossier?.trim();
|
||||||
if (!num) {
|
if (!num) {
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
/** Ligne de liste GET /dossiers (#153). */
|
||||||
|
export class DossierListItemDto {
|
||||||
|
@ApiProperty({
|
||||||
|
enum: ['famille', 'assistante_maternelle'],
|
||||||
|
description: 'Type de dossier',
|
||||||
|
})
|
||||||
|
type: 'famille' | 'assistante_maternelle';
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2026-000043' })
|
||||||
|
numero_dossier: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'Claire MARTIN & Thomas MARTIN',
|
||||||
|
description: 'Libellé affiché (noms)',
|
||||||
|
})
|
||||||
|
libelle: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
type: [String],
|
||||||
|
example: ['claire@example.com', 'thomas@example.com'],
|
||||||
|
})
|
||||||
|
emails: string[];
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
type: [String],
|
||||||
|
format: 'uuid',
|
||||||
|
description: 'IDs utilisateur liés au dossier (parents du foyer ou AM)',
|
||||||
|
})
|
||||||
|
user_ids: string[];
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
enum: StatutUtilisateurType,
|
||||||
|
description:
|
||||||
|
'Statut agrégé : en_attente si au moins un user en_attente, sinon statut du premier',
|
||||||
|
})
|
||||||
|
statut: StatutUtilisateurType;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'True si le dossier est en attente de validation (section haute UI)',
|
||||||
|
})
|
||||||
|
a_valider: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
nullable: true,
|
||||||
|
example: '2026-01-12T10:00:00.000Z',
|
||||||
|
description: 'Date de référence (MIN cree_le des users du dossier)',
|
||||||
|
})
|
||||||
|
date_reference: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description:
|
||||||
|
'True si dossier famille sans enfant lié (#159). Omis ou false pour AM.',
|
||||||
|
})
|
||||||
|
sans_enfant?: boolean;
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { Transform } from 'class-transformer';
|
||||||
import {
|
import {
|
||||||
IsBoolean,
|
IsBoolean,
|
||||||
IsDateString,
|
IsDateString,
|
||||||
@@ -6,13 +7,25 @@ import {
|
|||||||
IsNotEmpty,
|
IsNotEmpty,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
|
IsUUID,
|
||||||
MaxLength,
|
MaxLength,
|
||||||
ValidateIf,
|
ValidateIf,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
import { GenreType, StatutEnfantType } from 'src/entities/children.entity';
|
import { GenreType, StatutEnfantType } from 'src/entities/children.entity';
|
||||||
|
|
||||||
|
/** Multipart envoie des strings ("true"/"false") — JSON envoie déjà des booleans. */
|
||||||
|
function toBoolean({ value }: { value: unknown }): boolean | unknown {
|
||||||
|
if (typeof value === 'boolean') return value;
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const v = value.trim().toLowerCase();
|
||||||
|
if (v === 'true' || v === '1') return true;
|
||||||
|
if (v === 'false' || v === '0' || v === '') return false;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
export class CreateEnfantsDto {
|
export class CreateEnfantsDto {
|
||||||
@ApiProperty({ enum: StatutEnfantType, example: StatutEnfantType.ACTIF })
|
@ApiProperty({ enum: StatutEnfantType, example: StatutEnfantType.SANS_GARDE })
|
||||||
@IsEnum(StatutEnfantType)
|
@IsEnum(StatutEnfantType)
|
||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
status: StatutEnfantType;
|
status: StatutEnfantType;
|
||||||
@@ -52,6 +65,7 @@ export class CreateEnfantsDto {
|
|||||||
photo_url?: string;
|
photo_url?: string;
|
||||||
|
|
||||||
@ApiProperty({ default: false })
|
@ApiProperty({ default: false })
|
||||||
|
@Transform(toBoolean)
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
consent_photo: boolean;
|
consent_photo: boolean;
|
||||||
|
|
||||||
@@ -60,7 +74,16 @@ export class CreateEnfantsDto {
|
|||||||
@IsDateString()
|
@IsDateString()
|
||||||
consent_photo_at?: string;
|
consent_photo_at?: string;
|
||||||
|
|
||||||
@ApiProperty({ default: false })
|
/**
|
||||||
@IsBoolean()
|
* Parent pivot du foyer — obligatoire pour staff (gestionnaire/admin).
|
||||||
is_multiple: boolean;
|
* Ignoré / interdit en externe pour un PARENT (ticket #132).
|
||||||
|
*/
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description:
|
||||||
|
'UUID du parent pivot (staff only). Obligatoire pour GESTIONNAIRE / ADMIN / SUPER_ADMIN.',
|
||||||
|
format: 'uuid',
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsUUID('4')
|
||||||
|
parent_user_id?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ export class EnfantResponseDto {
|
|||||||
@ApiProperty({ example: false })
|
@ApiProperty({ example: false })
|
||||||
consent_photo: boolean;
|
consent_photo: boolean;
|
||||||
|
|
||||||
@ApiProperty({ example: false })
|
|
||||||
is_multiple: boolean;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'UUID-parent' })
|
@ApiProperty({ example: 'UUID-parent' })
|
||||||
parent_id: string;
|
parent_id: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,35 @@
|
|||||||
import {
|
import {
|
||||||
Body,
|
Body,
|
||||||
|
CallHandler,
|
||||||
Controller,
|
Controller,
|
||||||
Delete,
|
Delete,
|
||||||
|
ExecutionContext,
|
||||||
Get,
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
|
Injectable,
|
||||||
|
NestInterceptor,
|
||||||
Param,
|
Param,
|
||||||
ParseUUIDPipe,
|
ParseUUIDPipe,
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
|
Query,
|
||||||
|
UploadedFile,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
UseInterceptors,
|
UseInterceptors,
|
||||||
UploadedFile,
|
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { FileInterceptor } from '@nestjs/platform-express';
|
import { FileInterceptor } from '@nestjs/platform-express';
|
||||||
import { ApiBearerAuth, ApiTags, ApiConsumes } from '@nestjs/swagger';
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiBody,
|
||||||
|
ApiConsumes,
|
||||||
|
ApiOperation,
|
||||||
|
ApiQuery,
|
||||||
|
ApiTags,
|
||||||
|
} from '@nestjs/swagger';
|
||||||
import { diskStorage } from 'multer';
|
import { diskStorage } from 'multer';
|
||||||
import { extname } from 'path';
|
import { extname } from 'path';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
import { EnfantsService } from './enfants.service';
|
import { EnfantsService } from './enfants.service';
|
||||||
import { CreateEnfantsDto } from './dto/create_enfants.dto';
|
import { CreateEnfantsDto } from './dto/create_enfants.dto';
|
||||||
import { UpdateEnfantsDto } from './dto/update_enfants.dto';
|
import { UpdateEnfantsDto } from './dto/update_enfants.dto';
|
||||||
@@ -23,19 +38,9 @@ import { User } from 'src/common/decorators/user.decorator';
|
|||||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
import { SuppressionService } from '../suppressions/suppression.service';
|
||||||
|
|
||||||
@ApiBearerAuth('access-token')
|
const photoMulterOptions = {
|
||||||
@ApiTags('Enfants')
|
|
||||||
@UseGuards(AuthGuard, RolesGuard)
|
|
||||||
@Controller('enfants')
|
|
||||||
export class EnfantsController {
|
|
||||||
constructor(private readonly enfantsService: EnfantsService) { }
|
|
||||||
|
|
||||||
@Roles(RoleType.PARENT)
|
|
||||||
@Post()
|
|
||||||
@ApiConsumes('multipart/form-data')
|
|
||||||
@UseInterceptors(
|
|
||||||
FileInterceptor('photo', {
|
|
||||||
storage: diskStorage({
|
storage: diskStorage({
|
||||||
destination: './uploads/photos',
|
destination: './uploads/photos',
|
||||||
filename: (req, file, cb) => {
|
filename: (req, file, cb) => {
|
||||||
@@ -53,8 +58,60 @@ export class EnfantsController {
|
|||||||
limits: {
|
limits: {
|
||||||
fileSize: 5 * 1024 * 1024,
|
fileSize: 5 * 1024 * 1024,
|
||||||
},
|
},
|
||||||
}),
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Multer uniquement si Content-Type multipart (parent ou staff + photo).
|
||||||
|
* JSON sans photo (#132) passe sans interceptor fichier.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
class OptionalEnfantPhotoInterceptor implements NestInterceptor {
|
||||||
|
private readonly multipart = new (FileInterceptor(
|
||||||
|
'photo',
|
||||||
|
photoMulterOptions,
|
||||||
|
))();
|
||||||
|
|
||||||
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> | Promise<Observable<unknown>> {
|
||||||
|
const req = context.switchToHttp().getRequest();
|
||||||
|
const ct = String(req.headers['content-type'] ?? '');
|
||||||
|
if (!ct.includes('multipart/form-data')) {
|
||||||
|
return next.handle();
|
||||||
|
}
|
||||||
|
return this.multipart.intercept(context, next);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiBearerAuth('access-token')
|
||||||
|
@ApiTags('Enfants')
|
||||||
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
|
@Controller('enfants')
|
||||||
|
export class EnfantsController {
|
||||||
|
constructor(
|
||||||
|
private readonly enfantsService: EnfantsService,
|
||||||
|
private readonly suppressionService: SuppressionService,
|
||||||
|
) { }
|
||||||
|
|
||||||
|
@Roles(
|
||||||
|
RoleType.PARENT,
|
||||||
|
RoleType.GESTIONNAIRE,
|
||||||
|
RoleType.ADMINISTRATEUR,
|
||||||
|
RoleType.SUPER_ADMIN,
|
||||||
)
|
)
|
||||||
|
@Post()
|
||||||
|
@HttpCode(HttpStatus.CREATED)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Créer un enfant',
|
||||||
|
description:
|
||||||
|
'PARENT : multipart éventuel, rattache au compte connecté. ' +
|
||||||
|
'Staff : parent_user_id obligatoire ; JSON sans photo OK ; avec photo → multipart (champ fichier `photo`, max 5 Mo). Ticket #132.',
|
||||||
|
})
|
||||||
|
@ApiConsumes('application/json', 'multipart/form-data')
|
||||||
|
@ApiBody({
|
||||||
|
description:
|
||||||
|
'Champs métier (+ parent_user_id côté staff). Fichier optionnel `photo` en multipart.',
|
||||||
|
type: CreateEnfantsDto,
|
||||||
|
})
|
||||||
|
@UseInterceptors(OptionalEnfantPhotoInterceptor)
|
||||||
create(
|
create(
|
||||||
@Body() dto: CreateEnfantsDto,
|
@Body() dto: CreateEnfantsDto,
|
||||||
@UploadedFile() photo: Express.Multer.File,
|
@UploadedFile() photo: Express.Multer.File,
|
||||||
@@ -83,19 +140,54 @@ export class EnfantsController {
|
|||||||
return this.enfantsService.findOne(id, currentUser);
|
return this.enfantsService.findOne(id, currentUser);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.ADMINISTRATEUR, RoleType.SUPER_ADMIN, RoleType.PARENT)
|
@Roles(
|
||||||
|
RoleType.PARENT,
|
||||||
|
RoleType.ADMINISTRATEUR,
|
||||||
|
RoleType.SUPER_ADMIN,
|
||||||
|
RoleType.GESTIONNAIRE,
|
||||||
|
)
|
||||||
@Patch(':id')
|
@Patch(':id')
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Mettre à jour un enfant',
|
||||||
|
description:
|
||||||
|
'JSON sans photo OK ; avec nouvelle photo → multipart (champ fichier `photo`, max 5 Mo).',
|
||||||
|
})
|
||||||
|
@ApiConsumes('application/json', 'multipart/form-data')
|
||||||
|
@UseInterceptors(OptionalEnfantPhotoInterceptor)
|
||||||
update(
|
update(
|
||||||
@Param('id', new ParseUUIDPipe()) id: string,
|
@Param('id', new ParseUUIDPipe()) id: string,
|
||||||
@Body() dto: UpdateEnfantsDto,
|
@Body() dto: UpdateEnfantsDto,
|
||||||
|
@UploadedFile() photo: Express.Multer.File,
|
||||||
@User() currentUser: Users,
|
@User() currentUser: Users,
|
||||||
) {
|
) {
|
||||||
return this.enfantsService.update(id, dto, currentUser);
|
return this.enfantsService.update(id, dto, currentUser, photo);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN)
|
@Roles(
|
||||||
|
RoleType.SUPER_ADMIN,
|
||||||
|
RoleType.ADMINISTRATEUR,
|
||||||
|
RoleType.GESTIONNAIRE,
|
||||||
|
)
|
||||||
@Delete(':id')
|
@Delete(':id')
|
||||||
remove(@Param('id', new ParseUUIDPipe()) id: string) {
|
@ApiOperation({
|
||||||
return this.enfantsService.remove(id);
|
summary: 'Supprimer un enfant (#159)',
|
||||||
|
description:
|
||||||
|
'Query `deleteDossier=true` si dernier enfant et suppression du dossier famille souhaitée.',
|
||||||
|
})
|
||||||
|
@ApiQuery({
|
||||||
|
name: 'deleteDossier',
|
||||||
|
required: false,
|
||||||
|
description: 'Si true et dernier enfant : cascade dossier famille',
|
||||||
|
})
|
||||||
|
remove(
|
||||||
|
@Param('id', new ParseUUIDPipe()) id: string,
|
||||||
|
@Query('deleteDossier') deleteDossier: string | undefined,
|
||||||
|
@User() currentUser: Users,
|
||||||
|
) {
|
||||||
|
const flag =
|
||||||
|
deleteDossier === 'true' ||
|
||||||
|
deleteDossier === '1' ||
|
||||||
|
deleteDossier === 'yes';
|
||||||
|
return this.suppressionService.deleteEnfant(id, flag, currentUser);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,13 +6,16 @@ import { Children } from 'src/entities/children.entity';
|
|||||||
import { Parents } from 'src/entities/parents.entity';
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
import { AuthModule } from '../auth/auth.module';
|
import { AuthModule } from '../auth/auth.module';
|
||||||
|
import { SuppressionsModule } from '../suppressions/suppressions.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([Children, Parents, ParentsChildren]),
|
imports: [
|
||||||
AuthModule
|
TypeOrmModule.forFeature([Children, Parents, ParentsChildren]),
|
||||||
|
AuthModule,
|
||||||
|
SuppressionsModule,
|
||||||
],
|
],
|
||||||
controllers: [EnfantsController],
|
controllers: [EnfantsController],
|
||||||
providers: [EnfantsService]
|
providers: [EnfantsService],
|
||||||
|
exports: [EnfantsService],
|
||||||
})
|
})
|
||||||
export class EnfantsModule { }
|
export class EnfantsModule { }
|
||||||
|
|||||||
@@ -13,6 +13,12 @@ import { ParentsChildren } from 'src/entities/parents_children.entity';
|
|||||||
import { RoleType, Users } from 'src/entities/users.entity';
|
import { RoleType, Users } from 'src/entities/users.entity';
|
||||||
import { CreateEnfantsDto } from './dto/create_enfants.dto';
|
import { CreateEnfantsDto } from './dto/create_enfants.dto';
|
||||||
|
|
||||||
|
const STAFF_ROLES: RoleType[] = [
|
||||||
|
RoleType.GESTIONNAIRE,
|
||||||
|
RoleType.ADMINISTRATEUR,
|
||||||
|
RoleType.SUPER_ADMIN,
|
||||||
|
];
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class EnfantsService {
|
export class EnfantsService {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -24,20 +30,35 @@ export class EnfantsService {
|
|||||||
private readonly parentsChildrenRepository: Repository<ParentsChildren>,
|
private readonly parentsChildrenRepository: Repository<ParentsChildren>,
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
// Création d'un enfant
|
private isStaff(user: Users): boolean {
|
||||||
async create(dto: CreateEnfantsDto, currentUser: Users, photoFile?: Express.Multer.File): Promise<Children> {
|
return STAFF_ROLES.includes(user.role);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Création d'un enfant.
|
||||||
|
* - PARENT : rattache au parent connecté (multipart photo optionnel).
|
||||||
|
* - Staff : `parent_user_id` obligatoire ; JSON sans photo OK ;
|
||||||
|
* avec photo → multipart (même stockage `/uploads/photos/...`). Ticket #132.
|
||||||
|
*/
|
||||||
|
async create(
|
||||||
|
dto: CreateEnfantsDto,
|
||||||
|
currentUser: Users,
|
||||||
|
photoFile?: Express.Multer.File,
|
||||||
|
): Promise<Children> {
|
||||||
|
const pivotUserId = this.resolvePivotParentUserId(dto, currentUser);
|
||||||
|
|
||||||
const parent = await this.parentsRepository.findOne({
|
const parent = await this.parentsRepository.findOne({
|
||||||
where: { user_id: currentUser.id },
|
where: { user_id: pivotUserId },
|
||||||
relations: ['co_parent'],
|
relations: ['co_parent'],
|
||||||
});
|
});
|
||||||
if (!parent) throw new NotFoundException('Parent introuvable');
|
if (!parent) throw new NotFoundException('Parent introuvable');
|
||||||
|
|
||||||
// Vérif métier simple
|
// Vérif métier simple (aligné comportement historique parent)
|
||||||
if (dto.status !== StatutEnfantType.A_NAITRE && !dto.birth_date) {
|
if (dto.status !== StatutEnfantType.A_NAITRE && !dto.birth_date) {
|
||||||
throw new BadRequestException('Un enfant actif doit avoir une date de naissance');
|
throw new BadRequestException('Un enfant né doit avoir une date de naissance');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Vérif doublon éventuel (ex: même prénom + date de naissance pour ce parent)
|
// Vérif doublon éventuel (ex: même prénom + date de naissance)
|
||||||
const exist = await this.childrenRepository.findOne({
|
const exist = await this.childrenRepository.findOne({
|
||||||
where: {
|
where: {
|
||||||
first_name: dto.first_name,
|
first_name: dto.first_name,
|
||||||
@@ -47,50 +68,107 @@ export class EnfantsService {
|
|||||||
});
|
});
|
||||||
if (exist) throw new ConflictException('Cet enfant existe déjà');
|
if (exist) throw new ConflictException('Cet enfant existe déjà');
|
||||||
|
|
||||||
// Gestion de la photo uploadée
|
// Gestion de la photo uploadée (multipart parent ou staff)
|
||||||
|
let photoUrl = dto.photo_url;
|
||||||
|
let consentAt: Date | undefined;
|
||||||
if (photoFile) {
|
if (photoFile) {
|
||||||
dto.photo_url = `/uploads/photos/${photoFile.filename}`;
|
photoUrl = `/uploads/photos/${photoFile.filename}`;
|
||||||
if (dto.consent_photo) {
|
if (dto.consent_photo) {
|
||||||
dto.consent_photo_at = new Date().toISOString();
|
consentAt = new Date();
|
||||||
}
|
}
|
||||||
|
} else if (dto.consent_photo) {
|
||||||
|
consentAt = dto.consent_photo_at
|
||||||
|
? new Date(dto.consent_photo_at)
|
||||||
|
: new Date();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Création
|
const child = this.childrenRepository.create({
|
||||||
const child = this.childrenRepository.create(dto);
|
status: dto.status,
|
||||||
|
first_name: dto.first_name,
|
||||||
|
last_name: dto.last_name,
|
||||||
|
gender: dto.gender,
|
||||||
|
birth_date: dto.birth_date ? new Date(dto.birth_date) : undefined,
|
||||||
|
due_date: dto.due_date ? new Date(dto.due_date) : undefined,
|
||||||
|
photo_url: photoUrl,
|
||||||
|
consent_photo: !!dto.consent_photo,
|
||||||
|
consent_photo_at: consentAt,
|
||||||
|
});
|
||||||
await this.childrenRepository.save(child);
|
await this.childrenRepository.save(child);
|
||||||
|
|
||||||
// Lien parent-enfant (Parent 1)
|
// Lien parent-enfant (pivot)
|
||||||
const parentLink = this.parentsChildrenRepository.create({
|
await this.parentsChildrenRepository.save(
|
||||||
|
this.parentsChildrenRepository.create({
|
||||||
parentId: parent.user_id,
|
parentId: parent.user_id,
|
||||||
enfantId: child.id,
|
enfantId: child.id,
|
||||||
});
|
}),
|
||||||
await this.parentsChildrenRepository.save(parentLink);
|
);
|
||||||
|
|
||||||
// Rattachement automatique au co-parent s'il existe
|
// Rattachement automatique au co-parent s'il existe
|
||||||
if (parent.co_parent) {
|
if (parent.co_parent) {
|
||||||
const coParentLink = this.parentsChildrenRepository.create({
|
await this.parentsChildrenRepository.save(
|
||||||
|
this.parentsChildrenRepository.create({
|
||||||
parentId: parent.co_parent.id,
|
parentId: parent.co_parent.id,
|
||||||
enfantId: child.id,
|
enfantId: child.id,
|
||||||
});
|
}),
|
||||||
await this.parentsChildrenRepository.save(coParentLink);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.findOne(child.id, currentUser);
|
return this.findOne(child.id, currentUser);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Liste des enfants
|
private resolvePivotParentUserId(
|
||||||
async findAll(): Promise<Children[]> {
|
dto: CreateEnfantsDto,
|
||||||
return this.childrenRepository.find({
|
currentUser: Users,
|
||||||
relations: ['parentLinks'],
|
): string {
|
||||||
order: { last_name: 'ASC', first_name: 'ASC' },
|
if (this.isStaff(currentUser)) {
|
||||||
|
const id = dto.parent_user_id?.trim();
|
||||||
|
if (!id) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'parent_user_id est obligatoire pour créer un enfant (staff)',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentUser.role === RoleType.PARENT) {
|
||||||
|
if (
|
||||||
|
dto.parent_user_id &&
|
||||||
|
dto.parent_user_id.trim() !== currentUser.id
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Un parent ne peut pas créer un enfant pour un autre compte',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return currentUser.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new ForbiddenException('Accès interdit');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Flag API #157 — true si aucun lien enfants_parents. */
|
||||||
|
private withSansResponsable(child: Children): Children & { sans_responsable: boolean } {
|
||||||
|
return Object.assign(child, {
|
||||||
|
sans_responsable: !child.parentLinks || child.parentLinks.length === 0,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Liste des enfants (admin/gestionnaire) — inclut les orphelins (parentLinks: [])
|
||||||
|
async findAll(): Promise<Array<Children & { sans_responsable: boolean }>> {
|
||||||
|
const children = await this.childrenRepository.find({
|
||||||
|
relations: ['parentLinks', 'parentLinks.parent', 'parentLinks.parent.user'],
|
||||||
|
order: { last_name: 'ASC', first_name: 'ASC' },
|
||||||
|
});
|
||||||
|
return children.map((c) => this.withSansResponsable(c));
|
||||||
|
}
|
||||||
|
|
||||||
// Récupérer un enfant par id
|
// Récupérer un enfant par id
|
||||||
async findOne(id: string, currentUser: Users): Promise<Children> {
|
async findOne(
|
||||||
|
id: string,
|
||||||
|
currentUser: Users,
|
||||||
|
): Promise<Children & { sans_responsable: boolean }> {
|
||||||
const child = await this.childrenRepository.findOne({
|
const child = await this.childrenRepository.findOne({
|
||||||
where: { id },
|
where: { id },
|
||||||
relations: ['parentLinks'],
|
relations: ['parentLinks', 'parentLinks.parent', 'parentLinks.parent.user'],
|
||||||
});
|
});
|
||||||
if (!child) throw new NotFoundException('Enfant introuvable');
|
if (!child) throw new NotFoundException('Enfant introuvable');
|
||||||
|
|
||||||
@@ -104,23 +182,42 @@ export class EnfantsService {
|
|||||||
case RoleType.ADMINISTRATEUR:
|
case RoleType.ADMINISTRATEUR:
|
||||||
case RoleType.SUPER_ADMIN:
|
case RoleType.SUPER_ADMIN:
|
||||||
case RoleType.GESTIONNAIRE:
|
case RoleType.GESTIONNAIRE:
|
||||||
// accès complet
|
// accès complet (y compris orphelins)
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
throw new ForbiddenException('Accès interdit');
|
throw new ForbiddenException('Accès interdit');
|
||||||
}
|
}
|
||||||
|
|
||||||
return child;
|
return this.withSansResponsable(child);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Mise à jour
|
// Mise à jour
|
||||||
async update(id: string, dto: Partial<CreateEnfantsDto>, currentUser: Users): Promise<Children> {
|
async update(
|
||||||
|
id: string,
|
||||||
|
dto: Partial<CreateEnfantsDto>,
|
||||||
|
currentUser: Users,
|
||||||
|
photoFile?: Express.Multer.File,
|
||||||
|
): Promise<Children> {
|
||||||
const child = await this.childrenRepository.findOne({ where: { id } });
|
const child = await this.childrenRepository.findOne({ where: { id } });
|
||||||
if (!child) throw new NotFoundException('Enfant introuvable');
|
if (!child) throw new NotFoundException('Enfant introuvable');
|
||||||
|
|
||||||
await this.childrenRepository.update(id, dto);
|
const { parent_user_id: _ignored, ...rest } = dto;
|
||||||
|
const patch: Partial<Children> = { ...rest } as Partial<Children>;
|
||||||
|
if (dto.consent_photo !== undefined) {
|
||||||
|
patch.consent_photo = dto.consent_photo;
|
||||||
|
patch.consent_photo_at = dto.consent_photo ? new Date() : null!;
|
||||||
|
}
|
||||||
|
if (photoFile) {
|
||||||
|
patch.photo_url = `/uploads/photos/${photoFile.filename}`;
|
||||||
|
if (dto.consent_photo !== false) {
|
||||||
|
patch.consent_photo = true;
|
||||||
|
patch.consent_photo_at = new Date();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.childrenRepository.update(id, patch);
|
||||||
return this.findOne(id, currentUser);
|
return this.findOne(id, currentUser);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
/** Identité minimale enfant pour le bandeau couple — ticket #168 */
|
||||||
|
export class CoupleGardeEnfantDto {
|
||||||
|
@ApiProperty({ format: 'uuid' })
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
prenom?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
nom?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
photo_url?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Identité minimale AM pour le bandeau couple — ticket #168 */
|
||||||
|
export class CoupleGardeAmDto {
|
||||||
|
@ApiProperty({ format: 'uuid', description: 'UUID utilisateur de l’AM' })
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
prenom?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
nom?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
photo_url?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Un couple de garde = placement actif enfant ↔ AM */
|
||||||
|
export class CoupleGardeDto {
|
||||||
|
@ApiProperty({
|
||||||
|
format: 'uuid',
|
||||||
|
description: 'Id du placement (enfants_assistantes_maternelles.id)',
|
||||||
|
})
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@ApiProperty({ type: CoupleGardeEnfantDto })
|
||||||
|
enfant: CoupleGardeEnfantDto;
|
||||||
|
|
||||||
|
@ApiProperty({ type: CoupleGardeAmDto })
|
||||||
|
am: CoupleGardeAmDto;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'True si c’est le couple actuellement sélectionné' })
|
||||||
|
courant: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CouplesGardeResponseDto {
|
||||||
|
@ApiProperty({ type: [CoupleGardeDto] })
|
||||||
|
couples: CoupleGardeDto[];
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
format: 'uuid',
|
||||||
|
nullable: true,
|
||||||
|
description: 'Id du couple courant (null si aucun / premier couple implicite côté client)',
|
||||||
|
})
|
||||||
|
couple_courant_id: string | null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsNotEmpty, IsUUID } from 'class-validator';
|
||||||
|
|
||||||
|
/** Corps PUT couple de garde courant — ticket #168 */
|
||||||
|
export class DefinirCoupleGardeCourantDto {
|
||||||
|
@ApiProperty({
|
||||||
|
format: 'uuid',
|
||||||
|
description: 'Id du placement (enfants_assistantes_maternelles.id) à sélectionner',
|
||||||
|
})
|
||||||
|
@IsUUID()
|
||||||
|
@IsNotEmpty()
|
||||||
|
couple_id: string;
|
||||||
|
}
|
||||||
@@ -7,6 +7,12 @@ export class ParentPendingSummaryDto {
|
|||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
email: string;
|
email: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ nullable: true })
|
||||||
|
nom?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ nullable: true })
|
||||||
|
prenom?: string | null;
|
||||||
|
|
||||||
@ApiPropertyOptional({ nullable: true })
|
@ApiPropertyOptional({ nullable: true })
|
||||||
telephone?: string | null;
|
telephone?: string | null;
|
||||||
|
|
||||||
@@ -18,7 +24,10 @@ export class ParentPendingSummaryDto {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class PendingFamilyDto {
|
export class PendingFamilyDto {
|
||||||
@ApiProperty({ example: 'Famille Dupont', description: 'Libellé affiché pour la famille' })
|
@ApiProperty({
|
||||||
|
example: 'MARTIN Claire - MARTIN Thomas',
|
||||||
|
description: 'Libellé affiché : NOM Prénom (séparés par « - » si co-parent)',
|
||||||
|
})
|
||||||
libelle: string;
|
libelle: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
/** Réponse 201 POST /parents/:id/co-parent (#135). */
|
||||||
|
export class StaffAddCoParentResponseDto {
|
||||||
|
@ApiProperty()
|
||||||
|
message: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2026-000043' })
|
||||||
|
numero_dossier: string;
|
||||||
|
|
||||||
|
@ApiProperty({ format: 'uuid', description: 'UUID du parent pivot' })
|
||||||
|
parent_user_id: string;
|
||||||
|
|
||||||
|
@ApiProperty({ format: 'uuid', description: 'UUID du co-parent créé' })
|
||||||
|
co_parent_user_id: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
enum: StatutUtilisateurType,
|
||||||
|
example: StatutUtilisateurType.ACTIF,
|
||||||
|
})
|
||||||
|
statut: StatutUtilisateurType;
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import {
|
||||||
|
IsBoolean,
|
||||||
|
IsEmail,
|
||||||
|
IsNotEmpty,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
Matches,
|
||||||
|
MaxLength,
|
||||||
|
MinLength,
|
||||||
|
} from 'class-validator';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ajout d’un co-parent sur un foyer existant (staff) — ticket #135.
|
||||||
|
* Corps sans préfixe `co_parent_*` (l’URL cible déjà le pivot).
|
||||||
|
*/
|
||||||
|
export class StaffAddCoParentDto {
|
||||||
|
@ApiProperty({ example: 'thomas.martin@ptits-pas.fr' })
|
||||||
|
@IsEmail({}, { message: 'Email invalide' })
|
||||||
|
@IsNotEmpty({ message: "L'email est requis" })
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'Thomas' })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty({ message: 'Le prénom est requis' })
|
||||||
|
@MinLength(2)
|
||||||
|
@MaxLength(100)
|
||||||
|
prenom: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'MARTIN' })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty({ message: 'Le nom est requis' })
|
||||||
|
@MinLength(2)
|
||||||
|
@MaxLength(100)
|
||||||
|
nom: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '0678456789' })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty({ message: 'Le téléphone est requis' })
|
||||||
|
@Matches(/^(\+33|0)[1-9](\d{2}){4}$/, {
|
||||||
|
message: 'Le numéro de téléphone doit être valide (ex: 0689567890 ou +33689567890)',
|
||||||
|
})
|
||||||
|
telephone: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
example: true,
|
||||||
|
description: 'Si true, copie l’adresse du parent pivot',
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
meme_adresse?: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
adresse?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(10)
|
||||||
|
code_postal?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(150)
|
||||||
|
ville?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
/** Réponse 201 POST /parents/dossier (#129). */
|
||||||
|
export class StaffCreateParentDossierResponseDto {
|
||||||
|
@ApiProperty()
|
||||||
|
message: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: '2026-000043',
|
||||||
|
description: 'Numéro de dossier famille attribué',
|
||||||
|
})
|
||||||
|
numero_dossier: string;
|
||||||
|
|
||||||
|
@ApiProperty({ format: 'uuid', description: 'UUID user du parent pivot' })
|
||||||
|
parent_user_id: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
format: 'uuid',
|
||||||
|
nullable: true,
|
||||||
|
description: 'UUID user du co-parent, ou null',
|
||||||
|
})
|
||||||
|
co_parent_user_id: string | null;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
enum: StatutUtilisateurType,
|
||||||
|
example: StatutUtilisateurType.ACTIF,
|
||||||
|
})
|
||||||
|
statut: StatutUtilisateurType;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
type: [String],
|
||||||
|
format: 'uuid',
|
||||||
|
description: 'IDs des enfants créés',
|
||||||
|
})
|
||||||
|
enfant_ids: string[];
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { ApiPropertyOptional, OmitType } from '@nestjs/swagger';
|
||||||
|
import { IsBoolean, IsOptional } from 'class-validator';
|
||||||
|
import { RegisterParentCompletDto } from 'src/routes/auth/dto/register-parent-complet.dto';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Création dossier parent/famille par staff (#129).
|
||||||
|
* Mêmes champs que l'inscription publique, sans CGU/privacy obligatoires
|
||||||
|
* (acceptées côté serveur pour le compte du gestionnaire).
|
||||||
|
*/
|
||||||
|
export class StaffCreateParentDossierDto extends OmitType(RegisterParentCompletDto, [
|
||||||
|
'acceptation_cgu',
|
||||||
|
'acceptation_privacy',
|
||||||
|
] as const) {
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Ignoré côté staff (CGU acceptées serveur). Conservé pour compat éventuelle.',
|
||||||
|
default: true,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
acceptation_cgu?: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Ignoré côté staff (privacy acceptée serveur).',
|
||||||
|
default: true,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
acceptation_privacy?: boolean;
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import {
|
||||||
|
IsEmail,
|
||||||
|
IsEnum,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
MaxLength,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
/** Mise à jour fiche parent par admin/gestionnaire (doc 28 §6.1, ticket #131). */
|
||||||
|
export class UpdateParentFicheAdminDto {
|
||||||
|
@ApiPropertyOptional({ example: 'Dupont' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(100)
|
||||||
|
nom?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'Marie' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(100)
|
||||||
|
prenom?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'marie.dupont@example.com' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsEmail()
|
||||||
|
email?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: '+33612345678' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(20)
|
||||||
|
telephone?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: '10 rue de la Paix' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
adresse?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'Paris' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(150)
|
||||||
|
ville?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: '75001' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(10)
|
||||||
|
code_postal?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ enum: StatutUtilisateurType })
|
||||||
|
@IsOptional()
|
||||||
|
@IsEnum(StatutUtilisateurType)
|
||||||
|
statut?: StatutUtilisateurType;
|
||||||
|
}
|
||||||
@@ -1,18 +1,132 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { ParentsController } from './parents.controller';
|
import { ParentsController } from './parents.controller';
|
||||||
|
import { ParentsService } from './parents.service';
|
||||||
|
import { UserService } from '../user/user.service';
|
||||||
|
import { AuthService } from '../auth/auth.service';
|
||||||
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
describe('ParentsController', () => {
|
describe('ParentsController', () => {
|
||||||
let controller: ParentsController;
|
let controller: ParentsController;
|
||||||
|
const authServiceMock = {
|
||||||
|
createParentDossierStaff: jest.fn(),
|
||||||
|
addCoParentStaff: jest.fn(),
|
||||||
|
};
|
||||||
|
const parentsServiceMock = {
|
||||||
|
listerCouplesGarde: jest.fn(),
|
||||||
|
definirCoupleGardeCourant: jest.fn(),
|
||||||
|
};
|
||||||
|
const userServiceMock = {};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
controllers: [ParentsController],
|
controllers: [ParentsController],
|
||||||
}).compile();
|
providers: [
|
||||||
|
{ provide: ParentsService, useValue: parentsServiceMock },
|
||||||
|
{ provide: UserService, useValue: userServiceMock },
|
||||||
|
{ provide: AuthService, useValue: authServiceMock },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.overrideGuard(AuthGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.overrideGuard(RolesGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.compile();
|
||||||
|
|
||||||
controller = module.get<ParentsController>(ParentsController);
|
controller = module.get<ParentsController>(ParentsController);
|
||||||
|
jest.clearAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('should be defined', () => {
|
||||||
expect(controller).toBeDefined();
|
expect(controller).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('listerCouplesGarde délègue au service (#168)', async () => {
|
||||||
|
parentsServiceMock.listerCouplesGarde.mockResolvedValue({
|
||||||
|
couples: [],
|
||||||
|
couple_courant_id: null,
|
||||||
|
});
|
||||||
|
const res = await controller.listerCouplesGarde('parent-uuid');
|
||||||
|
expect(parentsServiceMock.listerCouplesGarde).toHaveBeenCalledWith('parent-uuid');
|
||||||
|
expect(res.couples).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('definirCoupleGardeCourant délègue au service (#168)', async () => {
|
||||||
|
parentsServiceMock.definirCoupleGardeCourant.mockResolvedValue({
|
||||||
|
couples: [{ id: 'pl-1', courant: true }],
|
||||||
|
couple_courant_id: 'pl-1',
|
||||||
|
});
|
||||||
|
const res = await controller.definirCoupleGardeCourant('parent-uuid', {
|
||||||
|
couple_id: 'pl-1',
|
||||||
|
});
|
||||||
|
expect(parentsServiceMock.definirCoupleGardeCourant).toHaveBeenCalledWith(
|
||||||
|
'parent-uuid',
|
||||||
|
'pl-1',
|
||||||
|
);
|
||||||
|
expect(res.couple_courant_id).toBe('pl-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('createDossier delegates to authService.createParentDossierStaff with CGU accepted', async () => {
|
||||||
|
authServiceMock.createParentDossierStaff.mockResolvedValue({
|
||||||
|
message: 'Dossier famille créé et validé. Un e-mail de création de mot de passe a été envoyé.',
|
||||||
|
parent_user_id: 'p1',
|
||||||
|
co_parent_user_id: 'p2',
|
||||||
|
enfant_ids: ['e1'],
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
numero_dossier: '2026-000043',
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = {
|
||||||
|
email: 'parent.staff@test.fr',
|
||||||
|
prenom: 'Claire',
|
||||||
|
nom: 'MARTIN',
|
||||||
|
telephone: '0689567890',
|
||||||
|
enfants: [
|
||||||
|
{
|
||||||
|
prenom: 'Emma',
|
||||||
|
nom: 'MARTIN',
|
||||||
|
date_naissance: '2023-02-15',
|
||||||
|
genre: 'F',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const res = await controller.createDossier(body as any);
|
||||||
|
expect(authServiceMock.createParentDossierStaff).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
email: body.email,
|
||||||
|
acceptation_cgu: true,
|
||||||
|
acceptation_privacy: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(res.numero_dossier).toBe('2026-000043');
|
||||||
|
expect(res.parent_user_id).toBe('p1');
|
||||||
|
expect(res.co_parent_user_id).toBe('p2');
|
||||||
|
expect(res.enfant_ids).toEqual(['e1']);
|
||||||
|
expect(res.statut).toBe(StatutUtilisateurType.ACTIF);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('addCoParent delegates to authService.addCoParentStaff', async () => {
|
||||||
|
authServiceMock.addCoParentStaff.mockResolvedValue({
|
||||||
|
message: 'ok',
|
||||||
|
numero_dossier: '2026-000043',
|
||||||
|
parent_user_id: 'p1',
|
||||||
|
co_parent_user_id: 'p2',
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = {
|
||||||
|
email: 'coparent@test.fr',
|
||||||
|
prenom: 'Thomas',
|
||||||
|
nom: 'MARTIN',
|
||||||
|
telephone: '0678456789',
|
||||||
|
meme_adresse: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const res = await controller.addCoParent('p1', body as any);
|
||||||
|
expect(authServiceMock.addCoParentStaff).toHaveBeenCalledWith('p1', body);
|
||||||
|
expect(res.co_parent_user_id).toBe('p2');
|
||||||
|
expect(res.statut).toBe(StatutUtilisateurType.ACTIF);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,36 +1,126 @@
|
|||||||
import {
|
import {
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
|
Delete,
|
||||||
Get,
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
Param,
|
Param,
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
|
Put,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ParentsService } from './parents.service';
|
import { ParentsService } from './parents.service';
|
||||||
import { UserService } from '../user/user.service';
|
import { UserService } from '../user/user.service';
|
||||||
|
import { AuthService } from '../auth/auth.service';
|
||||||
import { Parents } from 'src/entities/parents.entity';
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
import { Users } from 'src/entities/users.entity';
|
import { Users } from 'src/entities/users.entity';
|
||||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||||
import { RoleType, StatutUtilisateurType } from 'src/entities/users.entity';
|
import { RoleType, StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
import { ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiBody,
|
||||||
|
ApiOperation,
|
||||||
|
ApiParam,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from '@nestjs/swagger';
|
||||||
import { CreateParentDto } from '../user/dto/create_parent.dto';
|
import { CreateParentDto } from '../user/dto/create_parent.dto';
|
||||||
import { UpdateParentsDto } from '../user/dto/update_parent.dto';
|
import { UpdateParentsDto } from '../user/dto/update_parent.dto';
|
||||||
|
import { UpdateParentFicheAdminDto } from './dto/update-parent-fiche-admin.dto';
|
||||||
|
import { StaffCreateParentDossierDto } from './dto/staff-create-parent-dossier.dto';
|
||||||
|
import { StaffCreateParentDossierResponseDto } from './dto/staff-create-parent-dossier-response.dto';
|
||||||
|
import { StaffAddCoParentDto } from './dto/staff-add-co-parent.dto';
|
||||||
|
import { StaffAddCoParentResponseDto } from './dto/staff-add-co-parent-response.dto';
|
||||||
|
import { RegisterParentCompletDto } from '../auth/dto/register-parent-complet.dto';
|
||||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
import { User } from 'src/common/decorators/user.decorator';
|
import { User } from 'src/common/decorators/user.decorator';
|
||||||
import { PendingFamilyDto } from './dto/pending-family.dto';
|
import { PendingFamilyDto } from './dto/pending-family.dto';
|
||||||
import { DossierFamilleCompletDto } from './dto/dossier-famille-complet.dto';
|
import { DossierFamilleCompletDto } from './dto/dossier-famille-complet.dto';
|
||||||
|
import { mapParentForApi, mapParentsForApi } from './parents.mapper';
|
||||||
|
import { CouplesGardeResponseDto } from './dto/couples-garde.dto';
|
||||||
|
import { DefinirCoupleGardeCourantDto } from './dto/definir-couple-garde-courant.dto';
|
||||||
|
|
||||||
@ApiTags('Parents')
|
@ApiTags('Parents')
|
||||||
|
@ApiBearerAuth('access-token')
|
||||||
@Controller('parents')
|
@Controller('parents')
|
||||||
@UseGuards(AuthGuard, RolesGuard)
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
export class ParentsController {
|
export class ParentsController {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly parentsService: ParentsService,
|
private readonly parentsService: ParentsService,
|
||||||
private readonly userService: UserService,
|
private readonly userService: UserService,
|
||||||
|
private readonly authService: AuthService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
@Get('me/couples-garde')
|
||||||
|
@Roles(RoleType.PARENT)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Lister les couples de garde du parent connecté — ticket #168',
|
||||||
|
description:
|
||||||
|
'Retourne les placements actifs enfant↔AM rattachés au parent, ' +
|
||||||
|
'avec indication du couple courant (bandeau TdB quotidien).',
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: 200, type: CouplesGardeResponseDto })
|
||||||
|
@ApiResponse({ status: 403, description: 'Réservé au rôle parent' })
|
||||||
|
@ApiResponse({ status: 404, description: 'Parent introuvable' })
|
||||||
|
listerCouplesGarde(@User('id') userId: string): Promise<CouplesGardeResponseDto> {
|
||||||
|
return this.parentsService.listerCouplesGarde(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('me/couples-garde/courant')
|
||||||
|
@Roles(RoleType.PARENT)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Définir le couple de garde courant — ticket #168',
|
||||||
|
description:
|
||||||
|
'Persiste la préférence de couple actif (enfant|nounou) pour contextualiser le TdB.',
|
||||||
|
})
|
||||||
|
@ApiBody({ type: DefinirCoupleGardeCourantDto })
|
||||||
|
@ApiResponse({ status: 200, type: CouplesGardeResponseDto })
|
||||||
|
@ApiResponse({ status: 400, description: 'Couple hors périmètre du parent' })
|
||||||
|
@ApiResponse({ status: 404, description: 'Parent ou couple introuvable' })
|
||||||
|
definirCoupleGardeCourant(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@Body() dto: DefinirCoupleGardeCourantDto,
|
||||||
|
): Promise<CouplesGardeResponseDto> {
|
||||||
|
return this.parentsService.definirCoupleGardeCourant(userId, dto.couple_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
|
@Post('dossier')
|
||||||
|
@HttpCode(HttpStatus.CREATED)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Créer un dossier famille/parent complet (staff) — ticket #129',
|
||||||
|
description:
|
||||||
|
'Crée parent (+ co-parent optionnel) + enfants + n° dossier avec statut actif, ' +
|
||||||
|
'et envoie l’e-mail de création de mot de passe. ' +
|
||||||
|
'Ne pas utiliser POST /auth/register/parent depuis le dashboard.',
|
||||||
|
})
|
||||||
|
@ApiBody({ type: StaffCreateParentDossierDto })
|
||||||
|
@ApiResponse({ status: 201, type: StaffCreateParentDossierResponseDto })
|
||||||
|
@ApiResponse({ status: 400, description: 'Validation DTO / métier' })
|
||||||
|
@ApiResponse({ status: 403, description: 'Rôle non autorisé' })
|
||||||
|
@ApiResponse({ status: 409, description: 'Email pivot et/ou co-parent déjà pris' })
|
||||||
|
async createDossier(
|
||||||
|
@Body() dto: StaffCreateParentDossierDto,
|
||||||
|
): Promise<StaffCreateParentDossierResponseDto> {
|
||||||
|
const registerDto = {
|
||||||
|
...dto,
|
||||||
|
acceptation_cgu: true,
|
||||||
|
acceptation_privacy: true,
|
||||||
|
} as RegisterParentCompletDto;
|
||||||
|
const result = await this.authService.createParentDossierStaff(registerDto);
|
||||||
|
return {
|
||||||
|
message: result.message,
|
||||||
|
numero_dossier: result.numero_dossier,
|
||||||
|
parent_user_id: result.parent_user_id,
|
||||||
|
co_parent_user_id: result.co_parent_user_id ?? null,
|
||||||
|
statut: result.statut,
|
||||||
|
enfant_ids: result.enfant_ids,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
@Get('pending-families')
|
@Get('pending-families')
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
@ApiOperation({ summary: 'Liste des familles en attente (une entrée par famille)' })
|
@ApiOperation({ summary: 'Liste des familles en attente (une entrée par famille)' })
|
||||||
@@ -79,21 +169,25 @@ export class ParentsController {
|
|||||||
return validated;
|
return validated;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
|
||||||
@Get()
|
@Get()
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
|
@ApiOperation({ summary: 'Liste des parents (user, co_parent, parentChildren) — ticket #131' })
|
||||||
@ApiResponse({ status: 200, type: [Parents], description: 'Liste des parents' })
|
@ApiResponse({ status: 200, type: [Parents], description: 'Liste des parents' })
|
||||||
@ApiResponse({ status: 403, description: 'Accès refusé !' })
|
@ApiResponse({ status: 403, description: 'Accès refusé !' })
|
||||||
getAll(): Promise<Parents[]> {
|
async getAll(): Promise<Parents[]> {
|
||||||
return this.parentsService.findAll();
|
const parents = await this.parentsService.findAll();
|
||||||
|
return mapParentsForApi(parents);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
@Get(':id')
|
@Get(':id')
|
||||||
|
@ApiOperation({ summary: 'Détail parent par user_id (inclut co_parent si id_co_parent renseigné) — ticket #131' })
|
||||||
@ApiResponse({ status: 200, type: Parents, description: 'Détails du parent par ID utilisateur' })
|
@ApiResponse({ status: 200, type: Parents, description: 'Détails du parent par ID utilisateur' })
|
||||||
@ApiResponse({ status: 404, description: 'Parent non trouvé' })
|
@ApiResponse({ status: 404, description: 'Parent non trouvé' })
|
||||||
@ApiResponse({ status: 403, description: 'Accès refusé !' })
|
@ApiResponse({ status: 403, description: 'Accès refusé !' })
|
||||||
getOne(@Param('id') user_id: string): Promise<Parents> {
|
async getOne(@Param('id') user_id: string): Promise<Parents> {
|
||||||
return this.parentsService.findOne(user_id);
|
const parent = await this.parentsService.findOne(user_id);
|
||||||
|
return mapParentForApi(parent);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||||
@@ -101,8 +195,73 @@ export class ParentsController {
|
|||||||
@ApiBody({ type: CreateParentDto })
|
@ApiBody({ type: CreateParentDto })
|
||||||
@ApiResponse({ status: 201, type: Parents, description: 'Parent créé avec succès' })
|
@ApiResponse({ status: 201, type: Parents, description: 'Parent créé avec succès' })
|
||||||
@ApiResponse({ status: 403, description: 'Accès refusé !' })
|
@ApiResponse({ status: 403, description: 'Accès refusé !' })
|
||||||
create(@Body() dto: CreateParentDto): Promise<Parents> {
|
async create(@Body() dto: CreateParentDto): Promise<Parents> {
|
||||||
return this.parentsService.create(dto);
|
const parent = await this.parentsService.create(dto);
|
||||||
|
return mapParentForApi(parent);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
|
@Patch(':id/fiche')
|
||||||
|
@ApiOperation({ summary: 'Mettre à jour la fiche parent (admin/gestionnaire) — ticket #131' })
|
||||||
|
@ApiParam({ name: 'id', description: "UUID utilisateur du parent" })
|
||||||
|
@ApiBody({ type: UpdateParentFicheAdminDto })
|
||||||
|
@ApiResponse({ status: 200, type: Parents, description: 'Fiche parent mise à jour' })
|
||||||
|
async updateFicheAdmin(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() dto: UpdateParentFicheAdminDto,
|
||||||
|
): Promise<Parents> {
|
||||||
|
const parent = await this.parentsService.updateFicheAdmin(id, dto);
|
||||||
|
return mapParentForApi(parent);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
|
@Post(':id/co-parent')
|
||||||
|
@HttpCode(HttpStatus.CREATED)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Ajouter un co-parent à un foyer existant (staff) — ticket #135',
|
||||||
|
description:
|
||||||
|
'Foyer mono-parent uniquement. Crée le co-parent actif, liens foyer + enfants, ' +
|
||||||
|
'e-mail de création de mot de passe. Ne pas utiliser POST /auth/register/parent.',
|
||||||
|
})
|
||||||
|
@ApiParam({ name: 'id', description: 'UUID utilisateur du parent pivot' })
|
||||||
|
@ApiBody({ type: StaffAddCoParentDto })
|
||||||
|
@ApiResponse({ status: 201, type: StaffAddCoParentResponseDto })
|
||||||
|
@ApiResponse({ status: 400, description: 'Foyer déjà à 2 parents / validation' })
|
||||||
|
@ApiResponse({ status: 404, description: 'Parent introuvable' })
|
||||||
|
@ApiResponse({ status: 409, description: 'Email déjà pris' })
|
||||||
|
async addCoParent(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() dto: StaffAddCoParentDto,
|
||||||
|
): Promise<StaffAddCoParentResponseDto> {
|
||||||
|
return this.authService.addCoParentStaff(id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
|
@Post(':id/enfants/:enfantId')
|
||||||
|
@ApiOperation({ summary: 'Rattacher un enfant à un parent — ticket #115' })
|
||||||
|
@ApiParam({ name: 'id', description: "UUID utilisateur du parent" })
|
||||||
|
@ApiParam({ name: 'enfantId', description: "UUID de l'enfant" })
|
||||||
|
@ApiResponse({ status: 200, type: Parents, description: 'Parent avec enfants mis à jour' })
|
||||||
|
async attachEnfant(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Param('enfantId') enfantId: string,
|
||||||
|
): Promise<Parents> {
|
||||||
|
const parent = await this.parentsService.attachEnfant(id, enfantId);
|
||||||
|
return mapParentForApi(parent);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
|
@Delete(':id/enfants/:enfantId')
|
||||||
|
@ApiOperation({ summary: "Détacher un enfant d'un parent — ticket #115" })
|
||||||
|
@ApiParam({ name: 'id', description: "UUID utilisateur du parent" })
|
||||||
|
@ApiParam({ name: 'enfantId', description: "UUID de l'enfant" })
|
||||||
|
@ApiResponse({ status: 200, type: Parents, description: 'Parent avec enfants mis à jour' })
|
||||||
|
async detachEnfant(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Param('enfantId') enfantId: string,
|
||||||
|
): Promise<Parents> {
|
||||||
|
const parent = await this.parentsService.detachEnfant(id, enfantId);
|
||||||
|
return mapParentForApi(parent);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||||
@@ -111,7 +270,8 @@ export class ParentsController {
|
|||||||
@ApiResponse({ status: 200, type: Parents, description: 'Parent mis à jour avec succès' })
|
@ApiResponse({ status: 200, type: Parents, description: 'Parent mis à jour avec succès' })
|
||||||
@ApiResponse({ status: 404, description: 'Parent introuvable' })
|
@ApiResponse({ status: 404, description: 'Parent introuvable' })
|
||||||
@ApiResponse({ status: 403, description: 'Accès refusé !' })
|
@ApiResponse({ status: 403, description: 'Accès refusé !' })
|
||||||
update(@Param('id') id: string, @Body() dto: UpdateParentsDto): Promise<Parents> {
|
async update(@Param('id') id: string, @Body() dto: UpdateParentsDto): Promise<Parents> {
|
||||||
return this.parentsService.update(id, dto);
|
const parent = await this.parentsService.update(id, dto);
|
||||||
|
return mapParentForApi(parent);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { mapParentForApi } from './parents.mapper';
|
||||||
|
import { Parents } from '../../entities/parents.entity';
|
||||||
|
import { RoleType, StatutUtilisateurType, Users } from '../../entities/users.entity';
|
||||||
|
|
||||||
|
describe('mapParentForApi', () => {
|
||||||
|
it('expose co_parent avec prenom/nom sans secrets', () => {
|
||||||
|
const coParent = {
|
||||||
|
id: 'cp1',
|
||||||
|
email: 'co@b.fr',
|
||||||
|
prenom: 'Clara',
|
||||||
|
nom: 'Co',
|
||||||
|
role: RoleType.PARENT,
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
password: 'secret',
|
||||||
|
} as Users;
|
||||||
|
|
||||||
|
const parent = {
|
||||||
|
user_id: 'u1',
|
||||||
|
numero_dossier: '2026-000042',
|
||||||
|
user: {
|
||||||
|
id: 'u1',
|
||||||
|
email: 'p@b.fr',
|
||||||
|
prenom: 'Paul',
|
||||||
|
nom: 'Parent',
|
||||||
|
role: RoleType.PARENT,
|
||||||
|
password: 'secret',
|
||||||
|
} as Users,
|
||||||
|
co_parent: coParent,
|
||||||
|
parentChildren: [],
|
||||||
|
} as Parents;
|
||||||
|
|
||||||
|
const out = mapParentForApi(parent);
|
||||||
|
expect(out.co_parent?.prenom).toBe('Clara');
|
||||||
|
expect(out.co_parent?.nom).toBe('Co');
|
||||||
|
expect(out.co_parent?.password).toBeUndefined();
|
||||||
|
expect(out.user.password).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
|
import { sanitizeUserForApi } from '../../common/utils/sanitize-user-for-api';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sérialisation API fiche parent — ticket #131.
|
||||||
|
* Garantit `user`, `co_parent` (si présent) et relations sans champs sensibles.
|
||||||
|
*/
|
||||||
|
export function mapParentForApi(parent: Parents): Parents {
|
||||||
|
return {
|
||||||
|
...parent,
|
||||||
|
user: sanitizeUserForApi(parent.user)!,
|
||||||
|
co_parent: sanitizeUserForApi(parent.co_parent),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapParentsForApi(parents: Parents[]): Parents[] {
|
||||||
|
return parents.map(mapParentForApi);
|
||||||
|
}
|
||||||
@@ -4,15 +4,26 @@ import { ConfigModule, ConfigService } from '@nestjs/config';
|
|||||||
import { JwtModule } from '@nestjs/jwt';
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
import { Parents } from 'src/entities/parents.entity';
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
import { DossierFamille, DossierFamilleEnfant } from 'src/entities/dossier_famille.entity';
|
import { DossierFamille, DossierFamilleEnfant } from 'src/entities/dossier_famille.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
import { ParentsController } from './parents.controller';
|
import { ParentsController } from './parents.controller';
|
||||||
import { ParentsService } from './parents.service';
|
import { ParentsService } from './parents.service';
|
||||||
import { Users } from 'src/entities/users.entity';
|
import { Users } from 'src/entities/users.entity';
|
||||||
import { UserModule } from '../user/user.module';
|
import { UserModule } from '../user/user.module';
|
||||||
|
import { AuthModule } from '../auth/auth.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
TypeOrmModule.forFeature([Parents, Users, DossierFamille, DossierFamilleEnfant]),
|
TypeOrmModule.forFeature([
|
||||||
|
Parents,
|
||||||
|
Users,
|
||||||
|
DossierFamille,
|
||||||
|
DossierFamilleEnfant,
|
||||||
|
ParentsChildren,
|
||||||
|
AmChildren,
|
||||||
|
]),
|
||||||
forwardRef(() => UserModule),
|
forwardRef(() => UserModule),
|
||||||
|
forwardRef(() => AuthModule),
|
||||||
JwtModule.registerAsync({
|
JwtModule.registerAsync({
|
||||||
imports: [ConfigModule],
|
imports: [ConfigModule],
|
||||||
useFactory: (config: ConfigService) => ({
|
useFactory: (config: ConfigService) => ({
|
||||||
|
|||||||
@@ -1,12 +1,43 @@
|
|||||||
|
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
import { ParentsService } from './parents.service';
|
import { ParentsService } from './parents.service';
|
||||||
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
|
import { Users } from 'src/entities/users.entity';
|
||||||
|
import { DossierFamille } from 'src/entities/dossier_famille.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
|
||||||
describe('ParentsService', () => {
|
describe('ParentsService — couples de garde (#168)', () => {
|
||||||
let service: ParentsService;
|
let service: ParentsService;
|
||||||
|
|
||||||
|
const parentsRepository = {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
};
|
||||||
|
const parentsChildrenRepository = {
|
||||||
|
find: jest.fn(),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
const amChildrenRepository = {
|
||||||
|
find: jest.fn(),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks();
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [ParentsService],
|
providers: [
|
||||||
|
ParentsService,
|
||||||
|
{ provide: getRepositoryToken(Parents), useValue: parentsRepository },
|
||||||
|
{ provide: getRepositoryToken(Users), useValue: {} },
|
||||||
|
{ provide: getRepositoryToken(DossierFamille), useValue: {} },
|
||||||
|
{
|
||||||
|
provide: getRepositoryToken(ParentsChildren),
|
||||||
|
useValue: parentsChildrenRepository,
|
||||||
|
},
|
||||||
|
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepository },
|
||||||
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
service = module.get<ParentsService>(ParentsService);
|
service = module.get<ParentsService>(ParentsService);
|
||||||
@@ -15,4 +46,107 @@ describe('ParentsService', () => {
|
|||||||
it('should be defined', () => {
|
it('should be defined', () => {
|
||||||
expect(service).toBeDefined();
|
expect(service).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('listerCouplesGarde', () => {
|
||||||
|
it('retourne une liste vide si le parent n’a pas d’enfant', async () => {
|
||||||
|
parentsRepository.findOne.mockResolvedValue({
|
||||||
|
user_id: 'p1',
|
||||||
|
id_placement_garde_courant: null,
|
||||||
|
});
|
||||||
|
parentsChildrenRepository.find.mockResolvedValue([]);
|
||||||
|
|
||||||
|
const res = await service.listerCouplesGarde('p1');
|
||||||
|
expect(res).toEqual({ couples: [], couple_courant_id: null });
|
||||||
|
expect(amChildrenRepository.find).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('mappe les placements actifs en couples et marque le courant', async () => {
|
||||||
|
parentsRepository.findOne.mockResolvedValue({
|
||||||
|
user_id: 'p1',
|
||||||
|
id_placement_garde_courant: 'pl-2',
|
||||||
|
});
|
||||||
|
parentsChildrenRepository.find.mockResolvedValue([
|
||||||
|
{ enfantId: 'e1' },
|
||||||
|
{ enfantId: 'e2' },
|
||||||
|
]);
|
||||||
|
amChildrenRepository.find.mockResolvedValue([
|
||||||
|
{
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
child: { id: 'e1', first_name: 'Léo', last_name: 'M', photo_url: null },
|
||||||
|
am: { user: { prenom: 'Marie', nom: 'N', photo_url: '/a.jpg' } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'pl-2',
|
||||||
|
amId: 'am-2',
|
||||||
|
child: { id: 'e2', first_name: 'Léa', last_name: 'M', photo_url: null },
|
||||||
|
am: { user: { prenom: 'Sophie', nom: 'P', photo_url: null } },
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const res = await service.listerCouplesGarde('p1');
|
||||||
|
expect(res.couples).toHaveLength(2);
|
||||||
|
expect(res.couple_courant_id).toBe('pl-2');
|
||||||
|
expect(res.couples[1].courant).toBe(true);
|
||||||
|
expect(res.couples[0].am.prenom).toBe('Marie');
|
||||||
|
expect(res.couples[0].enfant.prenom).toBe('Léo');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('404 si parent inconnu', async () => {
|
||||||
|
parentsRepository.findOne.mockResolvedValue(null);
|
||||||
|
await expect(service.listerCouplesGarde('x')).rejects.toBeInstanceOf(
|
||||||
|
NotFoundException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('definirCoupleGardeCourant', () => {
|
||||||
|
it('persiste le couple si l’enfant est rattaché au parent', async () => {
|
||||||
|
parentsRepository.findOne.mockResolvedValue({
|
||||||
|
user_id: 'p1',
|
||||||
|
id_placement_garde_courant: null,
|
||||||
|
});
|
||||||
|
amChildrenRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
enfantId: 'e1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
parentsChildrenRepository.findOne.mockResolvedValue({
|
||||||
|
parentId: 'p1',
|
||||||
|
enfantId: 'e1',
|
||||||
|
});
|
||||||
|
parentsRepository.update.mockResolvedValue({ affected: 1 });
|
||||||
|
// second call via listerCouplesGarde
|
||||||
|
parentsChildrenRepository.find.mockResolvedValue([{ enfantId: 'e1' }]);
|
||||||
|
amChildrenRepository.find.mockResolvedValue([
|
||||||
|
{
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
child: { id: 'e1', first_name: 'Léo', last_name: null, photo_url: null },
|
||||||
|
am: { user: { prenom: 'Marie', nom: null, photo_url: null } },
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const res = await service.definirCoupleGardeCourant('p1', 'pl-1');
|
||||||
|
expect(parentsRepository.update).toHaveBeenCalledWith(
|
||||||
|
{ user_id: 'p1' },
|
||||||
|
{ id_placement_garde_courant: 'pl-1' },
|
||||||
|
);
|
||||||
|
expect(res.couple_courant_id).toBe('pl-1');
|
||||||
|
expect(res.couples[0].courant).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('400 si le couple n’appartient pas au parent', async () => {
|
||||||
|
parentsRepository.findOne.mockResolvedValue({ user_id: 'p1' });
|
||||||
|
amChildrenRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
enfantId: 'e99',
|
||||||
|
});
|
||||||
|
parentsChildrenRepository.findOne.mockResolvedValue(null);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.definirCoupleGardeCourant('p1', 'pl-1'),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { In, Repository } from 'typeorm';
|
import { In, IsNull, Repository } from 'typeorm';
|
||||||
import { Parents } from 'src/entities/parents.entity';
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
import { DossierFamille } from 'src/entities/dossier_famille.entity';
|
import { DossierFamille } from 'src/entities/dossier_famille.entity';
|
||||||
import { RoleType, Users } from 'src/entities/users.entity';
|
import { RoleType, Users } from 'src/entities/users.entity';
|
||||||
@@ -17,7 +17,11 @@ import {
|
|||||||
DossierFamilleParentDto,
|
DossierFamilleParentDto,
|
||||||
DossierFamilleEnfantDto,
|
DossierFamilleEnfantDto,
|
||||||
} from './dto/dossier-famille-complet.dto';
|
} from './dto/dossier-famille-complet.dto';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
import { Children } from 'src/entities/children.entity';
|
import { Children } from 'src/entities/children.entity';
|
||||||
|
import { UpdateParentFicheAdminDto } from './dto/update-parent-fiche-admin.dto';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { CouplesGardeResponseDto } from './dto/couples-garde.dto';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ParentsService {
|
export class ParentsService {
|
||||||
@@ -28,6 +32,10 @@ export class ParentsService {
|
|||||||
private readonly usersRepository: Repository<Users>,
|
private readonly usersRepository: Repository<Users>,
|
||||||
@InjectRepository(DossierFamille)
|
@InjectRepository(DossierFamille)
|
||||||
private readonly dossierFamilleRepository: Repository<DossierFamille>,
|
private readonly dossierFamilleRepository: Repository<DossierFamille>,
|
||||||
|
@InjectRepository(ParentsChildren)
|
||||||
|
private readonly parentsChildrenRepository: Repository<ParentsChildren>,
|
||||||
|
@InjectRepository(AmChildren)
|
||||||
|
private readonly amChildrenRepository: Repository<AmChildren>,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
// Création d’un parent
|
// Création d’un parent
|
||||||
@@ -62,7 +70,7 @@ export class ParentsService {
|
|||||||
// Liste des parents
|
// Liste des parents
|
||||||
async findAll(): Promise<Parents[]> {
|
async findAll(): Promise<Parents[]> {
|
||||||
return this.parentsRepository.find({
|
return this.parentsRepository.find({
|
||||||
relations: ['user', 'co_parent', 'parentChildren', 'dossiers'],
|
relations: ['user', 'co_parent', 'parentChildren', 'parentChildren.child', 'dossiers'],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,7 +78,7 @@ export class ParentsService {
|
|||||||
async findOne(user_id: string): Promise<Parents> {
|
async findOne(user_id: string): Promise<Parents> {
|
||||||
const parent = await this.parentsRepository.findOne({
|
const parent = await this.parentsRepository.findOne({
|
||||||
where: { user_id },
|
where: { user_id },
|
||||||
relations: ['user', 'co_parent', 'parentChildren', 'dossiers'],
|
relations: ['user', 'co_parent', 'parentChildren', 'parentChildren.child', 'dossiers'],
|
||||||
});
|
});
|
||||||
if (!parent) throw new NotFoundException('Parent introuvable');
|
if (!parent) throw new NotFoundException('Parent introuvable');
|
||||||
return parent;
|
return parent;
|
||||||
@@ -82,6 +90,131 @@ export class ParentsService {
|
|||||||
return this.findOne(id);
|
return this.findOne(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mise à jour fiche parent (champs user + statut) par admin/gestionnaire. Ticket #131 / doc 28 §6.1.
|
||||||
|
*/
|
||||||
|
async updateFicheAdmin(parentUserId: string, dto: UpdateParentFicheAdminDto): Promise<Parents> {
|
||||||
|
const parent = await this.findOne(parentUserId);
|
||||||
|
const user = parent.user;
|
||||||
|
|
||||||
|
if (dto.email && dto.email !== user.email) {
|
||||||
|
const existing = await this.usersRepository.findOne({ where: { email: dto.email } });
|
||||||
|
if (existing && existing.id !== user.id) {
|
||||||
|
throw new ConflictException('Cet email est déjà utilisé');
|
||||||
|
}
|
||||||
|
user.email = dto.email;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dto.nom !== undefined) user.nom = dto.nom;
|
||||||
|
if (dto.prenom !== undefined) user.prenom = dto.prenom;
|
||||||
|
if (dto.telephone !== undefined) user.telephone = dto.telephone;
|
||||||
|
if (dto.adresse !== undefined) user.adresse = dto.adresse;
|
||||||
|
if (dto.ville !== undefined) user.ville = dto.ville;
|
||||||
|
if (dto.code_postal !== undefined) user.code_postal = dto.code_postal;
|
||||||
|
if (dto.statut !== undefined) user.statut = dto.statut;
|
||||||
|
|
||||||
|
await this.usersRepository.save(user);
|
||||||
|
return this.findOne(parentUserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Membres du foyer (user ids) pour affiliation enfant.
|
||||||
|
* Pivot + co-parent (A→B et B→A) + même numero_dossier. Ticket #158.
|
||||||
|
*/
|
||||||
|
private async resolveFoyerParentUserIds(parent: Parents): Promise<string[]> {
|
||||||
|
const ids = new Set<string>([parent.user_id]);
|
||||||
|
|
||||||
|
if (parent.co_parent?.id) {
|
||||||
|
ids.add(parent.co_parent.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sens inverse : parents qui déclarent ce user comme co-parent
|
||||||
|
const reverseLinks = await this.parentsRepository.find({
|
||||||
|
where: { co_parent: { id: parent.user_id } },
|
||||||
|
relations: ['co_parent'],
|
||||||
|
});
|
||||||
|
for (const p of reverseLinks) {
|
||||||
|
ids.add(p.user_id);
|
||||||
|
if (p.co_parent?.id) ids.add(p.co_parent.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const dossier = parent.numero_dossier?.trim();
|
||||||
|
if (dossier) {
|
||||||
|
const sameDossier = await this.parentsRepository.find({
|
||||||
|
where: { numero_dossier: dossier },
|
||||||
|
relations: ['co_parent'],
|
||||||
|
});
|
||||||
|
for (const p of sameDossier) {
|
||||||
|
ids.add(p.user_id);
|
||||||
|
if (p.co_parent?.id) ids.add(p.co_parent.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...ids];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rattacher un enfant au foyer du parent (tous les responsables). Ticket #158.
|
||||||
|
* Un seul POST suffit : liens créés pour pivot + co-parent / même dossier.
|
||||||
|
*/
|
||||||
|
async attachEnfant(parentUserId: string, enfantId: string): Promise<Parents> {
|
||||||
|
const parent = await this.findOne(parentUserId);
|
||||||
|
|
||||||
|
const child = await this.parentsRepository.manager.findOne(Children, {
|
||||||
|
where: { id: enfantId },
|
||||||
|
});
|
||||||
|
if (!child) {
|
||||||
|
throw new NotFoundException('Enfant introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const foyerIds = await this.resolveFoyerParentUserIds(parent);
|
||||||
|
let created = 0;
|
||||||
|
|
||||||
|
for (const memberId of foyerIds) {
|
||||||
|
const existing = await this.parentsChildrenRepository.findOne({
|
||||||
|
where: { parentId: memberId, enfantId },
|
||||||
|
});
|
||||||
|
if (existing) continue;
|
||||||
|
|
||||||
|
await this.parentsChildrenRepository.save(
|
||||||
|
this.parentsChildrenRepository.create({
|
||||||
|
parentId: memberId,
|
||||||
|
enfantId,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
created += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (created === 0) {
|
||||||
|
throw new ConflictException('Cet enfant est déjà rattaché à ce foyer');
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.findOne(parentUserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Détacher un enfant du foyer du parent (tous les responsables). Ticket #158.
|
||||||
|
* Si plus aucun lien ensuite → enfant orphelin (#157).
|
||||||
|
*/
|
||||||
|
async detachEnfant(parentUserId: string, enfantId: string): Promise<Parents> {
|
||||||
|
const parent = await this.findOne(parentUserId);
|
||||||
|
|
||||||
|
const link = await this.parentsChildrenRepository.findOne({
|
||||||
|
where: { parentId: parentUserId, enfantId },
|
||||||
|
});
|
||||||
|
if (!link) {
|
||||||
|
throw new NotFoundException('Lien parent-enfant introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const foyerIds = await this.resolveFoyerParentUserIds(parent);
|
||||||
|
await this.parentsChildrenRepository.delete({
|
||||||
|
parentId: In(foyerIds),
|
||||||
|
enfantId,
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.findOne(parentUserId);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Liste des familles en attente (une entrée par famille).
|
* Liste des familles en attente (une entrée par famille).
|
||||||
* Famille = lien co_parent ou partage d'enfants (même logique que backfill #103).
|
* Famille = lien co_parent ou partage d'enfants (même logique que backfill #103).
|
||||||
@@ -122,7 +255,15 @@ export class ParentsService {
|
|||||||
SELECT id, (MIN(rep::text))::uuid AS rep FROM rec GROUP BY id
|
SELECT id, (MIN(rep::text))::uuid AS rep FROM rec GROUP BY id
|
||||||
)
|
)
|
||||||
SELECT
|
SELECT
|
||||||
'Famille ' || string_agg(u.nom, ' - ' ORDER BY u.nom, u.prenom) AS libelle,
|
string_agg(
|
||||||
|
UPPER(TRIM(u.nom))
|
||||||
|
|| CASE
|
||||||
|
WHEN u.prenom IS NOT NULL AND TRIM(u.prenom) <> ''
|
||||||
|
THEN ' ' || INITCAP(TRIM(u.prenom))
|
||||||
|
ELSE ''
|
||||||
|
END,
|
||||||
|
' - ' ORDER BY u.nom, u.prenom, u.id
|
||||||
|
) AS libelle,
|
||||||
array_agg(p.id_utilisateur ORDER BY u.nom, u.prenom, u.id) AS "parentIds",
|
array_agg(p.id_utilisateur ORDER BY u.nom, u.prenom, u.id) AS "parentIds",
|
||||||
(array_agg(p.numero_dossier))[1] AS numero_dossier,
|
(array_agg(p.numero_dossier))[1] AS numero_dossier,
|
||||||
MIN(u.cree_le) AS date_soumission,
|
MIN(u.cree_le) AS date_soumission,
|
||||||
@@ -138,6 +279,8 @@ export class ParentsService {
|
|||||||
json_build_object(
|
json_build_object(
|
||||||
'id', u.id::text,
|
'id', u.id::text,
|
||||||
'email', u.email,
|
'email', u.email,
|
||||||
|
'nom', u.nom,
|
||||||
|
'prenom', u.prenom,
|
||||||
'telephone', u.telephone,
|
'telephone', u.telephone,
|
||||||
'code_postal', u.code_postal,
|
'code_postal', u.code_postal,
|
||||||
'ville', u.ville
|
'ville', u.ville
|
||||||
@@ -188,11 +331,21 @@ export class ParentsService {
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeParents(parents: unknown): { id: string; email: string; telephone: string | null; code_postal: string | null; ville: string | null }[] {
|
private normalizeParents(parents: unknown): {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
nom: string | null;
|
||||||
|
prenom: string | null;
|
||||||
|
telephone: string | null;
|
||||||
|
code_postal: string | null;
|
||||||
|
ville: string | null;
|
||||||
|
}[] {
|
||||||
if (Array.isArray(parents)) {
|
if (Array.isArray(parents)) {
|
||||||
return parents.map((p: any) => ({
|
return parents.map((p: any) => ({
|
||||||
id: String(p?.id ?? ''),
|
id: String(p?.id ?? ''),
|
||||||
email: String(p?.email ?? ''),
|
email: String(p?.email ?? ''),
|
||||||
|
nom: p?.nom != null ? String(p.nom) : null,
|
||||||
|
prenom: p?.prenom != null ? String(p.prenom) : null,
|
||||||
telephone: p?.telephone != null ? String(p.telephone) : null,
|
telephone: p?.telephone != null ? String(p.telephone) : null,
|
||||||
code_postal: p?.code_postal != null ? String(p.code_postal) : null,
|
code_postal: p?.code_postal != null ? String(p.code_postal) : null,
|
||||||
ville: p?.ville != null ? String(p.ville) : null,
|
ville: p?.ville != null ? String(p.ville) : null,
|
||||||
@@ -356,4 +509,108 @@ export class ParentsService {
|
|||||||
}
|
}
|
||||||
return raw.map((r: { id: string }) => r.id);
|
return raw.map((r: { id: string }) => r.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Liste les couples de garde (enfant ↔ AM) du parent connecté — ticket #168.
|
||||||
|
* Un couple = un placement actif dans enfants_assistantes_maternelles pour un enfant du parent.
|
||||||
|
*/
|
||||||
|
async listerCouplesGarde(parentUserId: string): Promise<CouplesGardeResponseDto> {
|
||||||
|
const parent = await this.parentsRepository.findOne({
|
||||||
|
where: { user_id: parentUserId },
|
||||||
|
});
|
||||||
|
if (!parent) {
|
||||||
|
throw new NotFoundException('Parent introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const liensEnfants = await this.parentsChildrenRepository.find({
|
||||||
|
where: { parentId: parentUserId },
|
||||||
|
select: ['enfantId'],
|
||||||
|
});
|
||||||
|
const enfantIds = liensEnfants.map((l) => l.enfantId);
|
||||||
|
if (enfantIds.length === 0) {
|
||||||
|
return { couples: [], couple_courant_id: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const placements = await this.amChildrenRepository.find({
|
||||||
|
where: { enfantId: In(enfantIds), date_fin: IsNull() },
|
||||||
|
relations: ['child', 'am', 'am.user'],
|
||||||
|
order: { date_debut: 'ASC' },
|
||||||
|
});
|
||||||
|
|
||||||
|
let idCourant = parent.id_placement_garde_courant ?? null;
|
||||||
|
const idsValides = new Set(placements.map((p) => p.id));
|
||||||
|
if (idCourant && !idsValides.has(idCourant)) {
|
||||||
|
idCourant = null;
|
||||||
|
await this.parentsRepository.update(
|
||||||
|
{ user_id: parentUserId },
|
||||||
|
{ id_placement_garde_courant: () => 'NULL' },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!idCourant && placements.length === 1) {
|
||||||
|
idCourant = placements[0].id;
|
||||||
|
}
|
||||||
|
|
||||||
|
const couples = placements.map((p) => {
|
||||||
|
const amUser = p.am?.user;
|
||||||
|
return {
|
||||||
|
id: p.id,
|
||||||
|
enfant: {
|
||||||
|
id: p.child.id,
|
||||||
|
prenom: p.child.first_name ?? null,
|
||||||
|
nom: p.child.last_name ?? null,
|
||||||
|
photo_url: p.child.photo_url ?? null,
|
||||||
|
},
|
||||||
|
am: {
|
||||||
|
id: p.amId,
|
||||||
|
prenom: amUser?.prenom ?? null,
|
||||||
|
nom: amUser?.nom ?? null,
|
||||||
|
photo_url: amUser?.photo_url ?? null,
|
||||||
|
},
|
||||||
|
courant: idCourant != null && p.id === idCourant,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
couples,
|
||||||
|
couple_courant_id: idCourant,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persiste le couple de garde actif pour le parent — ticket #168.
|
||||||
|
*/
|
||||||
|
async definirCoupleGardeCourant(
|
||||||
|
parentUserId: string,
|
||||||
|
coupleId: string,
|
||||||
|
): Promise<CouplesGardeResponseDto> {
|
||||||
|
const parent = await this.parentsRepository.findOne({
|
||||||
|
where: { user_id: parentUserId },
|
||||||
|
});
|
||||||
|
if (!parent) {
|
||||||
|
throw new NotFoundException('Parent introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const placement = await this.amChildrenRepository.findOne({
|
||||||
|
where: { id: coupleId, date_fin: IsNull() },
|
||||||
|
});
|
||||||
|
if (!placement) {
|
||||||
|
throw new NotFoundException('Couple de garde introuvable ou inactif');
|
||||||
|
}
|
||||||
|
|
||||||
|
const lien = await this.parentsChildrenRepository.findOne({
|
||||||
|
where: { parentId: parentUserId, enfantId: placement.enfantId },
|
||||||
|
});
|
||||||
|
if (!lien) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Ce couple ne concerne pas un enfant rattaché à ce parent',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.parentsRepository.update(
|
||||||
|
{ user_id: parentUserId },
|
||||||
|
{ id_placement_garde_courant: coupleId },
|
||||||
|
);
|
||||||
|
|
||||||
|
return this.listerCouplesGarde(parentUserId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,15 +24,19 @@ export class RelaisController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
@ApiOperation({ summary: 'Lister tous les relais' })
|
@ApiOperation({
|
||||||
|
summary: 'Lister tous les relais',
|
||||||
|
description:
|
||||||
|
'Lecture ouverte aux gestionnaires (combobox fiches). CRUD write reste admin-only. Ticket #151.',
|
||||||
|
})
|
||||||
@ApiResponse({ status: 200, description: 'Liste des relais.' })
|
@ApiResponse({ status: 200, description: 'Liste des relais.' })
|
||||||
findAll() {
|
findAll() {
|
||||||
return this.relaisService.findAll();
|
return this.relaisService.findAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':id')
|
@Get(':id')
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
@ApiOperation({ summary: 'Récupérer un relais par ID' })
|
@ApiOperation({ summary: 'Récupérer un relais par ID' })
|
||||||
@ApiResponse({ status: 200, description: 'Le relais trouvé.' })
|
@ApiResponse({ status: 200, description: 'Le relais trouvé.' })
|
||||||
findOne(@Param('id') id: string) {
|
findOne(@Param('id') id: string) {
|
||||||
|
|||||||
@@ -0,0 +1,175 @@
|
|||||||
|
import { ForbiddenException, NotFoundException } from '@nestjs/common';
|
||||||
|
import { SuppressionService } from './suppression.service';
|
||||||
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
describe('SuppressionService (#159)', () => {
|
||||||
|
const dataSource = {
|
||||||
|
transaction: jest.fn(async (cb: (m: unknown) => Promise<unknown>) =>
|
||||||
|
cb({
|
||||||
|
delete: jest.fn(),
|
||||||
|
query: jest.fn(),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
const usersRepository = {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
count: jest.fn(),
|
||||||
|
};
|
||||||
|
const parentsRepository = {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
find: jest.fn(),
|
||||||
|
query: jest.fn(),
|
||||||
|
};
|
||||||
|
const amRepository = {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
const childrenRepository = {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
save: jest.fn(),
|
||||||
|
};
|
||||||
|
const parentsChildrenRepository = {
|
||||||
|
find: jest.fn(),
|
||||||
|
};
|
||||||
|
const amChildrenRepository = {
|
||||||
|
find: jest.fn(),
|
||||||
|
save: jest.fn(),
|
||||||
|
count: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let service: SuppressionService;
|
||||||
|
|
||||||
|
const staff = {
|
||||||
|
id: 'staff-1',
|
||||||
|
role: RoleType.GESTIONNAIRE,
|
||||||
|
} as never;
|
||||||
|
|
||||||
|
const admin = {
|
||||||
|
id: 'admin-1',
|
||||||
|
role: RoleType.ADMINISTRATEUR,
|
||||||
|
} as never;
|
||||||
|
|
||||||
|
const superAdmin = {
|
||||||
|
id: 'sa-1',
|
||||||
|
role: RoleType.SUPER_ADMIN,
|
||||||
|
} as never;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
service = new SuppressionService(
|
||||||
|
dataSource as never,
|
||||||
|
usersRepository as never,
|
||||||
|
parentsRepository as never,
|
||||||
|
amRepository as never,
|
||||||
|
childrenRepository as never,
|
||||||
|
parentsChildrenRepository as never,
|
||||||
|
amChildrenRepository as never,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse self-delete', async () => {
|
||||||
|
usersRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'admin-1',
|
||||||
|
role: RoleType.ADMINISTRATEUR,
|
||||||
|
});
|
||||||
|
await expect(service.deleteUser('admin-1', admin)).rejects.toBeInstanceOf(
|
||||||
|
ForbiddenException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse gestionnaire deleting another gestionnaire', async () => {
|
||||||
|
usersRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'g2',
|
||||||
|
role: RoleType.GESTIONNAIRE,
|
||||||
|
});
|
||||||
|
await expect(service.deleteUser('g2', staff)).rejects.toBeInstanceOf(
|
||||||
|
ForbiddenException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dernier admin : refus si pas super_admin', async () => {
|
||||||
|
usersRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'admin-2',
|
||||||
|
role: RoleType.ADMINISTRATEUR,
|
||||||
|
});
|
||||||
|
usersRepository.count.mockResolvedValue(1);
|
||||||
|
await expect(service.deleteUser('admin-2', admin)).rejects.toBeInstanceOf(
|
||||||
|
ForbiddenException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dernier admin : OK pour super_admin', async () => {
|
||||||
|
usersRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'admin-2',
|
||||||
|
role: RoleType.ADMINISTRATEUR,
|
||||||
|
});
|
||||||
|
usersRepository.count.mockResolvedValue(1);
|
||||||
|
usersRepository.delete.mockResolvedValue({ affected: 1 });
|
||||||
|
const res = await service.deleteUser('admin-2', superAdmin);
|
||||||
|
expect(res.deleted_user_ids).toEqual(['admin-2']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('delete AM : clos placements, pas d’enfants deleted', async () => {
|
||||||
|
usersRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'am-1',
|
||||||
|
role: RoleType.ASSISTANTE_MATERNELLE,
|
||||||
|
});
|
||||||
|
amRepository.findOne.mockResolvedValue({
|
||||||
|
user_id: 'am-1',
|
||||||
|
numero_dossier: '2026-000015',
|
||||||
|
});
|
||||||
|
amChildrenRepository.find.mockResolvedValue([
|
||||||
|
{
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e1',
|
||||||
|
child: { id: 'e1', status: 'garde' },
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
amChildrenRepository.count.mockResolvedValue(0);
|
||||||
|
amChildrenRepository.save.mockImplementation(async (x) => x);
|
||||||
|
childrenRepository.save.mockResolvedValue({});
|
||||||
|
usersRepository.delete.mockResolvedValue({ affected: 1 });
|
||||||
|
|
||||||
|
const res = await service.deleteUser('am-1', staff);
|
||||||
|
expect(res.deleted_enfant_ids).toEqual([]);
|
||||||
|
expect(res.deleted_user_ids).toEqual(['am-1']);
|
||||||
|
expect(res.type).toBe('assistante_maternelle');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('delete dossier famille introuvable', async () => {
|
||||||
|
parentsRepository.findOne.mockResolvedValue(null);
|
||||||
|
amRepository.findOne.mockResolvedValue(null);
|
||||||
|
await expect(
|
||||||
|
service.deleteDossier('2026-999999', staff),
|
||||||
|
).rejects.toBeInstanceOf(NotFoundException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('co-parent : delete user seul', async () => {
|
||||||
|
usersRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'p2',
|
||||||
|
role: RoleType.PARENT,
|
||||||
|
});
|
||||||
|
parentsRepository.findOne.mockResolvedValue({
|
||||||
|
user_id: 'p2',
|
||||||
|
numero_dossier: '2026-000010',
|
||||||
|
co_parent: { id: 'p1' },
|
||||||
|
});
|
||||||
|
parentsRepository.query.mockResolvedValue([
|
||||||
|
{ id: 'p1' },
|
||||||
|
{ id: 'p2' },
|
||||||
|
]);
|
||||||
|
dataSource.transaction.mockImplementation(async (cb) =>
|
||||||
|
cb({
|
||||||
|
delete: jest.fn(),
|
||||||
|
query: jest.fn(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const res = await service.deleteUser('p2', staff);
|
||||||
|
expect(res.deleted_enfant_ids).toEqual([]);
|
||||||
|
expect(res.deleted_user_ids).toEqual(['p2']);
|
||||||
|
expect(res.message).toMatch(/co-parent/i);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
ForbiddenException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { DataSource, In, IsNull, Repository } from 'typeorm';
|
||||||
|
import { RoleType, Users } from 'src/entities/users.entity';
|
||||||
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
|
import { Children, StatutEnfantType } from 'src/entities/children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
|
||||||
|
export type SuppressionResult = {
|
||||||
|
type?: 'famille' | 'assistante_maternelle';
|
||||||
|
numero_dossier?: string;
|
||||||
|
deleted_user_ids: string[];
|
||||||
|
deleted_enfant_ids: string[];
|
||||||
|
dossier_supprime?: boolean;
|
||||||
|
message: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const STAFF_METIER: RoleType[] = [
|
||||||
|
RoleType.GESTIONNAIRE,
|
||||||
|
RoleType.ADMINISTRATEUR,
|
||||||
|
RoleType.SUPER_ADMIN,
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cascades de suppression métier — tickets #154 / #159.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class SuppressionService {
|
||||||
|
constructor(
|
||||||
|
private readonly dataSource: DataSource,
|
||||||
|
@InjectRepository(Users)
|
||||||
|
private readonly usersRepository: Repository<Users>,
|
||||||
|
@InjectRepository(Parents)
|
||||||
|
private readonly parentsRepository: Repository<Parents>,
|
||||||
|
@InjectRepository(AssistanteMaternelle)
|
||||||
|
private readonly amRepository: Repository<AssistanteMaternelle>,
|
||||||
|
@InjectRepository(Children)
|
||||||
|
private readonly childrenRepository: Repository<Children>,
|
||||||
|
@InjectRepository(ParentsChildren)
|
||||||
|
private readonly parentsChildrenRepository: Repository<ParentsChildren>,
|
||||||
|
@InjectRepository(AmChildren)
|
||||||
|
private readonly amChildrenRepository: Repository<AmChildren>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
assertStaffMetier(currentUser: Users): void {
|
||||||
|
if (!STAFF_METIER.includes(currentUser.role)) {
|
||||||
|
throw new ForbiddenException('Accès refusé');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteDossier(
|
||||||
|
numeroDossier: string,
|
||||||
|
currentUser: Users,
|
||||||
|
): Promise<SuppressionResult> {
|
||||||
|
this.assertStaffMetier(currentUser);
|
||||||
|
const num = numeroDossier?.trim();
|
||||||
|
if (!num) {
|
||||||
|
throw new BadRequestException('Numéro de dossier requis.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const parentHit = await this.parentsRepository.findOne({
|
||||||
|
where: { numero_dossier: num },
|
||||||
|
});
|
||||||
|
if (parentHit) {
|
||||||
|
return this.deleteFamilleByNumero(num);
|
||||||
|
}
|
||||||
|
|
||||||
|
const amHit = await this.amRepository.findOne({
|
||||||
|
where: { numero_dossier: num },
|
||||||
|
relations: ['user'],
|
||||||
|
});
|
||||||
|
if (amHit?.user) {
|
||||||
|
return this.deleteAmUser(amHit.user.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new NotFoundException('Aucun dossier trouvé pour ce numéro.');
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteUser(
|
||||||
|
id: string,
|
||||||
|
currentUser: Users,
|
||||||
|
): Promise<SuppressionResult> {
|
||||||
|
const target = await this.usersRepository.findOne({ where: { id } });
|
||||||
|
if (!target) {
|
||||||
|
throw new NotFoundException('Utilisateur introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target.id === currentUser.id) {
|
||||||
|
throw new ForbiddenException('Vous ne pouvez pas supprimer votre propre compte.');
|
||||||
|
}
|
||||||
|
if (target.role === RoleType.SUPER_ADMIN) {
|
||||||
|
throw new ForbiddenException('Le super administrateur ne peut pas être supprimé.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target.role === RoleType.PARENT) {
|
||||||
|
this.assertStaffMetier(currentUser);
|
||||||
|
return this.deleteParentUser(target.id);
|
||||||
|
}
|
||||||
|
if (target.role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
this.assertStaffMetier(currentUser);
|
||||||
|
return this.deleteAmUser(target.id);
|
||||||
|
}
|
||||||
|
if (target.role === RoleType.GESTIONNAIRE) {
|
||||||
|
if (
|
||||||
|
currentUser.role !== RoleType.ADMINISTRATEUR &&
|
||||||
|
currentUser.role !== RoleType.SUPER_ADMIN
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Seul un administrateur peut supprimer un gestionnaire.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await this.usersRepository.delete(target.id);
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [target.id],
|
||||||
|
deleted_enfant_ids: [],
|
||||||
|
message: 'Gestionnaire supprimé.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (target.role === RoleType.ADMINISTRATEUR) {
|
||||||
|
await this.assertCanDeleteAdministrateur(target, currentUser);
|
||||||
|
await this.usersRepository.delete(target.id);
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [target.id],
|
||||||
|
deleted_enfant_ids: [],
|
||||||
|
message: 'Administrateur supprimé.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new BadRequestException('Type d’utilisateur non supprimable via cet endpoint.');
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteEnfant(
|
||||||
|
enfantId: string,
|
||||||
|
deleteDossier: boolean,
|
||||||
|
currentUser: Users,
|
||||||
|
): Promise<SuppressionResult> {
|
||||||
|
this.assertStaffMetier(currentUser);
|
||||||
|
|
||||||
|
const child = await this.childrenRepository.findOne({
|
||||||
|
where: { id: enfantId },
|
||||||
|
relations: ['parentLinks', 'parentLinks.parent'],
|
||||||
|
});
|
||||||
|
if (!child) {
|
||||||
|
throw new NotFoundException('Enfant introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const parentIds = (child.parentLinks ?? [])
|
||||||
|
.map((l) => l.parentId ?? l.parent?.user_id)
|
||||||
|
.filter(Boolean) as string[];
|
||||||
|
|
||||||
|
let numero: string | undefined;
|
||||||
|
if (parentIds.length > 0) {
|
||||||
|
const parents = await this.parentsRepository.find({
|
||||||
|
where: { user_id: In(parentIds) },
|
||||||
|
});
|
||||||
|
numero = parents.map((p) => p.numero_dossier?.trim()).find((n) => !!n);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!numero) {
|
||||||
|
await this.closePlacementsForEnfants([enfantId]);
|
||||||
|
await this.childrenRepository.delete(enfantId);
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [],
|
||||||
|
deleted_enfant_ids: [enfantId],
|
||||||
|
dossier_supprime: false,
|
||||||
|
message: 'Enfant supprimé.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const siblingIds = await this.listEnfantIdsForNumero(numero);
|
||||||
|
const isLast = siblingIds.length <= 1;
|
||||||
|
|
||||||
|
if (isLast && deleteDossier) {
|
||||||
|
const result = await this.deleteFamilleByNumero(numero);
|
||||||
|
return {
|
||||||
|
...result,
|
||||||
|
dossier_supprime: true,
|
||||||
|
message: 'Dernier enfant et dossier famille supprimés.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.closePlacementsForEnfants([enfantId]);
|
||||||
|
await this.childrenRepository.delete(enfantId);
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [],
|
||||||
|
deleted_enfant_ids: [enfantId],
|
||||||
|
dossier_supprime: false,
|
||||||
|
numero_dossier: numero,
|
||||||
|
type: 'famille',
|
||||||
|
message: isLast
|
||||||
|
? 'Dernier enfant supprimé. Le dossier famille reste sans enfant.'
|
||||||
|
: 'Enfant supprimé du dossier famille.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Compte enfants liés à un numero_dossier famille (pour flag sans_enfant). */
|
||||||
|
async countEnfantsForNumero(numeroDossier: string): Promise<number> {
|
||||||
|
const ids = await this.listEnfantIdsForNumero(numeroDossier);
|
||||||
|
return ids.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertCanDeleteAdministrateur(
|
||||||
|
target: Users,
|
||||||
|
currentUser: Users,
|
||||||
|
): Promise<void> {
|
||||||
|
if (
|
||||||
|
currentUser.role !== RoleType.ADMINISTRATEUR &&
|
||||||
|
currentUser.role !== RoleType.SUPER_ADMIN
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Seul un administrateur peut supprimer un administrateur.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const adminCount = await this.usersRepository.count({
|
||||||
|
where: { role: RoleType.ADMINISTRATEUR },
|
||||||
|
});
|
||||||
|
if (adminCount <= 1) {
|
||||||
|
if (currentUser.role !== RoleType.SUPER_ADMIN) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Seul le super administrateur peut supprimer le dernier administrateur.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async deleteParentUser(userId: string): Promise<SuppressionResult> {
|
||||||
|
const parent = await this.parentsRepository.findOne({
|
||||||
|
where: { user_id: userId },
|
||||||
|
relations: ['co_parent'],
|
||||||
|
});
|
||||||
|
if (!parent) {
|
||||||
|
// Compte parent sans fiche — hard delete user
|
||||||
|
await this.usersRepository.delete(userId);
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [userId],
|
||||||
|
deleted_enfant_ids: [],
|
||||||
|
message: 'Parent supprimé.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const numero = parent.numero_dossier?.trim();
|
||||||
|
const foyerIds = numero
|
||||||
|
? await this.listParentUserIdsForNumero(numero)
|
||||||
|
: [userId];
|
||||||
|
|
||||||
|
const isLast = foyerIds.filter((id) => id !== userId).length === 0;
|
||||||
|
|
||||||
|
if (!isLast) {
|
||||||
|
// Co-parent : retirer liens enfants de ce parent, clear co_parent refs, delete user
|
||||||
|
await this.dataSource.transaction(async (manager) => {
|
||||||
|
await manager.delete(ParentsChildren, { parentId: userId });
|
||||||
|
await manager.query(
|
||||||
|
`UPDATE parents SET id_co_parent = NULL WHERE id_co_parent = $1 OR id_utilisateur = $1`,
|
||||||
|
[userId],
|
||||||
|
);
|
||||||
|
await manager.delete(Users, { id: userId });
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [userId],
|
||||||
|
deleted_enfant_ids: [],
|
||||||
|
numero_dossier: numero,
|
||||||
|
type: 'famille',
|
||||||
|
message: 'Parent retiré du dossier (co-parent).',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dernier parent : + enfants
|
||||||
|
const enfantIds = numero
|
||||||
|
? await this.listEnfantIdsForNumero(numero)
|
||||||
|
: await this.listEnfantIdsForParent(userId);
|
||||||
|
await this.closePlacementsForEnfants(enfantIds);
|
||||||
|
await this.dataSource.transaction(async (manager) => {
|
||||||
|
if (enfantIds.length) {
|
||||||
|
await manager.delete(Children, { id: In(enfantIds) });
|
||||||
|
}
|
||||||
|
await manager.query(
|
||||||
|
`UPDATE parents SET id_co_parent = NULL WHERE id_utilisateur = $1 OR id_co_parent = $1`,
|
||||||
|
[userId],
|
||||||
|
);
|
||||||
|
await manager.delete(Users, { id: userId });
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [userId],
|
||||||
|
deleted_enfant_ids: enfantIds,
|
||||||
|
numero_dossier: numero,
|
||||||
|
type: 'famille',
|
||||||
|
message: 'Dernier parent et enfants rattachés supprimés.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async deleteFamilleByNumero(numero: string): Promise<SuppressionResult> {
|
||||||
|
const parentIds = await this.listParentUserIdsForNumero(numero);
|
||||||
|
if (parentIds.length === 0) {
|
||||||
|
throw new NotFoundException('Aucun parent pour ce dossier.');
|
||||||
|
}
|
||||||
|
const enfantIds = await this.listEnfantIdsForNumero(numero);
|
||||||
|
await this.closePlacementsForEnfants(enfantIds);
|
||||||
|
|
||||||
|
await this.dataSource.transaction(async (manager) => {
|
||||||
|
if (enfantIds.length) {
|
||||||
|
await manager.delete(Children, { id: In(enfantIds) });
|
||||||
|
}
|
||||||
|
await manager.query(
|
||||||
|
`UPDATE parents SET id_co_parent = NULL WHERE id_utilisateur = ANY($1::uuid[]) OR id_co_parent = ANY($1::uuid[])`,
|
||||||
|
[parentIds],
|
||||||
|
);
|
||||||
|
await manager.delete(Users, { id: In(parentIds) });
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'famille',
|
||||||
|
numero_dossier: numero,
|
||||||
|
deleted_user_ids: parentIds,
|
||||||
|
deleted_enfant_ids: enfantIds,
|
||||||
|
message: 'Dossier famille supprimé.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async deleteAmUser(userId: string): Promise<SuppressionResult> {
|
||||||
|
const am = await this.amRepository.findOne({ where: { user_id: userId } });
|
||||||
|
const numero = am?.numero_dossier?.trim();
|
||||||
|
|
||||||
|
const active = await this.amChildrenRepository.find({
|
||||||
|
where: { amId: userId, date_fin: IsNull() },
|
||||||
|
relations: ['child'],
|
||||||
|
});
|
||||||
|
const now = new Date();
|
||||||
|
for (const link of active) {
|
||||||
|
link.date_fin = now;
|
||||||
|
await this.amChildrenRepository.save(link);
|
||||||
|
if (link.child) {
|
||||||
|
await this.applySansGarde(link.child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.usersRepository.delete(userId);
|
||||||
|
return {
|
||||||
|
type: 'assistante_maternelle',
|
||||||
|
numero_dossier: numero,
|
||||||
|
deleted_user_ids: [userId],
|
||||||
|
deleted_enfant_ids: [],
|
||||||
|
message: 'Dossier assistante maternelle supprimé.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async applySansGarde(child: Children): Promise<void> {
|
||||||
|
if (
|
||||||
|
child.status === StatutEnfantType.A_NAITRE ||
|
||||||
|
child.status === StatutEnfantType.SCOLARISE
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const remaining = await this.amChildrenRepository.count({
|
||||||
|
where: { enfantId: child.id, date_fin: IsNull() },
|
||||||
|
});
|
||||||
|
if (remaining === 0) {
|
||||||
|
child.status = StatutEnfantType.SANS_GARDE;
|
||||||
|
await this.childrenRepository.save(child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async closePlacementsForEnfants(enfantIds: string[]): Promise<void> {
|
||||||
|
if (!enfantIds.length) return;
|
||||||
|
const links = await this.amChildrenRepository.find({
|
||||||
|
where: { enfantId: In(enfantIds), date_fin: IsNull() },
|
||||||
|
relations: ['child'],
|
||||||
|
});
|
||||||
|
const now = new Date();
|
||||||
|
for (const link of links) {
|
||||||
|
link.date_fin = now;
|
||||||
|
await this.amChildrenRepository.save(link);
|
||||||
|
if (link.child) {
|
||||||
|
await this.applySansGarde(link.child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async listParentUserIdsForNumero(numero: string): Promise<string[]> {
|
||||||
|
const rows: Array<{ id: string }> = await this.parentsRepository.query(
|
||||||
|
`
|
||||||
|
SELECT DISTINCT x.id::text AS id FROM (
|
||||||
|
SELECT id_utilisateur AS id FROM parents WHERE TRIM(numero_dossier) = $1
|
||||||
|
UNION
|
||||||
|
SELECT id_co_parent AS id FROM parents
|
||||||
|
WHERE TRIM(numero_dossier) = $1 AND id_co_parent IS NOT NULL
|
||||||
|
UNION
|
||||||
|
SELECT p2.id_utilisateur AS id FROM parents p1
|
||||||
|
JOIN parents p2 ON p2.id_utilisateur = p1.id_co_parent
|
||||||
|
WHERE TRIM(p1.numero_dossier) = $1
|
||||||
|
) x WHERE x.id IS NOT NULL
|
||||||
|
`,
|
||||||
|
[numero],
|
||||||
|
);
|
||||||
|
return rows.map((r) => r.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async listEnfantIdsForNumero(numero: string): Promise<string[]> {
|
||||||
|
const parentIds = await this.listParentUserIdsForNumero(numero);
|
||||||
|
if (!parentIds.length) return [];
|
||||||
|
return this.listEnfantIdsForParents(parentIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async listEnfantIdsForParent(parentId: string): Promise<string[]> {
|
||||||
|
return this.listEnfantIdsForParents([parentId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async listEnfantIdsForParents(parentIds: string[]): Promise<string[]> {
|
||||||
|
const links = await this.parentsChildrenRepository.find({
|
||||||
|
where: { parentId: In(parentIds) },
|
||||||
|
});
|
||||||
|
return [...new Set(links.map((l) => l.enfantId))];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { Users } from 'src/entities/users.entity';
|
||||||
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
|
import { Children } from 'src/entities/children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { SuppressionService } from './suppression.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
TypeOrmModule.forFeature([
|
||||||
|
Users,
|
||||||
|
Parents,
|
||||||
|
AssistanteMaternelle,
|
||||||
|
Children,
|
||||||
|
ParentsChildren,
|
||||||
|
AmChildren,
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
providers: [SuppressionService],
|
||||||
|
exports: [SuppressionService],
|
||||||
|
})
|
||||||
|
export class SuppressionsModule {}
|
||||||
@@ -1,20 +1,21 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import 'reflect-metadata';
|
||||||
import { GestionnairesController } from './gestionnaires.controller';
|
import { GestionnairesController } from './gestionnaires.controller';
|
||||||
import { GestionnairesService } from './gestionnaires.service';
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
describe('GestionnairesController', () => {
|
describe('GestionnairesController roles (#161)', () => {
|
||||||
let controller: GestionnairesController;
|
it('POST /gestionnaires autorise SUPER_ADMIN et ADMINISTRATEUR', () => {
|
||||||
|
const roles = Reflect.getMetadata('roles', GestionnairesController.prototype.create);
|
||||||
beforeEach(async () => {
|
expect(roles).toEqual(
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
expect.arrayContaining([RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR]),
|
||||||
controllers: [GestionnairesController],
|
);
|
||||||
providers: [GestionnairesService],
|
expect(roles).not.toContain(RoleType.GESTIONNAIRE);
|
||||||
}).compile();
|
|
||||||
|
|
||||||
controller = module.get<GestionnairesController>(GestionnairesController);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('PATCH /gestionnaires/:id autorise SUPER_ADMIN et ADMINISTRATEUR', () => {
|
||||||
expect(controller).toBeDefined();
|
const roles = Reflect.getMetadata('roles', GestionnairesController.prototype.update);
|
||||||
|
expect(roles).toEqual(
|
||||||
|
expect.arrayContaining([RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR]),
|
||||||
|
);
|
||||||
|
expect(roles).not.toContain(RoleType.GESTIONNAIRE);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -25,10 +25,10 @@ import { AuthGuard } from 'src/common/guards/auth.guard';
|
|||||||
export class GestionnairesController {
|
export class GestionnairesController {
|
||||||
constructor(private readonly gestionnairesService: GestionnairesService) { }
|
constructor(private readonly gestionnairesService: GestionnairesService) { }
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||||
@ApiResponse({ status: 201, description: 'Le gestionnaire a été créé avec succès.', type: Users })
|
@ApiResponse({ status: 201, description: 'Le gestionnaire a été créé avec succès.', type: Users })
|
||||||
@ApiResponse({ status: 409, description: 'Conflit. L\'email est déjà utilisé.' })
|
@ApiResponse({ status: 409, description: 'Conflit. L\'email est déjà utilisé.' })
|
||||||
@ApiOperation({ summary: 'Création d\'un gestionnaire' })
|
@ApiOperation({ summary: 'Création d\'un gestionnaire (admin / super admin)' })
|
||||||
@ApiBody({ type: CreateGestionnaireDto })
|
@ApiBody({ type: CreateGestionnaireDto })
|
||||||
@Post()
|
@Post()
|
||||||
create(@Body() dto: CreateGestionnaireDto): Promise<Users> {
|
create(@Body() dto: CreateGestionnaireDto): Promise<Users> {
|
||||||
@@ -43,7 +43,7 @@ export class GestionnairesController {
|
|||||||
return this.gestionnairesService.findAll();
|
return this.gestionnairesService.findAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.GESTIONNAIRE, RoleType.SUPER_ADMIN)
|
@Roles(RoleType.GESTIONNAIRE, RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||||
@ApiOperation({ summary: 'Récupérer un gestionnaire par ID' })
|
@ApiOperation({ summary: 'Récupérer un gestionnaire par ID' })
|
||||||
@ApiResponse({ status: 400, description: 'ID invalide' })
|
@ApiResponse({ status: 400, description: 'ID invalide' })
|
||||||
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||||
@@ -56,8 +56,8 @@ export class GestionnairesController {
|
|||||||
return this.gestionnairesService.findOne(id);
|
return this.gestionnairesService.findOne(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||||
@ApiOperation({ summary: 'Mettre à jour un gestionnaire' })
|
@ApiOperation({ summary: 'Mettre à jour un gestionnaire (admin / super admin)' })
|
||||||
@ApiResponse({ status: 200, description: 'Le gestionnaire a été mis à jour avec succès.', type: Users })
|
@ApiResponse({ status: 200, description: 'Le gestionnaire a été mis à jour avec succès.', type: Users })
|
||||||
@ApiResponse({ status: 404, description: 'Gestionnaire non trouvé' })
|
@ApiResponse({ status: 404, description: 'Gestionnaire non trouvé' })
|
||||||
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||||
|
|||||||
@@ -1,20 +1,13 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import 'reflect-metadata';
|
||||||
import { UserController } from './user.controller';
|
import { UserController } from './user.controller';
|
||||||
import { UserService } from './user.service';
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
describe('UserController', () => {
|
describe('UserController roles (#161)', () => {
|
||||||
let controller: UserController;
|
it('POST /users/admin autorise SUPER_ADMIN et ADMINISTRATEUR', () => {
|
||||||
|
const roles = Reflect.getMetadata('roles', UserController.prototype.createAdmin);
|
||||||
beforeEach(async () => {
|
expect(roles).toEqual(
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
expect.arrayContaining([RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR]),
|
||||||
controllers: [UserController],
|
);
|
||||||
providers: [UserService],
|
expect(roles).not.toContain(RoleType.GESTIONNAIRE);
|
||||||
}).compile();
|
|
||||||
|
|
||||||
controller = module.get<UserController>(UserController);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should be defined', () => {
|
|
||||||
expect(controller).toBeDefined();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -10,18 +10,22 @@ import { CreateUserDto } from './dto/create_user.dto';
|
|||||||
import { CreateAdminDto } from './dto/create_admin.dto';
|
import { CreateAdminDto } from './dto/create_admin.dto';
|
||||||
import { UpdateUserDto } from './dto/update_user.dto';
|
import { UpdateUserDto } from './dto/update_user.dto';
|
||||||
import { AffecterNumeroDossierDto } from './dto/affecter-numero-dossier.dto';
|
import { AffecterNumeroDossierDto } from './dto/affecter-numero-dossier.dto';
|
||||||
|
import { SuppressionService } from '../suppressions/suppression.service';
|
||||||
|
|
||||||
@ApiTags('Utilisateurs')
|
@ApiTags('Utilisateurs')
|
||||||
@ApiBearerAuth('access-token')
|
@ApiBearerAuth('access-token')
|
||||||
@UseGuards(AuthGuard, RolesGuard)
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
@Controller('users')
|
@Controller('users')
|
||||||
export class UserController {
|
export class UserController {
|
||||||
constructor(private readonly userService: UserService) { }
|
constructor(
|
||||||
|
private readonly userService: UserService,
|
||||||
|
private readonly suppressionService: SuppressionService,
|
||||||
|
) { }
|
||||||
|
|
||||||
// Création d'un administrateur (réservée aux super admins)
|
// Création d'un administrateur (admin + super admin) — #161
|
||||||
@Post('admin')
|
@Post('admin')
|
||||||
@Roles(RoleType.SUPER_ADMIN)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||||
@ApiOperation({ summary: 'Créer un nouvel administrateur (super admin seulement)' })
|
@ApiOperation({ summary: 'Créer un nouvel administrateur (admin / super admin)' })
|
||||||
createAdmin(
|
createAdmin(
|
||||||
@Body() dto: CreateAdminDto,
|
@Body() dto: CreateAdminDto,
|
||||||
@User() currentUser: Users
|
@User() currentUser: Users
|
||||||
@@ -146,12 +150,20 @@ export class UserController {
|
|||||||
return this.userService.suspendUser(id, currentUser, comment);
|
return this.userService.suspendUser(id, currentUser, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Supprimer un utilisateur (super_admin uniquement)
|
// Supprimer un utilisateur — cascades métier #159
|
||||||
@Delete(':id')
|
@Delete(':id')
|
||||||
@Roles(RoleType.SUPER_ADMIN)
|
@Roles(
|
||||||
@ApiOperation({ summary: 'Supprimer un utilisateur' })
|
RoleType.SUPER_ADMIN,
|
||||||
|
RoleType.ADMINISTRATEUR,
|
||||||
|
RoleType.GESTIONNAIRE,
|
||||||
|
)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Supprimer un utilisateur (cascades métier #159)',
|
||||||
|
description:
|
||||||
|
'Parent / AM / staff selon matrice. Gestionnaire ne peut pas supprimer un autre gestionnaire. Self interdit.',
|
||||||
|
})
|
||||||
@ApiParam({ name: 'id', description: "UUID de l'utilisateur" })
|
@ApiParam({ name: 'id', description: "UUID de l'utilisateur" })
|
||||||
remove(@Param('id') id: string, @User() currentUser: Users) {
|
remove(@Param('id') id: string, @User() currentUser: Users) {
|
||||||
return this.userService.remove(id, currentUser);
|
return this.suppressionService.deleteUser(id, currentUser);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { Parents } from 'src/entities/parents.entity';
|
|||||||
import { GestionnairesModule } from './gestionnaires/gestionnaires.module';
|
import { GestionnairesModule } from './gestionnaires/gestionnaires.module';
|
||||||
import { MailModule } from 'src/modules/mail/mail.module';
|
import { MailModule } from 'src/modules/mail/mail.module';
|
||||||
import { AppConfigModule } from 'src/modules/config/config.module';
|
import { AppConfigModule } from 'src/modules/config/config.module';
|
||||||
|
import { SuppressionsModule } from '../suppressions/suppressions.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature(
|
imports: [TypeOrmModule.forFeature(
|
||||||
@@ -26,6 +27,7 @@ import { AppConfigModule } from 'src/modules/config/config.module';
|
|||||||
GestionnairesModule,
|
GestionnairesModule,
|
||||||
MailModule,
|
MailModule,
|
||||||
AppConfigModule,
|
AppConfigModule,
|
||||||
|
SuppressionsModule,
|
||||||
],
|
],
|
||||||
controllers: [UserController],
|
controllers: [UserController],
|
||||||
providers: [UserService],
|
providers: [UserService],
|
||||||
|
|||||||
@@ -1,18 +1,87 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { BadRequestException, ForbiddenException } from '@nestjs/common';
|
||||||
import { UserService } from './user.service';
|
import { UserService } from './user.service';
|
||||||
|
import { RoleType, StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
describe('UserService.createAdmin (#161)', () => {
|
||||||
|
const usersRepository = {
|
||||||
|
findOneBy: jest.fn(),
|
||||||
|
create: jest.fn(),
|
||||||
|
save: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
describe('UserService', () => {
|
|
||||||
let service: UserService;
|
let service: UserService;
|
||||||
|
|
||||||
beforeEach(async () => {
|
const dto = {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
email: 'nouveau.admin@ptits-pas.fr',
|
||||||
providers: [UserService],
|
password: 'Password1!',
|
||||||
}).compile();
|
prenom: 'Nina',
|
||||||
|
nom: 'Admin',
|
||||||
|
telephone: '0601020304',
|
||||||
|
};
|
||||||
|
|
||||||
service = module.get<UserService>(UserService);
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
service = new UserService(
|
||||||
|
usersRepository as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('autorise un administrateur à créer un admin', async () => {
|
||||||
expect(service).toBeDefined();
|
usersRepository.findOneBy.mockResolvedValue(null);
|
||||||
|
usersRepository.create.mockImplementation((data) => data);
|
||||||
|
usersRepository.save.mockImplementation(async (entity) => ({
|
||||||
|
id: 'new-admin',
|
||||||
|
...entity,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const result = await service.createAdmin(dto as never, {
|
||||||
|
id: 'admin-1',
|
||||||
|
role: RoleType.ADMINISTRATEUR,
|
||||||
|
} as never);
|
||||||
|
|
||||||
|
expect(result.role).toBe(RoleType.ADMINISTRATEUR);
|
||||||
|
expect(result.statut).toBe(StatutUtilisateurType.ACTIF);
|
||||||
|
expect(usersRepository.save).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('autorise un super_admin à créer un admin', async () => {
|
||||||
|
usersRepository.findOneBy.mockResolvedValue(null);
|
||||||
|
usersRepository.create.mockImplementation((data) => data);
|
||||||
|
usersRepository.save.mockImplementation(async (entity) => ({
|
||||||
|
id: 'new-admin',
|
||||||
|
...entity,
|
||||||
|
}));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.createAdmin(dto as never, {
|
||||||
|
id: 'sa-1',
|
||||||
|
role: RoleType.SUPER_ADMIN,
|
||||||
|
} as never),
|
||||||
|
).resolves.toMatchObject({ role: RoleType.ADMINISTRATEUR });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse un gestionnaire (403 métier)', async () => {
|
||||||
|
await expect(
|
||||||
|
service.createAdmin(dto as never, {
|
||||||
|
id: 'gest-1',
|
||||||
|
role: RoleType.GESTIONNAIRE,
|
||||||
|
} as never),
|
||||||
|
).rejects.toBeInstanceOf(ForbiddenException);
|
||||||
|
expect(usersRepository.save).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse un email déjà utilisé', async () => {
|
||||||
|
usersRepository.findOneBy.mockResolvedValue({ id: 'exists' });
|
||||||
|
await expect(
|
||||||
|
service.createAdmin(dto as never, {
|
||||||
|
id: 'admin-1',
|
||||||
|
role: RoleType.ADMINISTRATEUR,
|
||||||
|
} as never),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { BadRequestException, ForbiddenException, Injectable, Logger, NotFoundException } from "@nestjs/common";
|
import { BadRequestException, ForbiddenException, Injectable, Logger, NotFoundException, ServiceUnavailableException } from "@nestjs/common";
|
||||||
import { InjectRepository } from "@nestjs/typeorm";
|
import { InjectRepository } from "@nestjs/typeorm";
|
||||||
import { RoleType, StatutUtilisateurType, Users } from "src/entities/users.entity";
|
import { RoleType, StatutUtilisateurType, Users } from "src/entities/users.entity";
|
||||||
import { In, MoreThan, Repository } from "typeorm";
|
import { In, MoreThan, Repository } from "typeorm";
|
||||||
@@ -117,8 +117,14 @@ export class UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async createAdmin(dto: CreateAdminDto, currentUser: Users): Promise<Users> {
|
async createAdmin(dto: CreateAdminDto, currentUser: Users): Promise<Users> {
|
||||||
if (currentUser.role !== RoleType.SUPER_ADMIN) {
|
// #161 — admin et super_admin peuvent créer un administrateur
|
||||||
throw new ForbiddenException('Seuls les super administrateurs peuvent créer un administrateur');
|
if (
|
||||||
|
currentUser.role !== RoleType.SUPER_ADMIN &&
|
||||||
|
currentUser.role !== RoleType.ADMINISTRATEUR
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Seuls les administrateurs et super administrateurs peuvent créer un administrateur',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const exist = await this.usersRepository.findOneBy({ email: dto.email });
|
const exist = await this.usersRepository.findOneBy({ email: dto.email });
|
||||||
@@ -332,7 +338,7 @@ export class UserService {
|
|||||||
return savedUser;
|
return savedUser;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Refuser un compte (en_attente -> refuse) ; tracé validations, token reprise, email. Ticket #110 */
|
/** Refuser un dossier (en_attente -> refuse) ; tracé validations, token reprise partagé, emails. Ticket #110 */
|
||||||
async refuseUser(user_id: string, currentUser: Users, comment?: string): Promise<Users> {
|
async refuseUser(user_id: string, currentUser: Users, comment?: string): Promise<Users> {
|
||||||
if (![RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE].includes(currentUser.role)) {
|
if (![RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE].includes(currentUser.role)) {
|
||||||
throw new ForbiddenException('Accès réservé aux super admins, administrateurs et gestionnaires');
|
throw new ForbiddenException('Accès réservé aux super admins, administrateurs et gestionnaires');
|
||||||
@@ -340,27 +346,58 @@ export class UserService {
|
|||||||
const user = await this.usersRepository.findOne({ where: { id: user_id } });
|
const user = await this.usersRepository.findOne({ where: { id: user_id } });
|
||||||
if (!user) throw new NotFoundException('Utilisateur introuvable');
|
if (!user) throw new NotFoundException('Utilisateur introuvable');
|
||||||
if (user.statut !== StatutUtilisateurType.EN_ATTENTE) {
|
if (user.statut !== StatutUtilisateurType.EN_ATTENTE) {
|
||||||
throw new BadRequestException('Seul un compte en attente peut être refusé.');
|
throw new BadRequestException('Seul un dossier en attente peut être refusé.');
|
||||||
}
|
}
|
||||||
|
|
||||||
const tokenReprise = crypto.randomUUID();
|
const tokenReprise = crypto.randomUUID();
|
||||||
const expireLe = new Date();
|
const expireLe = new Date();
|
||||||
expireLe.setDate(expireLe.getDate() + 7);
|
expireLe.setDate(expireLe.getDate() + 7);
|
||||||
|
|
||||||
user.statut = StatutUtilisateurType.REFUSE;
|
const usersDossier = user.role === RoleType.PARENT && user.numero_dossier
|
||||||
user.token_reprise = tokenReprise;
|
? await this.usersRepository.find({
|
||||||
user.token_reprise_expire_le = expireLe;
|
where: {
|
||||||
const savedUser = await this.usersRepository.save(user);
|
role: RoleType.PARENT,
|
||||||
|
numero_dossier: user.numero_dossier,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
: [user];
|
||||||
|
|
||||||
const validation = this.validationRepository.create({
|
const usersARefuser = usersDossier.length ? usersDossier : [user];
|
||||||
|
const utilisateurInvalide = usersARefuser.find(
|
||||||
|
(u) => u.statut !== StatutUtilisateurType.EN_ATTENTE,
|
||||||
|
);
|
||||||
|
if (utilisateurInvalide) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Tous les comptes du dossier doivent être en attente pour refuser le dossier.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const savedUsers = await this.usersRepository.manager.transaction(async (manager) => {
|
||||||
|
const updatedUsers: Users[] = [];
|
||||||
|
|
||||||
|
for (const userARefuser of usersARefuser) {
|
||||||
|
userARefuser.statut = StatutUtilisateurType.REFUSE;
|
||||||
|
userARefuser.token_reprise = tokenReprise;
|
||||||
|
userARefuser.token_reprise_expire_le = expireLe;
|
||||||
|
|
||||||
|
const savedUser = await manager.save(Users, userARefuser);
|
||||||
|
updatedUsers.push(savedUser);
|
||||||
|
|
||||||
|
const validation = manager.create(Validation, {
|
||||||
user: savedUser,
|
user: savedUser,
|
||||||
type: 'refus_compte',
|
type: 'refus_compte',
|
||||||
status: StatutValidationType.REFUSE,
|
status: StatutValidationType.REFUSE,
|
||||||
validated_by: currentUser,
|
validated_by: currentUser,
|
||||||
comment,
|
comment,
|
||||||
});
|
});
|
||||||
await this.validationRepository.save(validation);
|
await manager.save(Validation, validation);
|
||||||
|
}
|
||||||
|
|
||||||
|
return updatedUsers;
|
||||||
|
});
|
||||||
|
|
||||||
|
const emailFailures: string[] = [];
|
||||||
|
for (const savedUser of savedUsers) {
|
||||||
try {
|
try {
|
||||||
await this.mailService.sendRefusEmail(
|
await this.mailService.sendRefusEmail(
|
||||||
savedUser.email,
|
savedUser.email,
|
||||||
@@ -370,10 +407,18 @@ export class UserService {
|
|||||||
tokenReprise,
|
tokenReprise,
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.warn(`Envoi email refus échoué pour ${savedUser.email}`, err);
|
emailFailures.push(savedUser.email);
|
||||||
|
this.logger.error(`Envoi email refus échoué pour ${savedUser.email}`, err);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return savedUser;
|
if (emailFailures.length > 0) {
|
||||||
|
throw new ServiceUnavailableException(
|
||||||
|
`Le dossier a bien été refusé en base, mais l'envoi d'email a échoué pour : ${emailFailures.join(', ')}. Réessayez ou contactez le support.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return savedUsers.find((savedUser) => savedUser.id === user.id) ?? savedUsers[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -481,6 +526,7 @@ export class UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async remove(id: string, currentUser: Users): Promise<void> {
|
async remove(id: string, currentUser: Users): Promise<void> {
|
||||||
|
// Délégué historiquement ; préférer SuppressionService via controller (#159).
|
||||||
if (currentUser.role !== RoleType.SUPER_ADMIN) {
|
if (currentUser.role !== RoleType.SUPER_ADMIN) {
|
||||||
throw new ForbiddenException('Accès réservé aux super admins');
|
throw new ForbiddenException('Accès réservé aux super admins');
|
||||||
}
|
}
|
||||||
|
|||||||
+168
-110
@@ -1,3 +1,9 @@
|
|||||||
|
-- ==========================================================
|
||||||
|
-- P'titsPas — Schéma PostgreSQL (création from scratch)
|
||||||
|
-- Fichier canonique : toute nouvelle BDD doit partir d'ici.
|
||||||
|
-- Migrations dans database/migrations/ : BDD existantes uniquement.
|
||||||
|
-- ==========================================================
|
||||||
|
|
||||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
@@ -5,7 +11,9 @@ CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
|||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
DO $$ BEGIN
|
DO $$ BEGIN
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'role_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'role_type') THEN
|
||||||
CREATE TYPE role_type AS ENUM ('parent', 'gestionnaire', 'super_admin', 'administrateur', 'assistante_maternelle');
|
CREATE TYPE role_type AS ENUM (
|
||||||
|
'parent', 'gestionnaire', 'super_admin', 'administrateur', 'assistante_maternelle'
|
||||||
|
);
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'genre_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'genre_type') THEN
|
||||||
CREATE TYPE genre_type AS ENUM ('H', 'F', 'Autre');
|
CREATE TYPE genre_type AS ENUM ('H', 'F', 'Autre');
|
||||||
@@ -14,31 +22,54 @@ DO $$ BEGIN
|
|||||||
CREATE TYPE statut_utilisateur_type AS ENUM ('en_attente', 'actif', 'suspendu', 'refuse');
|
CREATE TYPE statut_utilisateur_type AS ENUM ('en_attente', 'actif', 'suspendu', 'refuse');
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_enfant_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_enfant_type') THEN
|
||||||
CREATE TYPE statut_enfant_type AS ENUM ('a_naitre','actif','scolarise');
|
CREATE TYPE statut_enfant_type AS ENUM ('a_naitre', 'garde', 'sans_garde', 'scolarise');
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_dossier_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_dossier_type') THEN
|
||||||
CREATE TYPE statut_dossier_type AS ENUM ('envoye', 'accepte', 'refuse');
|
CREATE TYPE statut_dossier_type AS ENUM ('envoye', 'accepte', 'refuse');
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_contrat_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_contrat_type') THEN
|
||||||
CREATE TYPE statut_contrat_type AS ENUM ('brouillon','en_attente_signature','valide','resilie');
|
CREATE TYPE statut_contrat_type AS ENUM (
|
||||||
|
'brouillon', 'en_attente_signature', 'valide', 'resilie'
|
||||||
|
);
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_avenant_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_avenant_type') THEN
|
||||||
CREATE TYPE statut_avenant_type AS ENUM ('propose', 'accepte', 'refuse');
|
CREATE TYPE statut_avenant_type AS ENUM ('propose', 'accepte', 'refuse');
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_evenement_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_absence_garde_type') THEN
|
||||||
CREATE TYPE type_evenement_type AS ENUM ('absence_enfant','conge_am','conge_parent','arret_maladie_am','evenement_rpe');
|
CREATE TYPE type_absence_garde_type AS ENUM (
|
||||||
|
'absence_enfant', 'conge_am', 'arret_maladie_am'
|
||||||
|
);
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_evenement_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_absence_garde_type') THEN
|
||||||
CREATE TYPE statut_evenement_type AS ENUM ('propose','valide','refuse');
|
CREATE TYPE statut_absence_garde_type AS ENUM (
|
||||||
|
'en_attente', 'accepte', 'refuse'
|
||||||
|
);
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_validation_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_validation_type') THEN
|
||||||
CREATE TYPE statut_validation_type AS ENUM ('en_attente', 'valide', 'refuse');
|
CREATE TYPE statut_validation_type AS ENUM ('en_attente', 'valide', 'refuse');
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'situation_familiale_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'situation_familiale_type') THEN
|
||||||
CREATE TYPE situation_familiale_type AS ENUM ('celibataire','marie','concubinage','pacse','separe','divorce','veuf','parent_isole');
|
CREATE TYPE situation_familiale_type AS ENUM (
|
||||||
|
'celibataire', 'marie', 'concubinage', 'pacse', 'separe', 'divorce', 'veuf', 'parent_isole'
|
||||||
|
);
|
||||||
END IF;
|
END IF;
|
||||||
END $$;
|
END $$;
|
||||||
|
|
||||||
|
-- ==========================================================
|
||||||
|
-- Table : relais (avant utilisateurs — FK relais_id)
|
||||||
|
-- ==========================================================
|
||||||
|
CREATE TABLE relais (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
nom VARCHAR(255) NOT NULL,
|
||||||
|
adresse TEXT NOT NULL,
|
||||||
|
horaires_ouverture JSONB,
|
||||||
|
ligne_fixe VARCHAR(20),
|
||||||
|
actif BOOLEAN DEFAULT true,
|
||||||
|
notes TEXT,
|
||||||
|
cree_le TIMESTAMPTZ DEFAULT now(),
|
||||||
|
modifie_le TIMESTAMPTZ DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Table : utilisateurs
|
-- Table : utilisateurs
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
@@ -46,23 +77,33 @@ CREATE TABLE utilisateurs (
|
|||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
email VARCHAR(255) NOT NULL UNIQUE,
|
email VARCHAR(255) NOT NULL UNIQUE,
|
||||||
CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'),
|
CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'),
|
||||||
password TEXT, -- NULL avant création via token
|
password TEXT,
|
||||||
prenom VARCHAR(100),
|
prenom VARCHAR(100),
|
||||||
nom VARCHAR(100),
|
nom VARCHAR(100),
|
||||||
genre genre_type,
|
genre genre_type,
|
||||||
role role_type NOT NULL,
|
role role_type NOT NULL,
|
||||||
statut statut_utilisateur_type DEFAULT 'en_attente',
|
statut statut_utilisateur_type DEFAULT 'en_attente',
|
||||||
telephone VARCHAR(20), -- Unifié (mobile privilégié)
|
telephone VARCHAR(20),
|
||||||
adresse TEXT,
|
adresse TEXT,
|
||||||
date_naissance DATE,
|
date_naissance DATE,
|
||||||
lieu_naissance_ville VARCHAR(100),
|
lieu_naissance_ville VARCHAR(100),
|
||||||
lieu_naissance_pays VARCHAR(100),
|
lieu_naissance_pays VARCHAR(100),
|
||||||
photo_url TEXT, -- Obligatoire pour AM, non utilisé pour parents
|
photo_url TEXT,
|
||||||
consentement_photo BOOLEAN DEFAULT false,
|
consentement_photo BOOLEAN DEFAULT false,
|
||||||
date_consentement_photo TIMESTAMPTZ,
|
date_consentement_photo TIMESTAMPTZ,
|
||||||
token_creation_mdp VARCHAR(255), -- Token pour créer MDP après validation
|
token_creation_mdp VARCHAR(255),
|
||||||
token_creation_mdp_expire_le TIMESTAMPTZ, -- Expiration 7 jours
|
token_creation_mdp_expire_le TIMESTAMPTZ,
|
||||||
|
password_reset_token VARCHAR(255),
|
||||||
|
password_reset_expires TIMESTAMPTZ,
|
||||||
|
token_reprise VARCHAR(255),
|
||||||
|
token_reprise_expire_le TIMESTAMPTZ,
|
||||||
changement_mdp_obligatoire BOOLEAN DEFAULT false,
|
changement_mdp_obligatoire BOOLEAN DEFAULT false,
|
||||||
|
numero_dossier VARCHAR(20),
|
||||||
|
cgu_version_acceptee INTEGER,
|
||||||
|
cgu_acceptee_le TIMESTAMPTZ,
|
||||||
|
privacy_version_acceptee INTEGER,
|
||||||
|
privacy_acceptee_le TIMESTAMPTZ,
|
||||||
|
relais_id UUID REFERENCES relais(id) ON DELETE SET NULL,
|
||||||
cree_le TIMESTAMPTZ DEFAULT now(),
|
cree_le TIMESTAMPTZ DEFAULT now(),
|
||||||
modifie_le TIMESTAMPTZ DEFAULT now(),
|
modifie_le TIMESTAMPTZ DEFAULT now(),
|
||||||
ville VARCHAR(150),
|
ville VARCHAR(150),
|
||||||
@@ -71,11 +112,22 @@ CREATE TABLE utilisateurs (
|
|||||||
situation_familiale situation_familiale_type
|
situation_familiale situation_familiale_type
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Index pour recherche par token
|
|
||||||
CREATE INDEX idx_utilisateurs_token_creation_mdp
|
CREATE INDEX idx_utilisateurs_token_creation_mdp
|
||||||
ON utilisateurs(token_creation_mdp)
|
ON utilisateurs(token_creation_mdp)
|
||||||
WHERE token_creation_mdp IS NOT NULL;
|
WHERE token_creation_mdp IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE INDEX idx_utilisateurs_password_reset_token
|
||||||
|
ON utilisateurs(password_reset_token)
|
||||||
|
WHERE password_reset_token IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE INDEX idx_utilisateurs_token_reprise
|
||||||
|
ON utilisateurs(token_reprise)
|
||||||
|
WHERE token_reprise IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE INDEX idx_utilisateurs_numero_dossier
|
||||||
|
ON utilisateurs(numero_dossier)
|
||||||
|
WHERE numero_dossier IS NOT NULL;
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Table : assistantes_maternelles
|
-- Table : assistantes_maternelles
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
@@ -90,17 +142,33 @@ CREATE TABLE assistantes_maternelles (
|
|||||||
date_agrement DATE,
|
date_agrement DATE,
|
||||||
annee_experience SMALLINT,
|
annee_experience SMALLINT,
|
||||||
specialite VARCHAR(100),
|
specialite VARCHAR(100),
|
||||||
place_disponible INT
|
place_disponible INT,
|
||||||
|
numero_dossier VARCHAR(20),
|
||||||
|
-- Préférence couple de garde actif (TdB quotidien AM) — ticket #171
|
||||||
|
-- FK ajoutée après création de enfants_assistantes_maternelles (voir ALTER plus bas)
|
||||||
|
id_placement_garde_courant UUID
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_assistantes_maternelles_numero_dossier
|
||||||
|
ON assistantes_maternelles(numero_dossier)
|
||||||
|
WHERE numero_dossier IS NOT NULL;
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Table : parents
|
-- Table : parents
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
CREATE TABLE parents (
|
CREATE TABLE parents (
|
||||||
id_utilisateur UUID PRIMARY KEY REFERENCES utilisateurs(id) ON DELETE CASCADE,
|
id_utilisateur UUID PRIMARY KEY REFERENCES utilisateurs(id) ON DELETE CASCADE,
|
||||||
id_co_parent UUID REFERENCES utilisateurs(id)
|
id_co_parent UUID REFERENCES utilisateurs(id),
|
||||||
|
numero_dossier VARCHAR(20),
|
||||||
|
-- Préférence couple de garde actif (TdB quotidien) — ticket #168
|
||||||
|
-- FK ajoutée après création de enfants_assistantes_maternelles (voir ALTER plus bas)
|
||||||
|
id_placement_garde_courant UUID
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_parents_numero_dossier
|
||||||
|
ON parents(numero_dossier)
|
||||||
|
WHERE numero_dossier IS NOT NULL;
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Table : enfants
|
-- Table : enfants
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
@@ -109,13 +177,12 @@ CREATE TABLE enfants (
|
|||||||
statut statut_enfant_type,
|
statut statut_enfant_type,
|
||||||
prenom VARCHAR(100),
|
prenom VARCHAR(100),
|
||||||
nom VARCHAR(100),
|
nom VARCHAR(100),
|
||||||
genre genre_type NOT NULL, -- Obligatoire selon CDC
|
genre genre_type NOT NULL,
|
||||||
date_naissance DATE,
|
date_naissance DATE,
|
||||||
date_prevue_naissance DATE,
|
date_prevue_naissance DATE,
|
||||||
photo_url TEXT,
|
photo_url TEXT,
|
||||||
consentement_photo BOOLEAN DEFAULT false,
|
consentement_photo BOOLEAN DEFAULT false,
|
||||||
date_consentement_photo TIMESTAMPTZ,
|
date_consentement_photo TIMESTAMPTZ
|
||||||
est_multiple BOOLEAN DEFAULT false
|
|
||||||
);
|
);
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
@@ -128,7 +195,47 @@ CREATE TABLE enfants_parents (
|
|||||||
);
|
);
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Table : dossier_famille (inscription parent, schéma simplifié — ticket #119)
|
-- Table : enfants_assistantes_maternelles (placement AM ↔ enfant — #131)
|
||||||
|
-- ==========================================================
|
||||||
|
CREATE TABLE enfants_assistantes_maternelles (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
id_am UUID NOT NULL REFERENCES assistantes_maternelles(id_utilisateur) ON DELETE CASCADE,
|
||||||
|
id_enfant UUID NOT NULL REFERENCES enfants(id) ON DELETE CASCADE,
|
||||||
|
date_debut DATE NOT NULL DEFAULT CURRENT_DATE,
|
||||||
|
date_fin DATE NULL,
|
||||||
|
cree_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
cree_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_eam_am ON enfants_assistantes_maternelles(id_am);
|
||||||
|
CREATE INDEX idx_eam_enfant ON enfants_assistantes_maternelles(id_enfant);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX uq_enfant_garde_active
|
||||||
|
ON enfants_assistantes_maternelles (id_enfant)
|
||||||
|
WHERE date_fin IS NULL;
|
||||||
|
|
||||||
|
-- FK couple courant parent → placement (#168) — après table enfants_assistantes_maternelles
|
||||||
|
ALTER TABLE parents
|
||||||
|
ADD CONSTRAINT fk_parents_placement_garde_courant
|
||||||
|
FOREIGN KEY (id_placement_garde_courant)
|
||||||
|
REFERENCES enfants_assistantes_maternelles(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX idx_parents_placement_garde_courant
|
||||||
|
ON parents(id_placement_garde_courant)
|
||||||
|
WHERE id_placement_garde_courant IS NOT NULL;
|
||||||
|
|
||||||
|
-- FK couple courant AM → placement (#171)
|
||||||
|
ALTER TABLE assistantes_maternelles
|
||||||
|
ADD CONSTRAINT fk_am_placement_garde_courant
|
||||||
|
FOREIGN KEY (id_placement_garde_courant)
|
||||||
|
REFERENCES enfants_assistantes_maternelles(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE INDEX idx_am_placement_garde_courant
|
||||||
|
ON assistantes_maternelles(id_placement_garde_courant)
|
||||||
|
WHERE id_placement_garde_courant IS NOT NULL;
|
||||||
|
|
||||||
|
-- ==========================================================
|
||||||
|
-- Table : dossier_famille (inscription parent — ticket #119)
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
CREATE TABLE dossier_famille (
|
CREATE TABLE dossier_famille (
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
@@ -215,25 +322,34 @@ CREATE TABLE avenants_contrats (
|
|||||||
);
|
);
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Table : evenements
|
-- Table : absences_garde (vérité métier absences/congés/arrêt)
|
||||||
|
-- 1 ligne = 1 période ; rattachement = placement AM↔enfant (#193)
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
CREATE TABLE evenements (
|
CREATE TABLE absences_garde (
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
type type_evenement_type,
|
id_placement UUID NOT NULL
|
||||||
id_enfant UUID REFERENCES enfants(id) ON DELETE CASCADE,
|
REFERENCES enfants_assistantes_maternelles(id) ON DELETE CASCADE,
|
||||||
id_am UUID REFERENCES utilisateurs(id),
|
type type_absence_garde_type NOT NULL,
|
||||||
id_parent UUID REFERENCES parents(id_utilisateur),
|
date_debut DATE NOT NULL,
|
||||||
cree_par UUID REFERENCES utilisateurs(id),
|
date_fin DATE NOT NULL,
|
||||||
date_debut TIMESTAMPTZ,
|
statut statut_absence_garde_type NOT NULL DEFAULT 'en_attente',
|
||||||
date_fin TIMESTAMPTZ,
|
expire_at TIMESTAMPTZ NOT NULL,
|
||||||
commentaires TEXT,
|
cree_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
||||||
statut statut_evenement_type DEFAULT 'propose',
|
id_card_instance UUID,
|
||||||
delai_grace TIMESTAMPTZ,
|
motif TEXT,
|
||||||
urgent BOOLEAN DEFAULT false,
|
cree_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
cree_le TIMESTAMPTZ DEFAULT now(),
|
modifie_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
modifie_le TIMESTAMPTZ DEFAULT now()
|
CONSTRAINT chk_absences_garde_dates CHECK (date_fin >= date_debut)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_absences_garde_placement_dates
|
||||||
|
ON absences_garde (id_placement, date_debut, date_fin);
|
||||||
|
CREATE INDEX idx_absences_garde_placement_type_statut
|
||||||
|
ON absences_garde (id_placement, type, statut);
|
||||||
|
CREATE INDEX idx_absences_garde_expire_at
|
||||||
|
ON absences_garde (expire_at)
|
||||||
|
WHERE statut IN ('en_attente', 'refuse');
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Table : signalements_bugs
|
-- Table : signalements_bugs
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
@@ -269,10 +385,6 @@ CREATE TABLE notifications (
|
|||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Table : validations
|
-- Table : validations
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Historique des décisions (validation / refus / suspension de compte).
|
|
||||||
-- Colonnes commentaire + valide_par : requises par l’API Nest (TypeORM).
|
|
||||||
-- FK en ON DELETE SET NULL : conserver la ligne si l’utilisateur référencé
|
|
||||||
-- est supprimé (voir database/docs/FK_POLICIES.md).
|
|
||||||
CREATE TABLE validations (
|
CREATE TABLE validations (
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
id_utilisateur UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
id_utilisateur UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
||||||
@@ -298,13 +410,10 @@ CREATE TABLE configuration (
|
|||||||
modifie_par UUID REFERENCES utilisateurs(id)
|
modifie_par UUID REFERENCES utilisateurs(id)
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Index pour performance
|
|
||||||
CREATE INDEX idx_configuration_cle ON configuration(cle);
|
CREATE INDEX idx_configuration_cle ON configuration(cle);
|
||||||
CREATE INDEX idx_configuration_categorie ON configuration(categorie);
|
CREATE INDEX idx_configuration_categorie ON configuration(categorie);
|
||||||
|
|
||||||
-- Seed initial de configuration
|
|
||||||
INSERT INTO configuration (cle, valeur, type, categorie, description) VALUES
|
INSERT INTO configuration (cle, valeur, type, categorie, description) VALUES
|
||||||
-- === Configuration Email (SMTP) ===
|
|
||||||
('smtp_host', 'localhost', 'string', 'email', 'Serveur SMTP (ex: mail.mairie-bezons.fr, smtp.gmail.com)'),
|
('smtp_host', 'localhost', 'string', 'email', 'Serveur SMTP (ex: mail.mairie-bezons.fr, smtp.gmail.com)'),
|
||||||
('smtp_port', '25', 'number', 'email', 'Port SMTP (25, 465, 587)'),
|
('smtp_port', '25', 'number', 'email', 'Port SMTP (25, 465, 587)'),
|
||||||
('smtp_secure', 'false', 'boolean', 'email', 'Utiliser SSL/TLS (true pour port 465)'),
|
('smtp_secure', 'false', 'boolean', 'email', 'Utiliser SSL/TLS (true pour port 465)'),
|
||||||
@@ -313,14 +422,10 @@ INSERT INTO configuration (cle, valeur, type, categorie, description) VALUES
|
|||||||
('smtp_password', '', 'encrypted', 'email', 'Mot de passe SMTP (chiffré en AES-256)'),
|
('smtp_password', '', 'encrypted', 'email', 'Mot de passe SMTP (chiffré en AES-256)'),
|
||||||
('email_from_name', 'P''titsPas', 'string', 'email', 'Nom de l''expéditeur affiché dans les emails'),
|
('email_from_name', 'P''titsPas', 'string', 'email', 'Nom de l''expéditeur affiché dans les emails'),
|
||||||
('email_from_address', 'no-reply@ptits-pas.fr', 'string', 'email', 'Adresse email de l''expéditeur'),
|
('email_from_address', 'no-reply@ptits-pas.fr', 'string', 'email', 'Adresse email de l''expéditeur'),
|
||||||
|
|
||||||
-- === Configuration Application ===
|
|
||||||
('app_name', 'P''titsPas', 'string', 'app', 'Nom de l''application (affiché dans l''interface)'),
|
('app_name', 'P''titsPas', 'string', 'app', 'Nom de l''application (affiché dans l''interface)'),
|
||||||
('app_url', 'https://app.ptits-pas.fr', 'string', 'app', 'URL publique de l''application (pour les liens dans emails)'),
|
('app_url', 'https://app.ptits-pas.fr', 'string', 'app', 'URL publique de l''application (pour les liens dans emails)'),
|
||||||
('app_logo_url', '/assets/logo.png', 'string', 'app', 'URL du logo de l''application'),
|
('app_logo_url', '/assets/logo.png', 'string', 'app', 'URL du logo de l''application'),
|
||||||
('setup_completed', 'false', 'boolean', 'app', 'Configuration initiale terminée'),
|
('setup_completed', 'false', 'boolean', 'app', 'Configuration initiale terminée'),
|
||||||
|
|
||||||
-- === Configuration Sécurité ===
|
|
||||||
('password_reset_token_expiry_days', '7', 'number', 'security', 'Durée de validité des tokens de création/réinitialisation de mot de passe (en jours)'),
|
('password_reset_token_expiry_days', '7', 'number', 'security', 'Durée de validité des tokens de création/réinitialisation de mot de passe (en jours)'),
|
||||||
('jwt_expiry_hours', '24', 'number', 'security', 'Durée de validité des sessions JWT (en heures)'),
|
('jwt_expiry_hours', '24', 'number', 'security', 'Durée de validité des sessions JWT (en heures)'),
|
||||||
('max_upload_size_mb', '5', 'number', 'security', 'Taille maximale des fichiers uploadés (en MB)'),
|
('max_upload_size_mb', '5', 'number', 'security', 'Taille maximale des fichiers uploadés (en MB)'),
|
||||||
@@ -331,19 +436,18 @@ INSERT INTO configuration (cle, valeur, type, categorie, description) VALUES
|
|||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
CREATE TABLE documents_legaux (
|
CREATE TABLE documents_legaux (
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
type VARCHAR(50) NOT NULL, -- 'cgu' ou 'privacy'
|
type VARCHAR(50) NOT NULL,
|
||||||
version INTEGER NOT NULL, -- Numéro de version (auto-incrémenté)
|
version INTEGER NOT NULL,
|
||||||
fichier_nom VARCHAR(255) NOT NULL, -- Nom original du fichier
|
fichier_nom VARCHAR(255) NOT NULL,
|
||||||
fichier_path VARCHAR(500) NOT NULL, -- Chemin de stockage
|
fichier_path VARCHAR(500) NOT NULL,
|
||||||
fichier_hash VARCHAR(64) NOT NULL, -- Hash SHA-256 pour intégrité
|
fichier_hash VARCHAR(64) NOT NULL,
|
||||||
actif BOOLEAN DEFAULT false, -- Version actuellement active
|
actif BOOLEAN DEFAULT false,
|
||||||
televerse_par UUID REFERENCES utilisateurs(id), -- Qui a uploadé
|
televerse_par UUID REFERENCES utilisateurs(id),
|
||||||
televerse_le TIMESTAMPTZ DEFAULT now(), -- Date d'upload
|
televerse_le TIMESTAMPTZ DEFAULT now(),
|
||||||
active_le TIMESTAMPTZ, -- Date d'activation
|
active_le TIMESTAMPTZ,
|
||||||
UNIQUE(type, version) -- Pas de doublon version
|
UNIQUE(type, version)
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Index pour performance
|
|
||||||
CREATE INDEX idx_documents_legaux_type_actif ON documents_legaux(type, actif);
|
CREATE INDEX idx_documents_legaux_type_actif ON documents_legaux(type, actif);
|
||||||
CREATE INDEX idx_documents_legaux_version ON documents_legaux(type, version DESC);
|
CREATE INDEX idx_documents_legaux_version ON documents_legaux(type, version DESC);
|
||||||
|
|
||||||
@@ -354,66 +458,23 @@ CREATE TABLE acceptations_documents (
|
|||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
id_utilisateur UUID REFERENCES utilisateurs(id) ON DELETE CASCADE,
|
id_utilisateur UUID REFERENCES utilisateurs(id) ON DELETE CASCADE,
|
||||||
id_document UUID REFERENCES documents_legaux(id),
|
id_document UUID REFERENCES documents_legaux(id),
|
||||||
type_document VARCHAR(50) NOT NULL, -- 'cgu' ou 'privacy'
|
type_document VARCHAR(50) NOT NULL,
|
||||||
version_document INTEGER NOT NULL, -- Version acceptée
|
version_document INTEGER NOT NULL,
|
||||||
accepte_le TIMESTAMPTZ DEFAULT now(), -- Date d'acceptation
|
accepte_le TIMESTAMPTZ DEFAULT now(),
|
||||||
ip_address INET, -- IP de l'utilisateur (RGPD)
|
ip_address INET,
|
||||||
user_agent TEXT -- Navigateur (preuve)
|
user_agent TEXT
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Index pour performance
|
|
||||||
CREATE INDEX idx_acceptations_utilisateur ON acceptations_documents(id_utilisateur);
|
CREATE INDEX idx_acceptations_utilisateur ON acceptations_documents(id_utilisateur);
|
||||||
CREATE INDEX idx_acceptations_document ON acceptations_documents(id_document);
|
CREATE INDEX idx_acceptations_document ON acceptations_documents(id_document);
|
||||||
|
|
||||||
-- ==========================================================
|
|
||||||
-- Table : relais
|
|
||||||
-- ==========================================================
|
|
||||||
CREATE TABLE relais (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
nom VARCHAR(255) NOT NULL,
|
|
||||||
adresse TEXT NOT NULL,
|
|
||||||
horaires_ouverture JSONB,
|
|
||||||
ligne_fixe VARCHAR(20),
|
|
||||||
actif BOOLEAN DEFAULT true,
|
|
||||||
notes TEXT,
|
|
||||||
cree_le TIMESTAMPTZ DEFAULT now(),
|
|
||||||
modifie_le TIMESTAMPTZ DEFAULT now()
|
|
||||||
);
|
|
||||||
|
|
||||||
-- ==========================================================
|
|
||||||
-- Modification Table : utilisateurs (ajout colonnes documents et relais)
|
|
||||||
-- ==========================================================
|
|
||||||
ALTER TABLE utilisateurs
|
|
||||||
ADD COLUMN IF NOT EXISTS cgu_version_acceptee INTEGER,
|
|
||||||
ADD COLUMN IF NOT EXISTS cgu_acceptee_le TIMESTAMPTZ,
|
|
||||||
ADD COLUMN IF NOT EXISTS privacy_version_acceptee INTEGER,
|
|
||||||
ADD COLUMN IF NOT EXISTS privacy_acceptee_le TIMESTAMPTZ,
|
|
||||||
ADD COLUMN IF NOT EXISTS relais_id UUID REFERENCES relais(id) ON DELETE SET NULL;
|
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Ticket #103 : Numéro de dossier (AAAA-NNNNNN, séquence par année)
|
-- Ticket #103 : Numéro de dossier (AAAA-NNNNNN, séquence par année)
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
CREATE TABLE IF NOT EXISTS numero_dossier_sequence (
|
CREATE TABLE numero_dossier_sequence (
|
||||||
annee INT PRIMARY KEY,
|
annee INT PRIMARY KEY,
|
||||||
prochain INT NOT NULL DEFAULT 1
|
prochain INT NOT NULL DEFAULT 1
|
||||||
);
|
);
|
||||||
ALTER TABLE utilisateurs ADD COLUMN IF NOT EXISTS numero_dossier VARCHAR(20) NULL;
|
|
||||||
ALTER TABLE assistantes_maternelles ADD COLUMN IF NOT EXISTS numero_dossier VARCHAR(20) NULL;
|
|
||||||
ALTER TABLE parents ADD COLUMN IF NOT EXISTS numero_dossier VARCHAR(20) NULL;
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_utilisateurs_numero_dossier ON utilisateurs(numero_dossier) WHERE numero_dossier IS NOT NULL;
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_assistantes_maternelles_numero_dossier ON assistantes_maternelles(numero_dossier) WHERE numero_dossier IS NOT NULL;
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_parents_numero_dossier ON parents(numero_dossier) WHERE numero_dossier IS NOT NULL;
|
|
||||||
|
|
||||||
-- ==========================================================
|
|
||||||
-- Ticket #110 : Token reprise après refus (lien email)
|
|
||||||
-- ==========================================================
|
|
||||||
ALTER TABLE utilisateurs ADD COLUMN IF NOT EXISTS token_reprise VARCHAR(255) NULL;
|
|
||||||
ALTER TABLE utilisateurs ADD COLUMN IF NOT EXISTS token_reprise_expire_le TIMESTAMPTZ NULL;
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_utilisateurs_token_reprise ON utilisateurs(token_reprise) WHERE token_reprise IS NOT NULL;
|
|
||||||
|
|
||||||
-- Lieu de naissance (aligné CREATE TABLE utilisateurs — idempotent si colonnes déjà présentes)
|
|
||||||
ALTER TABLE utilisateurs ADD COLUMN IF NOT EXISTS lieu_naissance_ville VARCHAR(100) NULL;
|
|
||||||
ALTER TABLE utilisateurs ADD COLUMN IF NOT EXISTS lieu_naissance_pays VARCHAR(100) NULL;
|
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Seed : Documents légaux génériques v1
|
-- Seed : Documents légaux génériques v1
|
||||||
@@ -424,10 +485,7 @@ INSERT INTO documents_legaux (type, version, fichier_nom, fichier_path, fichier_
|
|||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Seed : Super Administrateur par défaut
|
-- Seed : Super Administrateur par défaut
|
||||||
-- ==========================================================
|
-- Email: admin@ptits-pas.fr | Mot de passe: 4dm1n1strateur
|
||||||
-- Email: admin@ptits-pas.fr
|
|
||||||
-- Mot de passe: 4dm1n1strateur (hashé bcrypt)
|
|
||||||
-- IMPORTANT: Changer ce mot de passe en production !
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
INSERT INTO utilisateurs (
|
INSERT INTO utilisateurs (
|
||||||
email,
|
email,
|
||||||
|
|||||||
+6
-5
@@ -15,12 +15,13 @@ Ce projet contient la **base de données** pour l'application PtitsPas, avec scr
|
|||||||
|
|
||||||
## Structure du projet
|
## Structure du projet
|
||||||
|
|
||||||
- `migrations/` : scripts SQL pour la création et l'import de la base
|
- **`BDD.sql`** : schéma canonique (création from scratch — utilisé par `docker-compose.yml` racine)
|
||||||
- `bdd/data_test/` : fichiers CSV pour l'import de données de test
|
- `migrations/` : scripts SQL pour **mettre à jour** une BDD déjà en service
|
||||||
- `docs/` : documentation métier et technique
|
- `bdd/data_test/` : fichiers CSV (import legacy)
|
||||||
- `seed/` : scripts de seed
|
- `docs/` : documentation métier et technique (`ENUMS.md`, `FK_POLICIES.md`)
|
||||||
|
- `seed/` : scripts de seed (`03_seed_test_data.sql` — jeu dashboard admin)
|
||||||
- `tests/` : tests SQL
|
- `tests/` : tests SQL
|
||||||
- `docker-compose.dev.yml` : configuration Docker pour le développement
|
- `docker-compose.dev.yml` : Postgres standalone (BDD.sql + seed auto)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
"id","statut","prenom","nom","genre","date_naissance","date_prevue_naissance","photo_url","consentement_photo","date_consentement_photo","est_multiple"
|
"id","statut","prenom","nom","genre","date_naissance","date_prevue_naissance","photo_url","consentement_photo","date_consentement_photo"
|
||||||
"5e8574b7-63e6-4d48-9af3-8d3bf7a6a6cf","actif","Emma","Dupont","F","2020-06-01",,,False,,False
|
"5e8574b7-63e6-4d48-9af3-8d3bf7a6a6cf","sans_garde","Emma","Dupont","F","2020-06-01",,,False,
|
||||||
"a5c3268e-07eb-41a4-9f6c-2f9f16f37c3d","actif",,,,"2020-01-01","2025-01-01",,False,,False
|
"a5c3268e-07eb-41a4-9f6c-2f9f16f37c3d","sans_garde",,,,"2020-01-01","2025-01-01",,False,
|
||||||
"e1a2b3c4-d5e6-4f7a-8b9c-1d2e3f4a5b6c","actif","Emma","Martin",,"2023-02-15",,,False,,False
|
"e1a2b3c4-d5e6-4f7a-8b9c-1d2e3f4a5b6c","sans_garde","Emma","Martin",,"2023-02-15",,,False,
|
||||||
"e2b3c4d5-e6f7-4a8b-9c1d-2e3f4a5b6c7d","actif","Noah","Martin",,"2023-02-15",,,False,,False
|
"e2b3c4d5-e6f7-4a8b-9c1d-2e3f4a5b6c7d","sans_garde","Noah","Martin",,"2023-02-15",,,False,
|
||||||
"e3c4d5e6-f7a8-4b9c-1d2e-3f4a5b6c7d8e","actif","Léa","Martin",,"2023-02-15",,,False,,False
|
"e3c4d5e6-f7a8-4b9c-1d2e-3f4a5b6c7d8e","sans_garde","Léa","Martin",,"2023-02-15",,,False,
|
||||||
"e4d5e6f7-a8b9-4c1d-2e3f-4a5b6c7d8e9f","actif","Chloé","Rousseau",,"2022-04-20",,,False,,False
|
"e4d5e6f7-a8b9-4c1d-2e3f-4a5b6c7d8e9f","sans_garde","Chloé","Rousseau",,"2022-04-20",,,False,
|
||||||
"e5e6f7a8-b9c1-4d2e-3f4a-5b6c7d8e9f1a","actif","Hugo","Rousseau",,"2024-03-10",,,False,,False
|
"e5e6f7a8-b9c1-4d2e-3f4a-5b6c7d8e9f1a","sans_garde","Hugo","Rousseau",,"2024-03-10",,,False,
|
||||||
"e6f7a8b9-c1d2-4e3f-5a6b-7c8d9e0f1a2b","actif","Maxime","Lecomte",,"2023-04-15",,,False,,False
|
"e6f7a8b9-c1d2-4e3f-5a6b-7c8d9e0f1a2b","sans_garde","Maxime","Lecomte",,"2023-04-15",,,False,
|
||||||
"edd19cd1-bb67-4f14-8a37-c66b75c94537","scolarise","Lucas","Durand","H","2018-09-15",,,False,,False
|
"edd19cd1-bb67-4f14-8a37-c66b75c94537","scolarise","Lucas","Durand","H","2018-09-15",,,False,
|
||||||
|
|||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user