Compare commits
148
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8105c01501 | ||
|
|
2fa1e4a981 | ||
|
|
0cc6fa3a9d | ||
|
|
0befd4eb2a | ||
|
|
f442c85cb6 | ||
|
|
ab7845347b | ||
|
|
011ab26828 | ||
|
|
a9ce4a6756 | ||
|
|
d550e57cb8 | ||
|
|
b4b44cb1b9 | ||
|
|
58607cdbc9 | ||
|
|
12bf85b7bd | ||
|
|
01c1be8f16 | ||
|
|
cdae9b5f7c | ||
|
|
73efac482f | ||
|
|
62b2466cce | ||
|
|
d69768806c | ||
|
|
eac108c9f4 | ||
|
|
4dedd9b87a | ||
|
|
518b3f84df | ||
|
|
dc04e04598 | ||
|
|
fdd1e06e77 | ||
|
|
f1c9db2e7b | ||
|
|
ccfcfa3287 | ||
|
|
dbca12d5d1 | ||
|
|
4fe29799cd | ||
|
|
3bfdadd301 | ||
|
|
09289882d0 | ||
|
|
e7f0037ac3 | ||
|
|
4969be5809 | ||
|
|
d7ccbfbe35 | ||
|
|
2b3128ce4a | ||
|
|
077a1ca3ed | ||
|
|
bf05b1d7d7 | ||
|
|
110240b682 | ||
|
|
a723412043 | ||
|
|
1e21fe25f3 | ||
|
|
cd2bf63b8a | ||
|
|
de60a001cc | ||
|
|
481fa66630 | ||
|
|
cde676c4f9 | ||
|
|
0a07fade40 | ||
|
|
0e8a999e41 | ||
|
|
2e02f60601 | ||
|
|
0e6e473e84 | ||
|
|
cc3639b19a | ||
|
|
cf9cd495bf | ||
|
|
76ba28a7ce | ||
|
|
1772744c81 | ||
|
|
5465117238 | ||
|
|
6e2343087e | ||
|
|
f6fabc521e | ||
|
|
5390276ecd | ||
|
|
7e9306de01 | ||
|
|
d832559027 | ||
|
|
54ad1d2aa1 | ||
|
|
060e610a75 | ||
|
|
86b28abe51 | ||
|
|
7e32eef0a7 | ||
|
|
86d8189038 | ||
|
|
aa4e240ad1 | ||
|
|
dbcb3611d4 | ||
|
|
a92447aaf0 | ||
|
|
1fa70f4052 | ||
|
|
94c8a0d97a | ||
|
|
393a527c37 | ||
|
|
af489f39b4 | ||
|
|
dfd58d9b6c | ||
|
|
34a36b069e | ||
|
|
aefe590d2c | ||
|
|
2fa546e6b7 | ||
|
|
8636b16659 | ||
|
|
7e17e5ff8d | ||
|
|
f749484731 | ||
|
|
e8b6d906e6 | ||
|
|
ae0be04964 | ||
|
|
ca98821b3e | ||
|
|
447f3d4137 | ||
|
|
721f40599b | ||
|
|
a9c6b9e15b | ||
|
|
38c003ef6f | ||
|
|
3dbddbb8c4 | ||
|
|
f46740c6ab | ||
|
|
85bfef7a6b | ||
|
|
b1a80f85c9 | ||
|
|
3c2ecdff7a | ||
|
|
8b83702bd2 | ||
|
|
19b8be684f | ||
|
|
e713c05da1 | ||
|
|
5950d85876 | ||
|
|
4339e1e53d | ||
|
|
51d279e341 | ||
|
|
fffe8cd202 | ||
|
|
defa438edf | ||
|
|
e990d576cf | ||
|
|
619e39219f | ||
|
|
e8c6665a06 | ||
|
|
a4e6cfc50e | ||
|
|
6749f2025a | ||
|
|
119edbcfb4 | ||
|
|
80d69a5463 | ||
|
|
0579fda553 | ||
|
|
d14550a1cf | ||
|
|
2645cf1cd6 | ||
|
|
e2ebc6a0a1 | ||
|
|
090ce6e13b | ||
|
|
d66bdd04be | ||
|
|
d8572e7fd6 | ||
|
|
33cc7a9191 | ||
|
|
222d7c702f | ||
|
|
537c46127f | ||
|
|
10ebc77ba1 | ||
|
|
ed18dcab10 | ||
|
|
f9477d3fbe | ||
|
|
bb92f010bd | ||
|
|
42bb872c41 | ||
|
|
4d37131301 | ||
|
|
fac3ae9baa | ||
|
|
04b910295c | ||
|
|
5c28981ac5 | ||
|
|
57ce5af0f4 | ||
|
|
c136f28f12 | ||
|
|
c1204a3050 | ||
|
|
9d4363b2a7 | ||
|
|
4b176b7083 | ||
|
|
af06ab1e66 | ||
|
|
aa148354ec | ||
|
|
00c42c7bee | ||
|
|
a10dc5a195 | ||
|
|
04c0b05aae | ||
|
|
d0b730c8ab | ||
|
|
bc8362bdb7 | ||
|
|
ac3178903d | ||
|
|
aec1990ec9 | ||
|
|
5da2ab9005 | ||
|
|
b2d6414fab | ||
|
|
fbafef8f2c | ||
|
|
42c569e491 | ||
|
|
135c7c2255 | ||
|
|
9cce326046 | ||
|
|
d697083f54 | ||
|
|
ae786426fd | ||
|
|
d32d956b0e | ||
|
|
e4f7a35f0f | ||
|
|
8a6768b316 | ||
|
|
3892a8beab | ||
|
|
d39bc55be3 | ||
|
|
e0debf0394 |
@@ -12,6 +12,7 @@ dist/
|
||||
.env.*.local
|
||||
|
||||
# IDE
|
||||
.cursor/
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
|
||||
@@ -22,5 +22,13 @@ JWT_EXPIRATION_TIME=7d
|
||||
# Environnement
|
||||
NODE_ENV=development
|
||||
|
||||
# Photos inscription (fichiers écrits depuis base64). Préférer un chemin ABSOLU.
|
||||
# Local : laisser vide → ./uploads/photos (relatif au cwd du processus).
|
||||
# Docker (docker-compose) : UPLOAD_PHOTOS_DIR=/app/uploads/photos + volume nommé (voir docker-compose.yml).
|
||||
# UPLOAD_PHOTOS_DIR=
|
||||
#
|
||||
# Reverse proxy : si Nginx devant l’API, augmenter la taille du corps (ex. client_max_body_size 16m;).
|
||||
# Traefik en reverse proxy simple ne limite en général pas le corps ; si middleware buffering, prévoir ~16 Mo+.
|
||||
|
||||
# Log de chaque appel API (mode debug) — mettre à true pour tracer les requêtes front
|
||||
# LOG_API_REQUESTS=true
|
||||
|
||||
@@ -19,7 +19,8 @@
|
||||
"test:watch": "jest --watch",
|
||||
"test:cov": "jest --coverage",
|
||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||
"test:api-dossiers": "node scripts/test-api-dossiers.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.1.6",
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Commentaire de clôture + fermeture issue Gitea #120.
|
||||
* Usage: node backend/scripts/close-gitea-issue-120.js
|
||||
* Token : .gitea-token (racine), GITEA_TOKEN, ou docs/BRIEFING-FRONTEND.md
|
||||
*/
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const repoRoot = path.join(__dirname, '../..');
|
||||
const ISSUE = 120;
|
||||
const REPO = 'jmartin/petitspas';
|
||||
|
||||
const body = `## Fermeture ticket #120 — livré sur \`develop\`
|
||||
|
||||
Branche **\`feature/120-inscription-am-photo\`** mergée dans **\`develop\`** (livraison : inscription AM alignée parents + panneau validation gestionnaire).
|
||||
|
||||
### Inscription AM (alignement parents)
|
||||
- Photo, consentement, lieux de naissance : parcours et API alignés sur le modèle parents (DTO, entité user, migration SQL, écrans inscription AM, \`registration_photo_slot\`, scripts de test Node).
|
||||
|
||||
### Panneau gestionnaire — onglet « À valider »
|
||||
- Bouton **Ouvrir** : visible au **survol** (même principe que les cartes admin), **icône centrée** sur la ligne et **taille doublée** (\`iconSize\` 34).
|
||||
|
||||
### Wizard validation dossier AM
|
||||
- Titres : **Identité et coordonnées** · **Dossier professionnel** (au-dessus des champs à droite, pas de la photo) · **Présentation**.
|
||||
- **Photo** à gauche (ratio identité 35×45) ; **grille droite** \`[2,2,2,2]\` : NIR | date de naissance, ville | pays de naissance, n° agrément | date d'agrément, capacité | places.
|
||||
- **\`AppUser\`** : \`date_naissance\`, \`lieu_naissance_ville\`, \`lieu_naissance_pays\` ; affichage dates **\`dd/MM/yyyy\`** (\`formatIsoDateFr\`).
|
||||
- **\`ValidationDetailSection\`** : titre **optionnel** (wizard AM).
|
||||
|
||||
### Wizard validation famille
|
||||
- Étape 4 : titre **« Présentation »** (plus « Présentation / Motivation »).
|
||||
|
||||
### Nettoyage
|
||||
- Suppression des **\`debugPrint\`** liés aux médias / images / chargement dossier (\`api_config\`, \`auth_network_image\`, \`dossier_unifie\`, \`user_service\`, carte enfant validation).
|
||||
|
||||
---
|
||||
*Issue fermée après merge sur \`develop\` et recette.*`;
|
||||
|
||||
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/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,89 @@
|
||||
/**
|
||||
* Crée l'issue Gitea "[Frontend] Inscription Parent – Branchement soumission formulaire à l'API"
|
||||
* Usage: node backend/scripts/create-gitea-issue-parent-api.js
|
||||
* Token : .gitea-token (racine du dépôt), sinon GITEA_TOKEN, sinon docs/BRIEFING-FRONTEND.md (voir PROCEDURE-API-GITEA.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/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é : créer .gitea-token à la racine ou export GITEA_TOKEN (voir docs/PROCEDURE-API-GITEA.md)');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const body = `## Description
|
||||
|
||||
Branchement du formulaire d'inscription parent (étape 5, récapitulatif) à l'endpoint d'inscription. Aujourd'hui la soumission n'appelle pas l'API : elle affiche uniquement une modale puis redirige vers le login.
|
||||
|
||||
**Estimation** : 4h | **Labels** : frontend, p3, auth, cdc
|
||||
|
||||
## Tâches
|
||||
|
||||
- [ ] Créer un service ou méthode (ex. AuthService.registerParent) appelant POST /api/v1/auth/register/parent
|
||||
- [ ] Construire le body (DTO) à partir de UserRegistrationData (parent1, parent2, children, motivationText, CGU) en cohérence avec le backend (#18)
|
||||
- [ ] Dans ParentRegisterStep5Screen, au clic « Soumettre » : appel API puis modale + redirection ou message d'erreur
|
||||
- [ ] Gestion des photos enfants (base64 ou multipart selon API)
|
||||
|
||||
## Référence
|
||||
|
||||
20_WORKFLOW-CREATION-COMPTE.md § Étape 3 – Inscription d'un parent, backend #18`;
|
||||
|
||||
const payload = JSON.stringify({
|
||||
title: "[Frontend] Inscription Parent – Branchement soumission formulaire à l'API",
|
||||
body,
|
||||
});
|
||||
|
||||
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(payload),
|
||||
},
|
||||
};
|
||||
|
||||
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);
|
||||
} else {
|
||||
console.error('Erreur API:', o.message || d);
|
||||
process.exit(1);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Réponse:', d);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', (e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
req.write(payload);
|
||||
req.end();
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Liste toutes les issues Gitea (ouvertes + fermées) pour jmartin/petitspas.
|
||||
* Token : .gitea-token (racine), GITEA_TOKEN, ou docs/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/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é');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function get(path) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const opts = { hostname: 'git.ptits-pas.fr', path, method: 'GET', headers: { Authorization: 'token ' + token } };
|
||||
const req = https.request(opts, (res) => {
|
||||
let d = '';
|
||||
res.on('data', (c) => (d += c));
|
||||
res.on('end', () => {
|
||||
try { resolve(JSON.parse(d)); } catch (e) { reject(e); }
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const seen = new Map();
|
||||
for (const state of ['open', 'closed']) {
|
||||
for (let page = 1; ; page++) {
|
||||
const raw = await get('/api/v1/repos/jmartin/petitspas/issues?state=' + state + '&limit=50&page=' + page + '&type=issues');
|
||||
if (raw && raw.message && !Array.isArray(raw)) {
|
||||
console.error('API:', raw.message);
|
||||
process.exit(1);
|
||||
}
|
||||
const list = Array.isArray(raw) ? raw : [];
|
||||
for (const i of list) {
|
||||
if (!i.pull_request) seen.set(i.number, { number: i.number, title: i.title, state: i.state });
|
||||
}
|
||||
if (list.length < 50) break;
|
||||
}
|
||||
}
|
||||
const all = [...seen.values()].sort((a, b) => a.number - b.number);
|
||||
console.log(JSON.stringify(all, null, 2));
|
||||
}
|
||||
|
||||
main().catch((e) => { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Test API GET /dossiers/:numeroDossier (dossier unifié AM ou famille).
|
||||
*
|
||||
* Prérequis : backend démarré (npm run start:dev dans backend/).
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/test-api-dossiers.js
|
||||
* NUMERO_DOSSIER=2026-000001 node scripts/test-api-dossiers.js
|
||||
* BASE_URL=https://app.ptits-pas.fr/api/v1 TEST_EMAIL=xxx TEST_PASSWORD=yyy NUMERO_DOSSIER=2026-000001 node scripts/test-api-dossiers.js
|
||||
*
|
||||
* Sans TEST_EMAIL/TEST_PASSWORD : 401 sur les routes protégées.
|
||||
* NUMERO_DOSSIER : optionnel ; si absent, utilise le premier numero_dossier de pending-families (avec token).
|
||||
*/
|
||||
|
||||
const BASE_URL = process.env.BASE_URL || 'http://localhost:3000/api/v1';
|
||||
const TEST_EMAIL = process.env.TEST_EMAIL;
|
||||
const TEST_PASSWORD = process.env.TEST_PASSWORD;
|
||||
const NUMERO_DOSSIER = process.env.NUMERO_DOSSIER;
|
||||
|
||||
async function request(method, path, body = null, token = null) {
|
||||
const url = path.startsWith('http') ? path : `${BASE_URL}${path}`;
|
||||
const opts = {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
};
|
||||
if (token) opts.headers.Authorization = `Bearer ${token}`;
|
||||
if (body) opts.body = JSON.stringify(body);
|
||||
const res = await fetch(url, opts);
|
||||
const text = await res.text();
|
||||
let data = null;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : null;
|
||||
} catch (_) {
|
||||
data = text;
|
||||
}
|
||||
return { status: res.status, data };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('Base URL:', BASE_URL);
|
||||
console.log('Numéro dossier (env):', NUMERO_DOSSIER ?? '(sera déduit si token fourni)');
|
||||
console.log('');
|
||||
|
||||
let token = null;
|
||||
if (TEST_EMAIL && TEST_PASSWORD) {
|
||||
console.log('1. Login...');
|
||||
const loginRes = await request('POST', '/auth/login', {
|
||||
email: TEST_EMAIL,
|
||||
password: TEST_PASSWORD,
|
||||
});
|
||||
if (loginRes.status !== 200 && loginRes.status !== 201) {
|
||||
console.log(' Échec login:', loginRes.status, loginRes.data);
|
||||
process.exit(1);
|
||||
}
|
||||
token = loginRes.data?.access_token ?? loginRes.data?.accessToken ?? null;
|
||||
if (!token) {
|
||||
console.log(' Réponse login sans token:', JSON.stringify(loginRes.data, null, 2));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(' OK, token reçu.');
|
||||
console.log('');
|
||||
} else {
|
||||
console.log('TEST_EMAIL / TEST_PASSWORD non définis : GET /dossiers/:numero nécessite un token (401 attendu).');
|
||||
console.log('');
|
||||
}
|
||||
|
||||
let numeroDossier = NUMERO_DOSSIER;
|
||||
if (!numeroDossier && token) {
|
||||
console.log('2. Récupération d\'un numéro de dossier (GET /parents/pending-families)...');
|
||||
const pendingRes = await request('GET', '/parents/pending-families', null, token);
|
||||
if (pendingRes.status === 200 && Array.isArray(pendingRes.data) && pendingRes.data.length > 0) {
|
||||
numeroDossier = pendingRes.data[0].numero_dossier || null;
|
||||
console.log(' Premier numero_dossier:', numeroDossier);
|
||||
} else {
|
||||
console.log(' Aucune famille en attente ou erreur. Utilisez NUMERO_DOSSIER=2026-000001');
|
||||
}
|
||||
console.log('');
|
||||
}
|
||||
|
||||
if (!numeroDossier) {
|
||||
numeroDossier = '2026-000001';
|
||||
console.log('2. Pas de numéro fourni, test avec numéro par défaut:', numeroDossier);
|
||||
} else {
|
||||
console.log('2. GET /dossiers/' + encodeURIComponent(numeroDossier));
|
||||
}
|
||||
|
||||
const dossierRes = await request(
|
||||
'GET',
|
||||
'/dossiers/' + encodeURIComponent(numeroDossier),
|
||||
null,
|
||||
token
|
||||
);
|
||||
|
||||
console.log(' Status:', dossierRes.status);
|
||||
if (dossierRes.status === 200 && dossierRes.data) {
|
||||
const d = dossierRes.data;
|
||||
console.log(' type:', d.type);
|
||||
console.log(' dossier (clés):', d.dossier ? Object.keys(d.dossier) : '-');
|
||||
if (d.dossier && Array.isArray(d.dossier.enfants)) {
|
||||
console.log(' enfants:', d.dossier.enfants.length);
|
||||
d.dossier.enfants.forEach((e, i) => {
|
||||
console.log(
|
||||
` [${i + 1}] id=${e.id} first_name=${e.first_name} last_name=${e.last_name} birth_date=${e.birth_date} gender=${e.gender} genre=${e.genre} status=${e.status}`
|
||||
);
|
||||
});
|
||||
}
|
||||
console.log('');
|
||||
console.log('Réponse brute (dossier):');
|
||||
console.log(JSON.stringify(d.dossier, null, 2));
|
||||
} else {
|
||||
console.log(' Réponse:', JSON.stringify(dossierRes.data, null, 2));
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log('Fin du test.');
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('Erreur:', err.message || err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Test des endpoints "comptes en attente" (ticket #107).
|
||||
*
|
||||
* Prérequis : backend démarré (npm run start:dev dans backend/).
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/test-pending-api.js
|
||||
* TEST_EMAIL=xxx TEST_PASSWORD=yyy node scripts/test-pending-api.js
|
||||
* BASE_URL=https://app.ptits-pas.fr/api/v1 TEST_EMAIL=xxx TEST_PASSWORD=yyy node scripts/test-pending-api.js
|
||||
*
|
||||
* Sans TEST_EMAIL/TEST_PASSWORD : les GET protégés renverront 401 (normal).
|
||||
* Avec un compte gestionnaire ou admin : affiche les listes en attente.
|
||||
*/
|
||||
|
||||
const BASE_URL = process.env.BASE_URL || 'http://localhost:3000/api/v1';
|
||||
const TEST_EMAIL = process.env.TEST_EMAIL;
|
||||
const TEST_PASSWORD = process.env.TEST_PASSWORD;
|
||||
|
||||
async function request(method, path, body = null, token = null) {
|
||||
const url = path.startsWith('http') ? path : `${BASE_URL}${path}`;
|
||||
const opts = {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
};
|
||||
if (token) opts.headers.Authorization = `Bearer ${token}`;
|
||||
if (body) opts.body = JSON.stringify(body);
|
||||
const res = await fetch(url, opts);
|
||||
const text = await res.text();
|
||||
let data = null;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : null;
|
||||
} catch (_) {
|
||||
data = text;
|
||||
}
|
||||
return { status: res.status, data };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('Base URL:', BASE_URL);
|
||||
console.log('');
|
||||
|
||||
let token = null;
|
||||
if (TEST_EMAIL && TEST_PASSWORD) {
|
||||
console.log('1. Login...');
|
||||
const loginRes = await request('POST', '/auth/login', {
|
||||
email: TEST_EMAIL,
|
||||
password: TEST_PASSWORD,
|
||||
});
|
||||
if (loginRes.status !== 200 && loginRes.status !== 201) {
|
||||
console.log(' Échec login:', loginRes.status, loginRes.data);
|
||||
process.exit(1);
|
||||
}
|
||||
token = loginRes.data?.access_token ?? loginRes.data?.accessToken ?? null;
|
||||
if (!token) {
|
||||
console.log(' Réponse login sans token:', JSON.stringify(loginRes.data, null, 2));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(' OK, token reçu.');
|
||||
console.log('');
|
||||
} else {
|
||||
console.log('TEST_EMAIL / TEST_PASSWORD non définis : les appels protégés vont renvoyer 401.');
|
||||
console.log('Exemple: TEST_EMAIL=admin@example.com TEST_PASSWORD=xxx node scripts/test-pending-api.js');
|
||||
console.log('');
|
||||
}
|
||||
|
||||
console.log('2. GET /users/pending?role=assistante_maternelle');
|
||||
const pendingUsersRes = await request(
|
||||
'GET',
|
||||
'/users/pending?role=assistante_maternelle',
|
||||
null,
|
||||
token
|
||||
);
|
||||
console.log(' Status:', pendingUsersRes.status);
|
||||
if (pendingUsersRes.status === 200) {
|
||||
const list = Array.isArray(pendingUsersRes.data) ? pendingUsersRes.data : [];
|
||||
console.log(' Nombre d\'utilisateurs en attente (AM):', list.length);
|
||||
list.forEach((u, i) => {
|
||||
console.log(
|
||||
` [${i + 1}] id=${u.id} email=${u.email} role=${u.role} statut=${u.statut} numero_dossier=${u.numero_dossier ?? '-'}`
|
||||
);
|
||||
});
|
||||
} else {
|
||||
console.log(' Réponse:', JSON.stringify(pendingUsersRes.data, null, 2));
|
||||
}
|
||||
console.log('');
|
||||
|
||||
console.log('3. GET /parents/pending-families');
|
||||
const pendingFamiliesRes = await request('GET', '/parents/pending-families', null, token);
|
||||
console.log(' Status:', pendingFamiliesRes.status);
|
||||
if (pendingFamiliesRes.status === 200) {
|
||||
const list = Array.isArray(pendingFamiliesRes.data) ? pendingFamiliesRes.data : [];
|
||||
console.log(' Nombre de familles en attente:', list.length);
|
||||
list.forEach((f, i) => {
|
||||
console.log(
|
||||
` [${i + 1}] libelle=${f.libelle} parentIds=${JSON.stringify(f.parentIds)} numero_dossier=${f.numero_dossier ?? '-'}`
|
||||
);
|
||||
});
|
||||
} else {
|
||||
console.log(' Réponse:', JSON.stringify(pendingFamiliesRes.data, null, 2));
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log('Fin du test.');
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('Erreur:', err.message || err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,27 +1,32 @@
|
||||
#!/bin/bash
|
||||
# Test POST /auth/register/am (ticket #90)
|
||||
# Inscription AM complète : jeux officiels alignés sur database/seed/03_seed_test_data.sql
|
||||
# node tests/scripts/register-am-dubois-test.mjs [BASE_URL]
|
||||
# node tests/scripts/register-am-mansouri-test.mjs [BASE_URL]
|
||||
#
|
||||
# Smoke curl (email + NIR jetables, hors seed — ne pas mélanger avec Marie / Fatima) :
|
||||
# Usage: ./scripts/test-register-am.sh [BASE_URL]
|
||||
# Exemple: ./scripts/test-register-am.sh https://app.ptits-pas.fr/api/v1
|
||||
# ./scripts/test-register-am.sh http://localhost:3000/api/v1
|
||||
# Exemple: ./scripts/test-register-am.sh http://localhost:3000/api/v1
|
||||
|
||||
BASE_URL="${1:-http://localhost:3000/api/v1}"
|
||||
echo "Testing POST $BASE_URL/auth/register/am"
|
||||
echo "POST $BASE_URL/auth/register/am (profil smoke, pas les AM du seed)"
|
||||
echo "---"
|
||||
|
||||
curl -s -w "\n\nHTTP %{http_code}\n" -X POST "$BASE_URL/auth/register/am" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"email": "marie.dupont.test@ptits-pas.fr",
|
||||
"prenom": "Marie",
|
||||
"nom": "DUPONT",
|
||||
"email": "smoke.am.curl@ptits-pas.fr",
|
||||
"prenom": "Smoke",
|
||||
"nom": "CURLTEST",
|
||||
"telephone": "0612345678",
|
||||
"adresse": "1 rue Test",
|
||||
"code_postal": "75001",
|
||||
"ville": "Paris",
|
||||
"consentement_photo": true,
|
||||
"nir": "123456789012345",
|
||||
"numero_agrement": "AGR-2024-001",
|
||||
"capacite_accueil": 4,
|
||||
"adresse": "1 rue Smoke",
|
||||
"code_postal": "95870",
|
||||
"ville": "Bezons",
|
||||
"consentement_photo": false,
|
||||
"date_naissance": "1986-12-15",
|
||||
"nir": "186127500100279",
|
||||
"numero_agrement": "AGR-SMOKE-CURL-001",
|
||||
"capacite_accueil": 3,
|
||||
"places_disponibles": 2,
|
||||
"acceptation_cgu": true,
|
||||
"acceptation_privacy": true
|
||||
}'
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Met à jour l'issue Gitea #119 : endpoint unifié GET /dossiers/:numeroDossier (option A)
|
||||
* Usage: node backend/scripts/update-gitea-issue-119-dossiers.js
|
||||
* Token : .gitea-token (racine), GITEA_TOKEN, ou docs/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/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é');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const body = `## Besoin
|
||||
|
||||
Un **seul** endpoint **GET par numéro de dossier** qui renvoie le dossier complet, **AM ou famille** selon le numéro. Clé unique = numéro de dossier (usage : modale de validation, consultation gestionnaire, reprise, etc.).
|
||||
|
||||
**Option A – Endpoint unifié**
|
||||
|
||||
- **Route** : \`GET /api/v1/dossiers/:numeroDossier\` (ou \`GET /dossiers/:numeroDossier\` selon préfixe API).
|
||||
- Le backend détermine si le numéro appartient à une **AM** ou à une **famille** (ex. lookup \`users\` / \`parents\` / \`assistantes_maternelles\`).
|
||||
- **Réponse** avec discriminent :
|
||||
- \`{ type: 'family', dossier: { numero_dossier, parents, enfants, presentation } }\`
|
||||
- \`{ type: 'am', dossier: { numero_dossier, user, ... } }\` (fiche AM complète, champs utiles sans secrets)
|
||||
- **Rôles** : SUPER_ADMIN, ADMINISTRATEUR, GESTIONNAIRE.
|
||||
- **Réponses** : 200 (dossier), 403, 404 (numéro inconnu).
|
||||
|
||||
Aucun filtre par statut : on renvoie le dossier s'il existe ; le front affiche Valider/Refuser selon le statut.
|
||||
|
||||
**Labels suggérés** : backend, api, dossiers, gestionnaire
|
||||
|
||||
---
|
||||
|
||||
## Implémentation
|
||||
|
||||
- **Nouveau module ou route** : \`GET /dossiers/:numeroDossier\`.
|
||||
- **Service** : trouver qui possède ce \`numero_dossier\` (famille → \`parents\`, AM → \`users\` + \`assistantes_maternelles\`). Appeler la logique existante dossier-famille ou construire le payload AM, puis retourner \`{ type, dossier }\`.
|
||||
- **Réutiliser** : la logique actuelle \`GET /parents/dossier-famille/:numeroDossier\` peut être appelée en interne pour \`type: 'family'\` ; ajouter une branche \`type: 'am'\` avec un DTO « dossier AM complet ».
|
||||
- DTO(s) : garder \`DossierFamilleCompletDto\` pour la famille ; ajouter un DTO pour le dossier AM (user sans secrets + infos AM). Réponse unifiée : \`{ type: 'am' | 'family', dossier: ... }\`.`;
|
||||
|
||||
const payload = JSON.stringify({
|
||||
title: 'Endpoint unifié GET /dossiers/:numeroDossier (AM ou famille)',
|
||||
body,
|
||||
});
|
||||
|
||||
const opts = {
|
||||
hostname: 'git.ptits-pas.fr',
|
||||
path: '/api/v1/repos/jmartin/petitspas/issues/119',
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: 'token ' + token,
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(payload),
|
||||
},
|
||||
};
|
||||
|
||||
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 || o.id) {
|
||||
console.log('Issue #119 mise à jour.');
|
||||
console.log('URL:', o.html_url || 'https://git.ptits-pas.fr/jmartin/petitspas/issues/119');
|
||||
} else {
|
||||
console.error('Erreur API:', o.message || d);
|
||||
process.exit(1);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Réponse:', d);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on('error', (e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
req.write(payload);
|
||||
req.end();
|
||||
@@ -16,6 +16,8 @@ import { AllExceptionsFilter } from './common/filters/all_exceptions.filters';
|
||||
import { EnfantsModule } from './routes/enfants/enfants.module';
|
||||
import { AppConfigModule } from './modules/config/config.module';
|
||||
import { DocumentsLegauxModule } from './modules/documents-legaux';
|
||||
import { RelaisModule } from './routes/relais/relais.module';
|
||||
import { DossiersModule } from './routes/dossiers/dossiers.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -53,6 +55,8 @@ import { DocumentsLegauxModule } from './modules/documents-legaux';
|
||||
AuthModule,
|
||||
AppConfigModule,
|
||||
DocumentsLegauxModule,
|
||||
RelaisModule,
|
||||
DossiersModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Utilitaire de validation du NIR (numéro de sécurité sociale français).
|
||||
* - Format 15 caractères (chiffres ou 2A/2B pour la Corse).
|
||||
* - Clé de contrôle : 97 - (NIR13 mod 97). Pour 2A/2B, conversion temporaire (INSEE : 2A→19, 2B→20).
|
||||
* - En cas d'incohérence avec les données (sexe, date, lieu) : warning uniquement, pas de rejet.
|
||||
*/
|
||||
|
||||
const NIR_CORSE_2A = '19';
|
||||
const NIR_CORSE_2B = '20';
|
||||
|
||||
/** Regex 15 caractères : sexe (1-3) + 4 chiffres + (2A|2B|2 chiffres) + 6 chiffres + 2 chiffres clé */
|
||||
const NIR_FORMAT = /^[1-3]\d{4}(?:2A|2B|\d{2})\d{6}\d{2}$/i;
|
||||
|
||||
/**
|
||||
* Convertit le NIR en chaîne de 13 chiffres pour le calcul de la clé (2A→19, 2B→20).
|
||||
*/
|
||||
export function nirTo13Digits(nir: string): string {
|
||||
const n = nir.toUpperCase().replace(/\s/g, '');
|
||||
if (n.length !== 15) return '';
|
||||
const dept = n.slice(5, 7);
|
||||
let deptNum: string;
|
||||
if (dept === '2A') deptNum = NIR_CORSE_2A;
|
||||
else if (dept === '2B') deptNum = NIR_CORSE_2B;
|
||||
else deptNum = dept;
|
||||
return n.slice(0, 5) + deptNum + n.slice(7, 13);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie que le format NIR est valide (15 caractères, 2A/2B acceptés).
|
||||
*/
|
||||
export function isNirFormatValid(nir: string): boolean {
|
||||
if (!nir || typeof nir !== 'string') return false;
|
||||
const n = nir.replace(/\s/g, '').toUpperCase();
|
||||
return NIR_FORMAT.test(n);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calcule la clé de contrôle attendue (97 - (NIR13 mod 97)).
|
||||
* Retourne un nombre entre 1 et 97.
|
||||
*/
|
||||
export function computeNirKey(nir13: string): number {
|
||||
const num = parseInt(nir13, 10);
|
||||
if (Number.isNaN(num) || nir13.length !== 13) return -1;
|
||||
return 97 - (num % 97);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie la clé de contrôle du NIR (15 caractères).
|
||||
* Retourne true si le NIR est valide (format + clé).
|
||||
*/
|
||||
export function isNirKeyValid(nir: string): boolean {
|
||||
const n = nir.replace(/\s/g, '').toUpperCase();
|
||||
if (n.length !== 15) return false;
|
||||
const nir13 = nirTo13Digits(n);
|
||||
if (nir13.length !== 13) return false;
|
||||
const expectedKey = computeNirKey(nir13);
|
||||
const actualKey = parseInt(n.slice(13, 15), 10);
|
||||
return expectedKey === actualKey;
|
||||
}
|
||||
|
||||
export interface NirValidationResult {
|
||||
valid: boolean;
|
||||
error?: string;
|
||||
warning?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Valide le NIR (format + clé). En cas d'incohérence avec date de naissance ou sexe, ajoute un warning sans invalider.
|
||||
*/
|
||||
export function validateNir(
|
||||
nir: string,
|
||||
options?: { dateNaissance?: string; genre?: 'H' | 'F' },
|
||||
): NirValidationResult {
|
||||
const n = (nir || '').replace(/\s/g, '').toUpperCase();
|
||||
if (n.length === 0) return { valid: false, error: 'Le NIR est requis' };
|
||||
if (!isNirFormatValid(n)) {
|
||||
return { valid: false, error: 'Le NIR doit contenir 15 caractères (chiffres, ou 2A/2B pour la Corse)' };
|
||||
}
|
||||
if (!isNirKeyValid(n)) {
|
||||
return { valid: false, error: 'Clé de contrôle du NIR invalide' };
|
||||
}
|
||||
let warning: string | undefined;
|
||||
if (options?.genre) {
|
||||
const sexNir = n[0];
|
||||
const expectedSex = options.genre === 'F' ? '2' : '1';
|
||||
if (sexNir !== expectedSex) {
|
||||
warning = 'Le NIR ne correspond pas au genre indiqué (position 1 du NIR).';
|
||||
}
|
||||
}
|
||||
if (options?.dateNaissance) {
|
||||
try {
|
||||
const d = new Date(options.dateNaissance);
|
||||
if (!Number.isNaN(d.getTime())) {
|
||||
const year2 = d.getFullYear() % 100;
|
||||
const month = d.getMonth() + 1;
|
||||
const nirYear = parseInt(n.slice(1, 3), 10);
|
||||
const nirMonth = parseInt(n.slice(3, 5), 10);
|
||||
if (nirYear !== year2 || nirMonth !== month) {
|
||||
warning = warning
|
||||
? `${warning} Le NIR ne correspond pas à la date de naissance (positions 2-5).`
|
||||
: 'Le NIR ne correspond pas à la date de naissance indiquée (positions 2-5).';
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
return { valid: true, warning };
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { DataSource } from 'typeorm';
|
||||
import { config } from 'dotenv';
|
||||
|
||||
config();
|
||||
|
||||
export default new DataSource({
|
||||
type: 'postgres',
|
||||
host: process.env.DATABASE_HOST,
|
||||
port: parseInt(process.env.DATABASE_PORT || '5432', 10),
|
||||
username: process.env.DATABASE_USERNAME,
|
||||
password: process.env.DATABASE_PASSWORD,
|
||||
database: process.env.DATABASE_NAME,
|
||||
entities: ['src/**/*.entity.ts'],
|
||||
migrations: ['src/migrations/*.ts'],
|
||||
});
|
||||
@@ -48,4 +48,7 @@ export class AssistanteMaternelle {
|
||||
@Column( { name: 'place_disponible', type: 'integer', nullable: true })
|
||||
places_available?: number;
|
||||
|
||||
/** Numéro de dossier (format AAAA-NNNNNN), même valeur que sur utilisateurs (ticket #103) */
|
||||
@Column({ name: 'numero_dossier', length: 20, nullable: true })
|
||||
numero_dossier?: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import {
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
Column,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
CreateDateColumn,
|
||||
UpdateDateColumn,
|
||||
JoinColumn,
|
||||
} from 'typeorm';
|
||||
import { Parents } from './parents.entity';
|
||||
import { Children } from './children.entity';
|
||||
import { StatutDossierType } from './dossiers.entity';
|
||||
|
||||
/** Un dossier = une famille, N enfants (texte de motivation unique, liste d'enfants). */
|
||||
@Entity('dossier_famille')
|
||||
export class DossierFamille {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ name: 'numero_dossier', length: 20 })
|
||||
numero_dossier: string;
|
||||
|
||||
@ManyToOne(() => Parents, { onDelete: 'CASCADE', nullable: false })
|
||||
@JoinColumn({ name: 'id_parent', referencedColumnName: 'user_id' })
|
||||
parent: Parents;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
presentation?: string;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: StatutDossierType,
|
||||
enumName: 'statut_dossier_type',
|
||||
default: StatutDossierType.ENVOYE,
|
||||
name: 'statut',
|
||||
})
|
||||
statut: StatutDossierType;
|
||||
|
||||
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||
cree_le: Date;
|
||||
|
||||
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
|
||||
modifie_le: Date;
|
||||
|
||||
@OneToMany(() => DossierFamilleEnfant, (dfe) => dfe.dossier_famille)
|
||||
enfants: DossierFamilleEnfant[];
|
||||
}
|
||||
|
||||
@Entity('dossier_famille_enfants')
|
||||
export class DossierFamilleEnfant {
|
||||
@Column({ name: 'id_dossier_famille', primary: true })
|
||||
id_dossier_famille: string;
|
||||
|
||||
@Column({ name: 'id_enfant', primary: true })
|
||||
id_enfant: string;
|
||||
|
||||
@ManyToOne(() => DossierFamille, (df) => df.enfants, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'id_dossier_famille' })
|
||||
dossier_famille: DossierFamille;
|
||||
|
||||
@ManyToOne(() => Children, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'id_enfant' })
|
||||
enfant: Children;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import {
|
||||
Entity, PrimaryColumn, OneToOne, JoinColumn,
|
||||
Entity, PrimaryColumn, Column, OneToOne, JoinColumn,
|
||||
ManyToOne, OneToMany
|
||||
} from 'typeorm';
|
||||
import { Users } from './users.entity';
|
||||
@@ -21,6 +21,10 @@ export class Parents {
|
||||
@JoinColumn({ name: 'id_co_parent', referencedColumnName: 'id' })
|
||||
co_parent?: Users;
|
||||
|
||||
/** Numéro de dossier famille (format AAAA-NNNNNN), attribué à la soumission (ticket #103) */
|
||||
@Column({ name: 'numero_dossier', length: 20, nullable: true })
|
||||
numero_dossier?: string;
|
||||
|
||||
// Lien vers enfants via la table enfants_parents
|
||||
@OneToMany(() => ParentsChildren, pc => pc.parent)
|
||||
parentChildren: ParentsChildren[];
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, OneToMany } from 'typeorm';
|
||||
import { Users } from './users.entity';
|
||||
|
||||
@Entity('relais', { schema: 'public' })
|
||||
export class Relais {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ name: 'nom' })
|
||||
nom: string;
|
||||
|
||||
@Column({ name: 'adresse' })
|
||||
adresse: string;
|
||||
|
||||
@Column({ type: 'jsonb', name: 'horaires_ouverture', nullable: true })
|
||||
horaires_ouverture?: any;
|
||||
|
||||
@Column({ name: 'ligne_fixe', nullable: true })
|
||||
ligne_fixe?: string;
|
||||
|
||||
@Column({ default: true, name: 'actif' })
|
||||
actif: boolean;
|
||||
|
||||
@Column({ type: 'text', name: 'notes', nullable: true })
|
||||
notes?: string;
|
||||
|
||||
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||
cree_le: Date;
|
||||
|
||||
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
|
||||
modifie_le: Date;
|
||||
|
||||
@OneToMany(() => Users, user => user.relais)
|
||||
gestionnaires: Users[];
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
import {
|
||||
Entity, PrimaryGeneratedColumn, Column,
|
||||
CreateDateColumn, UpdateDateColumn,
|
||||
OneToOne, OneToMany
|
||||
OneToOne, OneToMany, ManyToOne, JoinColumn
|
||||
} from 'typeorm';
|
||||
import { AssistanteMaternelle } from './assistantes_maternelles.entity';
|
||||
import { Parents } from './parents.entity';
|
||||
import { Message } from './messages.entity';
|
||||
import { Relais } from './relais.entity';
|
||||
|
||||
// Enums alignés avec la BDD PostgreSQL
|
||||
export enum RoleType {
|
||||
@@ -28,6 +29,7 @@ export enum StatutUtilisateurType {
|
||||
EN_ATTENTE = 'en_attente',
|
||||
ACTIF = 'actif',
|
||||
SUSPENDU = 'suspendu',
|
||||
REFUSE = 'refuse',
|
||||
}
|
||||
|
||||
export enum SituationFamilialeType {
|
||||
@@ -80,7 +82,7 @@ export class Users {
|
||||
type: 'enum',
|
||||
enum: StatutUtilisateurType,
|
||||
enumName: 'statut_utilisateur_type', // correspond à l'enum de la db psql
|
||||
default: StatutUtilisateurType.EN_ATTENTE,
|
||||
default: StatutUtilisateurType.ACTIF,
|
||||
name: 'statut'
|
||||
})
|
||||
statut: StatutUtilisateurType;
|
||||
@@ -117,6 +119,13 @@ export class Users {
|
||||
@Column({ type: 'timestamptz', nullable: true, name: 'token_creation_mdp_expire_le' })
|
||||
token_creation_mdp_expire_le?: Date;
|
||||
|
||||
/** Token pour reprise après refus (lien email), ticket #110 */
|
||||
@Column({ nullable: true, name: 'token_reprise', length: 255 })
|
||||
token_reprise?: string;
|
||||
|
||||
@Column({ type: 'timestamptz', nullable: true, name: 'token_reprise_expire_le' })
|
||||
token_reprise_expire_le?: Date;
|
||||
|
||||
@Column({ nullable: true, name: 'ville' })
|
||||
ville?: string;
|
||||
|
||||
@@ -129,6 +138,12 @@ export class Users {
|
||||
@Column({ name: 'date_naissance', type: 'date', nullable: true })
|
||||
date_naissance?: Date;
|
||||
|
||||
@Column({ name: 'lieu_naissance_ville', length: 100, nullable: true })
|
||||
lieu_naissance_ville?: string;
|
||||
|
||||
@Column({ name: 'lieu_naissance_pays', length: 100, nullable: true })
|
||||
lieu_naissance_pays?: string;
|
||||
|
||||
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||
cree_le: Date;
|
||||
|
||||
@@ -147,4 +162,15 @@ export class Users {
|
||||
|
||||
@OneToMany(() => Parents, parent => parent.co_parent)
|
||||
co_parent_in?: Parents[];
|
||||
|
||||
@Column({ nullable: true, name: 'relais_id' })
|
||||
relaisId?: string;
|
||||
|
||||
/** Numéro de dossier (format AAAA-NNNNNN), attribué à la soumission (ticket #103) */
|
||||
@Column({ nullable: true, name: 'numero_dossier', length: 20 })
|
||||
numero_dossier?: string;
|
||||
|
||||
@ManyToOne(() => Relais, relais => relais.gestionnaires, { nullable: true })
|
||||
@JoinColumn({ name: 'relais_id' })
|
||||
relais?: Relais;
|
||||
}
|
||||
|
||||
+67
-6
@@ -1,26 +1,87 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||
import { AppModule } from './app.module';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { SwaggerModule } from '@nestjs/swagger/dist/swagger-module';
|
||||
import { DocumentBuilder } from '@nestjs/swagger';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { LogRequestInterceptor } from './common/interceptors/log-request.interceptor';
|
||||
import * as path from 'path';
|
||||
import * as express from 'express';
|
||||
|
||||
/** GET/HEAD photos : CORS + CORP pour Flutter web (cross-origin `Image.network`). Pas de cookie sur ces URLs. */
|
||||
function setStaticImageCorsHeaders(res: express.Response): void {
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
|
||||
}
|
||||
|
||||
const staticImageServeOptions = {
|
||||
index: false,
|
||||
fallthrough: true,
|
||||
setHeaders: (res: express.Response) => setStaticImageCorsHeaders(res),
|
||||
};
|
||||
|
||||
/** Préflight si le navigateur interroge OPTIONS sur les médias. */
|
||||
function uploadsCorsPreflight(
|
||||
req: express.Request,
|
||||
res: express.Response,
|
||||
next: express.NextFunction,
|
||||
): void {
|
||||
if (req.method === 'OPTIONS') {
|
||||
setStaticImageCorsHeaders(res);
|
||||
res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
|
||||
res.setHeader('Access-Control-Max-Age', '86400');
|
||||
res.status(204).end();
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/** Répertoire disque contenant le dossier `photos` (ex. /app/uploads si photos dans /app/uploads/photos). */
|
||||
function resolveUploadsFilesystemRoot(): string {
|
||||
const raw = process.env.UPLOAD_PHOTOS_DIR?.trim();
|
||||
const photosDir = raw
|
||||
? path.isAbsolute(raw)
|
||||
? raw
|
||||
: path.resolve(process.cwd(), raw)
|
||||
: path.join(process.cwd(), 'uploads', 'photos');
|
||||
return path.dirname(photosDir);
|
||||
}
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule,
|
||||
{ logger: ['error', 'warn', 'log', 'debug', 'verbose'] });
|
||||
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
|
||||
logger: ['error', 'warn', 'log', 'debug', 'verbose'],
|
||||
});
|
||||
|
||||
// Log de chaque appel API si LOG_API_REQUESTS=true (mode debug)
|
||||
app.useGlobalInterceptors(new LogRequestInterceptor());
|
||||
// Inscription (photos base64 dans le JSON) : sans limite > défaut Express (~100 ko) → 413/500 ou corps tronqué.
|
||||
app.useBodyParser('json', { limit: '15mb' });
|
||||
app.useBodyParser('urlencoded', { extended: true, limit: '15mb' });
|
||||
|
||||
// Configuration CORS pour autoriser les requêtes depuis localhost (dev) et production
|
||||
// CORS global **avant** les fichiers statiques pour que les réponses API et idéalement la chaîne Express restent cohérentes.
|
||||
app.enableCors({
|
||||
origin: true, // Autorise toutes les origines (dev) - à restreindre en prod
|
||||
origin: true, // Reflète l’Origin (dev / prod) — routes API + cookies JWT
|
||||
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
||||
allowedHeaders: ['Content-Type', 'Authorization', 'Accept'],
|
||||
credentials: true,
|
||||
});
|
||||
|
||||
const expressApp = app.getHttpAdapter().getInstance();
|
||||
const uploadsRoot = resolveUploadsFilesystemRoot();
|
||||
|
||||
// Photos : chemins stockés en base type /uploads/photos/...
|
||||
// En-têtes explicites sur les réponses fichier (les statics peuvent répondre sans repasser par la même couche que les contrôleurs).
|
||||
expressApp.use('/uploads', uploadsCorsPreflight);
|
||||
expressApp.use('/api/v1/uploads', uploadsCorsPreflight);
|
||||
|
||||
app.useStaticAssets(uploadsRoot, {
|
||||
prefix: '/uploads/',
|
||||
...staticImageServeOptions,
|
||||
});
|
||||
expressApp.use('/api/v1/uploads', express.static(uploadsRoot, staticImageServeOptions));
|
||||
|
||||
// Log de chaque appel API si LOG_API_REQUESTS=true (mode debug)
|
||||
app.useGlobalInterceptors(new LogRequestInterceptor());
|
||||
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MailService } from './mail.service';
|
||||
import { AppConfigModule } from '../config/config.module';
|
||||
|
||||
@Module({
|
||||
imports: [AppConfigModule],
|
||||
providers: [MailService],
|
||||
exports: [MailService],
|
||||
})
|
||||
export class MailModule {}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { AppConfigService } from '../config/config.service';
|
||||
|
||||
@Injectable()
|
||||
export class MailService {
|
||||
private readonly logger = new Logger(MailService.name);
|
||||
|
||||
constructor(private readonly configService: AppConfigService) {}
|
||||
|
||||
/**
|
||||
* Envoi d'un email générique
|
||||
* @param to Destinataire
|
||||
* @param subject Sujet
|
||||
* @param html Contenu HTML
|
||||
* @param text Contenu texte (optionnel)
|
||||
*/
|
||||
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 emailFromAddress = this.configService.get<string>('email_from_address');
|
||||
|
||||
// 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}>`,
|
||||
to,
|
||||
subject,
|
||||
text: text || html.replace(/<[^>]*>?/gm, ''), // Fallback texte simple
|
||||
html,
|
||||
});
|
||||
|
||||
this.logger.log(`📧 Email envoyé à ${to} : ${subject}`);
|
||||
} catch (error) {
|
||||
this.logger.error(`❌ Erreur lors de l'envoi de l'email à ${to}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Envoi de l'email de bienvenue pour un gestionnaire
|
||||
* @param to Email du gestionnaire
|
||||
* @param prenom Prénom
|
||||
* @param nom Nom
|
||||
* @param token Token de création de mot de passe (si applicable) ou mot de passe temporaire (si applicable)
|
||||
* @note Pour l'instant, on suppose que le gestionnaire doit définir son mot de passe via "Mot de passe oublié" ou un lien d'activation
|
||||
* Mais le ticket #17 parle de "Flag changement_mdp_obligatoire = TRUE", ce qui implique qu'on lui donne un mot de passe temporaire ou qu'on lui envoie un lien.
|
||||
* Le ticket #24 parle de "API Création mot de passe" via token.
|
||||
* Pour le ticket #17, on crée le gestionnaire avec un mot de passe (hashé).
|
||||
* Si on suit le ticket #35 (Frontend), on saisit un mot de passe.
|
||||
* Donc on envoie juste un email de confirmation de création de compte.
|
||||
*/
|
||||
async sendGestionnaireWelcomeEmail(to: string, prenom: string, nom: 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 subject = `Bienvenue sur ${appName}`;
|
||||
const html = `
|
||||
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
||||
<h2 style="color: #4CAF50;">Bienvenue ${prenom} ${nom} !</h2>
|
||||
<p>Votre compte gestionnaire sur <strong>${appName}</strong> a été créé avec succès.</p>
|
||||
<p>Vous pouvez dès à présent vous connecter avec l'adresse email <strong>${to}</strong> et le mot de passe qui vous a été communiqué.</p>
|
||||
<p>Lors de votre première connexion, il vous sera demandé de modifier votre mot de passe pour des raisons de sécurité.</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 à l'application</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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Accusé de réception inscription (parent ou assistante maternelle) :
|
||||
* demande enregistrée + n° de dossier. En attente de validation ; pas de lien création MDP à ce stade.
|
||||
*/
|
||||
async sendRegistrationPendingEmail(
|
||||
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 demande d'inscription sur ${appName} — dossier ${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 enregistré votre demande de création de compte sur <strong>${safe(appName)}</strong>.</p>
|
||||
<p><strong>Numéro de dossier :</strong> ${safe(numeroDossier)}</p>
|
||||
<p>Votre dossier est <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).
|
||||
* Ticket #110 – Refus sans suppression
|
||||
*/
|
||||
async sendRefusEmail(
|
||||
to: string,
|
||||
prenom: string,
|
||||
nom: string,
|
||||
comment: string | undefined,
|
||||
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');
|
||||
const repriseLink = `${appUrl}/reprise?token=${encodeURIComponent(token)}`;
|
||||
|
||||
const subject = `Votre dossier – compléments demandés`;
|
||||
const commentBlock = comment
|
||||
? `<p><strong>Message du gestionnaire :</strong></p><p>${comment.replace(/</g, '<').replace(/>/g, '>')}</p>`
|
||||
: '';
|
||||
const html = `
|
||||
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
||||
<h2 style="color: #333;">Bonjour ${prenom} ${nom},</h2>
|
||||
<p>Votre dossier d'inscription sur <strong>${appName}</strong> n'a pas pu être validé en l'état.</p>
|
||||
${commentBlock}
|
||||
<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;">
|
||||
<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>
|
||||
</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>
|
||||
<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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { NumeroDossierService } from './numero-dossier.service';
|
||||
|
||||
@Module({
|
||||
providers: [NumeroDossierService],
|
||||
exports: [NumeroDossierService],
|
||||
})
|
||||
export class NumeroDossierModule {}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { EntityManager } from 'typeorm';
|
||||
|
||||
const FORMAT_MAX_SEQUENCE = 990000;
|
||||
|
||||
/**
|
||||
* Service de génération du numéro de dossier (ticket #103).
|
||||
* Format AAAA-NNNNNN (année + 6 chiffres), séquence par année.
|
||||
* Si séquence >= 990000, overflowWarning est true (alerte gestionnaire).
|
||||
*/
|
||||
@Injectable()
|
||||
export class NumeroDossierService {
|
||||
/**
|
||||
* Génère le prochain numéro de dossier dans le cadre d'une transaction.
|
||||
* À appeler avec le manager de la transaction pour garantir l'unicité.
|
||||
*/
|
||||
async getNextNumeroDossier(manager: EntityManager): Promise<{
|
||||
numero: string;
|
||||
overflowWarning: boolean;
|
||||
}> {
|
||||
const year = new Date().getFullYear();
|
||||
|
||||
// Garantir l'existence de la ligne pour l'année
|
||||
await manager.query(
|
||||
`INSERT INTO numero_dossier_sequence (annee, prochain)
|
||||
VALUES ($1, 1)
|
||||
ON CONFLICT (annee) DO NOTHING`,
|
||||
[year],
|
||||
);
|
||||
|
||||
// Prendre le prochain numéro et incrémenter (FOR UPDATE pour concurrence)
|
||||
const selectRows = await manager.query(
|
||||
`SELECT prochain FROM numero_dossier_sequence WHERE annee = $1 FOR UPDATE`,
|
||||
[year],
|
||||
);
|
||||
const currentVal = selectRows?.[0]?.prochain ?? 1;
|
||||
|
||||
await manager.query(
|
||||
`UPDATE numero_dossier_sequence SET prochain = prochain + 1 WHERE annee = $1`,
|
||||
[year],
|
||||
);
|
||||
|
||||
const nextVal = currentVal;
|
||||
const overflowWarning = nextVal >= FORMAT_MAX_SEQUENCE;
|
||||
if (overflowWarning) {
|
||||
// Log pour alerte gestionnaire (ticket #103)
|
||||
console.warn(
|
||||
`[NumeroDossierService] Séquence année ${year} >= ${FORMAT_MAX_SEQUENCE} (valeur ${nextVal}). Prévoir renouvellement ou format.`,
|
||||
);
|
||||
}
|
||||
|
||||
const numero = `${year}-${String(nextVal).padStart(6, '0')}`;
|
||||
return { numero, overflowWarning };
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,24 @@
|
||||
import { Body, Controller, Get, Post, Req, UnauthorizedException, BadRequestException, UseGuards } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Patch, Post, Query, Req, UnauthorizedException, BadRequestException, UseGuards } from '@nestjs/common';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { AuthService } from './auth.service';
|
||||
import { Public } from 'src/common/decorators/public.decorator';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
import { RegisterParentCompletDto } from './dto/register-parent-complet.dto';
|
||||
import { RegisterAMCompletDto } from './dto/register-am-complet.dto';
|
||||
import { RegisterAmResponseDto } from './dto/register-am-response.dto';
|
||||
import { ChangePasswordRequiredDto } from './dto/change-password.dto';
|
||||
import { ApiBearerAuth, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { CreatePasswordDto } from './dto/create-password.dto';
|
||||
import { ApiBearerAuth, ApiOperation, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||
import type { Request } from 'express';
|
||||
import { UserService } from '../user/user.service';
|
||||
import { ProfileResponseDto } from './dto/profile_response.dto';
|
||||
import { RefreshTokenDto } from './dto/refresh_token.dto';
|
||||
import { ResoumettreRepriseDto } from './dto/resoumettre-reprise.dto';
|
||||
import { RepriseIdentifyBodyDto } from './dto/reprise-identify.dto';
|
||||
import { User } from 'src/common/decorators/user.decorator';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
import { RepriseDossierDto } from './dto/reprise-dossier.dto';
|
||||
|
||||
@ApiTags('Authentification')
|
||||
@Controller('auth')
|
||||
@@ -56,15 +61,45 @@ export class AuthController {
|
||||
@Post('register/am')
|
||||
@ApiOperation({
|
||||
summary: 'Inscription Assistante Maternelle COMPLÈTE',
|
||||
description: 'Crée User AM + entrée assistantes_maternelles (identité + infos pro + photo + CGU) en une transaction',
|
||||
description:
|
||||
'Crée User AM + entrée assistantes_maternelles (identité + infos pro + photo + CGU) en une transaction. Si photo_base64 est fourni sans photo_filename, le serveur utilise le nom par défaut photo_am.jpg (extension du fichier stocké = type du data-URL).',
|
||||
})
|
||||
@ApiResponse({ status: 201, description: 'Inscription réussie - Dossier en attente de validation' })
|
||||
@ApiResponse({ status: 201, description: 'Inscription réussie - Dossier en attente de validation', type: RegisterAmResponseDto })
|
||||
@ApiResponse({ status: 400, description: 'Données invalides ou CGU non acceptées' })
|
||||
@ApiResponse({ status: 409, description: 'Email déjà utilisé' })
|
||||
async inscrireAMComplet(@Body() dto: RegisterAMCompletDto) {
|
||||
async inscrireAMComplet(@Body() dto: RegisterAMCompletDto): Promise<RegisterAmResponseDto> {
|
||||
return this.authService.inscrireAMComplet(dto);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Get('reprise-dossier')
|
||||
@ApiOperation({ summary: 'Dossier pour reprise (token seul)' })
|
||||
@ApiQuery({ name: 'token', required: true, description: 'Token reprise (lien email)' })
|
||||
@ApiResponse({ status: 200, description: 'Données dossier pour préremplir', type: RepriseDossierDto })
|
||||
@ApiResponse({ status: 404, description: 'Token invalide ou expiré' })
|
||||
async getRepriseDossier(@Query('token') token: string): Promise<RepriseDossierDto> {
|
||||
return this.authService.getRepriseDossier(token);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Patch('reprise-resoumettre')
|
||||
@ApiOperation({ summary: 'Resoumettre le dossier (mise à jour + statut en_attente, invalide le token)' })
|
||||
@ApiResponse({ status: 200, description: 'Dossier resoumis' })
|
||||
@ApiResponse({ status: 404, description: 'Token invalide ou expiré' })
|
||||
async resoumettreReprise(@Body() dto: ResoumettreRepriseDto) {
|
||||
const { token, ...fields } = dto;
|
||||
return this.authService.resoumettreReprise(token, fields);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('reprise-identify')
|
||||
@ApiOperation({ summary: 'Modale reprise : numéro + email → type + token' })
|
||||
@ApiResponse({ status: 201, description: 'type (parent/AM) + token pour GET reprise-dossier / PUT reprise-resoumettre' })
|
||||
@ApiResponse({ status: 404, description: 'Aucun dossier en reprise pour ce numéro et email' })
|
||||
async repriseIdentify(@Body() dto: RepriseIdentifyBodyDto) {
|
||||
return this.authService.identifyReprise(dto.numero_dossier, dto.email);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('refresh')
|
||||
@ApiBearerAuth('refresh_token')
|
||||
@@ -75,6 +110,29 @@ export class AuthController {
|
||||
return this.authService.refreshTokens(dto.refresh_token);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Get('verify-token')
|
||||
@ApiOperation({ summary: 'Vérifier un token de création de mot de passe' })
|
||||
@ApiQuery({ name: 'token', required: true, description: 'Token UUID reçu par email' })
|
||||
@ApiResponse({ status: 200, description: 'Token valide' })
|
||||
@ApiResponse({ status: 404, description: 'Token invalide, expiré, ou déjà utilisé' })
|
||||
async verifyCreatePasswordToken(@Query('token') token: string) {
|
||||
return this.authService.verifyCreatePasswordToken(token);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Post('create-password')
|
||||
@ApiOperation({ summary: 'Créer le mot de passe initial via token email' })
|
||||
@ApiResponse({ status: 201, description: 'Mot de passe créé avec succès' })
|
||||
@ApiResponse({ status: 400, description: 'Confirmation invalide ou mot de passe invalide' })
|
||||
@ApiResponse({ status: 404, description: 'Token invalide, expiré, ou déjà utilisé' })
|
||||
async createPassword(@Body() dto: CreatePasswordDto) {
|
||||
if (dto.password !== dto.password_confirmation) {
|
||||
throw new BadRequestException('Les mots de passe ne correspondent pas');
|
||||
}
|
||||
return this.authService.createPasswordWithToken(dto.token, dto.password);
|
||||
}
|
||||
|
||||
@Get('me')
|
||||
@UseGuards(AuthGuard)
|
||||
@ApiBearerAuth('access-token')
|
||||
|
||||
@@ -10,12 +10,16 @@ import { Parents } from 'src/entities/parents.entity';
|
||||
import { Children } from 'src/entities/children.entity';
|
||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||
import { AppConfigModule } from 'src/modules/config';
|
||||
import { NumeroDossierModule } from 'src/modules/numero-dossier/numero-dossier.module';
|
||||
import { MailModule } from 'src/modules/mail/mail.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Users, Parents, Children, AssistanteMaternelle]),
|
||||
forwardRef(() => UserModule),
|
||||
AppConfigModule,
|
||||
MailModule,
|
||||
NumeroDossierModule,
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
UnauthorizedException,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { QueryFailedError, Repository } from 'typeorm';
|
||||
import { UserService } from '../user/user.service';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
@@ -21,22 +23,35 @@ import { Parents } from 'src/entities/parents.entity';
|
||||
import { Children, StatutEnfantType } from 'src/entities/children.entity';
|
||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||
import { DossierFamille, DossierFamilleEnfant } from 'src/entities/dossier_famille.entity';
|
||||
import { StatutDossierType } from 'src/entities/dossiers.entity';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { RepriseDossierDto } from './dto/reprise-dossier.dto';
|
||||
import { RepriseIdentifyResponseDto } from './dto/reprise-identify.dto';
|
||||
import { AppConfigService } from 'src/modules/config/config.service';
|
||||
import { validateNir } from 'src/common/utils/nir.util';
|
||||
import { NumeroDossierService } from 'src/modules/numero-dossier/numero-dossier.service';
|
||||
import { MailService } from 'src/modules/mail/mail.service';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
private readonly logger = new Logger(AuthService.name);
|
||||
|
||||
constructor(
|
||||
private readonly usersService: UserService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly configService: ConfigService,
|
||||
private readonly appConfigService: AppConfigService,
|
||||
private readonly mailService: MailService,
|
||||
private readonly numeroDossierService: NumeroDossierService,
|
||||
@InjectRepository(Parents)
|
||||
private readonly parentsRepo: Repository<Parents>,
|
||||
@InjectRepository(Users)
|
||||
private readonly usersRepo: Repository<Users>,
|
||||
@InjectRepository(Children)
|
||||
private readonly childrenRepo: Repository<Children>,
|
||||
@InjectRepository(AssistanteMaternelle)
|
||||
private readonly assistantesMaternellesRepo: Repository<AssistanteMaternelle>,
|
||||
) { }
|
||||
|
||||
/**
|
||||
@@ -93,6 +108,12 @@ export class AuthService {
|
||||
throw new UnauthorizedException('Votre compte a été suspendu. Contactez un administrateur.');
|
||||
}
|
||||
|
||||
if (user.statut === StatutUtilisateurType.REFUSE) {
|
||||
throw new UnauthorizedException(
|
||||
'Votre compte a été refusé. Vous pouvez corriger votre dossier et le soumettre à nouveau ; un gestionnaire pourra le réexaminer.',
|
||||
);
|
||||
}
|
||||
|
||||
return this.generateTokens(user.id, user.email, user.role);
|
||||
}
|
||||
|
||||
@@ -116,6 +137,116 @@ export class AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
async verifyCreatePasswordToken(token: string) {
|
||||
const cleanedToken = token?.trim();
|
||||
if (!cleanedToken) {
|
||||
throw new BadRequestException('Token manquant');
|
||||
}
|
||||
|
||||
const user = await this.usersRepo.findOne({
|
||||
where: { token_creation_mdp: cleanedToken },
|
||||
select: ['id', 'token_creation_mdp_expire_le', 'password'],
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new NotFoundException('Token invalide, expiré, ou déjà utilisé.');
|
||||
}
|
||||
|
||||
if (user.password) {
|
||||
throw new NotFoundException('Token invalide, expiré, ou déjà utilisé.');
|
||||
}
|
||||
|
||||
if (!user.token_creation_mdp_expire_le || user.token_creation_mdp_expire_le <= new Date()) {
|
||||
// Invalidation explicite d'un token expiré pour éviter toute réutilisation ultérieure.
|
||||
await this.usersRepo
|
||||
.createQueryBuilder()
|
||||
.update(Users)
|
||||
.set({
|
||||
token_creation_mdp: () => 'NULL',
|
||||
token_creation_mdp_expire_le: () => 'NULL',
|
||||
})
|
||||
.where('id = :id', { id: user.id })
|
||||
.execute();
|
||||
throw new NotFoundException('Token invalide, expiré, ou déjà utilisé.');
|
||||
}
|
||||
|
||||
return {
|
||||
valid: true,
|
||||
message: 'Token valide',
|
||||
};
|
||||
}
|
||||
|
||||
async createPasswordWithToken(token: string, plainPassword: string) {
|
||||
const cleanedToken = token?.trim();
|
||||
if (!cleanedToken) {
|
||||
throw new BadRequestException('Token manquant');
|
||||
}
|
||||
|
||||
const existingUser = await this.usersRepo.findOne({
|
||||
where: {
|
||||
token_creation_mdp: cleanedToken,
|
||||
},
|
||||
select: ['id', 'password', 'token_creation_mdp_expire_le'],
|
||||
});
|
||||
|
||||
if (!existingUser) {
|
||||
throw new NotFoundException('Token invalide, expiré, ou déjà utilisé.');
|
||||
}
|
||||
|
||||
if (existingUser.password) {
|
||||
throw new NotFoundException('Token invalide, expiré, ou déjà utilisé.');
|
||||
}
|
||||
|
||||
if (
|
||||
!existingUser.token_creation_mdp_expire_le ||
|
||||
existingUser.token_creation_mdp_expire_le <= new Date()
|
||||
) {
|
||||
await this.usersRepo
|
||||
.createQueryBuilder()
|
||||
.update(Users)
|
||||
.set({
|
||||
token_creation_mdp: () => 'NULL',
|
||||
token_creation_mdp_expire_le: () => 'NULL',
|
||||
})
|
||||
.where('id = :id', { id: existingUser.id })
|
||||
.execute();
|
||||
throw new NotFoundException('Token invalide, expiré, ou déjà utilisé.');
|
||||
}
|
||||
|
||||
const sel = await bcrypt.genSalt(12);
|
||||
const hashedPassword = await bcrypt.hash(plainPassword, sel);
|
||||
|
||||
// Usage unique atomique : une seule requête UPDATE avec garde-fous.
|
||||
const updateResult = await this.usersRepo
|
||||
.createQueryBuilder()
|
||||
.update(Users)
|
||||
.set({
|
||||
password: hashedPassword,
|
||||
token_creation_mdp: () => 'NULL',
|
||||
token_creation_mdp_expire_le: () => 'NULL',
|
||||
statut: StatutUtilisateurType.ACTIF,
|
||||
changement_mdp_obligatoire: false,
|
||||
})
|
||||
.where('token_creation_mdp = :token', { token: cleanedToken })
|
||||
.andWhere('token_creation_mdp_expire_le > NOW()')
|
||||
.andWhere('password IS NULL')
|
||||
.execute();
|
||||
|
||||
if (!updateResult.affected) {
|
||||
this.logger.warn(
|
||||
'[createPasswordWithToken] Token non consommé (course concurrente ou token invalidé)',
|
||||
);
|
||||
throw new NotFoundException('Token invalide, expiré, ou déjà utilisé.');
|
||||
}
|
||||
|
||||
this.logger.log('[createPasswordWithToken] Mot de passe initial créé avec succès');
|
||||
|
||||
return {
|
||||
message: 'Mot de passe créé avec succès. Vous pouvez maintenant vous connecter.',
|
||||
userId: existingUser.id,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Inscription utilisateur OBSOLÈTE - Utiliser inscrireParentComplet() ou registerAM()
|
||||
* @deprecated
|
||||
@@ -177,6 +308,11 @@ export class AuthService {
|
||||
}
|
||||
|
||||
if (dto.co_parent_email) {
|
||||
if (dto.email.trim().toLowerCase() === dto.co_parent_email.trim().toLowerCase()) {
|
||||
throw new BadRequestException(
|
||||
'L\'email du parent et du co-parent doivent être différents.',
|
||||
);
|
||||
}
|
||||
const coParentExiste = await this.usersService.findByEmailOrNull(dto.co_parent_email);
|
||||
if (coParentExiste) {
|
||||
throw new ConflictException('L\'email du co-parent est déjà utilisé');
|
||||
@@ -192,7 +328,18 @@ export class AuthService {
|
||||
const dateExpiration = new Date();
|
||||
dateExpiration.setDate(dateExpiration.getDate() + joursExpirationToken);
|
||||
|
||||
const resultat = await this.usersRepo.manager.transaction(async (manager) => {
|
||||
let resultat: {
|
||||
parent1: Users;
|
||||
parent2: Users | null;
|
||||
enfants: Children[];
|
||||
tokenCreationMdp: string;
|
||||
tokenCoParent: string | null;
|
||||
};
|
||||
|
||||
try {
|
||||
resultat = await this.usersRepo.manager.transaction(async (manager) => {
|
||||
const { numero: numeroDossier } = await this.numeroDossierService.getNextNumeroDossier(manager);
|
||||
|
||||
const parent1 = manager.create(Users, {
|
||||
email: dto.email,
|
||||
prenom: dto.prenom,
|
||||
@@ -205,6 +352,7 @@ export class AuthService {
|
||||
ville: dto.ville,
|
||||
token_creation_mdp: tokenCreationMdp,
|
||||
token_creation_mdp_expire_le: dateExpiration,
|
||||
numero_dossier: numeroDossier,
|
||||
});
|
||||
|
||||
const parent1Enregistre = await manager.save(Users, parent1);
|
||||
@@ -229,6 +377,7 @@ export class AuthService {
|
||||
ville: dto.co_parent_meme_adresse ? dto.ville : dto.co_parent_ville,
|
||||
token_creation_mdp: tokenCoParent,
|
||||
token_creation_mdp_expire_le: dateExpirationCoParent,
|
||||
numero_dossier: numeroDossier,
|
||||
});
|
||||
|
||||
parent2Enregistre = await manager.save(Users, parent2);
|
||||
@@ -236,6 +385,7 @@ export class AuthService {
|
||||
|
||||
const entiteParent = manager.create(Parents, {
|
||||
user_id: parent1Enregistre.id,
|
||||
numero_dossier: numeroDossier,
|
||||
});
|
||||
entiteParent.user = parent1Enregistre;
|
||||
if (parent2Enregistre) {
|
||||
@@ -247,6 +397,7 @@ export class AuthService {
|
||||
if (parent2Enregistre) {
|
||||
const entiteCoParent = manager.create(Parents, {
|
||||
user_id: parent2Enregistre.id,
|
||||
numero_dossier: numeroDossier,
|
||||
});
|
||||
entiteCoParent.user = parent2Enregistre;
|
||||
entiteCoParent.co_parent = parent1Enregistre;
|
||||
@@ -296,6 +447,25 @@ export class AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
// Dossier famille : motivation (texte_motivation côté GET) + liaisons enfants (ticket #119)
|
||||
const presentationTrim = dto.presentation_dossier?.trim();
|
||||
const dossierFamilleEnt = manager.create(DossierFamille, {
|
||||
numero_dossier: numeroDossier,
|
||||
presentation: presentationTrim || undefined,
|
||||
statut: StatutDossierType.ENVOYE,
|
||||
parent: entiteParent,
|
||||
});
|
||||
const dossierFamilleSaved = await manager.save(DossierFamille, dossierFamilleEnt);
|
||||
for (const enfantEnregistre of enfantsEnregistres) {
|
||||
await manager.save(
|
||||
DossierFamilleEnfant,
|
||||
manager.create(DossierFamilleEnfant, {
|
||||
id_dossier_famille: dossierFamilleSaved.id,
|
||||
id_enfant: enfantEnregistre.id,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
parent1: parent1Enregistre,
|
||||
parent2: parent2Enregistre,
|
||||
@@ -304,6 +474,38 @@ export class AuthService {
|
||||
tokenCoParent,
|
||||
};
|
||||
});
|
||||
} catch (err) {
|
||||
if (this.isPostgresUniqueViolation(err)) {
|
||||
throw new ConflictException(
|
||||
'Un compte avec cet email existe déjà (contrainte unique en base).',
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const numeroDossier = resultat.parent1.numero_dossier ?? '';
|
||||
|
||||
try {
|
||||
await this.mailService.sendRegistrationPendingEmail(
|
||||
resultat.parent1.email,
|
||||
resultat.parent1.prenom ?? '',
|
||||
resultat.parent1.nom ?? '',
|
||||
numeroDossier,
|
||||
);
|
||||
if (resultat.parent2) {
|
||||
await this.mailService.sendRegistrationPendingEmail(
|
||||
resultat.parent2.email,
|
||||
resultat.parent2.prenom ?? '',
|
||||
resultat.parent2.nom ?? '',
|
||||
numeroDossier,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
"[inscrireParentComplet] Échec envoi email d'accusé de réception (inscription conservée)",
|
||||
err instanceof Error ? err.stack : String(err),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
message: 'Inscription réussie. Votre dossier est en attente de validation par un gestionnaire.',
|
||||
@@ -311,6 +513,7 @@ export class AuthService {
|
||||
co_parent_id: resultat.parent2?.id,
|
||||
enfants_ids: resultat.enfants.map(e => e.id),
|
||||
statut: StatutUtilisateurType.EN_ATTENTE,
|
||||
numero_dossier: numeroDossier,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -325,11 +528,50 @@ export class AuthService {
|
||||
);
|
||||
}
|
||||
|
||||
if (dto.places_disponibles > dto.capacite_accueil) {
|
||||
throw new BadRequestException(
|
||||
'Le nombre de places disponibles ne peut pas dépasser la capacité d\'accueil.',
|
||||
);
|
||||
}
|
||||
|
||||
const nirNormalized = (dto.nir || '').replace(/\s/g, '').toUpperCase();
|
||||
const nirValidation = validateNir(nirNormalized, {
|
||||
dateNaissance: dto.date_naissance,
|
||||
});
|
||||
if (!nirValidation.valid) {
|
||||
throw new BadRequestException(nirValidation.error || 'NIR invalide');
|
||||
}
|
||||
if (nirValidation.warning) {
|
||||
// Warning uniquement : on ne bloque pas (AM souvent étrangères, DOM-TOM, Corse)
|
||||
console.warn('[inscrireAMComplet] NIR warning:', nirValidation.warning, 'email=', dto.email);
|
||||
}
|
||||
|
||||
const existe = await this.usersService.findByEmailOrNull(dto.email);
|
||||
if (existe) {
|
||||
throw new ConflictException('Un compte avec cet email existe déjà');
|
||||
}
|
||||
|
||||
const nirDejaUtilise = await this.assistantesMaternellesRepo.findOne({
|
||||
where: { nir: nirNormalized },
|
||||
});
|
||||
if (nirDejaUtilise) {
|
||||
throw new ConflictException(
|
||||
'Un compte assistante maternelle avec ce numéro NIR existe déjà.',
|
||||
);
|
||||
}
|
||||
|
||||
const numeroAgrement = (dto.numero_agrement || '').trim();
|
||||
if (numeroAgrement) {
|
||||
const agrementDejaUtilise = await this.assistantesMaternellesRepo.findOne({
|
||||
where: { approval_number: numeroAgrement },
|
||||
});
|
||||
if (agrementDejaUtilise) {
|
||||
throw new ConflictException(
|
||||
'Un compte assistante maternelle avec ce numéro d\'agrément existe déjà.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const joursExpirationToken = await this.appConfigService.get<number>(
|
||||
'password_reset_token_expiry_days',
|
||||
7,
|
||||
@@ -339,14 +581,21 @@ export class AuthService {
|
||||
dateExpiration.setDate(dateExpiration.getDate() + joursExpirationToken);
|
||||
|
||||
let urlPhoto: string | null = null;
|
||||
if (dto.photo_base64 && dto.photo_filename) {
|
||||
urlPhoto = await this.sauvegarderPhotoDepuisBase64(dto.photo_base64, dto.photo_filename);
|
||||
const photoB64 = (dto.photo_base64 ?? '').trim();
|
||||
if (photoB64) {
|
||||
const nomFichier =
|
||||
(dto.photo_filename ?? '').trim() || 'photo_am.jpg';
|
||||
urlPhoto = await this.sauvegarderPhotoDepuisBase64(photoB64, nomFichier);
|
||||
}
|
||||
|
||||
const dateConsentementPhoto =
|
||||
dto.consentement_photo ? new Date() : undefined;
|
||||
|
||||
const resultat = await this.usersRepo.manager.transaction(async (manager) => {
|
||||
let resultat: { user: Users };
|
||||
try {
|
||||
resultat = await this.usersRepo.manager.transaction(async (manager) => {
|
||||
const { numero: numeroDossier } = await this.numeroDossierService.getNextNumeroDossier(manager);
|
||||
|
||||
const user = manager.create(Users, {
|
||||
email: dto.email,
|
||||
prenom: dto.prenom,
|
||||
@@ -363,6 +612,9 @@ export class AuthService {
|
||||
consentement_photo: dto.consentement_photo,
|
||||
date_consentement_photo: dateConsentementPhoto,
|
||||
date_naissance: dto.date_naissance ? new Date(dto.date_naissance) : undefined,
|
||||
lieu_naissance_ville: dto.lieu_naissance_ville,
|
||||
lieu_naissance_pays: dto.lieu_naissance_pays,
|
||||
numero_dossier: numeroDossier,
|
||||
});
|
||||
const userEnregistre = await manager.save(Users, user);
|
||||
|
||||
@@ -370,23 +622,48 @@ export class AuthService {
|
||||
const am = amRepo.create({
|
||||
user_id: userEnregistre.id,
|
||||
approval_number: dto.numero_agrement,
|
||||
nir: dto.nir,
|
||||
nir: nirNormalized,
|
||||
max_children: dto.capacite_accueil,
|
||||
places_available: dto.places_disponibles,
|
||||
biography: dto.biographie,
|
||||
residence_city: dto.ville ?? undefined,
|
||||
agreement_date: dto.date_agrement ? new Date(dto.date_agrement) : undefined,
|
||||
available: true,
|
||||
numero_dossier: numeroDossier,
|
||||
});
|
||||
await amRepo.save(am);
|
||||
|
||||
return { user: userEnregistre };
|
||||
});
|
||||
} catch (err) {
|
||||
if (this.isPostgresUniqueViolation(err)) {
|
||||
throw new ConflictException('Un compte avec cet email existe déjà (contrainte unique en base).');
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const numeroDossier = resultat.user.numero_dossier ?? '';
|
||||
|
||||
try {
|
||||
await this.mailService.sendRegistrationPendingEmail(
|
||||
resultat.user.email,
|
||||
resultat.user.prenom ?? '',
|
||||
resultat.user.nom ?? '',
|
||||
numeroDossier,
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
"[inscrireAMComplet] Échec envoi email d'accusé de réception (inscription conservée)",
|
||||
err instanceof Error ? err.stack : String(err),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
message:
|
||||
'Inscription réussie. Votre dossier est en attente de validation par un gestionnaire.',
|
||||
user_id: resultat.user.id,
|
||||
statut: StatutUtilisateurType.EN_ATTENTE,
|
||||
numero_dossier: numeroDossier,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -402,7 +679,12 @@ export class AuthService {
|
||||
const extension = correspondances[1];
|
||||
const tamponImage = Buffer.from(correspondances[2], 'base64');
|
||||
|
||||
const dossierUpload = '/app/uploads/photos';
|
||||
const rawDir = process.env.UPLOAD_PHOTOS_DIR?.trim();
|
||||
const dossierUpload = rawDir
|
||||
? path.isAbsolute(rawDir)
|
||||
? rawDir
|
||||
: path.resolve(process.cwd(), rawDir)
|
||||
: path.join(process.cwd(), 'uploads', 'photos');
|
||||
await fs.mkdir(dossierUpload, { recursive: true });
|
||||
|
||||
const nomFichierUnique = `${Date.now()}-${crypto.randomUUID()}.${extension}`;
|
||||
@@ -470,4 +752,56 @@ export class AuthService {
|
||||
async logout(userId: string) {
|
||||
return { success: true, message: 'Deconnexion'}
|
||||
}
|
||||
|
||||
/** GET dossier reprise – token seul. Ticket #111 */
|
||||
async getRepriseDossier(token: string): Promise<RepriseDossierDto> {
|
||||
const user = await this.usersService.findByTokenReprise(token);
|
||||
if (!user) {
|
||||
throw new NotFoundException('Token reprise invalide ou expiré.');
|
||||
}
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
prenom: user.prenom,
|
||||
nom: user.nom,
|
||||
telephone: user.telephone,
|
||||
adresse: user.adresse,
|
||||
ville: user.ville,
|
||||
code_postal: user.code_postal,
|
||||
numero_dossier: user.numero_dossier,
|
||||
role: user.role,
|
||||
photo_url: user.photo_url,
|
||||
genre: user.genre,
|
||||
situation_familiale: user.situation_familiale,
|
||||
};
|
||||
}
|
||||
|
||||
/** PUT resoumission reprise. Ticket #111 */
|
||||
async resoumettreReprise(
|
||||
token: string,
|
||||
dto: { prenom?: string; nom?: string; telephone?: string; adresse?: string; ville?: string; code_postal?: string; photo_url?: string },
|
||||
): Promise<Users> {
|
||||
return this.usersService.resoumettreReprise(token, dto);
|
||||
}
|
||||
|
||||
/** POST reprise-identify : numero_dossier + email → type + token. Ticket #111 */
|
||||
async identifyReprise(numero_dossier: string, email: string): Promise<RepriseIdentifyResponseDto> {
|
||||
const user = await this.usersService.findByNumeroDossierAndEmailForReprise(numero_dossier, email);
|
||||
if (!user || !user.token_reprise) {
|
||||
throw new NotFoundException('Aucun dossier en reprise trouvé pour ce numéro et cet email.');
|
||||
}
|
||||
return {
|
||||
type: user.role === RoleType.PARENT ? 'parent' : 'assistante_maternelle',
|
||||
token: user.token_reprise,
|
||||
};
|
||||
}
|
||||
|
||||
/** Violation unique PostgreSQL (ex. email déjà présent malgré course entre requêtes). */
|
||||
private isPostgresUniqueViolation(err: unknown): boolean {
|
||||
if (!(err instanceof QueryFailedError)) {
|
||||
return false;
|
||||
}
|
||||
const code = (err.driverError as { code?: string } | undefined)?.code;
|
||||
return code === '23505';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsString, MinLength, Matches } from 'class-validator';
|
||||
|
||||
export class CreatePasswordDto {
|
||||
@ApiProperty({ description: 'Token de création de mot de passe reçu par email' })
|
||||
@IsString()
|
||||
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,4 +1,5 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { Transform } from 'class-transformer';
|
||||
import {
|
||||
IsEmail,
|
||||
IsNotEmpty,
|
||||
@@ -76,7 +77,12 @@ export class RegisterAMCompletDto {
|
||||
@IsString()
|
||||
photo_base64?: string;
|
||||
|
||||
@ApiProperty({ example: 'photo_profil.jpg', required: false })
|
||||
@ApiProperty({
|
||||
example: 'photo_profil.jpg',
|
||||
required: false,
|
||||
description:
|
||||
'Nom du fichier photo (optionnel si photo_base64 est fourni ; défaut serveur : photo_am.jpg). L’extension réelle du fichier stocké suit le type MIME du data-URL.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
photo_filename?: string;
|
||||
@@ -91,22 +97,28 @@ export class RegisterAMCompletDto {
|
||||
@IsDateString()
|
||||
date_naissance?: string;
|
||||
|
||||
@ApiProperty({ example: 'Paris', required: false, description: 'Ville de naissance' })
|
||||
@IsOptional()
|
||||
@ApiProperty({ example: 'Paris', description: 'Ville de naissance (obligatoire)' })
|
||||
@Transform(({ value }) => (typeof value === 'string' ? value.trim() : value))
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: 'La ville de naissance est requise' })
|
||||
@MinLength(2, { message: 'La ville de naissance doit contenir au moins 2 caractères' })
|
||||
@MaxLength(100)
|
||||
lieu_naissance_ville?: string;
|
||||
lieu_naissance_ville: string;
|
||||
|
||||
@ApiProperty({ example: 'France', required: false, description: 'Pays de naissance' })
|
||||
@IsOptional()
|
||||
@ApiProperty({ example: 'France', description: 'Pays de naissance (obligatoire)' })
|
||||
@Transform(({ value }) => (typeof value === 'string' ? value.trim() : value))
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: 'Le pays de naissance est requis' })
|
||||
@MinLength(2, { message: 'Le pays de naissance doit contenir au moins 2 caractères' })
|
||||
@MaxLength(100)
|
||||
lieu_naissance_pays?: string;
|
||||
lieu_naissance_pays: string;
|
||||
|
||||
@ApiProperty({ example: '123456789012345', description: 'NIR 15 chiffres' })
|
||||
@ApiProperty({ example: '123456789012345', description: 'NIR 15 caractères (chiffres, ou 2A/2B pour la Corse)' })
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: 'Le NIR est requis' })
|
||||
@Matches(/^\d{15}$/, { message: 'Le NIR doit contenir exactement 15 chiffres' })
|
||||
@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({ example: 'AGR-2024-12345', description: "Numéro d'agrément" })
|
||||
@@ -126,6 +138,17 @@ export class RegisterAMCompletDto {
|
||||
@Max(10, { message: 'La capacité ne peut pas dépasser 10' })
|
||||
capacite_accueil: number;
|
||||
|
||||
@ApiProperty({
|
||||
example: 2,
|
||||
description: 'Nombre de places libres actuellement (≤ capacité d\'accueil)',
|
||||
minimum: 0,
|
||||
maximum: 10,
|
||||
})
|
||||
@IsInt()
|
||||
@Min(0, { message: 'Les places disponibles ne peuvent pas être négatives' })
|
||||
@Max(10, { message: 'Les places disponibles ne peuvent pas dépasser 10' })
|
||||
places_disponibles: number;
|
||||
|
||||
// ============================================
|
||||
// ÉTAPE 3 : PRÉSENTATION (Optionnel)
|
||||
// ============================================
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||
|
||||
/** Réponse 201 POST /auth/register/am (alignée sur les champs clés de /auth/register/parent). */
|
||||
export class RegisterAmResponseDto {
|
||||
@ApiProperty()
|
||||
message: string;
|
||||
|
||||
@ApiProperty({ format: 'uuid' })
|
||||
user_id: string;
|
||||
|
||||
@ApiProperty({ enum: StatutUtilisateurType, example: StatutUtilisateurType.EN_ATTENTE })
|
||||
statut: StatutUtilisateurType;
|
||||
|
||||
@ApiProperty({ example: '2026-000015', description: 'Numéro de dossier attribué à l’inscription' })
|
||||
numero_dossier: string;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { RoleType } from 'src/entities/users.entity';
|
||||
|
||||
/** Réponse GET /auth/reprise-dossier – données dossier pour préremplir le formulaire reprise. Ticket #111 */
|
||||
export class RepriseDossierDto {
|
||||
@ApiProperty()
|
||||
id: string;
|
||||
|
||||
@ApiProperty()
|
||||
email: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
prenom?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
nom?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
telephone?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
adresse?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
ville?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
code_postal?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
numero_dossier?: string;
|
||||
|
||||
@ApiProperty({ enum: RoleType })
|
||||
role: RoleType;
|
||||
|
||||
@ApiProperty({ required: false, description: 'Pour AM' })
|
||||
photo_url?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
genre?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
situation_familiale?: string;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsEmail, IsString, MaxLength } from 'class-validator';
|
||||
|
||||
/** Body POST /auth/reprise-identify – numéro + email pour obtenir token reprise. Ticket #111 */
|
||||
export class RepriseIdentifyBodyDto {
|
||||
@ApiProperty({ example: '2026-000001' })
|
||||
@IsString()
|
||||
@MaxLength(20)
|
||||
numero_dossier: string;
|
||||
|
||||
@ApiProperty({ example: 'parent@example.com' })
|
||||
@IsEmail()
|
||||
email: string;
|
||||
}
|
||||
|
||||
/** Réponse POST /auth/reprise-identify */
|
||||
export class RepriseIdentifyResponseDto {
|
||||
@ApiProperty({ enum: ['parent', 'assistante_maternelle'] })
|
||||
type: 'parent' | 'assistante_maternelle';
|
||||
|
||||
@ApiProperty({ description: 'Token à utiliser pour GET reprise-dossier et PUT reprise-resoumettre' })
|
||||
token: string;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString, MaxLength, IsUUID } from 'class-validator';
|
||||
|
||||
/** Body PUT /auth/reprise-resoumettre – token + champs modifiables. Ticket #111 */
|
||||
export class ResoumettreRepriseDto {
|
||||
@ApiProperty({ description: 'Token reprise (reçu par email)' })
|
||||
@IsUUID()
|
||||
token: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
prenom?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
nom?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(20)
|
||||
telephone?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
adresse?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(150)
|
||||
ville?: string;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(10)
|
||||
code_postal?: string;
|
||||
|
||||
@ApiProperty({ required: false, description: 'Pour AM' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
photo_url?: string;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
|
||||
import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||
import { RoleType } from 'src/entities/users.entity';
|
||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||
import { DossiersService } from './dossiers.service';
|
||||
import { DossierUnifieDto } from './dto/dossier-unifie.dto';
|
||||
|
||||
@ApiTags('Dossiers')
|
||||
@Controller('dossiers')
|
||||
@UseGuards(AuthGuard, RolesGuard)
|
||||
export class DossiersController {
|
||||
constructor(private readonly dossiersService: DossiersService) {}
|
||||
|
||||
@Get(':numeroDossier')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||
@ApiOperation({ summary: 'Dossier complet par numéro (AM ou famille) – Ticket #119' })
|
||||
@ApiParam({ name: 'numeroDossier', description: 'Numéro de dossier (ex: 2026-000001)' })
|
||||
@ApiResponse({ status: 200, description: 'Dossier famille ou AM', type: DossierUnifieDto })
|
||||
@ApiResponse({ status: 404, description: 'Aucun dossier pour ce numéro' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||
getDossier(@Param('numeroDossier') numeroDossier: string): Promise<DossierUnifieDto> {
|
||||
return this.dossiersService.getDossierByNumero(numeroDossier);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,28 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||
import { ParentsModule } from '../parents/parents.module';
|
||||
import { DossiersController } from './dossiers.controller';
|
||||
import { DossiersService } from './dossiers.service';
|
||||
|
||||
@Module({})
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Parents, AssistanteMaternelle]),
|
||||
ParentsModule,
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
secret: config.get('jwt.accessSecret'),
|
||||
signOptions: { expiresIn: config.get('jwt.accessExpiresIn') },
|
||||
}),
|
||||
inject: [ConfigService],
|
||||
}),
|
||||
],
|
||||
controllers: [DossiersController],
|
||||
providers: [DossiersService],
|
||||
exports: [DossiersService],
|
||||
})
|
||||
export class DossiersModule {}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||
import { ParentsService } from '../parents/parents.service';
|
||||
import { DossierUnifieDto } from './dto/dossier-unifie.dto';
|
||||
import { DossierAmCompletDto, DossierAmUserDto } from './dto/dossier-am-complet.dto';
|
||||
|
||||
/**
|
||||
* Endpoint unifié GET /dossiers/:numeroDossier – AM ou famille. Ticket #119.
|
||||
*/
|
||||
@Injectable()
|
||||
export class DossiersService {
|
||||
constructor(
|
||||
@InjectRepository(Parents)
|
||||
private readonly parentsRepository: Repository<Parents>,
|
||||
@InjectRepository(AssistanteMaternelle)
|
||||
private readonly amRepository: Repository<AssistanteMaternelle>,
|
||||
private readonly parentsService: ParentsService,
|
||||
) {}
|
||||
|
||||
async getDossierByNumero(numeroDossier: string): Promise<DossierUnifieDto> {
|
||||
const num = numeroDossier?.trim();
|
||||
if (!num) {
|
||||
throw new NotFoundException('Numéro de dossier requis.');
|
||||
}
|
||||
|
||||
// 1) Famille : un parent a ce numéro ?
|
||||
const parentWithNum = await this.parentsRepository.findOne({
|
||||
where: { numero_dossier: num },
|
||||
select: ['user_id'],
|
||||
});
|
||||
if (parentWithNum) {
|
||||
const dossier = await this.parentsService.getDossierFamilleByNumero(num);
|
||||
return { type: 'family', dossier };
|
||||
}
|
||||
|
||||
// 2) AM : une assistante maternelle a ce numéro ?
|
||||
const am = await this.amRepository.findOne({
|
||||
where: { numero_dossier: num },
|
||||
relations: ['user'],
|
||||
});
|
||||
if (am?.user) {
|
||||
const dossier: DossierAmCompletDto = {
|
||||
numero_dossier: num,
|
||||
user: this.toDossierAmUserDto(am.user),
|
||||
numero_agrement: am.approval_number,
|
||||
nir: am.nir,
|
||||
biographie: am.biography,
|
||||
disponible: am.available,
|
||||
ville_residence: am.residence_city,
|
||||
date_agrement: am.agreement_date,
|
||||
annees_experience: am.years_experience,
|
||||
specialite: am.specialty,
|
||||
nb_max_enfants: am.max_children,
|
||||
place_disponible: am.places_available,
|
||||
};
|
||||
return { type: 'am', dossier };
|
||||
}
|
||||
|
||||
throw new NotFoundException('Aucun dossier trouvé pour ce numéro.');
|
||||
}
|
||||
|
||||
private toDossierAmUserDto(user: {
|
||||
id: string;
|
||||
email: string;
|
||||
prenom?: string;
|
||||
nom?: string;
|
||||
telephone?: string;
|
||||
adresse?: string;
|
||||
ville?: string;
|
||||
code_postal?: string;
|
||||
profession?: string;
|
||||
date_naissance?: Date;
|
||||
lieu_naissance_ville?: string;
|
||||
lieu_naissance_pays?: string;
|
||||
photo_url?: string;
|
||||
consentement_photo?: boolean;
|
||||
statut: any;
|
||||
}): DossierAmUserDto {
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
prenom: user.prenom,
|
||||
nom: user.nom,
|
||||
telephone: user.telephone,
|
||||
adresse: user.adresse,
|
||||
ville: user.ville,
|
||||
code_postal: user.code_postal,
|
||||
profession: user.profession,
|
||||
date_naissance: user.date_naissance,
|
||||
lieu_naissance_ville: user.lieu_naissance_ville,
|
||||
lieu_naissance_pays: user.lieu_naissance_pays,
|
||||
photo_url: user.photo_url,
|
||||
consentement_photo: user.consentement_photo,
|
||||
statut: user.statut,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||
|
||||
/** Utilisateur AM sans données sensibles (pour dossier AM complet). Ticket #119 */
|
||||
export class DossierAmUserDto {
|
||||
@ApiProperty()
|
||||
id: string;
|
||||
@ApiProperty()
|
||||
email: string;
|
||||
@ApiProperty({ required: false })
|
||||
prenom?: string;
|
||||
@ApiProperty({ required: false })
|
||||
nom?: string;
|
||||
@ApiProperty({ required: false })
|
||||
telephone?: string;
|
||||
@ApiProperty({ required: false })
|
||||
adresse?: string;
|
||||
@ApiProperty({ required: false })
|
||||
ville?: string;
|
||||
@ApiProperty({ required: false })
|
||||
code_postal?: string;
|
||||
@ApiProperty({ required: false })
|
||||
profession?: string;
|
||||
@ApiProperty({ required: false })
|
||||
date_naissance?: Date;
|
||||
@ApiProperty({ required: false, description: 'Ville de naissance' })
|
||||
lieu_naissance_ville?: string;
|
||||
@ApiProperty({ required: false, description: 'Pays de naissance' })
|
||||
lieu_naissance_pays?: string;
|
||||
@ApiProperty({ required: false })
|
||||
photo_url?: string;
|
||||
@ApiProperty({ required: false, description: 'Consentement utilisation photo' })
|
||||
consentement_photo?: boolean;
|
||||
@ApiProperty({ enum: StatutUtilisateurType })
|
||||
statut: StatutUtilisateurType;
|
||||
}
|
||||
|
||||
/** Dossier AM complet (fiche AM sans secrets). Ticket #119 */
|
||||
export class DossierAmCompletDto {
|
||||
@ApiProperty({ example: '2026-000003', description: 'Numéro de dossier AM' })
|
||||
numero_dossier: string;
|
||||
@ApiProperty({ type: DossierAmUserDto, description: 'Utilisateur (sans mot de passe ni tokens)' })
|
||||
user: DossierAmUserDto;
|
||||
@ApiProperty({ required: false })
|
||||
numero_agrement?: string;
|
||||
@ApiProperty({ required: false })
|
||||
nir?: string;
|
||||
@ApiProperty({ required: false })
|
||||
biographie?: string;
|
||||
@ApiProperty({ required: false })
|
||||
disponible?: boolean;
|
||||
@ApiProperty({ required: false })
|
||||
ville_residence?: string;
|
||||
@ApiProperty({ required: false })
|
||||
date_agrement?: Date;
|
||||
@ApiProperty({ required: false })
|
||||
annees_experience?: number;
|
||||
@ApiProperty({ required: false })
|
||||
specialite?: string;
|
||||
@ApiProperty({ required: false })
|
||||
nb_max_enfants?: number;
|
||||
@ApiProperty({ required: false })
|
||||
place_disponible?: number;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { DossierFamilleCompletDto } from '../../parents/dto/dossier-famille-complet.dto';
|
||||
import { DossierAmCompletDto } from './dossier-am-complet.dto';
|
||||
|
||||
/** Réponse unifiée GET /dossiers/:numeroDossier – AM ou famille. Ticket #119 */
|
||||
export class DossierUnifieDto {
|
||||
@ApiProperty({ enum: ['family', 'am'], description: 'Type de dossier' })
|
||||
type: 'family' | 'am';
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Dossier famille (si type=family) ou dossier AM (si type=am)',
|
||||
})
|
||||
dossier: DossierFamilleCompletDto | DossierAmCompletDto;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||
import { StatutEnfantType, GenreType } from 'src/entities/children.entity';
|
||||
|
||||
/** Parent dans le dossier famille (infos utilisateur + parent) */
|
||||
export class DossierFamilleParentDto {
|
||||
@ApiProperty()
|
||||
user_id: string;
|
||||
@ApiProperty()
|
||||
email: string;
|
||||
@ApiProperty({ required: false })
|
||||
prenom?: string;
|
||||
@ApiProperty({ required: false })
|
||||
nom?: string;
|
||||
@ApiProperty({ required: false })
|
||||
telephone?: string;
|
||||
@ApiProperty({ required: false })
|
||||
adresse?: string;
|
||||
@ApiProperty({ required: false })
|
||||
ville?: string;
|
||||
@ApiProperty({ required: false })
|
||||
code_postal?: string;
|
||||
@ApiProperty({ enum: StatutUtilisateurType })
|
||||
statut: StatutUtilisateurType;
|
||||
@ApiProperty({ required: false, description: 'Id du co-parent si couple' })
|
||||
co_parent_id?: string;
|
||||
}
|
||||
|
||||
/** Enfant dans le dossier famille */
|
||||
export class DossierFamilleEnfantDto {
|
||||
@ApiProperty()
|
||||
id: string;
|
||||
@ApiProperty({ required: false })
|
||||
first_name?: string;
|
||||
@ApiProperty({ required: false })
|
||||
last_name?: string;
|
||||
@ApiProperty({ required: false, enum: GenreType })
|
||||
genre?: GenreType;
|
||||
@ApiProperty({ required: false })
|
||||
birth_date?: Date;
|
||||
@ApiProperty({ required: false })
|
||||
due_date?: Date;
|
||||
@ApiProperty({ enum: StatutEnfantType })
|
||||
status: StatutEnfantType;
|
||||
|
||||
@ApiProperty({
|
||||
required: false,
|
||||
description: 'Chemin ou URL de la photo (souvent relatif, ex. /uploads/photos/...)',
|
||||
})
|
||||
photo_url?: string;
|
||||
|
||||
@ApiProperty({
|
||||
required: false,
|
||||
description: 'Consentement affichage photo (colonne consentement_photo)',
|
||||
})
|
||||
consent_photo?: boolean;
|
||||
}
|
||||
|
||||
/** Réponse GET /parents/dossier-famille/:numeroDossier – dossier famille complet. Ticket #119 */
|
||||
export class DossierFamilleCompletDto {
|
||||
@ApiProperty({ example: '2026-000001', description: 'Numéro de dossier famille' })
|
||||
numero_dossier: string;
|
||||
@ApiProperty({ type: [DossierFamilleParentDto] })
|
||||
parents: DossierFamilleParentDto[];
|
||||
@ApiProperty({ type: [DossierFamilleEnfantDto], description: 'Enfants de la famille' })
|
||||
enfants: DossierFamilleEnfantDto[];
|
||||
@ApiProperty({ required: false, description: 'Texte de présentation / motivation (un seul par famille)' })
|
||||
texte_motivation?: string;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class ParentPendingSummaryDto {
|
||||
@ApiProperty({ description: 'UUID utilisateur' })
|
||||
id: string;
|
||||
|
||||
@ApiProperty()
|
||||
email: string;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true })
|
||||
telephone?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true })
|
||||
code_postal?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ nullable: true })
|
||||
ville?: string | null;
|
||||
}
|
||||
|
||||
export class PendingFamilyDto {
|
||||
@ApiProperty({ example: 'Famille Dupont', description: 'Libellé affiché pour la famille' })
|
||||
libelle: string;
|
||||
|
||||
@ApiProperty({
|
||||
type: [String],
|
||||
example: ['uuid-parent-1', 'uuid-parent-2'],
|
||||
description: 'IDs utilisateur des parents de la famille',
|
||||
})
|
||||
parentIds: string[];
|
||||
|
||||
@ApiProperty({
|
||||
nullable: true,
|
||||
example: '2026-000001',
|
||||
description: 'Numéro de dossier famille (format AAAA-NNNNNN)',
|
||||
})
|
||||
numero_dossier: string | null;
|
||||
|
||||
@ApiProperty({
|
||||
nullable: true,
|
||||
example: '2026-01-12T10:00:00.000Z',
|
||||
description: 'Date de référence dossier soumis / en attente : MIN(cree_le) des parents en_attente du groupe (ISO 8601)',
|
||||
})
|
||||
date_soumission: string | null;
|
||||
|
||||
@ApiProperty({
|
||||
example: 3,
|
||||
description: 'Nombre d’enfants distincts liés aux parents de la famille (enfants_parents)',
|
||||
})
|
||||
nombre_enfants: number;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
type: [String],
|
||||
example: ['parent1@example.com', 'parent2@example.com'],
|
||||
description: 'Emails des parents du groupe (ordre stable : nom, prénom)',
|
||||
})
|
||||
emails?: string[];
|
||||
|
||||
@ApiPropertyOptional({
|
||||
type: [ParentPendingSummaryDto],
|
||||
description: 'Résumé des parents (ordre stable, aligné sur parentIds/emails)',
|
||||
})
|
||||
parents?: ParentPendingSummaryDto[];
|
||||
}
|
||||
@@ -1,24 +1,83 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ParentsService } from './parents.service';
|
||||
import { UserService } from '../user/user.service';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||
import { RoleType } from 'src/entities/users.entity';
|
||||
import { ApiBody, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { RoleType, StatutUtilisateurType } from 'src/entities/users.entity';
|
||||
import { ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { CreateParentDto } from '../user/dto/create_parent.dto';
|
||||
import { UpdateParentsDto } from '../user/dto/update_parent.dto';
|
||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||
import { User } from 'src/common/decorators/user.decorator';
|
||||
import { PendingFamilyDto } from './dto/pending-family.dto';
|
||||
import { DossierFamilleCompletDto } from './dto/dossier-famille-complet.dto';
|
||||
|
||||
@ApiTags('Parents')
|
||||
@Controller('parents')
|
||||
@UseGuards(AuthGuard, RolesGuard)
|
||||
export class ParentsController {
|
||||
constructor(private readonly parentsService: ParentsService) {}
|
||||
constructor(
|
||||
private readonly parentsService: ParentsService,
|
||||
private readonly userService: UserService,
|
||||
) {}
|
||||
|
||||
@Get('pending-families')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||
@ApiOperation({ summary: 'Liste des familles en attente (une entrée par famille)' })
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description:
|
||||
'Liste des familles (libellé, parentIds, numero_dossier, date_soumission, nombre_enfants, emails, parents)',
|
||||
type: [PendingFamilyDto],
|
||||
})
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||
getPendingFamilies(): Promise<PendingFamilyDto[]> {
|
||||
return this.parentsService.getPendingFamilies();
|
||||
}
|
||||
|
||||
@Get('dossier-famille/:numeroDossier')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||
@ApiOperation({ summary: 'Dossier famille complet par numéro de dossier (Ticket #119)' })
|
||||
@ApiParam({ name: 'numeroDossier', description: 'Numéro de dossier (ex: 2026-000001)' })
|
||||
@ApiResponse({ status: 200, description: 'Dossier famille (numero_dossier, parents, enfants, presentation)', type: DossierFamilleCompletDto })
|
||||
@ApiResponse({ status: 404, description: 'Aucun dossier pour ce numéro' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||
getDossierFamille(@Param('numeroDossier') numeroDossier: string): Promise<DossierFamilleCompletDto> {
|
||||
return this.parentsService.getDossierFamilleByNumero(numeroDossier);
|
||||
}
|
||||
|
||||
@Post(':parentId/valider-dossier')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||
@ApiOperation({ summary: 'Valider tout le dossier famille (les 2 parents en une fois)' })
|
||||
@ApiParam({ name: 'parentId', description: "UUID d'un des parents (user_id)" })
|
||||
@ApiResponse({ status: 200, description: 'Utilisateurs validés (famille)' })
|
||||
@ApiResponse({ status: 404, description: 'Parent introuvable' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||
async validerDossierFamille(
|
||||
@Param('parentId') parentId: string,
|
||||
@User() currentUser: Users,
|
||||
@Body('comment') comment?: string,
|
||||
): Promise<Users[]> {
|
||||
const familyIds = await this.parentsService.getFamilyUserIds(parentId);
|
||||
const validated: Users[] = [];
|
||||
for (const userId of familyIds) {
|
||||
const user = await this.userService.findOne(userId);
|
||||
if (user.statut !== StatutUtilisateurType.EN_ATTENTE && user.statut !== StatutUtilisateurType.REFUSE) continue;
|
||||
const saved = await this.userService.validateUser(userId, currentUser, comment);
|
||||
validated.push(saved);
|
||||
}
|
||||
return validated;
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||
@Get()
|
||||
|
||||
@@ -1,12 +1,27 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { Module, forwardRef } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { DossierFamille, DossierFamilleEnfant } from 'src/entities/dossier_famille.entity';
|
||||
import { ParentsController } from './parents.controller';
|
||||
import { ParentsService } from './parents.service';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
import { UserModule } from '../user/user.module';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([Parents, Users])],
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Parents, Users, DossierFamille, DossierFamilleEnfant]),
|
||||
forwardRef(() => UserModule),
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
secret: config.get('jwt.accessSecret'),
|
||||
signOptions: { expiresIn: config.get('jwt.accessExpiresIn') },
|
||||
}),
|
||||
inject: [ConfigService],
|
||||
}),
|
||||
],
|
||||
controllers: [ParentsController],
|
||||
providers: [ParentsService],
|
||||
exports: [ParentsService,
|
||||
|
||||
@@ -5,11 +5,19 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { In, Repository } from 'typeorm';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { DossierFamille } from 'src/entities/dossier_famille.entity';
|
||||
import { RoleType, Users } from 'src/entities/users.entity';
|
||||
import { CreateParentDto } from '../user/dto/create_parent.dto';
|
||||
import { UpdateParentsDto } from '../user/dto/update_parent.dto';
|
||||
import { PendingFamilyDto } from './dto/pending-family.dto';
|
||||
import {
|
||||
DossierFamilleCompletDto,
|
||||
DossierFamilleParentDto,
|
||||
DossierFamilleEnfantDto,
|
||||
} from './dto/dossier-famille-complet.dto';
|
||||
import { Children } from 'src/entities/children.entity';
|
||||
|
||||
@Injectable()
|
||||
export class ParentsService {
|
||||
@@ -18,6 +26,8 @@ export class ParentsService {
|
||||
private readonly parentsRepository: Repository<Parents>,
|
||||
@InjectRepository(Users)
|
||||
private readonly usersRepository: Repository<Users>,
|
||||
@InjectRepository(DossierFamille)
|
||||
private readonly dossierFamilleRepository: Repository<DossierFamille>,
|
||||
) {}
|
||||
|
||||
// Création d’un parent
|
||||
@@ -71,4 +81,279 @@ export class ParentsService {
|
||||
await this.parentsRepository.update(id, dto);
|
||||
return this.findOne(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Liste des familles en attente (une entrée par famille).
|
||||
* Famille = lien co_parent ou partage d'enfants (même logique que backfill #103).
|
||||
* Uniquement les parents dont l'utilisateur a statut = en_attente.
|
||||
*/
|
||||
async getPendingFamilies(): Promise<PendingFamilyDto[]> {
|
||||
let raw: {
|
||||
libelle: string;
|
||||
parentIds: unknown;
|
||||
numero_dossier: string | null;
|
||||
date_soumission: Date | string | null;
|
||||
nombre_enfants: string | number | null;
|
||||
emails: unknown;
|
||||
parents: unknown;
|
||||
}[];
|
||||
try {
|
||||
raw = await this.parentsRepository.query(`
|
||||
WITH RECURSIVE
|
||||
links AS (
|
||||
SELECT p.id_utilisateur AS p1, p.id_co_parent AS p2 FROM parents p WHERE p.id_co_parent IS NOT NULL
|
||||
UNION ALL
|
||||
SELECT p.id_co_parent AS p1, p.id_utilisateur AS p2 FROM parents p WHERE p.id_co_parent IS NOT NULL
|
||||
UNION ALL
|
||||
SELECT ep1.id_parent AS p1, ep2.id_parent AS p2
|
||||
FROM enfants_parents ep1
|
||||
JOIN enfants_parents ep2 ON ep2.id_enfant = ep1.id_enfant AND ep1.id_parent < ep2.id_parent
|
||||
UNION ALL
|
||||
SELECT ep2.id_parent AS p1, ep1.id_parent AS p2
|
||||
FROM enfants_parents ep1
|
||||
JOIN enfants_parents ep2 ON ep2.id_enfant = ep1.id_enfant AND ep1.id_parent < ep2.id_parent
|
||||
),
|
||||
rec AS (
|
||||
SELECT id_utilisateur AS id, id_utilisateur AS rep FROM parents
|
||||
UNION
|
||||
SELECT l.p2 AS id, LEAST(rec_alias.rep, l.p2) AS rep FROM links l JOIN rec rec_alias ON rec_alias.id = l.p1
|
||||
),
|
||||
family_rep AS (
|
||||
SELECT id, (MIN(rep::text))::uuid AS rep FROM rec GROUP BY id
|
||||
)
|
||||
SELECT
|
||||
'Famille ' || string_agg(u.nom, ' - ' ORDER BY u.nom, u.prenom) AS libelle,
|
||||
array_agg(p.id_utilisateur ORDER BY u.nom, u.prenom, u.id) AS "parentIds",
|
||||
(array_agg(p.numero_dossier))[1] AS numero_dossier,
|
||||
MIN(u.cree_le) AS date_soumission,
|
||||
COALESCE((
|
||||
SELECT COUNT(DISTINCT ep.id_enfant)::int
|
||||
FROM enfants_parents ep
|
||||
WHERE ep.id_parent IN (
|
||||
SELECT frx.id FROM family_rep frx WHERE frx.rep = fr.rep
|
||||
)
|
||||
), 0) AS nombre_enfants,
|
||||
array_agg(u.email ORDER BY u.nom, u.prenom, u.id) AS emails,
|
||||
json_agg(
|
||||
json_build_object(
|
||||
'id', u.id::text,
|
||||
'email', u.email,
|
||||
'telephone', u.telephone,
|
||||
'code_postal', u.code_postal,
|
||||
'ville', u.ville
|
||||
)
|
||||
ORDER BY u.nom, u.prenom, u.id
|
||||
) AS parents
|
||||
FROM family_rep fr
|
||||
JOIN parents p ON p.id_utilisateur = fr.id
|
||||
JOIN utilisateurs u ON u.id = p.id_utilisateur
|
||||
WHERE u.role = 'parent' AND u.statut = 'en_attente'
|
||||
GROUP BY fr.rep
|
||||
ORDER BY libelle
|
||||
`);
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.map((r) => ({
|
||||
libelle: r.libelle ?? '',
|
||||
parentIds: this.normalizeParentIds(r.parentIds),
|
||||
numero_dossier: r.numero_dossier ?? null,
|
||||
date_soumission: this.toIsoDateTimeOrNull(r.date_soumission),
|
||||
nombre_enfants: this.normalizeNombreEnfants(r.nombre_enfants),
|
||||
emails: this.normalizeEmails(r.emails),
|
||||
parents: this.normalizeParents(r.parents),
|
||||
}));
|
||||
}
|
||||
|
||||
private toIsoDateTimeOrNull(value: Date | string | null | undefined): string | null {
|
||||
if (value == null) return null;
|
||||
if (value instanceof Date) return value.toISOString();
|
||||
const d = new Date(value);
|
||||
return Number.isNaN(d.getTime()) ? null : d.toISOString();
|
||||
}
|
||||
|
||||
private normalizeNombreEnfants(v: string | number | null | undefined): number {
|
||||
if (v == null) return 0;
|
||||
const n = typeof v === 'number' ? v : parseInt(String(v), 10);
|
||||
return Number.isFinite(n) && n >= 0 ? n : 0;
|
||||
}
|
||||
|
||||
private normalizeEmails(emails: unknown): string[] {
|
||||
if (Array.isArray(emails)) return emails.map(String);
|
||||
if (typeof emails === 'string') {
|
||||
const s = emails.replace(/^\{|\}$/g, '').trim();
|
||||
return s ? s.split(',').map((x) => x.trim()) : [];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
private normalizeParents(parents: unknown): { id: string; email: string; telephone: string | null; code_postal: string | null; ville: string | null }[] {
|
||||
if (Array.isArray(parents)) {
|
||||
return parents.map((p: any) => ({
|
||||
id: String(p?.id ?? ''),
|
||||
email: String(p?.email ?? ''),
|
||||
telephone: p?.telephone != null ? String(p.telephone) : null,
|
||||
code_postal: p?.code_postal != null ? String(p.code_postal) : null,
|
||||
ville: p?.ville != null ? String(p.ville) : null,
|
||||
}));
|
||||
}
|
||||
if (typeof parents === 'string') {
|
||||
try {
|
||||
const parsed = JSON.parse(parents);
|
||||
return this.normalizeParents(parsed);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/** Convertit parentIds (array ou chaîne PG) en string[] pour éviter 500 si le driver renvoie une chaîne. */
|
||||
private childToDossierFamilleEnfantDto(child: Children): DossierFamilleEnfantDto {
|
||||
return {
|
||||
id: child.id,
|
||||
first_name: child.first_name,
|
||||
last_name: child.last_name,
|
||||
genre: child.gender,
|
||||
birth_date: child.birth_date,
|
||||
due_date: child.due_date,
|
||||
status: child.status,
|
||||
photo_url: child.photo_url ?? undefined,
|
||||
consent_photo: child.consent_photo,
|
||||
};
|
||||
}
|
||||
|
||||
private normalizeParentIds(parentIds: unknown): string[] {
|
||||
if (Array.isArray(parentIds)) return parentIds.map(String);
|
||||
if (typeof parentIds === 'string') {
|
||||
const s = parentIds.replace(/^\{|\}$/g, '').trim();
|
||||
return s ? s.split(',').map((x) => x.trim()) : [];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Dossier famille complet par numéro de dossier. Ticket #119.
|
||||
* Rôles : admin, gestionnaire.
|
||||
* @throws NotFoundException si aucun parent avec ce numéro de dossier
|
||||
*/
|
||||
async getDossierFamilleByNumero(numeroDossier: string): Promise<DossierFamilleCompletDto> {
|
||||
const num = numeroDossier?.trim();
|
||||
if (!num) {
|
||||
throw new NotFoundException('Numéro de dossier requis.');
|
||||
}
|
||||
const firstParent = await this.parentsRepository.findOne({
|
||||
where: { numero_dossier: num },
|
||||
relations: ['user'],
|
||||
});
|
||||
if (!firstParent || !firstParent.user) {
|
||||
throw new NotFoundException('Aucun dossier famille trouvé pour ce numéro.');
|
||||
}
|
||||
const familyUserIds = await this.getFamilyUserIds(firstParent.user_id);
|
||||
const parents = await this.parentsRepository.find({
|
||||
where: { user_id: In(familyUserIds) },
|
||||
relations: ['user', 'co_parent', 'parentChildren', 'parentChildren.child', 'dossiers', 'dossiers.child'],
|
||||
});
|
||||
const enfantsMap = new Map<string, DossierFamilleEnfantDto>();
|
||||
let texte_motivation: string | undefined;
|
||||
|
||||
// Un dossier = une famille, un seul texte de motivation
|
||||
const dossierFamille = await this.dossierFamilleRepository.findOne({
|
||||
where: { numero_dossier: num },
|
||||
relations: ['parent', 'enfants', 'enfants.enfant'],
|
||||
});
|
||||
if (dossierFamille?.presentation) {
|
||||
texte_motivation = dossierFamille.presentation;
|
||||
}
|
||||
|
||||
for (const p of parents) {
|
||||
// Enfants via parentChildren
|
||||
if (p.parentChildren) {
|
||||
for (const pc of p.parentChildren) {
|
||||
if (pc.child && !enfantsMap.has(pc.child.id)) {
|
||||
enfantsMap.set(pc.child.id, this.childToDossierFamilleEnfantDto(pc.child));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Fallback : anciens dossiers (un texte, on prend le premier)
|
||||
if (texte_motivation == null && p.dossiers?.length) {
|
||||
texte_motivation = p.dossiers[0].presentation ?? undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Enfants uniquement liés via dossier_famille_enfants (legacy / parcours alternatif)
|
||||
if (dossierFamille?.enfants?.length) {
|
||||
for (const dfe of dossierFamille.enfants) {
|
||||
const c = dfe.enfant;
|
||||
if (c && !enfantsMap.has(c.id)) {
|
||||
enfantsMap.set(c.id, this.childToDossierFamilleEnfantDto(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const parentsDto: DossierFamilleParentDto[] = parents.map((p) => ({
|
||||
user_id: p.user_id,
|
||||
email: p.user.email,
|
||||
prenom: p.user.prenom,
|
||||
nom: p.user.nom,
|
||||
telephone: p.user.telephone,
|
||||
adresse: p.user.adresse,
|
||||
ville: p.user.ville,
|
||||
code_postal: p.user.code_postal,
|
||||
statut: p.user.statut,
|
||||
co_parent_id: p.co_parent?.id,
|
||||
}));
|
||||
return {
|
||||
numero_dossier: num,
|
||||
parents: parentsDto,
|
||||
enfants: Array.from(enfantsMap.values()),
|
||||
texte_motivation,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Retourne les user_id de tous les parents de la même famille (co_parent ou enfants partagés).
|
||||
* @throws NotFoundException si parentId n'est pas un parent
|
||||
*/
|
||||
async getFamilyUserIds(parentId: string): Promise<string[]> {
|
||||
const raw = await this.parentsRepository.query(
|
||||
`
|
||||
WITH RECURSIVE
|
||||
links AS (
|
||||
SELECT p.id_utilisateur AS p1, p.id_co_parent AS p2 FROM parents p WHERE p.id_co_parent IS NOT NULL
|
||||
UNION ALL
|
||||
SELECT p.id_co_parent AS p1, p.id_utilisateur AS p2 FROM parents p WHERE p.id_co_parent IS NOT NULL
|
||||
UNION ALL
|
||||
SELECT ep1.id_parent AS p1, ep2.id_parent AS p2
|
||||
FROM enfants_parents ep1
|
||||
JOIN enfants_parents ep2 ON ep2.id_enfant = ep1.id_enfant AND ep1.id_parent < ep2.id_parent
|
||||
UNION ALL
|
||||
SELECT ep2.id_parent AS p1, ep1.id_parent AS p2
|
||||
FROM enfants_parents ep1
|
||||
JOIN enfants_parents ep2 ON ep2.id_enfant = ep1.id_enfant AND ep1.id_parent < ep2.id_parent
|
||||
),
|
||||
rec AS (
|
||||
SELECT id_utilisateur AS id, id_utilisateur AS rep FROM parents
|
||||
UNION
|
||||
SELECT l.p2 AS id, LEAST(rec_alias.rep, l.p2) AS rep FROM links l JOIN rec rec_alias ON rec_alias.id = l.p1
|
||||
),
|
||||
family_rep AS (
|
||||
SELECT id, (MIN(rep::text))::uuid AS rep FROM rec GROUP BY id
|
||||
),
|
||||
input_rep AS (
|
||||
SELECT rep FROM family_rep WHERE id = $1::uuid LIMIT 1
|
||||
)
|
||||
SELECT fr.id::text AS id
|
||||
FROM family_rep fr
|
||||
CROSS JOIN input_rep ir
|
||||
WHERE fr.rep = ir.rep
|
||||
`,
|
||||
[parentId],
|
||||
);
|
||||
if (!raw || raw.length === 0) {
|
||||
throw new NotFoundException('Parent introuvable ou pas encore enregistré en base.');
|
||||
}
|
||||
return raw.map((r: { id: string }) => r.id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsBoolean, IsNotEmpty, IsOptional, IsString, IsObject } from 'class-validator';
|
||||
|
||||
export class CreateRelaisDto {
|
||||
@ApiProperty({ example: 'Relais Petite Enfance Centre' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
nom: string;
|
||||
|
||||
@ApiProperty({ example: '12 rue de la Mairie, 75000 Paris' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
adresse: string;
|
||||
|
||||
@ApiProperty({ example: { lundi: '09:00-17:00' }, required: false })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
horaires_ouverture?: any;
|
||||
|
||||
@ApiProperty({ example: '0123456789', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ligne_fixe?: string;
|
||||
|
||||
@ApiProperty({ default: true, required: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
actif?: boolean;
|
||||
|
||||
@ApiProperty({ example: 'Notes internes...', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateRelaisDto } from './create-relais.dto';
|
||||
|
||||
export class UpdateRelaisDto extends PartialType(CreateRelaisDto) {}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards } from '@nestjs/common';
|
||||
import { RelaisService } from './relais.service';
|
||||
import { CreateRelaisDto } from './dto/create-relais.dto';
|
||||
import { UpdateRelaisDto } from './dto/update-relais.dto';
|
||||
import { ApiBearerAuth, ApiTags, ApiOperation, ApiResponse } 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 { RoleType } from 'src/entities/users.entity';
|
||||
|
||||
@ApiTags('Relais')
|
||||
@ApiBearerAuth('access-token')
|
||||
@UseGuards(AuthGuard, RolesGuard)
|
||||
@Controller('relais')
|
||||
export class RelaisController {
|
||||
constructor(private readonly relaisService: RelaisService) {}
|
||||
|
||||
@Post()
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Créer un relais' })
|
||||
@ApiResponse({ status: 201, description: 'Le relais a été créé.' })
|
||||
create(@Body() createRelaisDto: CreateRelaisDto) {
|
||||
return this.relaisService.create(createRelaisDto);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Lister tous les relais' })
|
||||
@ApiResponse({ status: 200, description: 'Liste des relais.' })
|
||||
findAll() {
|
||||
return this.relaisService.findAll();
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Récupérer un relais par ID' })
|
||||
@ApiResponse({ status: 200, description: 'Le relais trouvé.' })
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.relaisService.findOne(id);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Mettre à jour un relais' })
|
||||
@ApiResponse({ status: 200, description: 'Le relais a été mis à jour.' })
|
||||
update(@Param('id') id: string, @Body() updateRelaisDto: UpdateRelaisDto) {
|
||||
return this.relaisService.update(id, updateRelaisDto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Supprimer un relais' })
|
||||
@ApiResponse({ status: 200, description: 'Le relais a été supprimé.' })
|
||||
remove(@Param('id') id: string) {
|
||||
return this.relaisService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { RelaisService } from './relais.service';
|
||||
import { RelaisController } from './relais.controller';
|
||||
import { Relais } from 'src/entities/relais.entity';
|
||||
import { AuthModule } from 'src/routes/auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Relais]),
|
||||
AuthModule,
|
||||
],
|
||||
controllers: [RelaisController],
|
||||
providers: [RelaisService],
|
||||
exports: [RelaisService],
|
||||
})
|
||||
export class RelaisModule {}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { Relais } from 'src/entities/relais.entity';
|
||||
import { CreateRelaisDto } from './dto/create-relais.dto';
|
||||
import { UpdateRelaisDto } from './dto/update-relais.dto';
|
||||
|
||||
@Injectable()
|
||||
export class RelaisService {
|
||||
constructor(
|
||||
@InjectRepository(Relais)
|
||||
private readonly relaisRepository: Repository<Relais>,
|
||||
) {}
|
||||
|
||||
create(createRelaisDto: CreateRelaisDto) {
|
||||
const relais = this.relaisRepository.create(createRelaisDto);
|
||||
return this.relaisRepository.save(relais);
|
||||
}
|
||||
|
||||
findAll() {
|
||||
return this.relaisRepository.find({ order: { nom: 'ASC' } });
|
||||
}
|
||||
|
||||
async findOne(id: string) {
|
||||
const relais = await this.relaisRepository.findOne({ where: { id } });
|
||||
if (!relais) {
|
||||
throw new NotFoundException(`Relais #${id} not found`);
|
||||
}
|
||||
return relais;
|
||||
}
|
||||
|
||||
async update(id: string, updateRelaisDto: UpdateRelaisDto) {
|
||||
const relais = await this.findOne(id);
|
||||
Object.assign(relais, updateRelaisDto);
|
||||
return this.relaisRepository.save(relais);
|
||||
}
|
||||
|
||||
async remove(id: string) {
|
||||
const relais = await this.findOne(id);
|
||||
return this.relaisRepository.remove(relais);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, Matches } from 'class-validator';
|
||||
|
||||
/** Format AAAA-NNNNNN (année + 6 chiffres) */
|
||||
const NUMERO_DOSSIER_REGEX = /^\d{4}-\d{6}$/;
|
||||
|
||||
export class AffecterNumeroDossierDto {
|
||||
@ApiProperty({ example: '2026-000004', description: 'Numéro de dossier (AAAA-NNNNNN)' })
|
||||
@IsNotEmpty({ message: 'Le numéro de dossier est requis' })
|
||||
@Matches(NUMERO_DOSSIER_REGEX, {
|
||||
message: 'Le numéro de dossier doit être au format AAAA-NNNNNN (ex: 2026-000001)',
|
||||
})
|
||||
numero_dossier: string;
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
import { OmitType } from "@nestjs/swagger";
|
||||
import { PickType } from "@nestjs/swagger";
|
||||
import { CreateUserDto } from "./create_user.dto";
|
||||
|
||||
export class CreateAdminDto extends OmitType(CreateUserDto, ['role'] as const) {}
|
||||
export class CreateAdminDto extends PickType(CreateUserDto, [
|
||||
'nom',
|
||||
'prenom',
|
||||
'email',
|
||||
'password',
|
||||
'telephone'
|
||||
] as const) {}
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { OmitType } from "@nestjs/swagger";
|
||||
import { ApiProperty, OmitType } from "@nestjs/swagger";
|
||||
import { CreateUserDto } from "./create_user.dto";
|
||||
import { IsOptional, IsUUID } from "class-validator";
|
||||
|
||||
export class CreateGestionnaireDto extends OmitType(CreateUserDto, ['role'] as const) {}
|
||||
export class CreateGestionnaireDto extends OmitType(CreateUserDto, ['role', 'adresse', 'genre', 'statut', 'situation_familiale', 'ville', 'code_postal', 'photo_url', 'consentement_photo', 'date_consentement_photo', 'changement_mdp_obligatoire'] as const) {
|
||||
@ApiProperty({ required: false, description: 'ID du relais de rattachement' })
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
relaisId?: string;
|
||||
}
|
||||
|
||||
@@ -36,10 +36,10 @@ export class CreateUserDto {
|
||||
@MaxLength(100)
|
||||
nom: string;
|
||||
|
||||
@ApiProperty({ enum: GenreType, required: false, default: GenreType.AUTRE })
|
||||
@ApiProperty({ enum: GenreType, required: false })
|
||||
@IsOptional()
|
||||
@IsEnum(GenreType)
|
||||
genre?: GenreType = GenreType.AUTRE;
|
||||
genre?: GenreType;
|
||||
|
||||
@ApiProperty({ enum: RoleType })
|
||||
@IsEnum(RoleType)
|
||||
@@ -86,7 +86,7 @@ export class CreateUserDto {
|
||||
@ApiProperty({ default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
consentement_photo?: boolean = false;
|
||||
consentement_photo?: boolean;
|
||||
|
||||
@ApiProperty({ required: false })
|
||||
@IsOptional()
|
||||
@@ -96,7 +96,7 @@ export class CreateUserDto {
|
||||
@ApiProperty({ default: false })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
changement_mdp_obligatoire?: boolean = false;
|
||||
changement_mdp_obligatoire?: boolean;
|
||||
|
||||
@ApiProperty({ example: true })
|
||||
@IsBoolean()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { CreateGestionnaireDto } from "./create_gestionnaire.dto";
|
||||
|
||||
export class UpdateGestionnaireDto extends PartialType(CreateGestionnaireDto) {}
|
||||
export class UpdateGestionnaireDto extends PartialType(CreateGestionnaireDto) {}
|
||||
|
||||
@@ -4,11 +4,13 @@ import { GestionnairesController } from './gestionnaires.controller';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AuthModule } from 'src/routes/auth/auth.module';
|
||||
import { MailModule } from 'src/modules/mail/mail.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Users]),
|
||||
AuthModule,
|
||||
MailModule,
|
||||
],
|
||||
controllers: [GestionnairesController],
|
||||
providers: [GestionnairesService],
|
||||
|
||||
@@ -5,16 +5,18 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { RoleType, Users } from 'src/entities/users.entity';
|
||||
import { RoleType, StatutUtilisateurType, Users } from 'src/entities/users.entity';
|
||||
import { CreateGestionnaireDto } from '../dto/create_gestionnaire.dto';
|
||||
import { UpdateGestionnaireDto } from '../dto/update_gestionnaire.dto';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { MailService } from 'src/modules/mail/mail.service';
|
||||
|
||||
@Injectable()
|
||||
export class GestionnairesService {
|
||||
constructor(
|
||||
@InjectRepository(Users)
|
||||
private readonly gestionnaireRepository: Repository<Users>,
|
||||
private readonly mailService: MailService,
|
||||
) { }
|
||||
|
||||
// Création d’un gestionnaire
|
||||
@@ -30,30 +32,51 @@ export class GestionnairesService {
|
||||
password: hashedPassword,
|
||||
prenom: dto.prenom,
|
||||
nom: dto.nom,
|
||||
genre: dto.genre,
|
||||
statut: dto.statut,
|
||||
// genre: dto.genre, // Retiré
|
||||
// statut: dto.statut, // Retiré
|
||||
statut: StatutUtilisateurType.ACTIF,
|
||||
telephone: dto.telephone,
|
||||
adresse: dto.adresse,
|
||||
photo_url: dto.photo_url,
|
||||
consentement_photo: dto.consentement_photo ?? false,
|
||||
date_consentement_photo: dto.date_consentement_photo
|
||||
? new Date(dto.date_consentement_photo)
|
||||
: undefined,
|
||||
changement_mdp_obligatoire: dto.changement_mdp_obligatoire ?? false,
|
||||
// adresse: dto.adresse, // Retiré
|
||||
// photo_url: dto.photo_url, // Retiré
|
||||
// consentement_photo: dto.consentement_photo ?? false, // Retiré
|
||||
// date_consentement_photo: dto.date_consentement_photo // Retiré
|
||||
// ? new Date(dto.date_consentement_photo)
|
||||
// : undefined,
|
||||
changement_mdp_obligatoire: true,
|
||||
role: RoleType.GESTIONNAIRE,
|
||||
relaisId: dto.relaisId,
|
||||
});
|
||||
return this.gestionnaireRepository.save(entity);
|
||||
|
||||
const savedUser = await this.gestionnaireRepository.save(entity);
|
||||
|
||||
// Envoi de l'email de bienvenue
|
||||
try {
|
||||
await this.mailService.sendGestionnaireWelcomeEmail(
|
||||
savedUser.email,
|
||||
savedUser.prenom || '',
|
||||
savedUser.nom || '',
|
||||
);
|
||||
} catch (error) {
|
||||
// On ne bloque pas la création si l'envoi d'email échoue, mais on log l'erreur
|
||||
console.error('Erreur lors de l\'envoi de l\'email de bienvenue au gestionnaire', error);
|
||||
}
|
||||
|
||||
return savedUser;
|
||||
}
|
||||
|
||||
// Liste des gestionnaires
|
||||
async findAll(): Promise<Users[]> {
|
||||
return this.gestionnaireRepository.find({ where: { role: RoleType.GESTIONNAIRE } });
|
||||
return this.gestionnaireRepository.find({
|
||||
where: { role: RoleType.GESTIONNAIRE },
|
||||
relations: ['relais'],
|
||||
});
|
||||
}
|
||||
|
||||
// Récupérer un gestionnaire par ID
|
||||
async findOne(id: string): Promise<Users> {
|
||||
const gestionnaire = await this.gestionnaireRepository.findOne({
|
||||
where: { id, role: RoleType.GESTIONNAIRE },
|
||||
relations: ['relais'],
|
||||
});
|
||||
if (!gestionnaire) throw new NotFoundException('Gestionnaire introuvable');
|
||||
return gestionnaire;
|
||||
@@ -68,13 +91,7 @@ export class GestionnairesService {
|
||||
gestionnaire.password = await bcrypt.hash(dto.password, salt);
|
||||
}
|
||||
|
||||
if (dto.date_consentement_photo !== undefined) {
|
||||
gestionnaire.date_consentement_photo = dto.date_consentement_photo
|
||||
? new Date(dto.date_consentement_photo)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
const { password, date_consentement_photo, ...rest } = dto;
|
||||
const { password, ...rest } = dto;
|
||||
Object.entries(rest).forEach(([key, value]) => {
|
||||
if (value !== undefined) {
|
||||
(gestionnaire as any)[key] = value;
|
||||
|
||||
@@ -1,20 +1,34 @@
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post, UseGuards } from '@nestjs/common';
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiParam, 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, Users } from 'src/entities/users.entity';
|
||||
import { UserService } from './user.service';
|
||||
import { CreateUserDto } from './dto/create_user.dto';
|
||||
import { CreateAdminDto } from './dto/create_admin.dto';
|
||||
import { UpdateUserDto } from './dto/update_user.dto';
|
||||
import { AffecterNumeroDossierDto } from './dto/affecter-numero-dossier.dto';
|
||||
|
||||
@ApiTags('Utilisateurs')
|
||||
@ApiBearerAuth('access-token')
|
||||
@UseGuards(AuthGuard)
|
||||
@UseGuards(AuthGuard, RolesGuard)
|
||||
@Controller('users')
|
||||
export class UserController {
|
||||
constructor(private readonly userService: UserService) { }
|
||||
|
||||
// Création d'un administrateur (réservée aux super admins)
|
||||
@Post('admin')
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@ApiOperation({ summary: 'Créer un nouvel administrateur (super admin seulement)' })
|
||||
createAdmin(
|
||||
@Body() dto: CreateAdminDto,
|
||||
@User() currentUser: Users
|
||||
) {
|
||||
return this.userService.createAdmin(dto, currentUser);
|
||||
}
|
||||
|
||||
// Création d'un utilisateur (réservée aux super admins)
|
||||
@Post()
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@@ -26,6 +40,26 @@ export class UserController {
|
||||
return this.userService.createUser(dto, currentUser);
|
||||
}
|
||||
|
||||
// Lister les utilisateurs en attente de validation
|
||||
@Get('pending')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||
@ApiOperation({ summary: 'Lister les utilisateurs en attente de validation' })
|
||||
findPendingUsers(
|
||||
@Query('role') role?: RoleType
|
||||
) {
|
||||
return this.userService.findPendingUsers(role);
|
||||
}
|
||||
|
||||
// Lister les comptes refusés (à corriger / reprise)
|
||||
@Get('reprise')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||
@ApiOperation({ summary: 'Lister les comptes refusés (reprise)' })
|
||||
findRefusedUsers(
|
||||
@Query('role') role?: RoleType
|
||||
) {
|
||||
return this.userService.findRefusedUsers(role);
|
||||
}
|
||||
|
||||
// Lister tous les utilisateurs (super_admin uniquement)
|
||||
@Get()
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||
@@ -43,9 +77,9 @@ export class UserController {
|
||||
return this.userService.findOne(id);
|
||||
}
|
||||
|
||||
// Modifier un utilisateur (réservé super_admin)
|
||||
// Modifier un utilisateur (réservé super_admin et admin)
|
||||
@Patch(':id')
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Mettre à jour un utilisateur' })
|
||||
@ApiParam({ name: 'id', description: "UUID de l'utilisateur" })
|
||||
updateUser(
|
||||
@@ -56,6 +90,23 @@ export class UserController {
|
||||
return this.userService.updateUser(id, dto, currentUser);
|
||||
}
|
||||
|
||||
@Patch(':id/numero-dossier')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||
@ApiOperation({
|
||||
summary: 'Affecter un numéro de dossier à un utilisateur',
|
||||
description: 'Permet de rapprocher deux dossiers ou d’attribuer un numéro existant à un parent/AM. Réservé aux gestionnaires et administrateurs.',
|
||||
})
|
||||
@ApiParam({ name: 'id', description: "UUID de l'utilisateur (parent ou AM)" })
|
||||
@ApiResponse({ status: 200, description: 'Numéro de dossier affecté' })
|
||||
@ApiResponse({ status: 400, description: 'Format invalide, rôle non éligible, ou dossier déjà associé à 2 parents' })
|
||||
@ApiResponse({ status: 404, description: 'Utilisateur introuvable' })
|
||||
affecterNumeroDossier(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: AffecterNumeroDossierDto,
|
||||
) {
|
||||
return this.userService.affecterNumeroDossier(id, dto.numero_dossier);
|
||||
}
|
||||
|
||||
@Patch(':id/valider')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Valider un compte utilisateur' })
|
||||
@@ -71,6 +122,18 @@ export class UserController {
|
||||
return this.userService.validateUser(id, currentUser, comment);
|
||||
}
|
||||
|
||||
@Patch(':id/refuser')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Refuser un compte (à corriger)' })
|
||||
@ApiParam({ name: 'id', description: "UUID de l'utilisateur" })
|
||||
refuse(
|
||||
@Param('id') id: string,
|
||||
@User() currentUser: Users,
|
||||
@Body('comment') comment?: string,
|
||||
) {
|
||||
return this.userService.refuseUser(id, currentUser, comment);
|
||||
}
|
||||
|
||||
@Patch(':id/suspendre')
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Suspendre un compte utilisateur' })
|
||||
|
||||
@@ -10,6 +10,7 @@ import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entit
|
||||
import { AssistantesMaternellesModule } from '../assistantes_maternelles/assistantes_maternelles.module';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { GestionnairesModule } from './gestionnaires/gestionnaires.module';
|
||||
import { MailModule } from 'src/modules/mail/mail.module';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature(
|
||||
@@ -22,6 +23,7 @@ import { GestionnairesModule } from './gestionnaires/gestionnaires.module';
|
||||
ParentsModule,
|
||||
AssistantesMaternellesModule,
|
||||
GestionnairesModule,
|
||||
MailModule,
|
||||
],
|
||||
controllers: [UserController],
|
||||
providers: [UserService],
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { BadRequestException, ForbiddenException, Injectable, Logger, NotFoundException } from "@nestjs/common";
|
||||
import { InjectRepository } from "@nestjs/typeorm";
|
||||
import { RoleType, StatutUtilisateurType, Users } from "src/entities/users.entity";
|
||||
import { In, Repository } from "typeorm";
|
||||
import { In, MoreThan, Repository } from "typeorm";
|
||||
import { CreateUserDto } from "./dto/create_user.dto";
|
||||
import { CreateAdminDto } from "./dto/create_admin.dto";
|
||||
import { UpdateUserDto } from "./dto/update_user.dto";
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { StatutValidationType, Validation } from "src/entities/validations.entity";
|
||||
import { Parents } from "src/entities/parents.entity";
|
||||
import { AssistanteMaternelle } from "src/entities/assistantes_maternelles.entity";
|
||||
import { MailService } from "src/modules/mail/mail.service";
|
||||
import * as crypto from 'crypto';
|
||||
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
private readonly logger = new Logger(UserService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(Users)
|
||||
private readonly usersRepository: Repository<Users>,
|
||||
@@ -22,7 +27,9 @@ export class UserService {
|
||||
private readonly parentsRepository: Repository<Parents>,
|
||||
|
||||
@InjectRepository(AssistanteMaternelle)
|
||||
private readonly assistantesRepository: Repository<AssistanteMaternelle>
|
||||
private readonly assistantesRepository: Repository<AssistanteMaternelle>,
|
||||
|
||||
private readonly mailService: MailService,
|
||||
) { }
|
||||
|
||||
async createUser(dto: CreateUserDto, currentUser?: Users): Promise<Users> {
|
||||
@@ -106,6 +113,48 @@ export class UserService {
|
||||
return this.findOne(saved.id);
|
||||
}
|
||||
|
||||
async createAdmin(dto: CreateAdminDto, currentUser: Users): Promise<Users> {
|
||||
if (currentUser.role !== RoleType.SUPER_ADMIN) {
|
||||
throw new ForbiddenException('Seuls les super administrateurs peuvent créer un administrateur');
|
||||
}
|
||||
|
||||
const exist = await this.usersRepository.findOneBy({ email: dto.email });
|
||||
if (exist) throw new BadRequestException('Email déjà utilisé');
|
||||
|
||||
const salt = await bcrypt.genSalt();
|
||||
const hashedPassword = await bcrypt.hash(dto.password, salt);
|
||||
|
||||
const entity = this.usersRepository.create({
|
||||
email: dto.email,
|
||||
password: hashedPassword,
|
||||
prenom: dto.prenom,
|
||||
nom: dto.nom,
|
||||
role: RoleType.ADMINISTRATEUR,
|
||||
statut: StatutUtilisateurType.ACTIF,
|
||||
telephone: dto.telephone,
|
||||
changement_mdp_obligatoire: true,
|
||||
});
|
||||
|
||||
return this.usersRepository.save(entity);
|
||||
}
|
||||
|
||||
async findPendingUsers(role?: RoleType): Promise<Users[]> {
|
||||
const where: any = { statut: StatutUtilisateurType.EN_ATTENTE };
|
||||
if (role) {
|
||||
where.role = role;
|
||||
}
|
||||
return this.usersRepository.find({ where });
|
||||
}
|
||||
|
||||
/** Comptes refusés (à corriger) : liste pour reprise par le gestionnaire */
|
||||
async findRefusedUsers(role?: RoleType): Promise<Users[]> {
|
||||
const where: any = { statut: StatutUtilisateurType.REFUSE };
|
||||
if (role) {
|
||||
where.role = role;
|
||||
}
|
||||
return this.usersRepository.find({ where });
|
||||
}
|
||||
|
||||
async findAll(): Promise<Users[]> {
|
||||
return this.usersRepository.find();
|
||||
}
|
||||
@@ -129,11 +178,26 @@ export class UserService {
|
||||
async updateUser(id: string, dto: UpdateUserDto, currentUser: Users): Promise<Users> {
|
||||
const user = await this.findOne(id);
|
||||
|
||||
// Le super administrateur conserve une identité figée.
|
||||
if (
|
||||
user.role === RoleType.SUPER_ADMIN &&
|
||||
(dto.nom !== undefined || dto.prenom !== undefined)
|
||||
) {
|
||||
throw new ForbiddenException(
|
||||
'Le nom et le prénom du super administrateur ne peuvent pas être modifiés',
|
||||
);
|
||||
}
|
||||
|
||||
// Interdire changement de rôle si pas super admin
|
||||
if (dto.role && currentUser.role !== RoleType.SUPER_ADMIN) {
|
||||
throw new ForbiddenException('Accès réservé aux super admins');
|
||||
}
|
||||
|
||||
// Un admin ne peut pas modifier un super admin
|
||||
if (currentUser.role === RoleType.ADMINISTRATEUR && user.role === RoleType.SUPER_ADMIN) {
|
||||
throw new ForbiddenException('Vous ne pouvez pas modifier un super administrateur');
|
||||
}
|
||||
|
||||
// Empêcher de modifier le flag changement_mdp_obligatoire pour admin/gestionnaire
|
||||
if (
|
||||
(user.role === RoleType.ADMINISTRATEUR || user.role === RoleType.GESTIONNAIRE) &&
|
||||
@@ -165,7 +229,7 @@ export class UserService {
|
||||
return this.usersRepository.save(user);
|
||||
}
|
||||
|
||||
// Valider un compte utilisateur
|
||||
// Valider un compte utilisateur (en_attente ou refuse -> actif)
|
||||
async validateUser(user_id: string, currentUser: Users, comment?: string): Promise<Users> {
|
||||
if (![RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE].includes(currentUser.role)) {
|
||||
throw new ForbiddenException('Accès réservé aux super admins, administrateurs et gestionnaires');
|
||||
@@ -173,7 +237,11 @@ export class UserService {
|
||||
|
||||
const user = await this.usersRepository.findOne({ where: { id: user_id } });
|
||||
if (!user) throw new NotFoundException('Utilisateur introuvable');
|
||||
|
||||
|
||||
if (user.statut !== StatutUtilisateurType.EN_ATTENTE && user.statut !== StatutUtilisateurType.REFUSE) {
|
||||
throw new BadRequestException('Seuls les comptes en attente ou refusés (à corriger) peuvent être validés.');
|
||||
}
|
||||
|
||||
user.statut = StatutUtilisateurType.ACTIF;
|
||||
const savedUser = await this.usersRepository.save(user);
|
||||
if (user.role === RoleType.PARENT) {
|
||||
@@ -221,10 +289,165 @@ export class UserService {
|
||||
await this.validationRepository.save(suspend);
|
||||
return savedUser;
|
||||
}
|
||||
|
||||
/** Refuser un compte (en_attente -> refuse) ; tracé validations, token reprise, email. Ticket #110 */
|
||||
async refuseUser(user_id: string, currentUser: Users, comment?: string): Promise<Users> {
|
||||
if (![RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE].includes(currentUser.role)) {
|
||||
throw new ForbiddenException('Accès réservé aux super admins, administrateurs et gestionnaires');
|
||||
}
|
||||
const user = await this.usersRepository.findOne({ where: { id: user_id } });
|
||||
if (!user) throw new NotFoundException('Utilisateur introuvable');
|
||||
if (user.statut !== StatutUtilisateurType.EN_ATTENTE) {
|
||||
throw new BadRequestException('Seul un compte en attente peut être refusé.');
|
||||
}
|
||||
|
||||
const tokenReprise = crypto.randomUUID();
|
||||
const expireLe = new Date();
|
||||
expireLe.setDate(expireLe.getDate() + 7);
|
||||
|
||||
user.statut = StatutUtilisateurType.REFUSE;
|
||||
user.token_reprise = tokenReprise;
|
||||
user.token_reprise_expire_le = expireLe;
|
||||
const savedUser = await this.usersRepository.save(user);
|
||||
|
||||
const validation = this.validationRepository.create({
|
||||
user: savedUser,
|
||||
type: 'refus_compte',
|
||||
status: StatutValidationType.REFUSE,
|
||||
validated_by: currentUser,
|
||||
comment,
|
||||
});
|
||||
await this.validationRepository.save(validation);
|
||||
|
||||
try {
|
||||
await this.mailService.sendRefusEmail(
|
||||
savedUser.email,
|
||||
savedUser.prenom ?? '',
|
||||
savedUser.nom ?? '',
|
||||
comment,
|
||||
tokenReprise,
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(`Envoi email refus échoué pour ${savedUser.email}`, err);
|
||||
}
|
||||
|
||||
return savedUser;
|
||||
}
|
||||
|
||||
/**
|
||||
* Affecter ou modifier le numéro de dossier d'un utilisateur (parent ou AM).
|
||||
* Permet au gestionnaire/admin de rapprocher deux dossiers (même numéro pour plusieurs personnes).
|
||||
* Garde-fou : au plus 2 parents par numéro de dossier (couple / co-parents).
|
||||
*/
|
||||
async affecterNumeroDossier(userId: string, numeroDossier: string): Promise<Users> {
|
||||
const user = await this.usersRepository.findOne({ where: { id: userId } });
|
||||
if (!user) throw new NotFoundException('Utilisateur introuvable');
|
||||
|
||||
if (user.role !== RoleType.PARENT && user.role !== RoleType.ASSISTANTE_MATERNELLE) {
|
||||
throw new BadRequestException(
|
||||
'Le numéro de dossier ne peut être affecté qu\'à un parent ou une assistante maternelle',
|
||||
);
|
||||
}
|
||||
|
||||
if (user.role === RoleType.PARENT) {
|
||||
const uneAMALe = await this.assistantesRepository.count({
|
||||
where: { numero_dossier: numeroDossier },
|
||||
});
|
||||
if (uneAMALe > 0) {
|
||||
throw new BadRequestException(
|
||||
'Ce numéro de dossier est celui d\'une assistante maternelle. Un numéro AM ne peut pas être affecté à un parent.',
|
||||
);
|
||||
}
|
||||
const parentsAvecCeNumero = await this.parentsRepository.count({
|
||||
where: { numero_dossier: numeroDossier },
|
||||
});
|
||||
const userADejaCeNumero = user.numero_dossier === numeroDossier;
|
||||
if (!userADejaCeNumero && parentsAvecCeNumero >= 2) {
|
||||
throw new BadRequestException(
|
||||
'Un numéro de dossier ne peut être associé qu\'à 2 parents au maximum (couple / co-parents). Ce dossier a déjà 2 parents.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (user.role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||
const unParentLA = await this.parentsRepository.count({
|
||||
where: { numero_dossier: numeroDossier },
|
||||
});
|
||||
if (unParentLA > 0) {
|
||||
throw new BadRequestException(
|
||||
'Ce numéro de dossier est celui d\'une famille (parent). Un numéro famille ne peut pas être affecté à une assistante maternelle.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
user.numero_dossier = numeroDossier;
|
||||
const savedUser = await this.usersRepository.save(user);
|
||||
|
||||
if (user.role === RoleType.PARENT) {
|
||||
await this.parentsRepository.update({ user_id: userId }, { numero_dossier: numeroDossier });
|
||||
} else {
|
||||
await this.assistantesRepository.update({ user_id: userId }, { numero_dossier: numeroDossier });
|
||||
}
|
||||
|
||||
return savedUser;
|
||||
}
|
||||
|
||||
/** Trouve un user par token reprise valide (non expiré). Ticket #111 */
|
||||
async findByTokenReprise(token: string): Promise<Users | null> {
|
||||
return this.usersRepository.findOne({
|
||||
where: {
|
||||
token_reprise: token,
|
||||
statut: StatutUtilisateurType.REFUSE,
|
||||
token_reprise_expire_le: MoreThan(new Date()),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Resoumission reprise : met à jour les champs autorisés, passe en en_attente, invalide le token. Ticket #111 */
|
||||
async resoumettreReprise(
|
||||
token: string,
|
||||
dto: { prenom?: string; nom?: string; telephone?: string; adresse?: string; ville?: string; code_postal?: string; photo_url?: string },
|
||||
): Promise<Users> {
|
||||
const user = await this.findByTokenReprise(token);
|
||||
if (!user) {
|
||||
throw new NotFoundException('Token reprise invalide ou expiré.');
|
||||
}
|
||||
if (dto.prenom !== undefined) user.prenom = dto.prenom;
|
||||
if (dto.nom !== undefined) user.nom = dto.nom;
|
||||
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.photo_url !== undefined) user.photo_url = dto.photo_url;
|
||||
user.statut = StatutUtilisateurType.EN_ATTENTE;
|
||||
user.token_reprise = undefined;
|
||||
user.token_reprise_expire_le = undefined;
|
||||
return this.usersRepository.save(user);
|
||||
}
|
||||
|
||||
/** Pour modale reprise : numero_dossier + email → user en REFUSE avec token valide. Ticket #111 */
|
||||
async findByNumeroDossierAndEmailForReprise(numero_dossier: string, email: string): Promise<Users | null> {
|
||||
const user = await this.usersRepository.findOne({
|
||||
where: {
|
||||
email: email.trim().toLowerCase(),
|
||||
numero_dossier: numero_dossier.trim(),
|
||||
statut: StatutUtilisateurType.REFUSE,
|
||||
token_reprise_expire_le: MoreThan(new Date()),
|
||||
},
|
||||
});
|
||||
return user ?? null;
|
||||
}
|
||||
|
||||
async remove(id: string, currentUser: Users): Promise<void> {
|
||||
if (currentUser.role !== RoleType.SUPER_ADMIN) {
|
||||
throw new ForbiddenException('Accès réservé aux super admins');
|
||||
}
|
||||
const user = await this.findOne(id);
|
||||
if (user.role === RoleType.SUPER_ADMIN) {
|
||||
throw new ForbiddenException(
|
||||
'Le super administrateur ne peut pas être supprimé',
|
||||
);
|
||||
}
|
||||
const result = await this.usersRepository.delete(id);
|
||||
if (result.affected === 0) {
|
||||
throw new NotFoundException('Utilisateur introuvable');
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
const bcrypt = require('bcrypt');
|
||||
|
||||
const pass = '!Bezons2014';
|
||||
|
||||
bcrypt.hash(pass, 10).then(hash => {
|
||||
console.log('New Hash:', hash);
|
||||
}).catch(err => console.error(err));
|
||||
+75
-5
@@ -8,10 +8,10 @@ DO $$ BEGIN
|
||||
CREATE TYPE role_type AS ENUM ('parent', 'gestionnaire', 'super_admin', 'administrateur', 'assistante_maternelle');
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'genre_type') THEN
|
||||
CREATE TYPE genre_type AS ENUM ('H', 'F');
|
||||
CREATE TYPE genre_type AS ENUM ('H', 'F', 'Autre');
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_utilisateur_type') THEN
|
||||
CREATE TYPE statut_utilisateur_type AS ENUM ('en_attente','actif','suspendu');
|
||||
CREATE TYPE statut_utilisateur_type AS ENUM ('en_attente','actif','suspendu','refuse');
|
||||
END IF;
|
||||
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');
|
||||
@@ -55,6 +55,8 @@ CREATE TABLE utilisateurs (
|
||||
telephone VARCHAR(20), -- Unifié (mobile privilégié)
|
||||
adresse TEXT,
|
||||
date_naissance DATE,
|
||||
lieu_naissance_ville VARCHAR(100),
|
||||
lieu_naissance_pays VARCHAR(100),
|
||||
photo_url TEXT, -- Obligatoire pour AM, non utilisé pour parents
|
||||
consentement_photo BOOLEAN DEFAULT false,
|
||||
date_consentement_photo TIMESTAMPTZ,
|
||||
@@ -80,7 +82,7 @@ CREATE INDEX idx_utilisateurs_token_creation_mdp
|
||||
CREATE TABLE assistantes_maternelles (
|
||||
id_utilisateur UUID PRIMARY KEY REFERENCES utilisateurs(id) ON DELETE CASCADE,
|
||||
numero_agrement VARCHAR(50),
|
||||
nir_chiffre CHAR(15),
|
||||
nir_chiffre CHAR(15) NOT NULL,
|
||||
nb_max_enfants INT,
|
||||
biographie TEXT,
|
||||
disponible BOOLEAN DEFAULT true,
|
||||
@@ -125,6 +127,33 @@ CREATE TABLE enfants_parents (
|
||||
PRIMARY KEY (id_parent, id_enfant)
|
||||
);
|
||||
|
||||
-- ==========================================================
|
||||
-- Table : dossier_famille (inscription parent, schéma simplifié — ticket #119)
|
||||
-- ==========================================================
|
||||
CREATE TABLE dossier_famille (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
numero_dossier VARCHAR(20) NOT NULL,
|
||||
id_parent UUID NOT NULL REFERENCES parents(id_utilisateur) ON DELETE CASCADE,
|
||||
presentation TEXT,
|
||||
statut statut_dossier_type NOT NULL DEFAULT 'envoye',
|
||||
cree_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
modifie_le TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_dossier_famille_numero ON dossier_famille(numero_dossier);
|
||||
CREATE INDEX idx_dossier_famille_id_parent ON dossier_famille(id_parent);
|
||||
|
||||
-- ==========================================================
|
||||
-- Table : dossier_famille_enfants
|
||||
-- ==========================================================
|
||||
CREATE TABLE dossier_famille_enfants (
|
||||
id_dossier_famille UUID NOT NULL REFERENCES dossier_famille(id) ON DELETE CASCADE,
|
||||
id_enfant UUID NOT NULL REFERENCES enfants(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (id_dossier_famille, id_enfant)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_dossier_famille_enfants_enfant ON dossier_famille_enfants(id_enfant);
|
||||
|
||||
-- ==========================================================
|
||||
-- Table : dossiers
|
||||
-- ==========================================================
|
||||
@@ -331,13 +360,54 @@ CREATE INDEX idx_acceptations_utilisateur ON acceptations_documents(id_utilisate
|
||||
CREATE INDEX idx_acceptations_document ON acceptations_documents(id_document);
|
||||
|
||||
-- ==========================================================
|
||||
-- Modification Table : utilisateurs (ajout colonnes documents)
|
||||
-- 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 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)
|
||||
-- ==========================================================
|
||||
CREATE TABLE IF NOT EXISTS numero_dossier_sequence (
|
||||
annee INT PRIMARY KEY,
|
||||
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
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
-- Un dossier = une famille, N enfants. Ticket #119 évolution.
|
||||
-- Table: un enregistrement par famille (lien via numero_dossier / id_parent).
|
||||
CREATE TABLE IF NOT EXISTS dossier_famille (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
numero_dossier VARCHAR(20) NOT NULL,
|
||||
id_parent UUID NOT NULL REFERENCES parents(id_utilisateur) ON DELETE CASCADE,
|
||||
presentation TEXT,
|
||||
type_contrat VARCHAR(50),
|
||||
repas BOOLEAN NOT NULL DEFAULT false,
|
||||
budget NUMERIC(10,2),
|
||||
planning_souhaite JSONB,
|
||||
statut statut_dossier_type NOT NULL DEFAULT 'envoye',
|
||||
cree_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
modifie_le TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_dossier_famille_numero ON dossier_famille(numero_dossier);
|
||||
CREATE INDEX IF NOT EXISTS idx_dossier_famille_id_parent ON dossier_famille(id_parent);
|
||||
|
||||
-- Enfants concernés par ce dossier famille (N par dossier).
|
||||
CREATE TABLE IF NOT EXISTS dossier_famille_enfants (
|
||||
id_dossier_famille UUID NOT NULL REFERENCES dossier_famille(id) ON DELETE CASCADE,
|
||||
id_enfant UUID NOT NULL REFERENCES enfants(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (id_dossier_famille, id_enfant)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_dossier_famille_enfants_enfant ON dossier_famille_enfants(id_enfant);
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Dossier famille = inscription uniquement, pas les données de dossier de garde (repas, type_contrat, budget, etc.)
|
||||
ALTER TABLE dossier_famille DROP COLUMN IF EXISTS repas;
|
||||
ALTER TABLE dossier_famille DROP COLUMN IF EXISTS type_contrat;
|
||||
ALTER TABLE dossier_famille DROP COLUMN IF EXISTS budget;
|
||||
ALTER TABLE dossier_famille DROP COLUMN IF EXISTS planning_souhaite;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Lieu de naissance (inscription AM, affichage dossier / validation). Nullable pour l'historique.
|
||||
ALTER TABLE utilisateurs
|
||||
ADD COLUMN IF NOT EXISTS lieu_naissance_ville VARCHAR(100) NULL,
|
||||
ADD COLUMN IF NOT EXISTS lieu_naissance_pays VARCHAR(100) NULL;
|
||||
@@ -0,0 +1,16 @@
|
||||
-- Migration : rendre nir_chiffre NOT NULL (ticket #102)
|
||||
-- À exécuter sur les bases existantes avant déploiement du schéma avec nir_chiffre NOT NULL.
|
||||
-- Les lignes sans NIR reçoivent un NIR de test valide (format + clé) pour satisfaire la contrainte.
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- Renseigner un NIR de test valide pour toute ligne où nir_chiffre est NULL
|
||||
UPDATE assistantes_maternelles
|
||||
SET nir_chiffre = '275119900100102'
|
||||
WHERE nir_chiffre IS NULL;
|
||||
|
||||
-- Appliquer la contrainte NOT NULL
|
||||
ALTER TABLE assistantes_maternelles
|
||||
ALTER COLUMN nir_chiffre SET NOT NULL;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,33 @@
|
||||
-- Migration #103 : Numéro de dossier (format AAAA-NNNNNN, séquence par année)
|
||||
-- Colonnes sur utilisateurs, assistantes_maternelles, parents.
|
||||
-- Table de séquence par année pour génération unique.
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- Table de séquence : une ligne par année, prochain = prochain numéro à attribuer (1..999999)
|
||||
CREATE TABLE IF NOT EXISTS numero_dossier_sequence (
|
||||
annee INT PRIMARY KEY,
|
||||
prochain INT NOT NULL DEFAULT 1
|
||||
);
|
||||
|
||||
-- Colonne sur utilisateurs (AM et parents : numéro attribué à la soumission)
|
||||
ALTER TABLE utilisateurs
|
||||
ADD COLUMN IF NOT EXISTS numero_dossier VARCHAR(20) NULL;
|
||||
|
||||
-- Colonne sur assistantes_maternelles (redondant avec users pour accès direct)
|
||||
ALTER TABLE assistantes_maternelles
|
||||
ADD COLUMN IF NOT EXISTS numero_dossier VARCHAR(20) NULL;
|
||||
|
||||
-- Colonne sur parents (un numéro par famille, même valeur sur les deux lignes si co-parent)
|
||||
ALTER TABLE parents
|
||||
ADD COLUMN IF NOT EXISTS numero_dossier VARCHAR(20) NULL;
|
||||
|
||||
-- Index pour recherche par numéro
|
||||
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;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,122 @@
|
||||
-- Backfill #103 : attribuer un numero_dossier aux entrées existantes (NULL)
|
||||
-- Famille = lien co_parent OU partage d'au moins un enfant (même dossier).
|
||||
-- Ordre : par année, AM puis familles (une entrée par famille), séquence 000001, 000002...
|
||||
-- À exécuter après 2026_numero_dossier.sql
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
yr INT;
|
||||
seq INT;
|
||||
num TEXT;
|
||||
r RECORD;
|
||||
family_user_ids UUID[];
|
||||
BEGIN
|
||||
-- Réinitialiser pour rejouer le backfill (cohérence AM + familles)
|
||||
UPDATE parents SET numero_dossier = NULL;
|
||||
UPDATE utilisateurs SET numero_dossier = NULL
|
||||
WHERE role IN ('parent', 'assistante_maternelle');
|
||||
UPDATE assistantes_maternelles SET numero_dossier = NULL;
|
||||
|
||||
FOR yr IN
|
||||
SELECT DISTINCT EXTRACT(YEAR FROM u.cree_le)::INT
|
||||
FROM utilisateurs u
|
||||
WHERE (
|
||||
(u.role = 'assistante_maternelle' AND u.numero_dossier IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM parents p WHERE p.id_utilisateur = u.id AND p.numero_dossier IS NULL)
|
||||
)
|
||||
ORDER BY 1
|
||||
LOOP
|
||||
seq := 0;
|
||||
|
||||
-- 1) AM : par ordre de création
|
||||
FOR r IN
|
||||
SELECT u.id
|
||||
FROM utilisateurs u
|
||||
WHERE u.role = 'assistante_maternelle'
|
||||
AND u.numero_dossier IS NULL
|
||||
AND EXTRACT(YEAR FROM u.cree_le) = yr
|
||||
ORDER BY u.cree_le
|
||||
LOOP
|
||||
seq := seq + 1;
|
||||
num := yr || '-' || LPAD(seq::TEXT, 6, '0');
|
||||
UPDATE utilisateurs SET numero_dossier = num WHERE id = r.id;
|
||||
UPDATE assistantes_maternelles SET numero_dossier = num WHERE id_utilisateur = r.id;
|
||||
END LOOP;
|
||||
|
||||
-- 2) Familles : une entrée par "dossier" (co_parent OU enfants partagés)
|
||||
-- family_rep = min(id) de la composante connexe (lien co_parent + partage d'enfants)
|
||||
FOR r IN
|
||||
WITH RECURSIVE
|
||||
links AS (
|
||||
SELECT p.id_utilisateur AS p1, p.id_co_parent AS p2 FROM parents p WHERE p.id_co_parent IS NOT NULL
|
||||
UNION ALL
|
||||
SELECT p.id_co_parent AS p1, p.id_utilisateur AS p2 FROM parents p WHERE p.id_co_parent IS NOT NULL
|
||||
UNION ALL
|
||||
SELECT ep1.id_parent AS p1, ep2.id_parent AS p2
|
||||
FROM enfants_parents ep1
|
||||
JOIN enfants_parents ep2 ON ep2.id_enfant = ep1.id_enfant AND ep1.id_parent < ep2.id_parent
|
||||
UNION ALL
|
||||
SELECT ep2.id_parent AS p1, ep1.id_parent AS p2
|
||||
FROM enfants_parents ep1
|
||||
JOIN enfants_parents ep2 ON ep2.id_enfant = ep1.id_enfant AND ep1.id_parent < ep2.id_parent
|
||||
),
|
||||
rec AS (
|
||||
SELECT id_utilisateur AS id, id_utilisateur AS rep FROM parents
|
||||
UNION
|
||||
SELECT l.p2 AS id, LEAST(rec_alias.rep, l.p2) AS rep FROM links l JOIN rec rec_alias ON rec_alias.id = l.p1
|
||||
),
|
||||
family_rep AS (
|
||||
SELECT id, MIN(rep::text)::uuid AS rep FROM rec GROUP BY id
|
||||
),
|
||||
fam_ordered AS (
|
||||
SELECT fr.rep AS family_rep, MIN(u.cree_le) AS cree_le
|
||||
FROM family_rep fr
|
||||
JOIN parents p ON p.id_utilisateur = fr.id
|
||||
JOIN utilisateurs u ON u.id = p.id_utilisateur
|
||||
WHERE p.numero_dossier IS NULL
|
||||
AND EXTRACT(YEAR FROM u.cree_le) = yr
|
||||
GROUP BY fr.rep
|
||||
ORDER BY MIN(u.cree_le)
|
||||
)
|
||||
SELECT fo.family_rep
|
||||
FROM fam_ordered fo
|
||||
LOOP
|
||||
seq := seq + 1;
|
||||
num := yr || '-' || LPAD(seq::TEXT, 6, '0');
|
||||
|
||||
WITH RECURSIVE
|
||||
links AS (
|
||||
SELECT p.id_utilisateur AS p1, p.id_co_parent AS p2 FROM parents p WHERE p.id_co_parent IS NOT NULL
|
||||
UNION ALL
|
||||
SELECT p.id_co_parent AS p1, p.id_utilisateur AS p2 FROM parents p WHERE p.id_co_parent IS NOT NULL
|
||||
UNION ALL
|
||||
SELECT ep1.id_parent AS p1, ep2.id_parent AS p2
|
||||
FROM enfants_parents ep1
|
||||
JOIN enfants_parents ep2 ON ep2.id_enfant = ep1.id_enfant AND ep1.id_parent < ep2.id_parent
|
||||
UNION ALL
|
||||
SELECT ep2.id_parent AS p1, ep1.id_parent AS p2
|
||||
FROM enfants_parents ep1
|
||||
JOIN enfants_parents ep2 ON ep2.id_enfant = ep1.id_enfant AND ep1.id_parent < ep2.id_parent
|
||||
),
|
||||
rec AS (
|
||||
SELECT id_utilisateur AS id, id_utilisateur AS rep FROM parents
|
||||
UNION
|
||||
SELECT l.p2 AS id, LEAST(rec_alias.rep, l.p2) AS rep FROM links l JOIN rec rec_alias ON rec_alias.id = l.p1
|
||||
),
|
||||
family_rep AS (
|
||||
SELECT id, MIN(rep::text)::uuid AS rep FROM rec GROUP BY id
|
||||
)
|
||||
SELECT array_agg(DISTINCT fr.id) INTO family_user_ids
|
||||
FROM family_rep fr
|
||||
WHERE fr.rep = r.family_rep;
|
||||
|
||||
UPDATE utilisateurs SET numero_dossier = num WHERE id = ANY(family_user_ids);
|
||||
UPDATE parents SET numero_dossier = num WHERE id_utilisateur = ANY(family_user_ids);
|
||||
END LOOP;
|
||||
|
||||
INSERT INTO numero_dossier_sequence (annee, prochain)
|
||||
VALUES (yr, seq + 1)
|
||||
ON CONFLICT (annee) DO UPDATE
|
||||
SET prochain = GREATEST(numero_dossier_sequence.prochain, seq + 1);
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Migration #105 : Statut utilisateur « refusé » (à corriger)
|
||||
-- Ajout de la valeur 'refuse' à l'enum statut_utilisateur_type.
|
||||
|
||||
ALTER TYPE statut_utilisateur_type ADD VALUE IF NOT EXISTS 'refuse';
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Migration #110 : Token reprise après refus (lien email)
|
||||
-- Permet à l'utilisateur refusé de corriger et resoumettre via un lien sécurisé.
|
||||
|
||||
ALTER TABLE utilisateurs
|
||||
ADD COLUMN IF NOT EXISTS token_reprise VARCHAR(255) NULL,
|
||||
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;
|
||||
@@ -58,9 +58,9 @@ INSERT INTO parents (id_utilisateur, id_co_parent)
|
||||
VALUES ('55555555-5555-5555-5555-555555555555', NULL) -- parent2 sans co-parent
|
||||
ON CONFLICT (id_utilisateur) DO NOTHING;
|
||||
|
||||
-- assistantes_maternelles
|
||||
INSERT INTO assistantes_maternelles (id_utilisateur, numero_agrement, nb_max_enfants, disponible, ville_residence)
|
||||
VALUES ('66666666-6666-6666-6666-666666666666', 'AGR-2025-0001', 3, true, 'Lille')
|
||||
-- assistantes_maternelles (nir_chiffre NOT NULL depuis ticket #102)
|
||||
INSERT INTO assistantes_maternelles (id_utilisateur, numero_agrement, nir_chiffre, nb_max_enfants, disponible, ville_residence)
|
||||
VALUES ('66666666-6666-6666-6666-666666666666', 'AGR-2025-0001', '275119900100102', 3, true, 'Lille')
|
||||
ON CONFLICT (id_utilisateur) DO NOTHING;
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
-- 03_seed_test_data.sql : Données de test complètes (dashboard admin)
|
||||
-- Aligné sur utilisateurs-test-complet.json
|
||||
-- Mot de passe universel : password (bcrypt)
|
||||
-- NIR : numéros de test (non réels), cohérents avec les données (date naissance, genre).
|
||||
-- - Marie Dubois : née en Corse à Ajaccio → NIR 2A (test exception Corse).
|
||||
-- - Fatima El Mansouri : née à l'étranger → NIR 99.
|
||||
-- Même jeu : docs/test-data/README.md, utilisateurs-test.csv/.html, tests/scripts/register-am-*-test.mjs
|
||||
-- À exécuter après BDD.sql (init DB)
|
||||
-- ============================================================
|
||||
|
||||
@@ -36,10 +40,12 @@ VALUES
|
||||
ON CONFLICT (id_utilisateur) DO NOTHING;
|
||||
|
||||
-- ========== ASSISTANTES MATERNELLES ==========
|
||||
-- Marie Dubois (a0000003) : née en Corse à Ajaccio – NIR 2A pour test exception Corse (1980-06-08, F).
|
||||
-- Fatima El Mansouri (a0000004) : née à l'étranger – NIR 99 pour test (1975-11-12, F).
|
||||
INSERT INTO assistantes_maternelles (id_utilisateur, numero_agrement, nir_chiffre, nb_max_enfants, biographie, date_agrement, ville_residence, disponible, place_disponible)
|
||||
VALUES
|
||||
('a0000003-0003-0003-0003-000000000003', 'AGR-2019-095001', '280069512345671', 4, 'Assistante maternelle agréée depuis 2019. Spécialité bébés 0-18 mois. Accueil bienveillant et cadre sécurisant. 2 places disponibles.', '2019-09-01', 'Bezons', true, 2),
|
||||
('a0000004-0004-0004-0004-000000000004', 'AGR-2017-095002', '275119512345672', 3, 'Assistante maternelle expérimentée. Spécialité 1-3 ans. Accueil à la journée. 1 place disponible.', '2017-06-15', 'Bezons', true, 1)
|
||||
('a0000003-0003-0003-0003-000000000003', 'AGR-2019-095001', '280062A00100191', 4, 'Assistante maternelle agréée depuis 2019. Née en Corse à Ajaccio. Spécialité bébés 0-18 mois. Accueil bienveillant et cadre sécurisant. 2 places disponibles.', '2019-09-01', 'Bezons', true, 2),
|
||||
('a0000004-0004-0004-0004-000000000004', 'AGR-2017-095002', '275119900100102', 3, 'Assistante maternelle expérimentée. Née à l''étranger. Spécialité 1-3 ans. Accueil à la journée. 1 place disponible.', '2017-06-15', 'Bezons', true, 1)
|
||||
ON CONFLICT (id_utilisateur) DO NOTHING;
|
||||
|
||||
-- ========== ENFANTS ==========
|
||||
|
||||
@@ -57,6 +57,10 @@ services:
|
||||
NODE_ENV: ${NODE_ENV}
|
||||
LOG_API_REQUESTS: ${LOG_API_REQUESTS:-false}
|
||||
CONFIG_ENCRYPTION_KEY: ${CONFIG_ENCRYPTION_KEY}
|
||||
# Photos inscription (base64) — chemin absolu dans le conteneur (voir volume backend_uploads)
|
||||
UPLOAD_PHOTOS_DIR: ${UPLOAD_PHOTOS_DIR:-/app/uploads/photos}
|
||||
volumes:
|
||||
- backend_uploads:/app/uploads/photos
|
||||
depends_on:
|
||||
- database
|
||||
labels:
|
||||
@@ -66,6 +70,12 @@ services:
|
||||
- "traefik.http.routers.ptitspas-api.tls.certresolver=leresolver"
|
||||
- "traefik.http.routers.ptitspas-api.priority=20"
|
||||
- "traefik.http.services.ptitspas-api.loadbalancer.server.port=3000"
|
||||
# Fichiers statiques photos (URL relatives /uploads/...) — priorité > front (10)
|
||||
- "traefik.http.routers.ptitspas-uploads.rule=Host(\"app.ptits-pas.fr\") && PathPrefix(\"/uploads\")"
|
||||
- "traefik.http.routers.ptitspas-uploads.entrypoints=websecure"
|
||||
- "traefik.http.routers.ptitspas-uploads.tls.certresolver=leresolver"
|
||||
- "traefik.http.routers.ptitspas-uploads.priority=18"
|
||||
- "traefik.http.routers.ptitspas-uploads.service=ptitspas-api"
|
||||
networks:
|
||||
- ptitspas_network
|
||||
- proxy_network
|
||||
@@ -94,6 +104,7 @@ services:
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
backend_uploads:
|
||||
|
||||
networks:
|
||||
ptitspas_network:
|
||||
|
||||
+244
-34
@@ -1,15 +1,15 @@
|
||||
# 🎫 Liste Complète des Tickets - Projet P'titsPas
|
||||
|
||||
**Version** : 1.4
|
||||
**Date** : 9 Février 2026
|
||||
**Version** : 1.7
|
||||
**Date** : 25 Mars 2026
|
||||
**Auteur** : Équipe PtitsPas
|
||||
**Estimation totale** : ~184h
|
||||
**Estimation totale** : ~208h
|
||||
|
||||
---
|
||||
|
||||
## 🔗 Liste des tickets Gitea
|
||||
|
||||
**Les numéros de section dans ce document = numéros d’issues Gitea.** Ticket #14 dans le doc = issue Gitea #14, etc. Source : dépôt `jmartin/petitspas` (état au 9 février 2026).
|
||||
**Les numéros de section dans ce document = numéros d’issues Gitea.** Ticket #14 dans le doc = issue Gitea #14, etc. Source : dépôt `jmartin/petitspas` (état au 25 mars 2026 ; #106, #107, #109, #119 fermés via API).
|
||||
|
||||
| Gitea # | Titre (dépôt) | Statut |
|
||||
|--------|----------------|--------|
|
||||
@@ -25,13 +25,88 @@
|
||||
| 12 | [Backend] Guard Configuration Initiale | ✅ Fermé |
|
||||
| 13 | [Backend] Adaptation MailService pour config dynamique | ✅ Fermé |
|
||||
| 14 | [Frontend] Panneau Paramètres / Configuration (première config + accès permanent) | Ouvert |
|
||||
| 15 | [Frontend] Écran Paramètres (accès permanent) | Ouvert |
|
||||
| 15 | [Frontend] Écran Paramètres (accès permanent) / Intégration panneau | Ouvert |
|
||||
| 16 | [Doc] Documentation configuration on-premise | Ouvert |
|
||||
| 17–88 | (voir sections ci‑dessous ; #82, #78, #79, #81, #83 ; #86, #87, #88 fermés en doublon) | — |
|
||||
| 92 | [Frontend] Dashboard Admin - Données réelles et branchement API | Ouvert |
|
||||
| 17 | [Backend] API Création gestionnaire | ✅ Terminé |
|
||||
| 18 | [Backend] API Inscription Parent - REFONTE (Workflow complet 6 étapes) | ✅ Terminé |
|
||||
| 19 | [Backend] API Inscription Parent (étape 2 - Parent 2) | ✅ Terminé |
|
||||
| 20 | [Backend] API Inscription Parent (étape 3 - Enfants) | ✅ Terminé |
|
||||
| 21 | [Backend] API Inscription Parent (étape 4-6 - Finalisation) | ✅ Terminé |
|
||||
| 24 | [Backend] API Création mot de passe | Ouvert |
|
||||
| 25 | [Backend] API Liste comptes en attente | ✅ Fermé (obsolète, couvert #103-#111) |
|
||||
| 26 | [Backend] API Validation/Refus comptes | ✅ Fermé (obsolète, couvert #103-#111) |
|
||||
| 27 | [Backend] Service Email - Installation Nodemailer | ✅ Fermé (obsolète, couvert #103-#111) |
|
||||
| 28 | [Backend] Templates Email - Validation | Ouvert |
|
||||
| 29 | [Backend] Templates Email - Refus | ✅ Fermé (obsolète, couvert #103-#111) |
|
||||
| 30 | [Backend] Connexion - Vérification statut | ✅ Fermé (obsolète, couvert #103-#111) |
|
||||
| 31 | [Backend] Changement MDP obligatoire première connexion | ✅ Terminé |
|
||||
| 32 | [Backend] Service Documents Légaux | Ouvert |
|
||||
| 33 | [Backend] API Documents Légaux | Ouvert |
|
||||
| 34 | [Backend] Traçabilité acceptations documents | Ouvert |
|
||||
| 35 | [Frontend] Écran Création Gestionnaire | Ouvert |
|
||||
| 36 | [Frontend] Inscription Parent - Étape 1 (Parent 1) | ✅ Terminé |
|
||||
| 37 | [Frontend] Inscription Parent - Étape 2 (Parent 2) | Ouvert |
|
||||
| 38 | [Frontend] Inscription Parent - Étape 3 (Enfants) | ✅ Terminé |
|
||||
| 39 | [Frontend] Inscription Parent - Étapes 4-6 (Finalisation) | ✅ Terminé |
|
||||
| 40 | [Frontend] Inscription AM - Panneau 1 (Identité) | ✅ Terminé |
|
||||
| 41 | [Frontend] Inscription AM - Panneau 2 (Infos pro) | ✅ Terminé |
|
||||
| 42 | [Frontend] Inscription AM - Finalisation | ✅ Terminé |
|
||||
| 43 | [Frontend] Écran Création Mot de Passe | Ouvert |
|
||||
| 44 | [Frontend] Dashboard Gestionnaire - Structure | ✅ Terminé |
|
||||
| 45 | [Frontend] Dashboard Gestionnaire - Liste Parents | ✅ Fermé (obsolète, couvert #103-#111) |
|
||||
| 46 | [Frontend] Dashboard Gestionnaire - Liste AM | ✅ Fermé (obsolète, couvert #103-#111) |
|
||||
| 47 | [Frontend] Écran Changement MDP Obligatoire | Ouvert |
|
||||
| 48 | [Frontend] Gestion Erreurs & Messages | Ouvert |
|
||||
| 49 | [Frontend] Écran Gestion Documents Légaux (Admin) | Ouvert |
|
||||
| 50 | [Frontend] Affichage dynamique CGU lors inscription | Ouvert |
|
||||
| 51 | [Frontend] Écran Logs Admin (optionnel v1.1) | Ouvert |
|
||||
| 52 | [Tests] Tests unitaires Backend | Ouvert |
|
||||
| 53 | [Tests] Tests intégration Backend | Ouvert |
|
||||
| 54 | [Tests] Tests E2E Frontend | Ouvert |
|
||||
| 55 | [Doc] Documentation API OpenAPI/Swagger | Ouvert |
|
||||
| 56 | [Backend] Service Upload & Stockage fichiers | Ouvert |
|
||||
| 58 | [Backend] Service Logging (Winston) | Ouvert |
|
||||
| 59 | [Infra] Volume Docker pour uploads | Ouvert |
|
||||
| 60 | [Infra] Volume Docker pour documents légaux | Ouvert |
|
||||
| 61 | [Doc] Guide installation & configuration | Ouvert |
|
||||
| 62 | [Doc] Amendement CDC v1.4 - Suppression SMS | Ouvert |
|
||||
| 63 | [Doc] Rédaction CGU/Privacy génériques v1 | Ouvert |
|
||||
| 78 | [Frontend] Refonte Infrastructure Formulaires Multi-modes | ✅ Terminé |
|
||||
| 79 | [Frontend] Renommer "Nanny" en "Assistante Maternelle" (AM) | ✅ Terminé |
|
||||
| 81 | [Frontend] Corrections suite refactoring widgets | ✅ Terminé |
|
||||
| 83 | [Frontend] Adapter RegisterChoiceScreen pour mobile | ✅ Terminé |
|
||||
| 86 / 88 | Doublons fermés (voir #12, #14, #15) | ✅ Fermé |
|
||||
| 89 | Log des appels API en mode debug | Ouvert |
|
||||
| 91 | [Frontend] Inscription AM – Branchement soumission formulaire à l'API | Ouvert |
|
||||
| 92 | [Frontend] Dashboard Admin - Données réelles et branchement API | ✅ Terminé |
|
||||
| 93 | [Frontend] Panneau Admin - Homogénéisation des onglets | ✅ Fermé |
|
||||
| 94 | [Backend] Relais - Modèle, API CRUD et liaison gestionnaire | ✅ Terminé |
|
||||
| 95 | [Frontend] Admin - Gestion des Relais et rattachement gestionnaire | ✅ Fermé |
|
||||
| 96 | [Frontend] Admin - Création administrateur via modale (sans relais) | ✅ Terminé |
|
||||
| 97 | [Backend] Harmoniser API création administrateur avec le contrat frontend | ✅ Terminé |
|
||||
| 101 | [Frontend] Inscription Parent – Branchement soumission formulaire à l'API | Ouvert |
|
||||
| 103 | Numéro de dossier – backend | Ouvert |
|
||||
| 104 | Numéro de dossier – frontend | Ouvert |
|
||||
| 105 | Statut « refusé » | Ouvert |
|
||||
| 106 | Liste familles en attente | ✅ Fermé |
|
||||
| 107 | Onglet « À valider » + listes | ✅ Fermé |
|
||||
| 108 | Validation dossier famille | Ouvert |
|
||||
| 109 | Modale de validation | ✅ Fermé |
|
||||
| 110 | Refus sans suppression | Ouvert |
|
||||
| 111 | Reprise après refus – backend | Ouvert |
|
||||
| 112 | Reprise après refus – frontend | Ouvert |
|
||||
| 113 | Doublons à l'inscription | Ouvert |
|
||||
| 114 | Doublons – alerte gestionnaire | Ouvert |
|
||||
| 115 | Rattachement parent – backend | Ouvert |
|
||||
| 116 | Rattachement parent – frontend | Ouvert |
|
||||
| 117 | Évolution du cahier des charges | Ouvert |
|
||||
| 119 | Endpoint unifié GET /dossiers/:numeroDossier (AM ou famille) | ✅ Fermé |
|
||||
| 120 | [Full-stack] Inscription AM — photo, API et UX alignés sur les parents (suite #91) | ✅ Fermé |
|
||||
|
||||
*Gitea #1 et #2 = anciens tickets de test (fermés). Liste complète : https://git.ptits-pas.fr/jmartin/petitspas/issues*
|
||||
|
||||
*Tickets #103 à #117 = périmètre « Validation des nouveaux comptes par le gestionnaire » (voir plan de spec).*
|
||||
|
||||
---
|
||||
|
||||
## 📊 Vue d'ensemble
|
||||
@@ -316,21 +391,22 @@ Rédiger la documentation pour aider les collectivités à configurer l'applicat
|
||||
|
||||
## 🟢 PRIORITÉ 2 : Backend - Authentification & Gestion Comptes
|
||||
|
||||
### Ticket #17 : [Backend] API Création gestionnaire
|
||||
### Ticket #17 : [Backend] API Création gestionnaire ✅
|
||||
**Estimation** : 3h
|
||||
**Labels** : `backend`, `p2`, `auth`
|
||||
**Statut** : ✅ TERMINÉ (Fermé le 2026-02-23)
|
||||
|
||||
**Description** :
|
||||
Créer l'endpoint pour permettre au super admin de créer des gestionnaires.
|
||||
|
||||
**Tâches** :
|
||||
- [ ] Endpoint `POST /api/v1/gestionnaires`
|
||||
- [ ] Validation DTO
|
||||
- [ ] Hash bcrypt
|
||||
- [ ] Flag `changement_mdp_obligatoire = TRUE`
|
||||
- [ ] Guards (super_admin only)
|
||||
- [ ] Email de notification (utiliser MailService avec config dynamique)
|
||||
- [ ] Tests unitaires
|
||||
- [x] Endpoint `POST /api/v1/gestionnaires`
|
||||
- [x] Validation DTO
|
||||
- [x] Hash bcrypt
|
||||
- [x] Flag `changement_mdp_obligatoire = TRUE`
|
||||
- [x] Guards (super_admin only)
|
||||
- [x] Email de notification (utiliser MailService avec config dynamique)
|
||||
- [x] Tests unitaires
|
||||
|
||||
**Référence** : [20_WORKFLOW-CREATION-COMPTE.md](./20_WORKFLOW-CREATION-COMPTE.md#étape-2--création-dun-gestionnaire)
|
||||
|
||||
@@ -567,17 +643,18 @@ Modifier l'endpoint de connexion pour bloquer les comptes en attente ou suspendu
|
||||
|
||||
---
|
||||
|
||||
### Ticket #31 : [Backend] Changement MDP obligatoire première connexion
|
||||
### Ticket #31 : [Backend] Changement MDP obligatoire première connexion ✅
|
||||
**Estimation** : 2h
|
||||
**Labels** : `backend`, `p2`, `auth`, `security`
|
||||
**Labels** : `backend`, `p2`, `auth`, `security`
|
||||
**Statut** : ✅ TERMINÉ
|
||||
|
||||
**Description** :
|
||||
Implémenter le changement de mot de passe obligatoire pour les gestionnaires/admins à la première connexion.
|
||||
|
||||
**Tâches** :
|
||||
- [ ] Endpoint `POST /api/v1/auth/change-password-required`
|
||||
- [ ] Vérification flag `changement_mdp_obligatoire`
|
||||
- [ ] Mise à jour flag après changement
|
||||
- [x] Endpoint `POST /api/v1/auth/change-password-required`
|
||||
- [x] Vérification flag `changement_mdp_obligatoire`
|
||||
- [x] Mise à jour flag après changement
|
||||
- [ ] Tests unitaires
|
||||
|
||||
---
|
||||
@@ -641,6 +718,39 @@ Enregistrer les acceptations de documents légaux lors de l'inscription (traçab
|
||||
|
||||
---
|
||||
|
||||
### Ticket #94 : [Backend] Relais - Modèle, API CRUD et liaison gestionnaire ✅
|
||||
**Estimation** : 4h
|
||||
**Labels** : `backend`, `p2`, `admin`
|
||||
**Statut** : ✅ TERMINÉ (Fermé le 2026-02-21)
|
||||
|
||||
**Description** :
|
||||
Le back-office admin doit gérer des Relais avec des données réelles en base, et permettre une liaison simple avec les gestionnaires.
|
||||
|
||||
**Tâches** :
|
||||
- [x] Créer le modèle `Relais` (nom, adresse, horaires, téléphone, actif, notes)
|
||||
- [x] Exposer les endpoints admin CRUD pour les relais (`GET`, `POST`, `PATCH`, `DELETE`)
|
||||
- [x] Ajouter la liaison : un gestionnaire peut être rattaché à un relais principal (`relais_id` dans `users` ?)
|
||||
- [x] Validations (champs requis, format horaires)
|
||||
|
||||
---
|
||||
|
||||
### Ticket #97 : [Backend] Harmoniser API création administrateur avec le contrat frontend ✅
|
||||
**Estimation** : 3h
|
||||
**Labels** : `backend`, `p2`, `auth`, `admin`
|
||||
**Statut** : ✅ TERMINÉ (Fermé le 2026-02-24)
|
||||
|
||||
**Description** :
|
||||
Rendre l'API de création administrateur cohérente et stable avec le besoin frontend (modale simplifiée), en définissant un contrat clair et minimal.
|
||||
|
||||
**Tâches** :
|
||||
- [ ] Introduire un DTO dédié `CreateAdministrateurDto`
|
||||
- [ ] Champs autorisés : nom, prenom, email, password, telephone
|
||||
- [ ] Champs exclus : adresse, ville, photo, etc.
|
||||
- [ ] Rôle forcé à `ADMINISTRATEUR`
|
||||
- [ ] Validation stricte
|
||||
|
||||
---
|
||||
|
||||
## 🟢 PRIORITÉ 3 : Frontend - Interfaces
|
||||
|
||||
### Ticket #35 : [Frontend] Écran Création Gestionnaire
|
||||
@@ -798,7 +908,7 @@ Créer l'écran de création de mot de passe (lien reçu par email).
|
||||
|
||||
---
|
||||
|
||||
### Ticket #44 : [Frontend] Dashboard Gestionnaire - Structure
|
||||
### Ticket #44 : [Frontend] Dashboard Gestionnaire - Structure ✅
|
||||
**Estimation** : 2h
|
||||
**Labels** : `frontend`, `p3`, `gestionnaire`
|
||||
|
||||
@@ -806,9 +916,10 @@ Créer l'écran de création de mot de passe (lien reçu par email).
|
||||
Créer la structure du dashboard gestionnaire avec 2 onglets.
|
||||
|
||||
**Tâches** :
|
||||
- [ ] Layout avec 2 onglets (Parents / AM)
|
||||
- [ ] Navigation entre onglets
|
||||
- [ ] État vide ("Aucune demande")
|
||||
- [x] Dashboard gestionnaire = même shell que admin (sans onglet Paramètres), libellé « Gestionnaire »
|
||||
- [x] Réutilisation du widget UserManagementPanel (ex-AdminUserManagementPanel) avec 3 onglets (Gestionnaires, Parents, Assistantes maternelles) ; onglet Administrateurs masqué
|
||||
- [x] Redirection login rôle `gestionnaire` vers `/gestionnaire-dashboard`
|
||||
- [ ] État vide dédié ("Aucune demande") — optionnel, contenu actuel = listes existantes
|
||||
|
||||
---
|
||||
|
||||
@@ -894,9 +1005,10 @@ Créer l'écran de gestion des documents légaux (CGU/Privacy) pour l'admin.
|
||||
|
||||
---
|
||||
|
||||
### Ticket #92 : [Frontend] Dashboard Admin - Données réelles et branchement API
|
||||
### Ticket #92 : [Frontend] Dashboard Admin - Données réelles et branchement API ✅
|
||||
**Estimation** : 8h
|
||||
**Labels** : `frontend`, `p3`, `admin`
|
||||
**Statut** : ✅ TERMINÉ (Fermé le 2026-02-17)
|
||||
|
||||
**Description** :
|
||||
Le dashboard admin (onglets Gestionnaires | Parents | Assistantes maternelles | Administrateurs) affiche actuellement des données en dur (mock). Remplacer par des appels API pour afficher les vrais utilisateurs et permettre les actions de gestion (voir, modifier, valider/refuser). Référence : [90_AUDIT.md](./90_AUDIT.md).
|
||||
@@ -1018,6 +1130,89 @@ Adapter l'écran de choix Parent/AM pour une meilleure expérience mobile et coh
|
||||
|
||||
---
|
||||
|
||||
### Ticket #91 : [Frontend] Inscription AM – Branchement soumission formulaire à l'API
|
||||
**Estimation** : 3h
|
||||
**Labels** : `frontend`, `p3`, `auth`, `cdc`
|
||||
|
||||
**Description** :
|
||||
Branchement du formulaire d'inscription AM (étape 4) à l'endpoint d'inscription.
|
||||
|
||||
**Tâches** :
|
||||
- [ ] Construire le body (DTO) à partir de `AmRegistrationData`
|
||||
- [ ] Appel HTTP `POST /api/v1/auth/register/am`
|
||||
- [ ] Gestion réponse (201 : succès + redirection ; 4xx : erreur)
|
||||
- [ ] Conversion photo en base64 si nécessaire
|
||||
|
||||
---
|
||||
|
||||
### Ticket #101 : [Frontend] Inscription Parent – Branchement soumission formulaire à l'API
|
||||
**Estimation** : 4h
|
||||
**Labels** : `frontend`, `p3`, `auth`, `cdc`
|
||||
|
||||
**Description** :
|
||||
Branchement du formulaire d'inscription parent (étape 5, récapitulatif) à l'endpoint d'inscription. Aujourd'hui la soumission n'appelle pas l'API : elle affiche uniquement une modale de confirmation puis redirige vers le login. Ce ticket vise à envoyer les données collectées (Parent 1, Parent 2 optionnel, enfants, présentation, CGU) à l'API.
|
||||
|
||||
**Tâches** :
|
||||
- [ ] Créer un service ou méthode (ex. `AuthService.registerParent` ou `UserService`) appelant `POST /api/v1/auth/register/parent`
|
||||
- [ ] Construire le body (DTO) à partir de `UserRegistrationData` (parent1, parent2, children, motivationText, CGU acceptée, etc.) en cohérence avec le contrat backend (voir ticket #18 refonte)
|
||||
- [ ] Dans `ParentRegisterStep5Screen`, au clic « Soumettre » : appel API puis en cas de succès afficher la modale et redirection vers `/login` ; en cas d'erreur afficher le message (SnackBar/dialog)
|
||||
- [ ] Gestion des photos enfants (base64 ou multipart selon API)
|
||||
- [ ] Optionnel : réinitialiser ou conserver `UserRegistrationData` après succès (selon UX)
|
||||
|
||||
**Référence** : [20_WORKFLOW-CREATION-COMPTE.md](./20_WORKFLOW-CREATION-COMPTE.md#étape-3--inscription-dun-parent), backend #18 (refonte API inscription parent).
|
||||
|
||||
**Création** : issue Gitea #101 créée. Pour recréer ou script : `node backend/scripts/create-gitea-issue-parent-api.js` (token dans `.gitea-token` ou voir [PROCEDURE-API-GITEA.md](./PROCEDURE-API-GITEA.md)).
|
||||
|
||||
---
|
||||
|
||||
### Ticket #93 : [Frontend] Panneau Admin - Homogénéisation des onglets ✅
|
||||
**Estimation** : 4h
|
||||
**Labels** : `frontend`, `p3`, `admin`, `ux`
|
||||
**Statut** : ✅ TERMINÉ (Fermé le 2026-02-24)
|
||||
|
||||
**Description** :
|
||||
Uniformiser l'UI/UX des 4 onglets du dashboard admin (Gestionnaires, Parents, AM, Admins).
|
||||
|
||||
**Tâches** :
|
||||
- [ ] Standardiser le header de liste (Recherche, Filtres, Bouton Action)
|
||||
- [ ] Standardiser les cartes utilisateurs (`ListTile` uniforme)
|
||||
- [ ] Standardiser les états (Loading, Erreur, Vide)
|
||||
- [ ] Factoriser les composants partagés
|
||||
|
||||
---
|
||||
|
||||
### Ticket #95 : [Frontend] Admin - Gestion des Relais et rattachement gestionnaire ✅
|
||||
**Estimation** : 5h
|
||||
**Labels** : `frontend`, `p3`, `admin`
|
||||
**Statut** : ✅ TERMINÉ (Fermé le 2026-02-24)
|
||||
|
||||
**Description** :
|
||||
Interface de gestion des Relais dans le dashboard admin et rattachement des gestionnaires.
|
||||
|
||||
**Tâches** :
|
||||
- [ ] Section Relais avec 2 sous-onglets : Paramètres techniques / Paramètres territoriaux
|
||||
- [ ] Liste, Création, Édition, Activation/Désactivation des relais
|
||||
- [ ] Champs UI : nom, adresse, horaires, téléphone, statut, notes
|
||||
- [ ] Onglet Gestionnaires : Ajout contrôle de rattachement au relais principal
|
||||
|
||||
---
|
||||
|
||||
### Ticket #96 : [Frontend] Admin - Création administrateur via modale (sans relais) ✅
|
||||
**Estimation** : 3h
|
||||
**Labels** : `frontend`, `p3`, `admin`
|
||||
**Statut** : ✅ TERMINÉ (Fermé le 2026-02-24)
|
||||
|
||||
**Description** :
|
||||
Permettre la création d'un administrateur via une modale simple depuis le dashboard admin.
|
||||
|
||||
**Tâches** :
|
||||
- [x] Bouton "Créer administrateur" dans l'onglet Administrateurs
|
||||
- [x] Modale avec formulaire simplifié (Nom, Prénom, Email, MDP, Téléphone)
|
||||
- [x] Appel API `POST /users` (ou endpoint dédié si #97 implémenté)
|
||||
- [x] Gestion succès/erreur et rafraîchissement liste
|
||||
|
||||
---
|
||||
|
||||
## 🔵 PRIORITÉ 4 : Tests & Documentation
|
||||
|
||||
### Ticket #52 : [Tests] Tests unitaires Backend
|
||||
@@ -1133,6 +1328,20 @@ Mettre en place un système de logs centralisé avec Winston pour faciliter le d
|
||||
|
||||
---
|
||||
|
||||
### Ticket #89 : Log des appels API en mode debug
|
||||
**Estimation** : 2h
|
||||
**Labels** : `backend`, `monitoring`
|
||||
|
||||
**Description** :
|
||||
Ajouter des logs détaillés pour les appels API en mode debug pour faciliter le diagnostic.
|
||||
|
||||
**Tâches** :
|
||||
- [ ] Middleware ou Intercepteur pour logger les requêtes entrantes (méthode, URL, body)
|
||||
- [ ] Logger les réponses (status, temps d'exécution)
|
||||
- [ ] Activable via variable d'environnement `DEBUG=true` ou niveau de log
|
||||
|
||||
---
|
||||
|
||||
### Ticket #51 (réf.) : [Frontend] Écran Logs Admin (optionnel v1.1)
|
||||
**Estimation** : 4h
|
||||
**Labels** : `frontend`, `p3`, `monitoring`, `admin`
|
||||
@@ -1235,28 +1444,29 @@ Rédiger les documents légaux génériques (CGU et Politique de confidentialit
|
||||
|
||||
## 📊 Résumé final
|
||||
|
||||
**Total** : 65 tickets
|
||||
**Estimation** : ~184h de développement
|
||||
**Total** : 72 tickets
|
||||
**Estimation** : ~208h de développement
|
||||
|
||||
### Par priorité
|
||||
- **P0 (Bloquant BDD)** : 7 tickets (~5h)
|
||||
- **P1 (Bloquant Config)** : 7 tickets (~22h)
|
||||
- **P2 (Backend)** : 18 tickets (~50h)
|
||||
- **P3 (Frontend)** : 22 tickets (~71h) ← +1 mobile RegisterChoice
|
||||
- **P2 (Backend)** : 19 tickets (~54h)
|
||||
- **P3 (Frontend)** : 25 tickets (~83h)
|
||||
- **P4 (Tests/Doc)** : 4 tickets (~24h)
|
||||
- **Critiques** : 6 tickets (~13h)
|
||||
- **Juridique** : 1 ticket (~8h)
|
||||
|
||||
### Par domaine
|
||||
- **BDD** : 7 tickets
|
||||
- **Backend** : 23 tickets
|
||||
- **Frontend** : 22 tickets ← +1 mobile RegisterChoice
|
||||
- **Backend** : 24 tickets
|
||||
- **Frontend** : 25 tickets
|
||||
- **Tests** : 3 tickets
|
||||
- **Documentation** : 5 tickets
|
||||
- **Infra** : 2 tickets
|
||||
- **Juridique** : 1 ticket
|
||||
|
||||
### Modifications par rapport à la version initiale
|
||||
- ✅ **v1.5** : Ajout tickets #91, #93, #94, #95. Ticket #92 terminé.
|
||||
- ✅ **v1.4** : Numéros de section du doc = numéros Gitea (Ticket #n = issue #n). Tableau et sections renumérotés. Doublons #86, #87, #88 fermés sur Gitea (#86→#12, #87→#14, #88→#15) ; tickets sources #12, #14, #15 mis à jour (doc + body Gitea).
|
||||
- ✅ **Concept v1.3** : Configuration initiale = un seul panneau Paramètres (3 sections) dans le dashboard ; plus de page dédiée « Setup Wizard » ; navigation bloquée jusqu’à sauvegarde au premier déploiement. Tickets #10, #12, #13 alignés.
|
||||
- ❌ **Supprimé** : Tickets "Renvoyer email validation" (backend + frontend) - Pas prioritaire
|
||||
@@ -1270,7 +1480,7 @@ Rédiger les documents légaux génériques (CGU et Politique de confidentialit
|
||||
|
||||
---
|
||||
|
||||
**Dernière mise à jour** : 9 Février 2026
|
||||
**Version** : 1.4
|
||||
**Statut** : ✅ Aligné avec le dépôt Gitea
|
||||
**Dernière mise à jour** : 25 Février 2026
|
||||
**Version** : 1.6
|
||||
**Statut** : ✅ Aligné avec le dépôt Gitea (tickets #103-#117 créés)
|
||||
|
||||
|
||||
+21
-1
@@ -255,4 +255,24 @@ Pour chaque évolution identifiée, ce document suivra la structure suivante :
|
||||
#### X.1.3 Impact sur l'application
|
||||
- Modification du flux de sélection d'image dans les écrans concernés (ex: `parent_register_step3_screen.dart`).
|
||||
- Ajout potentiel de nouvelles dépendances et configurations spécifiques aux plateformes.
|
||||
- Mise à jour de la documentation utilisateur si cette fonctionnalité est implémentée.
|
||||
- Mise à jour de la documentation utilisateur si cette fonctionnalité est implémentée.
|
||||
|
||||
## 8. Évolution future - Gouvernance intra-RPE
|
||||
|
||||
### 8.1 Niveaux d'accès et rôles différenciés dans un même Relais
|
||||
|
||||
#### 8.1.1 Situation actuelle
|
||||
- Le périmètre actuel prévoit un rattachement simple entre gestionnaire et relais.
|
||||
- Le rôle "gestionnaire" est traité de manière uniforme dans l'outil.
|
||||
|
||||
#### 8.1.2 Évolution à prévoir
|
||||
- Introduire un modèle de rôles internes au relais (par exemple : responsable/coordinatrice, animatrice/référente, administratif).
|
||||
- Permettre des niveaux d'autorité différents selon les actions (pilotage, validation, consultation, administration locale).
|
||||
- Définir des permissions fines par fonctionnalité (lecture, création, modification, suppression, validation).
|
||||
- Prévoir une gestion multi-utilisateurs par relais avec traçabilité des décisions.
|
||||
|
||||
#### 8.1.3 Impact attendu
|
||||
- Évolution du modèle de données vers un RBAC intra-RPE.
|
||||
- Adaptation des écrans d'administration pour gérer les rôles locaux.
|
||||
- Renforcement des contrôles d'accès backend et des règles métier.
|
||||
- Clarification des workflows décisionnels dans l'application.
|
||||
@@ -14,7 +14,7 @@ Num | Etat | Titre
|
||||
41 | closed | [Frontend] Inscription AM - Panneau 2 (Infos pro)
|
||||
42 | closed | [Frontend] Inscription AM - Finalisation
|
||||
43 | open | [Frontend] Écran Création Mot de Passe
|
||||
44 | open | [Frontend] Dashboard Gestionnaire - Structure
|
||||
44 | closed | [Frontend] Dashboard Gestionnaire - Structure
|
||||
45 | open | [Frontend] Dashboard Gestionnaire - Liste Parents
|
||||
46 | open | [Frontend] Dashboard Gestionnaire - Liste AM
|
||||
47 | open | [Frontend] Écran Changement MDP Obligatoire
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# SuperNounou – SSS-001
|
||||
## Spécification technique & opérationnelle unifiée
|
||||
_Version 0.2 – 24 avril 2025_
|
||||
_Version 0.3 – 27 janvier 2026_
|
||||
|
||||
---
|
||||
|
||||
@@ -62,6 +62,13 @@ Collection Postman, scripts cURL, guide « Appeler l’API ».
|
||||
### B.4 Intégrations futures
|
||||
SSO LDAP/SAML, webhook `contract.validated`, export statistiques CSV.
|
||||
|
||||
### B.5 Contrat de gestion des comptes d'administration
|
||||
- Création d'un administrateur avec un contrat minimal stable : `nom`, `prenom`, `email`, `password`, `telephone`.
|
||||
- Le rôle n'est jamais fourni par le frontend pour ce flux ; le backend impose `ADMINISTRATEUR`.
|
||||
- Les champs hors périmètre (adresse complète, photo, métadonnées métier non nécessaires) ne sont pas requis.
|
||||
- Les protections d'autorisation restent actives : un `SUPER_ADMIN` n'est pas supprimable et son identité (`nom`, `prenom`) est non modifiable.
|
||||
- Côté interface d'administration, les actions d'édition sont conditionnées aux droits ; les entrées non éditables restent consultables en lecture seule.
|
||||
|
||||
---
|
||||
|
||||
# C – Déploiement, CI/CD et Observabilité *(nouveau)*
|
||||
@@ -106,3 +113,4 @@ AES-256, JWT, KMS, OpenAPI, RPO, RTO, rate-limit, HMAC, Compose, CI/CD…
|
||||
|---------|------------|------------------|---------------------------------|
|
||||
| 0.1-draft | 2025-04-24 | Équipe projet | Création du SSS unifié |
|
||||
| 0.2 | 2025-04-24 | ChatGPT & Julien | Ajout déploiement / CI/CD / logs |
|
||||
| 0.3 | 2026-01-27 | Équipe projet | Contrat admin harmonisé et règles d'autorisation |
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# TEMP — Alignement front / API (inscription AM & validation gestionnaire)
|
||||
|
||||
> **Fichier temporaire** : à supprimer ou renommer une fois le front livré.
|
||||
|
||||
Ce document décrit les changements **côté API** et ce que **Flutter** doit faire pour rester aligné. Aucune modification front n’a été faite dans le chantier backend associé.
|
||||
|
||||
## 1. `POST /auth/register/am` — lieu de naissance obligatoire
|
||||
|
||||
- **`lieu_naissance_ville`** et **`lieu_naissance_pays`** sont **obligatoires** (non vides après trim, min. **2 caractères** chacun, max 100).
|
||||
- Réponses **400** si manquants ou invalides (messages class-validator).
|
||||
- **Action front** : champs obligatoires dans le parcours AM (étapes identité / naissance), validation UI avant envoi ; afficher les erreurs renvoyées par l’API.
|
||||
|
||||
## 2. Réponse `GET /dossiers/:numeroDossier` (type `am`)
|
||||
|
||||
Sous `dossier.user`, l’API peut inclure :
|
||||
|
||||
| Clé JSON | Description |
|
||||
|----------|-------------|
|
||||
| `date_naissance` | Date (si renseignée à l’inscription) |
|
||||
| `lieu_naissance_ville` | Ville de naissance |
|
||||
| `lieu_naissance_pays` | Pays de naissance |
|
||||
| `consentement_photo` | Booléen (exposé dans `dossier.user`) |
|
||||
|
||||
À la **racine** de `dossier` (objet AM), champs déjà renvoyés par le backend : `disponible`, `annees_experience`, `specialite`, `nb_max_enfants`, `place_disponible`, etc.
|
||||
|
||||
**Action front** :
|
||||
|
||||
- Étendre **`AppUser.fromJson` / `toJson`** (`lib/models/user.dart`) pour mapper `date_naissance`, `lieu_naissance_ville`, `lieu_naissance_pays`, `consentement_photo`.
|
||||
- Étendre **`DossierAM.fromJson`** (`lib/models/dossier_unifie.dart`) pour parser `disponible`, `annees_experience`, `specialite` à la racine du dossier (noms snake_case comme dans la réponse JSON Nest).
|
||||
|
||||
## 3. `ValidationAmWizard` (admin)
|
||||
|
||||
Afficher pour cohérence avec le formulaire d’inscription :
|
||||
|
||||
- **Informations personnelles** : date de naissance, ville / pays de naissance, consentement photo (Oui/Non).
|
||||
- **Informations professionnelles** : disponibilité, années d’expérience, spécialité (afficher « – » si `null`).
|
||||
|
||||
## 4. `place_disponible` à l’inscription
|
||||
|
||||
- Le backend initialise **`place_disponible`** sur la fiche AM à la **même valeur** que **`capacite_accueil`** à la création. Le wizard peut donc afficher une valeur cohérente avec la capacité sans champ séparé côté public.
|
||||
|
||||
---
|
||||
|
||||
*Dernière mise à jour : alignement backend branche `feature/120-inscription-am-photo-backend`.*
|
||||
+25
-15
@@ -16,6 +16,8 @@ Fichier CSV contenant les utilisateurs de test pour valider le workflow de créa
|
||||
|
||||
## 👥 Utilisateurs de test
|
||||
|
||||
**Source de vérité (identités, NIR, agréments, adresses)** : `database/seed/03_seed_test_data.sql`, complété par `utilisateurs-test.csv` et ce README. Les scripts Node `tests/scripts/register-am-*-test.mjs` reprennent les mêmes valeurs.
|
||||
|
||||
### 1. Administrateur
|
||||
|
||||
| Nom | Prénom | Email | Téléphone | Mobile |
|
||||
@@ -49,7 +51,14 @@ Fichier CSV contenant les utilisateurs de test pour valider le workflow de créa
|
||||
**Rôle** : `assistante_maternelle`
|
||||
**Spécialité** : Bébés 0-18 mois
|
||||
**Agrément** : 4 enfants
|
||||
**Places disponibles** : 2
|
||||
**Places disponibles** : 2
|
||||
**Date de naissance** : 1980-06-08
|
||||
**Lieu de naissance (inscription)** : Ajaccio (Corse, France) — NIR de test avec code département **2A**
|
||||
**NIR (fictif, clé valide)** : `280062A00100191`
|
||||
**N° d'agrément** : `AGR-2019-095001`
|
||||
**Date d'agrément** : 2019-09-01
|
||||
**Adresse** : 25 Rue de la République, 95870 Bezons
|
||||
**Script d'inscription** : `tests/scripts/register-am-dubois-test.mjs`
|
||||
|
||||
#### Fatima EL MANSOURI
|
||||
|
||||
@@ -60,7 +69,14 @@ Fichier CSV contenant les utilisateurs de test pour valider le workflow de créa
|
||||
**Rôle** : `assistante_maternelle`
|
||||
**Spécialité** : 1-3 ans
|
||||
**Agrément** : 3 enfants
|
||||
**Places disponibles** : 1
|
||||
**Places disponibles** : 1
|
||||
**Date de naissance** : 1975-11-12
|
||||
**Lieu de naissance (inscription)** : exemple Casablanca (Maroc) — NIR de test avec code **99** (naissance à l'étranger)
|
||||
**NIR (fictif, clé valide)** : `275119900100102`
|
||||
**N° d'agrément** : `AGR-2017-095002`
|
||||
**Date d'agrément** : 2017-06-15
|
||||
**Adresse** : 17 Boulevard Aristide Briand, 95870 Bezons
|
||||
**Script d'inscription** : `tests/scripts/register-am-mansouri-test.mjs`
|
||||
|
||||
---
|
||||
|
||||
@@ -160,20 +176,14 @@ POST /api/v1/gestionnaires
|
||||
}
|
||||
```
|
||||
|
||||
#### Scénario 2 : Inscription assistante maternelle
|
||||
#### Scénario 2 : Inscription assistante maternelle (complète)
|
||||
|
||||
```typescript
|
||||
// Marie DUBOIS s'inscrit
|
||||
POST /api/v1/auth/register
|
||||
{
|
||||
"email": "marie.dubois@ptits-pas.fr",
|
||||
"password": "Test1234!",
|
||||
"prenom": "Marie",
|
||||
"nom": "DUBOIS",
|
||||
"telephone": "01 39 98 67 89",
|
||||
"mobile": "06 96 34 56 78",
|
||||
"role": "assistante_maternelle"
|
||||
}
|
||||
Inscription en un flux : `POST /api/v1/auth/register/am` (identité, NIR, agrément, photo optionnelle, CGU). Voir le DTO backend `RegisterAMCompletDto`.
|
||||
|
||||
```bash
|
||||
# Jeux alignés sur le seed (mêmes NIR / dates / agréments que 03_seed_test_data.sql) :
|
||||
node tests/scripts/register-am-dubois-test.mjs [BASE_URL]
|
||||
node tests/scripts/register-am-mansouri-test.mjs [BASE_URL]
|
||||
```
|
||||
|
||||
#### Scénario 3 : Inscription parent
|
||||
|
||||
@@ -177,10 +177,12 @@
|
||||
</div>
|
||||
<div class="info-section">
|
||||
<div class="info-title">Profession</div>
|
||||
<p><strong>Agrément :</strong> 4 enfants max</p>
|
||||
<p><strong>Agrément :</strong> 4 enfants max (n° AGR-2019-095001, depuis le 01/09/2019)</p>
|
||||
<p><strong>Expérience :</strong> 12 ans</p>
|
||||
<p><strong>Spécialité :</strong> Bébés 0-18 mois</p>
|
||||
<p><strong>Places disponibles :</strong> 2</p>
|
||||
<p><strong>NIR (test, fictif) :</strong> 280062A00100191</p>
|
||||
<p><strong>Lieu de naissance :</strong> Ajaccio (Corse)</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -207,10 +209,12 @@
|
||||
</div>
|
||||
<div class="info-section">
|
||||
<div class="info-title">Profession</div>
|
||||
<p><strong>Agrément :</strong> 3 enfants max</p>
|
||||
<p><strong>Agrément :</strong> 3 enfants max (n° AGR-2017-095002, depuis le 15/06/2017)</p>
|
||||
<p><strong>Expérience :</strong> 15 ans</p>
|
||||
<p><strong>Spécialité :</strong> Enfants 1-3 ans</p>
|
||||
<p><strong>Places disponibles :</strong> 1</p>
|
||||
<p><strong>NIR (test, fictif) :</strong> 275119900100102</p>
|
||||
<p><strong>Lieu de naissance :</strong> à l'étranger (ex. Casablanca, Maroc — inscription)</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 157 KiB |
@@ -20,7 +20,11 @@ import '../screens/auth/am_register_step3_screen.dart';
|
||||
import '../screens/auth/am_register_step4_screen.dart';
|
||||
import '../screens/home/home_screen.dart';
|
||||
import '../screens/administrateurs/admin_dashboardScreen.dart';
|
||||
import '../screens/gestionnaire/gestionnaire_dashboard_screen.dart';
|
||||
import '../screens/home/parent_screen/ParentDashboardScreen.dart';
|
||||
import '../screens/am/am_dashboard_screen.dart';
|
||||
import '../screens/legal/privacy_page.dart';
|
||||
import '../screens/legal/legal_page.dart';
|
||||
import '../screens/unknown_screen.dart';
|
||||
|
||||
// --- Provider Instances ---
|
||||
@@ -53,13 +57,26 @@ class AppRouter {
|
||||
path: '/admin-dashboard',
|
||||
builder: (BuildContext context, GoRouterState state) => const AdminDashboardScreen(),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/gestionnaire-dashboard',
|
||||
builder: (BuildContext context, GoRouterState state) => const GestionnaireDashboardScreen(),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/parent-dashboard',
|
||||
builder: (BuildContext context, GoRouterState state) => const ParentDashboardScreen(),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/am-dashboard',
|
||||
builder: (BuildContext context, GoRouterState state) => const HomeScreen(),
|
||||
builder: (BuildContext context, GoRouterState state) =>
|
||||
const AmDashboardScreen(),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/privacy',
|
||||
builder: (BuildContext context, GoRouterState state) => const PrivacyPage(),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/legal',
|
||||
builder: (BuildContext context, GoRouterState state) => const LegalPage(),
|
||||
),
|
||||
|
||||
// --- Parent Registration Flow ---
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
/// Accueil simultané : plafond légal courant en France pour une AM agréée (enfants de moins de 3 ans).
|
||||
const int kAmCapaciteAccueilMax = 4;
|
||||
|
||||
class AmRegistrationData extends ChangeNotifier {
|
||||
// Step 1: Identity Info
|
||||
String firstName = '';
|
||||
@@ -14,7 +17,9 @@ class AmRegistrationData extends ChangeNotifier {
|
||||
// bool photoConsent = false; // Déplacé ou géré à l'étape 2
|
||||
|
||||
// Step 2: Professional Info
|
||||
String? photoPath; // Ajouté pour l'étape 2
|
||||
String? photoPath; // Chemin fichier local (hors web) si pas d’octets en mémoire
|
||||
Uint8List? photoBytes; // Galerie / web (ImagePicker)
|
||||
String? photoFilename; // Nom pour l’API (ex. image.jpg)
|
||||
bool photoConsent = false; // Ajouté pour l'étape 2
|
||||
DateTime? dateOfBirth;
|
||||
String birthCity = ''; // Nouveau
|
||||
@@ -22,7 +27,11 @@ class AmRegistrationData extends ChangeNotifier {
|
||||
// String placeOfBirth = ''; // Remplacé par birthCity et birthCountry
|
||||
String nir = ''; // Numéro de Sécurité Sociale
|
||||
String agrementNumber = ''; // Numéro d'agrément
|
||||
/// Date d'obtention de l'agrément — obligatoire (API `date_agrement`).
|
||||
DateTime? agreementDate;
|
||||
int? capacity; // Number of children the AM can look after
|
||||
/// Places libres actuellement (0 ≤ valeur ≤ capacité) — API `places_disponibles`.
|
||||
int? placesAvailable;
|
||||
|
||||
// Step 3: Presentation & CGU
|
||||
String presentationText = '';
|
||||
@@ -57,6 +66,8 @@ class AmRegistrationData extends ChangeNotifier {
|
||||
|
||||
void updateProfessionalInfo({
|
||||
String? photoPath,
|
||||
Uint8List? photoBytes,
|
||||
String? photoFilename,
|
||||
bool? photoConsent,
|
||||
DateTime? dateOfBirth,
|
||||
String? birthCity, // Nouveau
|
||||
@@ -64,12 +75,13 @@ class AmRegistrationData extends ChangeNotifier {
|
||||
// String? placeOfBirth, // Remplacé
|
||||
String? nir,
|
||||
String? agrementNumber,
|
||||
DateTime? agreementDate,
|
||||
int? capacity,
|
||||
int? placesAvailable,
|
||||
}) {
|
||||
// Allow setting photoPath to null explicitly
|
||||
if (photoPath != null || this.photoPath != null) {
|
||||
this.photoPath = photoPath;
|
||||
}
|
||||
this.photoPath = photoPath;
|
||||
this.photoBytes = photoBytes;
|
||||
this.photoFilename = photoFilename;
|
||||
this.photoConsent = photoConsent ?? this.photoConsent;
|
||||
this.dateOfBirth = dateOfBirth ?? this.dateOfBirth;
|
||||
this.birthCity = birthCity ?? this.birthCity; // Nouveau
|
||||
@@ -77,7 +89,9 @@ class AmRegistrationData extends ChangeNotifier {
|
||||
// this.placeOfBirth = placeOfBirth ?? this.placeOfBirth; // Remplacé
|
||||
this.nir = nir ?? this.nir;
|
||||
this.agrementNumber = agrementNumber ?? this.agrementNumber;
|
||||
this.agreementDate = agreementDate ?? this.agreementDate;
|
||||
this.capacity = capacity ?? this.capacity;
|
||||
this.placesAvailable = placesAvailable ?? this.placesAvailable;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@@ -92,27 +106,37 @@ class AmRegistrationData extends ChangeNotifier {
|
||||
|
||||
// --- Getters for validation or display ---
|
||||
bool get isStep1Complete =>
|
||||
firstName.isNotEmpty &&
|
||||
lastName.isNotEmpty &&
|
||||
streetAddress.isNotEmpty && // Modifié
|
||||
postalCode.isNotEmpty && // Nouveau
|
||||
city.isNotEmpty && // Nouveau
|
||||
firstName.trim().length >= 2 &&
|
||||
lastName.trim().length >= 2 &&
|
||||
streetAddress.isNotEmpty &&
|
||||
postalCode.isNotEmpty &&
|
||||
city.isNotEmpty &&
|
||||
phone.isNotEmpty &&
|
||||
email.isNotEmpty;
|
||||
// password n'est pas requis à l'inscription (défini après validation par lien email)
|
||||
|
||||
/// Photo réelle (pas seulement un placeholder asset).
|
||||
bool get _hasUserPhoto =>
|
||||
(photoBytes != null && photoBytes!.isNotEmpty) ||
|
||||
(photoPath != null &&
|
||||
photoPath!.isNotEmpty &&
|
||||
!photoPath!.startsWith('assets/'));
|
||||
|
||||
bool get isStep2Complete =>
|
||||
// photoConsent is mandatory if a photo is system-required, otherwise optional.
|
||||
// For now, let's assume if photoPath is present, consent should ideally be true.
|
||||
// Or, make consent always mandatory if photo section exists.
|
||||
// Based on new mockup, photo is present, so consent might be implicitly or explicitly needed.
|
||||
(photoPath != null ? photoConsent == true : true) && // Ajuster selon la logique de consentement désirée
|
||||
_hasUserPhoto &&
|
||||
photoConsent == true &&
|
||||
dateOfBirth != null &&
|
||||
birthCity.isNotEmpty &&
|
||||
birthCountry.isNotEmpty &&
|
||||
nir.isNotEmpty && // Basic check, could add validation
|
||||
birthCity.trim().length >= 2 &&
|
||||
birthCountry.trim().length >= 2 &&
|
||||
nir.isNotEmpty &&
|
||||
agrementNumber.isNotEmpty &&
|
||||
capacity != null && capacity! > 0;
|
||||
agreementDate != null &&
|
||||
capacity != null &&
|
||||
capacity! >= 1 &&
|
||||
capacity! <= kAmCapaciteAccueilMax &&
|
||||
placesAvailable != null &&
|
||||
placesAvailable! >= 0 &&
|
||||
placesAvailable! <= capacity!;
|
||||
|
||||
bool get isStep3Complete =>
|
||||
// presentationText is optional as per CDC (message au gestionnaire)
|
||||
@@ -129,7 +153,7 @@ class AmRegistrationData extends ChangeNotifier {
|
||||
'phone: $phone, email: $email, '
|
||||
// 'photoPath: $photoPath, photoConsent: $photoConsent, ' // Commenté car déplacé/modifié
|
||||
'dateOfBirth: $dateOfBirth, birthCity: $birthCity, birthCountry: $birthCountry, '
|
||||
'nir: $nir, agrementNumber: $agrementNumber, capacity: $capacity, '
|
||||
'nir: $nir, agrementNumber: $agrementNumber, agreementDate: $agreementDate, capacity: $capacity, placesAvailable: $placesAvailable, '
|
||||
'photoPath (step2): $photoPath, photoConsent (step2): $photoConsent, '
|
||||
'presentationText: $presentationText, cguAccepted: $cguAccepted)';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
import 'package:p_tits_pas/models/user.dart';
|
||||
|
||||
/// Réponse unifiée GET /dossiers/:numeroDossier. Ticket #119, #107.
|
||||
class DossierUnifie {
|
||||
final String type; // 'am' | 'family'
|
||||
final dynamic dossier; // DossierAM | DossierFamille
|
||||
|
||||
DossierUnifie({required this.type, required this.dossier});
|
||||
|
||||
bool get isAm => type == 'am';
|
||||
bool get isFamily => type == 'family';
|
||||
|
||||
DossierAM get asAm => dossier as DossierAM;
|
||||
DossierFamille get asFamily => dossier as DossierFamille;
|
||||
|
||||
factory DossierUnifie.fromJson(Map<String, dynamic> json) {
|
||||
final t = json['type'];
|
||||
final raw = t is String ? t : 'family';
|
||||
final typeStr = raw.toLowerCase();
|
||||
final d = json['dossier'];
|
||||
if (d == null || d is! Map<String, dynamic>) {
|
||||
throw FormatException('dossier manquant ou invalide');
|
||||
}
|
||||
final dossierMap = Map<String, dynamic>.from(d as Map);
|
||||
// Seul `am` (casse tolérée) charge le dossier AM ; le reste = famille (API : type "family").
|
||||
final isAm = typeStr == 'am';
|
||||
final dossier = isAm ? DossierAM.fromJson(dossierMap) : DossierFamille.fromJson(dossierMap);
|
||||
return DossierUnifie(type: isAm ? 'am' : 'family', dossier: dossier);
|
||||
}
|
||||
}
|
||||
|
||||
/// Dossier AM (type: 'am'). Champs alignés API.
|
||||
class DossierAM {
|
||||
final String? numeroDossier;
|
||||
final AppUser user;
|
||||
final String? numeroAgrement;
|
||||
final String? nir;
|
||||
final String? presentation;
|
||||
final String? dateAgrement;
|
||||
final int? nbMaxEnfants;
|
||||
final int? placesDisponibles;
|
||||
final String? villeResidence;
|
||||
|
||||
DossierAM({
|
||||
this.numeroDossier,
|
||||
required this.user,
|
||||
this.numeroAgrement,
|
||||
this.nir,
|
||||
this.presentation,
|
||||
this.dateAgrement,
|
||||
this.nbMaxEnfants,
|
||||
this.placesDisponibles,
|
||||
this.villeResidence,
|
||||
});
|
||||
|
||||
factory DossierAM.fromJson(Map<String, dynamic> json) {
|
||||
final userJson = json['user'];
|
||||
final userMap = userJson is Map<String, dynamic>
|
||||
? userJson
|
||||
: <String, dynamic>{};
|
||||
final nbMax = json['nb_max_enfants'];
|
||||
final places = json['place_disponible'];
|
||||
return DossierAM(
|
||||
numeroDossier: json['numero_dossier']?.toString(),
|
||||
user: AppUser.fromJson(Map<String, dynamic>.from(userMap)),
|
||||
numeroAgrement: json['numero_agrement']?.toString(),
|
||||
nir: json['nir']?.toString(),
|
||||
presentation: (json['biographie'] ?? json['presentation'])?.toString(),
|
||||
dateAgrement: json['date_agrement']?.toString(),
|
||||
nbMaxEnfants: nbMax is int ? nbMax : (nbMax is num ? nbMax.toInt() : null),
|
||||
placesDisponibles: places is int ? places : (places is num ? places.toInt() : null),
|
||||
villeResidence: json['ville_residence']?.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Dossier famille (type: 'family'). Champs alignés API.
|
||||
class DossierFamille {
|
||||
final String? numeroDossier;
|
||||
final List<ParentDossier> parents;
|
||||
final List<EnfantDossier> enfants;
|
||||
final String? presentation;
|
||||
|
||||
DossierFamille({
|
||||
this.numeroDossier,
|
||||
required this.parents,
|
||||
required this.enfants,
|
||||
this.presentation,
|
||||
});
|
||||
|
||||
factory DossierFamille.fromJson(Map<String, dynamic> json) {
|
||||
final parentsRaw = json['parents'];
|
||||
final parentsList = parentsRaw is List
|
||||
? (parentsRaw)
|
||||
.where((e) => e is Map)
|
||||
.map((e) => ParentDossier.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList()
|
||||
: <ParentDossier>[];
|
||||
final enfantsRaw = json['enfants'];
|
||||
final enfantsList = enfantsRaw is List
|
||||
? (enfantsRaw)
|
||||
.where((e) => e is Map)
|
||||
.map((e) => EnfantDossier.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList()
|
||||
: <EnfantDossier>[];
|
||||
return DossierFamille(
|
||||
numeroDossier: json['numero_dossier']?.toString(),
|
||||
parents: parentsList,
|
||||
enfants: enfantsList,
|
||||
presentation: (json['texte_motivation'] ??
|
||||
json['presentation'] ??
|
||||
json['presentation_dossier'] ??
|
||||
json['texteMotivation'] ??
|
||||
json['presentationDossier'])
|
||||
?.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
bool get isEnAttente =>
|
||||
parents.any((p) => p.statut == 'en_attente');
|
||||
}
|
||||
|
||||
/// Parent dans un dossier famille (champs user exposés).
|
||||
class ParentDossier {
|
||||
final String id;
|
||||
final String email;
|
||||
final String? prenom;
|
||||
final String? nom;
|
||||
final String? telephone;
|
||||
final String? adresse;
|
||||
final String? ville;
|
||||
final String? codePostal;
|
||||
final String? dateNaissance;
|
||||
final String? genre;
|
||||
final String? situationFamiliale;
|
||||
final String? creeLe;
|
||||
final String? statut;
|
||||
|
||||
ParentDossier({
|
||||
required this.id,
|
||||
required this.email,
|
||||
this.prenom,
|
||||
this.nom,
|
||||
this.telephone,
|
||||
this.adresse,
|
||||
this.ville,
|
||||
this.codePostal,
|
||||
this.dateNaissance,
|
||||
this.genre,
|
||||
this.situationFamiliale,
|
||||
this.creeLe,
|
||||
this.statut,
|
||||
});
|
||||
|
||||
String get fullName => '${prenom ?? ''} ${nom ?? ''}'.trim();
|
||||
|
||||
factory ParentDossier.fromJson(Map<String, dynamic> json) {
|
||||
return ParentDossier(
|
||||
id: json['user_id']?.toString() ?? json['id']?.toString() ?? '',
|
||||
email: json['email']?.toString() ?? '',
|
||||
prenom: json['prenom']?.toString(),
|
||||
nom: json['nom']?.toString(),
|
||||
telephone: json['telephone']?.toString(),
|
||||
adresse: json['adresse']?.toString(),
|
||||
ville: json['ville']?.toString(),
|
||||
codePostal: json['code_postal']?.toString(),
|
||||
dateNaissance: json['date_naissance']?.toString(),
|
||||
genre: json['genre']?.toString(),
|
||||
situationFamiliale: json['situation_familiale']?.toString(),
|
||||
creeLe: json['cree_le']?.toString(),
|
||||
statut: json['statut']?.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Enfant dans un dossier famille.
|
||||
class EnfantDossier {
|
||||
final String id;
|
||||
final String? firstName;
|
||||
final String? lastName;
|
||||
final String? birthDate;
|
||||
final String? gender;
|
||||
final String? status;
|
||||
final String? dueDate;
|
||||
final String? photoUrl;
|
||||
final bool consentPhoto;
|
||||
|
||||
EnfantDossier({
|
||||
required this.id,
|
||||
this.firstName,
|
||||
this.lastName,
|
||||
this.birthDate,
|
||||
this.gender,
|
||||
this.status,
|
||||
this.dueDate,
|
||||
this.photoUrl,
|
||||
this.consentPhoto = false,
|
||||
});
|
||||
|
||||
String get fullName => '${firstName ?? ''} ${lastName ?? ''}'.trim();
|
||||
|
||||
static String? _optionalPhotoUrl(dynamic v) {
|
||||
if (v == null) return null;
|
||||
if (v is String) {
|
||||
final s = v.trim();
|
||||
return s.isEmpty ? null : s;
|
||||
}
|
||||
final s = v.toString().trim();
|
||||
return s.isEmpty ? null : s;
|
||||
}
|
||||
|
||||
factory EnfantDossier.fromJson(Map<String, dynamic> json) {
|
||||
final rawPhoto = json['photo_url'] ?? json['photoUrl'];
|
||||
final resolvedPhoto = _optionalPhotoUrl(rawPhoto);
|
||||
return EnfantDossier(
|
||||
id: json['id']?.toString() ?? '',
|
||||
firstName: (json['first_name'] ?? json['prenom'])?.toString(),
|
||||
lastName: (json['last_name'] ?? json['nom'])?.toString(),
|
||||
birthDate: json['birth_date']?.toString(),
|
||||
gender: (json['gender'] ?? json['genre'])?.toString(),
|
||||
status: json['status']?.toString(),
|
||||
dueDate: json['due_date']?.toString(),
|
||||
photoUrl: resolvedPhoto,
|
||||
consentPhoto:
|
||||
json['consent_photo'] == true || json['consentPhoto'] == true,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
/// Résumé affichable pour un parent (liste pending-families).
|
||||
class PendingParentLine {
|
||||
final String? email;
|
||||
final String? telephone;
|
||||
final String? codePostal;
|
||||
final String? ville;
|
||||
|
||||
const PendingParentLine({
|
||||
this.email,
|
||||
this.telephone,
|
||||
this.codePostal,
|
||||
this.ville,
|
||||
});
|
||||
|
||||
bool get isEmpty {
|
||||
final e = email?.trim();
|
||||
final t = telephone?.trim();
|
||||
final loc = _locationTrimmed;
|
||||
return (e == null || e.isEmpty) &&
|
||||
(t == null || t.isEmpty) &&
|
||||
(loc == null || loc.isEmpty);
|
||||
}
|
||||
|
||||
String? get _locationTrimmed {
|
||||
final cp = codePostal?.trim();
|
||||
final v = ville?.trim();
|
||||
final loc = [if (cp != null && cp.isNotEmpty) cp, if (v != null && v.isNotEmpty) v]
|
||||
.join(' ')
|
||||
.trim();
|
||||
return loc.isEmpty ? null : loc;
|
||||
}
|
||||
}
|
||||
|
||||
/// Famille en attente de validation (GET /parents/pending-families). Ticket #107.
|
||||
///
|
||||
/// Contrat API : `libelle`, `parentIds`, `numero_dossier`, `date_soumission`,
|
||||
/// `nombre_enfants`, `emails`, éventuellement `parents` / tableaux parallèles.
|
||||
class PendingFamily {
|
||||
final String libelle;
|
||||
final List<String> parentIds;
|
||||
final String? numeroDossier;
|
||||
|
||||
/// Date affichée : `date_soumission` (ISO), sinon alias `cree_le` / etc.
|
||||
final DateTime? dateSoumission;
|
||||
|
||||
/// Emails seuls (API) — le sous-titre utilise de préférence [parentLines].
|
||||
final List<String> emails;
|
||||
|
||||
/// Une entrée par parent : email, tél., CP ville (si fournis par l’API).
|
||||
final List<PendingParentLine> parentLines;
|
||||
|
||||
final int nombreEnfants;
|
||||
|
||||
/// Compat : premier email.
|
||||
final String? email;
|
||||
|
||||
PendingFamily({
|
||||
required this.libelle,
|
||||
required this.parentIds,
|
||||
this.numeroDossier,
|
||||
this.dateSoumission,
|
||||
this.emails = const [],
|
||||
this.parentLines = const [],
|
||||
this.nombreEnfants = 0,
|
||||
this.email,
|
||||
});
|
||||
|
||||
static DateTime? _parseDate(dynamic v) {
|
||||
if (v == null) return null;
|
||||
if (v is DateTime) return v;
|
||||
if (v is String) {
|
||||
return DateTime.tryParse(v);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static List<String> _parseStringList(dynamic raw) {
|
||||
if (raw is! List) return [];
|
||||
return raw
|
||||
.map((e) => e?.toString().trim() ?? '')
|
||||
.where((s) => s.isNotEmpty)
|
||||
.toList();
|
||||
}
|
||||
|
||||
static List<PendingParentLine> _parseParentLinesFromMaps(dynamic raw) {
|
||||
if (raw is! List) return [];
|
||||
final out = <PendingParentLine>[];
|
||||
for (final e in raw) {
|
||||
if (e is! Map) continue;
|
||||
final m = Map<String, dynamic>.from(e);
|
||||
final em = m['email']?.toString().trim();
|
||||
final tel = m['telephone']?.toString().trim();
|
||||
final cp = (m['code_postal'] ?? m['codePostal'])?.toString().trim();
|
||||
final ville = m['ville']?.toString().trim();
|
||||
out.add(PendingParentLine(
|
||||
email: em != null && em.isNotEmpty ? em : null,
|
||||
telephone: tel != null && tel.isNotEmpty ? tel : null,
|
||||
codePostal: cp != null && cp.isNotEmpty ? cp : null,
|
||||
ville: ville != null && ville.isNotEmpty ? ville : null,
|
||||
));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Construit [parentLines] : objets `parents`, tableaux parallèles, ou emails + champs racine.
|
||||
static List<PendingParentLine> _buildParentLines(
|
||||
Map<String, dynamic> json,
|
||||
List<String> emails,
|
||||
) {
|
||||
final fromMaps = _parseParentLinesFromMaps(
|
||||
json['parents'] ?? json['resume_parents'] ?? json['parent_summaries'] ?? json['parent_lines'],
|
||||
);
|
||||
if (fromMaps.isNotEmpty) {
|
||||
return fromMaps;
|
||||
}
|
||||
|
||||
List<String>? parallel(dynamic keySingular, dynamic keyPlural) {
|
||||
final pl = json[keyPlural];
|
||||
if (pl is List) return _parseStringList(pl);
|
||||
final s = json[keySingular];
|
||||
if (s is String && s.trim().isNotEmpty) return [s.trim()];
|
||||
return null;
|
||||
}
|
||||
|
||||
final tels = parallel('telephone', 'telephones');
|
||||
final cps = parallel('code_postal', 'code_postaux') ?? parallel('codePostal', 'codes_postaux');
|
||||
final villes = parallel('ville', 'villes');
|
||||
|
||||
if (emails.isNotEmpty &&
|
||||
((tels?.isNotEmpty ?? false) ||
|
||||
(cps?.isNotEmpty ?? false) ||
|
||||
(villes?.isNotEmpty ?? false))) {
|
||||
return List.generate(emails.length, (i) {
|
||||
return PendingParentLine(
|
||||
email: emails[i],
|
||||
telephone: tels != null && i < tels.length ? tels[i] : null,
|
||||
codePostal: cps != null && i < cps.length ? cps[i] : null,
|
||||
ville: villes != null && i < villes.length ? villes[i] : null,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
final rootTel = json['telephone']?.toString().trim();
|
||||
final rootTelOk = rootTel != null && rootTel.isNotEmpty ? rootTel : null;
|
||||
final rootCp = (json['code_postal'] ?? json['codePostal'])?.toString().trim();
|
||||
final rootCpOk = rootCp != null && rootCp.isNotEmpty ? rootCp : null;
|
||||
final rootVille = json['ville']?.toString().trim();
|
||||
final rootVilleOk = rootVille != null && rootVille.isNotEmpty ? rootVille : null;
|
||||
|
||||
if (emails.isNotEmpty) {
|
||||
return List.generate(emails.length, (i) {
|
||||
return PendingParentLine(
|
||||
email: emails[i],
|
||||
telephone: i == 0 ? rootTelOk : null,
|
||||
codePostal: i == 0 ? rootCpOk : null,
|
||||
ville: i == 0 ? rootVilleOk : null,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
if (rootTelOk != null || rootCpOk != null || rootVilleOk != null) {
|
||||
final em = json['email']?.toString().trim();
|
||||
return [
|
||||
PendingParentLine(
|
||||
email: em != null && em.isNotEmpty ? em : null,
|
||||
telephone: rootTelOk,
|
||||
codePostal: rootCpOk,
|
||||
ville: rootVilleOk,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
factory PendingFamily.fromJson(Map<String, dynamic> json) {
|
||||
final parentIdsRaw = json['parentIds'] ?? json['parent_ids'];
|
||||
final List<String> ids = parentIdsRaw is List
|
||||
? (parentIdsRaw).map((e) => e?.toString() ?? '').where((s) => s.isNotEmpty).toList()
|
||||
: [];
|
||||
final libelle = json['libelle'];
|
||||
final libelleStr = libelle is String ? libelle : (libelle?.toString() ?? 'Famille');
|
||||
final nd = json['numero_dossier'] ?? json['numeroDossier'];
|
||||
final numeroDossier = (nd is String && nd.isNotEmpty) ? nd : null;
|
||||
|
||||
DateTime? dateSoumission = _parseDate(
|
||||
json['date_soumission'] ?? json['dateSoumission'],
|
||||
);
|
||||
dateSoumission ??= _parseDate(
|
||||
json['cree_le'] ?? json['creeLe'] ?? json['date_inscription'],
|
||||
);
|
||||
|
||||
List<String> emails = _parseStringList(json['emails']);
|
||||
if (emails.isEmpty) {
|
||||
final emailRaw = json['email'];
|
||||
if (emailRaw is String && emailRaw.trim().isNotEmpty) {
|
||||
emails = [emailRaw.trim()];
|
||||
}
|
||||
}
|
||||
final String? emailCompat = emails.isNotEmpty
|
||||
? emails.first
|
||||
: (json['email'] is String && (json['email'] as String).trim().isNotEmpty
|
||||
? (json['email'] as String).trim()
|
||||
: null);
|
||||
|
||||
final nbRaw = json['nombre_enfants'] ?? json['nombreEnfants'];
|
||||
int nombreEnfants = 0;
|
||||
if (nbRaw is int) {
|
||||
nombreEnfants = nbRaw;
|
||||
} else if (nbRaw is num) {
|
||||
nombreEnfants = nbRaw.toInt();
|
||||
} else if (nbRaw != null) {
|
||||
nombreEnfants = int.tryParse(nbRaw.toString()) ?? 0;
|
||||
}
|
||||
|
||||
var parentLines = _buildParentLines(json, emails);
|
||||
if (parentLines.isEmpty && emails.isNotEmpty) {
|
||||
parentLines = emails.map((e) => PendingParentLine(email: e)).toList();
|
||||
}
|
||||
|
||||
return PendingFamily(
|
||||
libelle: libelleStr.isEmpty ? 'Famille' : libelleStr,
|
||||
parentIds: ids,
|
||||
numeroDossier: numeroDossier,
|
||||
dateSoumission: dateSoumission,
|
||||
emails: emails,
|
||||
parentLines: parentLines,
|
||||
nombreEnfants: nombreEnfants,
|
||||
email: emailCompat,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
class RelaisModel {
|
||||
final String id;
|
||||
final String nom;
|
||||
final String adresse;
|
||||
final Map<String, dynamic>? horairesOuverture;
|
||||
final String? ligneFixe;
|
||||
final bool actif;
|
||||
final String? notes;
|
||||
|
||||
const RelaisModel({
|
||||
required this.id,
|
||||
required this.nom,
|
||||
required this.adresse,
|
||||
this.horairesOuverture,
|
||||
this.ligneFixe,
|
||||
required this.actif,
|
||||
this.notes,
|
||||
});
|
||||
|
||||
factory RelaisModel.fromJson(Map<String, dynamic> json) {
|
||||
return RelaisModel(
|
||||
id: (json['id'] ?? '').toString(),
|
||||
nom: (json['nom'] ?? '').toString(),
|
||||
adresse: (json['adresse'] ?? '').toString(),
|
||||
horairesOuverture: json['horaires_ouverture'] is Map<String, dynamic>
|
||||
? json['horaires_ouverture'] as Map<String, dynamic>
|
||||
: null,
|
||||
ligneFixe: json['ligne_fixe'] as String?,
|
||||
actif: json['actif'] as bool? ?? true,
|
||||
notes: json['notes'] as String?,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,12 @@ class AppUser {
|
||||
final String? adresse;
|
||||
final String? ville;
|
||||
final String? codePostal;
|
||||
final String? relaisId;
|
||||
final String? relaisNom;
|
||||
final String? numeroDossier;
|
||||
final String? dateNaissance;
|
||||
final String? lieuNaissanceVille;
|
||||
final String? lieuNaissancePays;
|
||||
|
||||
AppUser({
|
||||
required this.id,
|
||||
@@ -29,48 +35,73 @@ class AppUser {
|
||||
this.adresse,
|
||||
this.ville,
|
||||
this.codePostal,
|
||||
this.relaisId,
|
||||
this.relaisNom,
|
||||
this.numeroDossier,
|
||||
this.dateNaissance,
|
||||
this.lieuNaissanceVille,
|
||||
this.lieuNaissancePays,
|
||||
});
|
||||
|
||||
static String _str(dynamic v) {
|
||||
if (v == null) return '';
|
||||
if (v is String) return v;
|
||||
return v.toString();
|
||||
}
|
||||
|
||||
static DateTime _date(dynamic v) {
|
||||
if (v == null) return DateTime.now();
|
||||
if (v is DateTime) return v;
|
||||
try {
|
||||
return DateTime.parse(v.toString());
|
||||
} catch (_) {
|
||||
return DateTime.now();
|
||||
}
|
||||
}
|
||||
|
||||
factory AppUser.fromJson(Map<String, dynamic> json) {
|
||||
final id = json['id']?.toString();
|
||||
final email = json['email']?.toString();
|
||||
final role = json['role']?.toString();
|
||||
if (id == null || id.isEmpty) {
|
||||
throw Exception('Profil invalide: id manquant');
|
||||
}
|
||||
if (email == null || email.isEmpty) {
|
||||
throw Exception('Profil invalide: email manquant');
|
||||
}
|
||||
if (role == null || role.isEmpty) {
|
||||
throw Exception('Profil invalide: rôle manquant');
|
||||
}
|
||||
final relaisJson = json['relais'];
|
||||
final relaisMap =
|
||||
relaisJson is Map<String, dynamic> ? relaisJson : <String, dynamic>{};
|
||||
|
||||
return AppUser(
|
||||
id: id,
|
||||
email: email,
|
||||
role: role,
|
||||
createdAt: json['cree_le'] != null
|
||||
? DateTime.tryParse(json['cree_le'].toString()) ?? DateTime.now()
|
||||
: (json['createdAt'] != null
|
||||
? DateTime.tryParse(json['createdAt'].toString()) ?? DateTime.now()
|
||||
: DateTime.now()),
|
||||
updatedAt: json['modifie_le'] != null
|
||||
? DateTime.tryParse(json['modifie_le'].toString()) ?? DateTime.now()
|
||||
: (json['updatedAt'] != null
|
||||
? DateTime.tryParse(json['updatedAt'].toString()) ?? DateTime.now()
|
||||
: DateTime.now()),
|
||||
id: _str(json['id']),
|
||||
email: _str(json['email']),
|
||||
role: _str(json['role']),
|
||||
createdAt: _date(json['cree_le'] ?? json['createdAt']),
|
||||
updatedAt: _date(json['modifie_le'] ?? json['updatedAt']),
|
||||
changementMdpObligatoire:
|
||||
json['changement_mdp_obligatoire'] == true,
|
||||
nom: json['nom']?.toString(),
|
||||
prenom: json['prenom']?.toString(),
|
||||
statut: json['statut']?.toString(),
|
||||
telephone: json['telephone']?.toString(),
|
||||
photoUrl: json['photo_url']?.toString(),
|
||||
adresse: json['adresse']?.toString(),
|
||||
ville: json['ville']?.toString(),
|
||||
codePostal: json['code_postal']?.toString(),
|
||||
nom: json['nom'] is String ? json['nom'] as String : null,
|
||||
prenom: json['prenom'] is String ? json['prenom'] as String : null,
|
||||
statut: json['statut'] is String ? json['statut'] as String : null,
|
||||
telephone: json['telephone'] is String ? json['telephone'] as String : null,
|
||||
photoUrl: json['photo_url'] is String ? json['photo_url'] as String : null,
|
||||
adresse: json['adresse'] is String ? json['adresse'] as String : null,
|
||||
ville: json['ville'] is String ? json['ville'] as String : null,
|
||||
codePostal: json['code_postal'] is String ? json['code_postal'] as String : null,
|
||||
relaisId: (json['relaisId'] ?? json['relais_id'] ?? relaisMap['id'])
|
||||
?.toString(),
|
||||
relaisNom: relaisMap['nom']?.toString(),
|
||||
numeroDossier: json['numero_dossier'] is String ? json['numero_dossier'] as String : null,
|
||||
dateNaissance: _optionalDateString(json['date_naissance']),
|
||||
lieuNaissanceVille: json['lieu_naissance_ville'] is String
|
||||
? json['lieu_naissance_ville'] as String
|
||||
: null,
|
||||
lieuNaissancePays: json['lieu_naissance_pays'] is String
|
||||
? json['lieu_naissance_pays'] as String
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
static String? _optionalDateString(dynamic v) {
|
||||
if (v == null) return null;
|
||||
if (v is String) return v.isEmpty ? null : v;
|
||||
if (v is DateTime) return v.toIso8601String().split('T').first;
|
||||
final s = v.toString();
|
||||
return s.isEmpty ? null : s;
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
@@ -87,6 +118,12 @@ class AppUser {
|
||||
'adresse': adresse,
|
||||
'ville': ville,
|
||||
'code_postal': codePostal,
|
||||
'relais_id': relaisId,
|
||||
'relais_nom': relaisNom,
|
||||
'numero_dossier': numeroDossier,
|
||||
'date_naissance': dateNaissance,
|
||||
'lieu_naissance_ville': lieuNaissanceVille,
|
||||
'lieu_naissance_pays': lieuNaissancePays,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import 'dart:io'; // Pour File
|
||||
import '../models/card_assets.dart'; // Import de l'enum CardColorVertical
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
// import 'package:p_tits_pas/models/child.dart'; // Commenté car fichier non trouvé
|
||||
|
||||
class ParentData {
|
||||
@@ -29,25 +28,61 @@ class ParentData {
|
||||
}
|
||||
|
||||
class ChildData {
|
||||
static const Object _unsetImage = Object();
|
||||
static const Object _unsetImageBytes = Object();
|
||||
|
||||
String firstName;
|
||||
String lastName;
|
||||
String dob; // Date de naissance ou prévisionnelle
|
||||
/// Valeurs API : `H`, `F`, `Autre` (GenreType backend). Vide tant que non choisi.
|
||||
String genre;
|
||||
bool photoConsent;
|
||||
bool multipleBirth;
|
||||
bool isUnbornChild;
|
||||
File? imageFile;
|
||||
/// Octets de la photo (fiable à l’envoi API ; [imageFile] peut être absent sur le web).
|
||||
Uint8List? imageBytes;
|
||||
CardColorVertical cardColor; // Nouveau champ pour la couleur de la carte
|
||||
|
||||
ChildData({
|
||||
this.firstName = '',
|
||||
this.lastName = '',
|
||||
this.dob = '',
|
||||
this.genre = '',
|
||||
this.photoConsent = false,
|
||||
this.multipleBirth = false,
|
||||
this.isUnbornChild = false,
|
||||
this.imageFile,
|
||||
this.imageBytes,
|
||||
required this.cardColor, // Rendre requis dans le constructeur
|
||||
});
|
||||
|
||||
ChildData copyWith({
|
||||
String? firstName,
|
||||
String? lastName,
|
||||
String? dob,
|
||||
String? genre,
|
||||
bool? photoConsent,
|
||||
bool? multipleBirth,
|
||||
bool? isUnbornChild,
|
||||
Object? imageFile = _unsetImage,
|
||||
Object? imageBytes = _unsetImageBytes,
|
||||
CardColorVertical? cardColor,
|
||||
}) {
|
||||
return ChildData(
|
||||
firstName: firstName ?? this.firstName,
|
||||
lastName: lastName ?? this.lastName,
|
||||
dob: dob ?? this.dob,
|
||||
genre: genre ?? this.genre,
|
||||
photoConsent: photoConsent ?? this.photoConsent,
|
||||
multipleBirth: multipleBirth ?? this.multipleBirth,
|
||||
isUnbornChild: isUnbornChild ?? this.isUnbornChild,
|
||||
imageFile: identical(imageFile, _unsetImage) ? this.imageFile : imageFile as File?,
|
||||
imageBytes:
|
||||
identical(imageBytes, _unsetImageBytes) ? this.imageBytes : imageBytes as Uint8List?,
|
||||
cardColor: cardColor ?? this.cardColor,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Nouvelle classe pour les détails bancaires
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:p_tits_pas/models/user.dart';
|
||||
import 'package:p_tits_pas/services/auth_service.dart';
|
||||
import 'package:p_tits_pas/services/configuration_service.dart';
|
||||
import 'package:p_tits_pas/widgets/admin/assistante_maternelle_management_widget.dart';
|
||||
import 'package:p_tits_pas/widgets/admin/gestionnaire_management_widget.dart';
|
||||
import 'package:p_tits_pas/widgets/admin/parent_managmant_widget.dart';
|
||||
import 'package:p_tits_pas/widgets/admin/admin_management_widget.dart';
|
||||
import 'package:p_tits_pas/widgets/admin/parametres_panel.dart';
|
||||
import 'package:p_tits_pas/widgets/app_footer.dart';
|
||||
import 'package:p_tits_pas/widgets/admin/dashboard_admin.dart';
|
||||
import 'package:p_tits_pas/widgets/admin/parametres_panel.dart';
|
||||
import 'package:p_tits_pas/widgets/admin/user_management_panel.dart';
|
||||
import 'package:p_tits_pas/widgets/app_footer.dart';
|
||||
import 'package:p_tits_pas/widgets/dashboard/dashboard_bandeau.dart';
|
||||
|
||||
class AdminDashboardScreen extends StatefulWidget {
|
||||
const AdminDashboardScreen({super.key});
|
||||
@@ -17,8 +17,9 @@ class AdminDashboardScreen extends StatefulWidget {
|
||||
|
||||
class _AdminDashboardScreenState extends State<AdminDashboardScreen> {
|
||||
bool? _setupCompleted;
|
||||
AppUser? _user;
|
||||
int mainTabIndex = 0;
|
||||
int subIndex = 0;
|
||||
int settingsSubIndex = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -26,19 +27,28 @@ class _AdminDashboardScreenState extends State<AdminDashboardScreen> {
|
||||
_loadSetupStatus();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadSetupStatus() async {
|
||||
try {
|
||||
final completed = await ConfigurationService.getSetupStatus();
|
||||
final user = await AuthService.getCurrentUser();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_setupCompleted = completed;
|
||||
_user = user;
|
||||
if (!completed) mainTabIndex = 1;
|
||||
});
|
||||
} catch (e) {
|
||||
if (mounted) setState(() {
|
||||
_setupCompleted = false;
|
||||
mainTabIndex = 1;
|
||||
});
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_setupCompleted = false;
|
||||
mainTabIndex = 1;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,9 +58,9 @@ class _AdminDashboardScreenState extends State<AdminDashboardScreen> {
|
||||
});
|
||||
}
|
||||
|
||||
void onSubTabChange(int index) {
|
||||
void onSettingsSubTabChange(int index) {
|
||||
setState(() {
|
||||
subIndex = index;
|
||||
settingsSubIndex = index;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -64,25 +74,39 @@ class _AdminDashboardScreenState extends State<AdminDashboardScreen> {
|
||||
return Scaffold(
|
||||
appBar: PreferredSize(
|
||||
preferredSize: const Size.fromHeight(60.0),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
border: Border(
|
||||
bottom: BorderSide(color: Colors.grey.shade300),
|
||||
child: DashboardBandeau(
|
||||
tabItems: [
|
||||
DashboardTabItem(
|
||||
label: 'Gestion des utilisateurs',
|
||||
enabled: _setupCompleted!,
|
||||
),
|
||||
),
|
||||
child: DashboardAppBarAdmin(
|
||||
selectedIndex: mainTabIndex,
|
||||
onTabChange: onMainTabChange,
|
||||
setupCompleted: _setupCompleted!,
|
||||
),
|
||||
const DashboardTabItem(label: 'Paramètres'),
|
||||
],
|
||||
selectedTabIndex: mainTabIndex,
|
||||
onTabSelected: onMainTabChange,
|
||||
userDisplayName: _user?.fullName.isNotEmpty == true
|
||||
? _user!.fullName
|
||||
: 'Admin',
|
||||
userEmail: _user?.email,
|
||||
userRole: _user?.role,
|
||||
onProfileTap: () {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Modification du profil – à venir')),
|
||||
);
|
||||
},
|
||||
onSettingsTap: () => onMainTabChange(1),
|
||||
onLogout: () {},
|
||||
showLogoutConfirmation: true,
|
||||
),
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
if (mainTabIndex == 0)
|
||||
DashboardUserManagementSubBar(
|
||||
selectedSubIndex: subIndex,
|
||||
onSubTabChange: onSubTabChange,
|
||||
const SizedBox.shrink()
|
||||
else
|
||||
DashboardSettingsSubBar(
|
||||
selectedSubIndex: settingsSubIndex,
|
||||
onSubTabChange: onSettingsSubTabChange,
|
||||
),
|
||||
Expanded(
|
||||
child: _getBody(),
|
||||
@@ -95,19 +119,11 @@ class _AdminDashboardScreenState extends State<AdminDashboardScreen> {
|
||||
|
||||
Widget _getBody() {
|
||||
if (mainTabIndex == 1) {
|
||||
return ParametresPanel(redirectToLoginAfterSave: !_setupCompleted!);
|
||||
}
|
||||
switch (subIndex) {
|
||||
case 0:
|
||||
return const GestionnaireManagementWidget();
|
||||
case 1:
|
||||
return const ParentManagementWidget();
|
||||
case 2:
|
||||
return const AssistanteMaternelleManagementWidget();
|
||||
case 3:
|
||||
return const AdminManagementWidget();
|
||||
default:
|
||||
return const Center(child: Text('Page non trouvée'));
|
||||
return ParametresPanel(
|
||||
redirectToLoginAfterSave: !_setupCompleted!,
|
||||
selectedSettingsTabIndex: settingsSubIndex,
|
||||
);
|
||||
}
|
||||
return const UserManagementPanel();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:p_tits_pas/utils/phone_utils.dart';
|
||||
import 'package:p_tits_pas/models/user.dart';
|
||||
import 'package:p_tits_pas/services/user_service.dart';
|
||||
import 'package:p_tits_pas/utils/email_utils.dart';
|
||||
import 'package:p_tits_pas/widgets/email_text_field.dart';
|
||||
import 'package:p_tits_pas/widgets/french_phone_field.dart';
|
||||
|
||||
class AdminCreateDialog extends StatefulWidget {
|
||||
final AppUser? initialUser;
|
||||
|
||||
const AdminCreateDialog({
|
||||
super.key,
|
||||
this.initialUser,
|
||||
});
|
||||
|
||||
@override
|
||||
State<AdminCreateDialog> createState() => _AdminCreateDialogState();
|
||||
}
|
||||
|
||||
class _AdminCreateDialogState extends State<AdminCreateDialog> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _nomController = TextEditingController();
|
||||
final _prenomController = TextEditingController();
|
||||
final _emailController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
final _telephoneController = TextEditingController();
|
||||
|
||||
bool _isSubmitting = false;
|
||||
bool _obscurePassword = true;
|
||||
bool get _isEditMode => widget.initialUser != null;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final user = widget.initialUser;
|
||||
if (user != null) {
|
||||
_nomController.text = user.nom ?? '';
|
||||
_prenomController.text = user.prenom ?? '';
|
||||
_emailController.text = user.email;
|
||||
_telephoneController.text = formatPhoneForDisplay(user.telephone ?? '');
|
||||
// En édition, on ne préremplit jamais le mot de passe.
|
||||
_passwordController.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nomController.dispose();
|
||||
_prenomController.dispose();
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
_telephoneController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String? _required(String? value, String field) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return '$field est requis';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String? _validateEmail(String? value) {
|
||||
final base = _required(value, 'Email');
|
||||
if (base != null) {
|
||||
return base;
|
||||
}
|
||||
return validateEmail(value, allowEmpty: true);
|
||||
}
|
||||
|
||||
String? _validatePassword(String? value) {
|
||||
if (_isEditMode && (value == null || value.trim().isEmpty)) {
|
||||
return null;
|
||||
}
|
||||
final base = _required(value, 'Mot de passe');
|
||||
if (base != null) return base;
|
||||
if (value!.trim().length < 6) return 'Minimum 6 caractères';
|
||||
return null;
|
||||
}
|
||||
|
||||
String? _validateTelephone(String? value) {
|
||||
if (_isEditMode && (value == null || value.trim().isEmpty)) {
|
||||
return null;
|
||||
}
|
||||
final base = _required(value, 'Téléphone');
|
||||
if (base != null) {
|
||||
return base;
|
||||
}
|
||||
return validateFrenchNationalPhone(value, allowEmpty: false);
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
if (_isSubmitting) return;
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
|
||||
setState(() {
|
||||
_isSubmitting = true;
|
||||
});
|
||||
|
||||
try {
|
||||
if (_isEditMode) {
|
||||
await UserService.updateAdmin(
|
||||
adminId: widget.initialUser!.id,
|
||||
nom: _nomController.text.trim(),
|
||||
prenom: _prenomController.text.trim(),
|
||||
email: _emailController.text.trim(),
|
||||
telephone: normalizePhone(_telephoneController.text),
|
||||
password: _passwordController.text.trim().isEmpty
|
||||
? null
|
||||
: _passwordController.text,
|
||||
);
|
||||
} else {
|
||||
await UserService.createAdmin(
|
||||
nom: _nomController.text.trim(),
|
||||
prenom: _prenomController.text.trim(),
|
||||
email: _emailController.text.trim(),
|
||||
password: _passwordController.text,
|
||||
telephone: normalizePhone(_telephoneController.text),
|
||||
);
|
||||
}
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
_isEditMode
|
||||
? 'Administrateur modifié avec succès.'
|
||||
: 'Administrateur créé avec succès.',
|
||||
),
|
||||
),
|
||||
);
|
||||
Navigator.of(context).pop(true);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
e.toString().replaceFirst('Exception: ', ''),
|
||||
),
|
||||
backgroundColor: Colors.red.shade700,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_isSubmitting = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _delete() async {
|
||||
if (!_isEditMode || _isSubmitting) return;
|
||||
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) {
|
||||
return AlertDialog(
|
||||
title: const Text('Confirmer la suppression'),
|
||||
content: Text(
|
||||
'Supprimer ${widget.initialUser!.fullName.isEmpty ? widget.initialUser!.email : widget.initialUser!.fullName} ?',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(false),
|
||||
child: const Text('Annuler'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(true),
|
||||
style: FilledButton.styleFrom(backgroundColor: Colors.red.shade700),
|
||||
child: const Text('Supprimer'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
if (confirmed != true) return;
|
||||
|
||||
setState(() {
|
||||
_isSubmitting = true;
|
||||
});
|
||||
try {
|
||||
await UserService.deleteUser(widget.initialUser!.id);
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Administrateur supprimé.')),
|
||||
);
|
||||
Navigator.of(context).pop(true);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(e.toString().replaceFirst('Exception: ', '')),
|
||||
backgroundColor: Colors.red.shade700,
|
||||
),
|
||||
);
|
||||
setState(() {
|
||||
_isSubmitting = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
_isEditMode
|
||||
? 'Modifier un administrateur'
|
||||
: 'Créer un administrateur',
|
||||
),
|
||||
),
|
||||
if (_isEditMode)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
tooltip: 'Fermer',
|
||||
onPressed: _isSubmitting
|
||||
? null
|
||||
: () => Navigator.of(context).pop(false),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: SizedBox(
|
||||
width: 620,
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: _buildNomField()),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: _buildPrenomField()),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_buildEmailField(),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: _buildPasswordField()),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: _buildTelephoneField()),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
if (_isEditMode) ...[
|
||||
OutlinedButton(
|
||||
onPressed: _isSubmitting ? null : _delete,
|
||||
style: OutlinedButton.styleFrom(foregroundColor: Colors.red.shade700),
|
||||
child: const Text('Supprimer'),
|
||||
),
|
||||
FilledButton.icon(
|
||||
onPressed: _isSubmitting ? null : _submit,
|
||||
icon: _isSubmitting
|
||||
? const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.edit),
|
||||
label: Text(_isSubmitting ? 'Modification...' : 'Modifier'),
|
||||
),
|
||||
] else ...[
|
||||
OutlinedButton(
|
||||
onPressed:
|
||||
_isSubmitting ? null : () => Navigator.of(context).pop(false),
|
||||
child: const Text('Annuler'),
|
||||
),
|
||||
FilledButton.icon(
|
||||
onPressed: _isSubmitting ? null : _submit,
|
||||
icon: _isSubmitting
|
||||
? const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.person_add_alt_1),
|
||||
label: Text(_isSubmitting ? 'Création...' : 'Créer'),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildNomField() {
|
||||
return TextFormField(
|
||||
controller: _nomController,
|
||||
textCapitalization: TextCapitalization.words,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nom',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (v) => _required(v, 'Nom'),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPrenomField() {
|
||||
return TextFormField(
|
||||
controller: _prenomController,
|
||||
textCapitalization: TextCapitalization.words,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Prénom',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (v) => _required(v, 'Prénom'),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEmailField() {
|
||||
return EmailTextFormField(
|
||||
controller: _emailController,
|
||||
label: 'Email',
|
||||
validator: _validateEmail,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPasswordField() {
|
||||
return TextFormField(
|
||||
controller: _passwordController,
|
||||
obscureText: _obscurePassword,
|
||||
enableSuggestions: false,
|
||||
autocorrect: false,
|
||||
autofillHints: _isEditMode
|
||||
? const <String>[]
|
||||
: const [AutofillHints.newPassword],
|
||||
decoration: InputDecoration(
|
||||
labelText: _isEditMode
|
||||
? 'Nouveau mot de passe'
|
||||
: 'Mot de passe',
|
||||
border: const OutlineInputBorder(),
|
||||
suffixIcon: IconButton(
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_obscurePassword = !_obscurePassword;
|
||||
});
|
||||
},
|
||||
icon: Icon(
|
||||
_obscurePassword ? Icons.visibility_off : Icons.visibility,
|
||||
),
|
||||
),
|
||||
),
|
||||
validator: _validatePassword,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTelephoneField() {
|
||||
return FrenchPhoneTextFormField(
|
||||
controller: _telephoneController,
|
||||
label: 'Téléphone (ex: 06 12 34 56 78)',
|
||||
validator: _validateTelephone,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,630 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:p_tits_pas/models/relais_model.dart';
|
||||
import 'package:p_tits_pas/utils/phone_utils.dart';
|
||||
import 'package:p_tits_pas/utils/email_utils.dart';
|
||||
import 'package:p_tits_pas/widgets/email_text_field.dart';
|
||||
import 'package:p_tits_pas/widgets/french_phone_field.dart';
|
||||
import 'package:p_tits_pas/models/user.dart';
|
||||
import 'package:p_tits_pas/services/relais_service.dart';
|
||||
import 'package:p_tits_pas/services/user_service.dart';
|
||||
|
||||
class GestionnairesCreate extends StatelessWidget {
|
||||
const GestionnairesCreate({super.key});
|
||||
class AdminUserFormDialog extends StatefulWidget {
|
||||
final AppUser? initialUser;
|
||||
final bool withRelais;
|
||||
final bool adminMode;
|
||||
final bool readOnly;
|
||||
|
||||
const AdminUserFormDialog({
|
||||
super.key,
|
||||
this.initialUser,
|
||||
this.withRelais = true,
|
||||
this.adminMode = false,
|
||||
this.readOnly = false,
|
||||
});
|
||||
|
||||
@override
|
||||
State<AdminUserFormDialog> createState() => _AdminUserFormDialogState();
|
||||
}
|
||||
|
||||
class _AdminUserFormDialogState extends State<AdminUserFormDialog> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _nomController = TextEditingController();
|
||||
final _prenomController = TextEditingController();
|
||||
final _emailController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
final _telephoneController = TextEditingController();
|
||||
final _passwordToggleFocusNode =
|
||||
FocusNode(skipTraversal: true, canRequestFocus: false);
|
||||
|
||||
bool _isSubmitting = false;
|
||||
bool _obscurePassword = true;
|
||||
bool _isLoadingRelais = true;
|
||||
List<RelaisModel> _relais = [];
|
||||
String? _selectedRelaisId;
|
||||
bool get _isEditMode => widget.initialUser != null;
|
||||
bool get _isSuperAdminTarget =>
|
||||
(widget.initialUser?.role ?? '').toLowerCase() == 'super_admin';
|
||||
bool get _isLockedAdminIdentity =>
|
||||
_isEditMode && widget.adminMode && _isSuperAdminTarget;
|
||||
String get _targetRoleKey {
|
||||
if (widget.initialUser != null) {
|
||||
return (widget.initialUser!.role).toLowerCase();
|
||||
}
|
||||
return widget.adminMode ? 'administrateur' : 'gestionnaire';
|
||||
}
|
||||
|
||||
String get _targetRoleLabel {
|
||||
switch (_targetRoleKey) {
|
||||
case 'super_admin':
|
||||
return 'Super administrateur';
|
||||
case 'administrateur':
|
||||
return 'Administrateur';
|
||||
case 'gestionnaire':
|
||||
return 'Gestionnaire';
|
||||
case 'assistante_maternelle':
|
||||
return 'Assistante maternelle';
|
||||
case 'parent':
|
||||
return 'Parent';
|
||||
default:
|
||||
return 'Utilisateur';
|
||||
}
|
||||
}
|
||||
|
||||
IconData get _targetRoleIcon {
|
||||
switch (_targetRoleKey) {
|
||||
case 'super_admin':
|
||||
return Icons.verified_user_outlined;
|
||||
case 'administrateur':
|
||||
return Icons.admin_panel_settings_outlined;
|
||||
case 'gestionnaire':
|
||||
return Icons.assignment_ind_outlined;
|
||||
case 'assistante_maternelle':
|
||||
return Icons.child_care_outlined;
|
||||
case 'parent':
|
||||
return Icons.supervisor_account_outlined;
|
||||
default:
|
||||
return Icons.person_outline;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final user = widget.initialUser;
|
||||
if (user != null) {
|
||||
_nomController.text = user.nom ?? '';
|
||||
_prenomController.text = user.prenom ?? '';
|
||||
_emailController.text = user.email;
|
||||
_telephoneController.text = formatPhoneForDisplay(user.telephone ?? '');
|
||||
// En édition, on ne préremplit jamais le mot de passe.
|
||||
_passwordController.clear();
|
||||
final initialRelaisId = user.relaisId?.trim();
|
||||
_selectedRelaisId =
|
||||
(initialRelaisId == null || initialRelaisId.isEmpty)
|
||||
? null
|
||||
: initialRelaisId;
|
||||
}
|
||||
if (widget.withRelais) {
|
||||
_loadRelais();
|
||||
} else {
|
||||
_isLoadingRelais = false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nomController.dispose();
|
||||
_prenomController.dispose();
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
_telephoneController.dispose();
|
||||
_passwordToggleFocusNode.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadRelais() async {
|
||||
try {
|
||||
final list = await RelaisService.getRelais();
|
||||
if (!mounted) return;
|
||||
final uniqueById = <String, RelaisModel>{};
|
||||
for (final relais in list) {
|
||||
uniqueById[relais.id] = relais;
|
||||
}
|
||||
|
||||
final filtered = uniqueById.values.where((r) => r.actif).toList();
|
||||
if (_selectedRelaisId != null &&
|
||||
!filtered.any((r) => r.id == _selectedRelaisId)) {
|
||||
final selected = uniqueById[_selectedRelaisId!];
|
||||
if (selected != null) {
|
||||
filtered.add(selected);
|
||||
} else {
|
||||
_selectedRelaisId = null;
|
||||
}
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_relais = filtered;
|
||||
_isLoadingRelais = false;
|
||||
});
|
||||
} catch (_) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_selectedRelaisId = null;
|
||||
_relais = [];
|
||||
_isLoadingRelais = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
String? _required(String? value, String field) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return '$field est requis';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String? _validateEmail(String? value) {
|
||||
final base = _required(value, 'Email');
|
||||
if (base != null) {
|
||||
return base;
|
||||
}
|
||||
return validateEmail(value, allowEmpty: true);
|
||||
}
|
||||
|
||||
String? _validatePassword(String? value) {
|
||||
if (_isEditMode && (value == null || value.trim().isEmpty)) {
|
||||
return null;
|
||||
}
|
||||
final base = _required(value, 'Mot de passe');
|
||||
if (base != null) return base;
|
||||
if (value!.trim().length < 6) return 'Minimum 6 caractères';
|
||||
return null;
|
||||
}
|
||||
|
||||
String? _validatePhone(String? value) {
|
||||
if (_isEditMode && (value == null || value.trim().isEmpty)) {
|
||||
return null;
|
||||
}
|
||||
final base = _required(value, 'Téléphone');
|
||||
if (base != null) {
|
||||
return base;
|
||||
}
|
||||
return validateFrenchNationalPhone(value, allowEmpty: false);
|
||||
}
|
||||
|
||||
String _toTitleCase(String raw) {
|
||||
final trimmed = raw.trim();
|
||||
if (trimmed.isEmpty) return trimmed;
|
||||
final words = trimmed.split(RegExp(r'\s+'));
|
||||
final normalizedWords = words.map(_capitalizeComposedWord).toList();
|
||||
return normalizedWords.join(' ');
|
||||
}
|
||||
|
||||
String _capitalizeComposedWord(String word) {
|
||||
if (word.isEmpty) return word;
|
||||
final lower = word.toLowerCase();
|
||||
final separators = <String>{"-", "'", "’"};
|
||||
final buffer = StringBuffer();
|
||||
var capitalizeNext = true;
|
||||
|
||||
for (var i = 0; i < lower.length; i++) {
|
||||
final char = lower[i];
|
||||
if (capitalizeNext && RegExp(r'[a-zà-öø-ÿ]').hasMatch(char)) {
|
||||
buffer.write(char.toUpperCase());
|
||||
capitalizeNext = false;
|
||||
} else {
|
||||
buffer.write(char);
|
||||
capitalizeNext = separators.contains(char);
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
if (widget.readOnly) return;
|
||||
if (_isSubmitting) return;
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
|
||||
setState(() {
|
||||
_isSubmitting = true;
|
||||
});
|
||||
|
||||
try {
|
||||
final normalizedNom = _toTitleCase(_nomController.text);
|
||||
final normalizedPrenom = _toTitleCase(_prenomController.text);
|
||||
final normalizedPhone = normalizePhone(_telephoneController.text);
|
||||
final passwordProvided = _passwordController.text.trim().isNotEmpty;
|
||||
|
||||
if (_isEditMode) {
|
||||
if (widget.adminMode) {
|
||||
final lockedNom = _toTitleCase(widget.initialUser!.nom ?? '');
|
||||
final lockedPrenom = _toTitleCase(widget.initialUser!.prenom ?? '');
|
||||
await UserService.updateAdministrateur(
|
||||
adminId: widget.initialUser!.id,
|
||||
nom: _isLockedAdminIdentity ? lockedNom : normalizedNom,
|
||||
prenom: _isLockedAdminIdentity ? lockedPrenom : normalizedPrenom,
|
||||
email: _emailController.text.trim(),
|
||||
telephone: normalizedPhone.isEmpty
|
||||
? normalizePhone(widget.initialUser!.telephone ?? '')
|
||||
: normalizedPhone,
|
||||
password: passwordProvided ? _passwordController.text : null,
|
||||
);
|
||||
} else {
|
||||
final currentUser = widget.initialUser!;
|
||||
final initialNom = _toTitleCase(currentUser.nom ?? '');
|
||||
final initialPrenom = _toTitleCase(currentUser.prenom ?? '');
|
||||
final initialEmail = currentUser.email.trim();
|
||||
final initialPhone = normalizePhone(currentUser.telephone ?? '');
|
||||
|
||||
final onlyRelaisChanged =
|
||||
normalizedNom == initialNom &&
|
||||
normalizedPrenom == initialPrenom &&
|
||||
_emailController.text.trim() == initialEmail &&
|
||||
normalizedPhone == initialPhone &&
|
||||
!passwordProvided;
|
||||
|
||||
if (onlyRelaisChanged) {
|
||||
await UserService.updateGestionnaireRelais(
|
||||
gestionnaireId: currentUser.id,
|
||||
relaisId: _selectedRelaisId,
|
||||
);
|
||||
} else {
|
||||
await UserService.updateGestionnaire(
|
||||
gestionnaireId: currentUser.id,
|
||||
nom: normalizedNom,
|
||||
prenom: normalizedPrenom,
|
||||
email: _emailController.text.trim(),
|
||||
telephone: normalizedPhone.isEmpty ? initialPhone : normalizedPhone,
|
||||
relaisId: _selectedRelaisId,
|
||||
password: passwordProvided ? _passwordController.text : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (widget.adminMode) {
|
||||
await UserService.createAdministrateur(
|
||||
nom: normalizedNom,
|
||||
prenom: normalizedPrenom,
|
||||
email: _emailController.text.trim(),
|
||||
password: _passwordController.text,
|
||||
telephone: normalizePhone(_telephoneController.text),
|
||||
);
|
||||
} else {
|
||||
await UserService.createGestionnaire(
|
||||
nom: normalizedNom,
|
||||
prenom: normalizedPrenom,
|
||||
email: _emailController.text.trim(),
|
||||
password: _passwordController.text,
|
||||
telephone: normalizePhone(_telephoneController.text),
|
||||
relaisId: _selectedRelaisId,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
_isEditMode
|
||||
? (widget.adminMode
|
||||
? 'Administrateur modifié avec succès.'
|
||||
: 'Gestionnaire modifié avec succès.')
|
||||
: (widget.adminMode
|
||||
? 'Administrateur créé avec succès.'
|
||||
: 'Gestionnaire créé avec succès.'),
|
||||
),
|
||||
),
|
||||
);
|
||||
Navigator.of(context).pop(true);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
e.toString().replaceFirst('Exception: ', ''),
|
||||
),
|
||||
backgroundColor: Colors.red.shade700,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_isSubmitting = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _delete() async {
|
||||
if (widget.readOnly) return;
|
||||
if (_isSuperAdminTarget) return;
|
||||
if (!_isEditMode || _isSubmitting) return;
|
||||
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) {
|
||||
return AlertDialog(
|
||||
title: const Text('Confirmer la suppression'),
|
||||
content: Text(
|
||||
'Supprimer ${widget.initialUser!.fullName.isEmpty ? widget.initialUser!.email : widget.initialUser!.fullName} ?',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(false),
|
||||
child: const Text('Annuler'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(true),
|
||||
style: FilledButton.styleFrom(backgroundColor: Colors.red.shade700),
|
||||
child: const Text('Supprimer'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
if (confirmed != true) return;
|
||||
|
||||
setState(() {
|
||||
_isSubmitting = true;
|
||||
});
|
||||
try {
|
||||
await UserService.deleteUser(widget.initialUser!.id);
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Gestionnaire supprimé.')),
|
||||
);
|
||||
Navigator.of(context).pop(true);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(e.toString().replaceFirst('Exception: ', '')),
|
||||
backgroundColor: Colors.red.shade700,
|
||||
),
|
||||
);
|
||||
setState(() {
|
||||
_isSubmitting = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Créer un gestionnaire'),
|
||||
return AlertDialog(
|
||||
title: Row(
|
||||
children: [
|
||||
CircleAvatar(
|
||||
radius: 16,
|
||||
backgroundColor: const Color(0xFFEDE5FA),
|
||||
child: Icon(
|
||||
_targetRoleIcon,
|
||||
size: 20,
|
||||
color: const Color(0xFF6B3FA0),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_isEditMode
|
||||
? (widget.readOnly
|
||||
? 'Consulter un "$_targetRoleLabel"'
|
||||
: 'Modifier un "$_targetRoleLabel"')
|
||||
: 'Créer un "$_targetRoleLabel"',
|
||||
),
|
||||
),
|
||||
if (_isEditMode && !widget.readOnly)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
tooltip: 'Fermer',
|
||||
onPressed: _isSubmitting
|
||||
? null
|
||||
: () => Navigator.of(context).pop(false),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: const Center(
|
||||
child: Text('Formulaire de création de gestionnaire'),
|
||||
content: SizedBox(
|
||||
width: 620,
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: _buildPrenomField()),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: _buildNomField()),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_buildEmailField(),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: _buildPasswordField()),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: _buildTelephoneField()),
|
||||
],
|
||||
),
|
||||
if (widget.withRelais) ...[
|
||||
const SizedBox(height: 12),
|
||||
_buildRelaisField(),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
if (widget.readOnly) ...[
|
||||
FilledButton(
|
||||
onPressed: _isSubmitting ? null : () => Navigator.of(context).pop(false),
|
||||
child: const Text('Fermer'),
|
||||
),
|
||||
] else if (_isEditMode) ...[
|
||||
if (!_isSuperAdminTarget)
|
||||
OutlinedButton(
|
||||
onPressed: _isSubmitting ? null : _delete,
|
||||
style: OutlinedButton.styleFrom(foregroundColor: Colors.red.shade700),
|
||||
child: const Text('Supprimer'),
|
||||
),
|
||||
FilledButton.icon(
|
||||
onPressed: _isSubmitting ? null : _submit,
|
||||
icon: _isSubmitting
|
||||
? const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.edit),
|
||||
label: Text(_isSubmitting ? 'Modification...' : 'Modifier'),
|
||||
),
|
||||
] else ...[
|
||||
OutlinedButton(
|
||||
onPressed:
|
||||
_isSubmitting ? null : () => Navigator.of(context).pop(false),
|
||||
child: const Text('Annuler'),
|
||||
),
|
||||
FilledButton.icon(
|
||||
onPressed: _isSubmitting ? null : _submit,
|
||||
icon: _isSubmitting
|
||||
? const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.person_add_alt_1),
|
||||
label: Text(_isSubmitting ? 'Création...' : 'Créer'),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildNomField() {
|
||||
return TextFormField(
|
||||
controller: _nomController,
|
||||
readOnly: widget.readOnly || _isLockedAdminIdentity,
|
||||
textCapitalization: TextCapitalization.words,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nom',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (widget.readOnly || _isLockedAdminIdentity)
|
||||
? null
|
||||
: (v) => _required(v, 'Nom'),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPrenomField() {
|
||||
return TextFormField(
|
||||
controller: _prenomController,
|
||||
readOnly: widget.readOnly || _isLockedAdminIdentity,
|
||||
textCapitalization: TextCapitalization.words,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Prénom',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
validator: (widget.readOnly || _isLockedAdminIdentity)
|
||||
? null
|
||||
: (v) => _required(v, 'Prénom'),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEmailField() {
|
||||
return EmailTextFormField(
|
||||
controller: _emailController,
|
||||
readOnly: widget.readOnly,
|
||||
label: 'Email',
|
||||
validator: widget.readOnly ? null : _validateEmail,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPasswordField() {
|
||||
return TextFormField(
|
||||
controller: _passwordController,
|
||||
readOnly: widget.readOnly,
|
||||
obscureText: _obscurePassword,
|
||||
enableSuggestions: false,
|
||||
autocorrect: false,
|
||||
autofillHints: _isEditMode
|
||||
? const <String>[]
|
||||
: const [AutofillHints.newPassword],
|
||||
decoration: InputDecoration(
|
||||
labelText: _isEditMode
|
||||
? 'Nouveau mot de passe'
|
||||
: 'Mot de passe',
|
||||
border: const OutlineInputBorder(),
|
||||
suffixIcon: widget.readOnly
|
||||
? null
|
||||
: ExcludeFocus(
|
||||
child: IconButton(
|
||||
focusNode: _passwordToggleFocusNode,
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_obscurePassword = !_obscurePassword;
|
||||
});
|
||||
},
|
||||
icon: Icon(
|
||||
_obscurePassword ? Icons.visibility_off : Icons.visibility,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
validator: widget.readOnly ? null : _validatePassword,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTelephoneField() {
|
||||
return FrenchPhoneTextFormField(
|
||||
controller: _telephoneController,
|
||||
readOnly: widget.readOnly,
|
||||
label: 'Téléphone (ex: 06 12 34 56 78)',
|
||||
validator: widget.readOnly ? null : _validatePhone,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildRelaisField() {
|
||||
final selectedValue = _selectedRelaisId != null &&
|
||||
_relais.any((relais) => relais.id == _selectedRelaisId)
|
||||
? _selectedRelaisId
|
||||
: null;
|
||||
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
DropdownButtonFormField<String?>(
|
||||
isExpanded: true,
|
||||
value: selectedValue,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Relais principal',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
items: [
|
||||
const DropdownMenuItem<String?>(
|
||||
value: null,
|
||||
child: Text('Aucun relais'),
|
||||
),
|
||||
..._relais.map(
|
||||
(relais) => DropdownMenuItem<String?>(
|
||||
value: relais.id,
|
||||
child: Text(relais.nom),
|
||||
),
|
||||
),
|
||||
],
|
||||
onChanged: (_isLoadingRelais || widget.readOnly)
|
||||
? null
|
||||
: (value) {
|
||||
setState(() {
|
||||
_selectedRelaisId = value;
|
||||
});
|
||||
},
|
||||
),
|
||||
if (_isLoadingRelais) ...[
|
||||
const SizedBox(height: 8),
|
||||
const LinearProgressIndicator(minHeight: 2),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:p_tits_pas/models/user.dart';
|
||||
import 'package:p_tits_pas/services/auth_service.dart';
|
||||
import 'package:p_tits_pas/widgets/app_footer.dart';
|
||||
import 'package:p_tits_pas/widgets/dashboard/dashboard_bandeau.dart';
|
||||
|
||||
/// Dashboard assistante maternelle – page blanche avec bandeau générique.
|
||||
/// Contenu détaillé à venir.
|
||||
class AmDashboardScreen extends StatefulWidget {
|
||||
const AmDashboardScreen({super.key});
|
||||
|
||||
@override
|
||||
State<AmDashboardScreen> createState() => _AmDashboardScreenState();
|
||||
}
|
||||
|
||||
class _AmDashboardScreenState extends State<AmDashboardScreen> {
|
||||
int selectedTabIndex = 0;
|
||||
AppUser? _user;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadUser();
|
||||
}
|
||||
|
||||
Future<void> _loadUser() async {
|
||||
final user = await AuthService.getCurrentUser();
|
||||
if (mounted) setState(() => _user = user);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: PreferredSize(
|
||||
preferredSize: const Size.fromHeight(60.0),
|
||||
child: DashboardBandeau(
|
||||
tabItems: const [
|
||||
DashboardTabItem(label: 'Mon tableau de bord'),
|
||||
DashboardTabItem(label: 'Paramètres'),
|
||||
],
|
||||
selectedTabIndex: selectedTabIndex,
|
||||
onTabSelected: (index) => setState(() => selectedTabIndex = index),
|
||||
userDisplayName: _user?.fullName.isNotEmpty == true
|
||||
? _user!.fullName
|
||||
: 'Assistante maternelle',
|
||||
userEmail: _user?.email,
|
||||
userRole: _user?.role,
|
||||
onProfileTap: () {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Modification du profil – à venir')),
|
||||
);
|
||||
},
|
||||
onSettingsTap: () {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Paramètres – à venir')),
|
||||
);
|
||||
},
|
||||
onLogout: () {},
|
||||
showLogoutConfirmation: true,
|
||||
),
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Center(
|
||||
child: Text(
|
||||
'Dashboard AM – à venir',
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
),
|
||||
),
|
||||
const AppFooter(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import 'package:provider/provider.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../models/am_registration_data.dart';
|
||||
import '../../utils/data_generator.dart';
|
||||
import '../../widgets/personal_info_form_screen.dart';
|
||||
import '../../models/card_assets.dart';
|
||||
|
||||
@@ -14,37 +13,22 @@ class AmRegisterStep1Screen extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
final registrationData = Provider.of<AmRegistrationData>(context, listen: false);
|
||||
|
||||
// Générer des données de test si vide
|
||||
PersonalInfoData initialData;
|
||||
if (registrationData.firstName.isEmpty) {
|
||||
final genFirstName = DataGenerator.firstName();
|
||||
final genLastName = DataGenerator.lastName();
|
||||
initialData = PersonalInfoData(
|
||||
firstName: genFirstName,
|
||||
lastName: genLastName,
|
||||
phone: DataGenerator.phone(),
|
||||
email: DataGenerator.email(genFirstName, genLastName),
|
||||
address: DataGenerator.address(),
|
||||
postalCode: DataGenerator.postalCode(),
|
||||
city: DataGenerator.city(),
|
||||
);
|
||||
} else {
|
||||
initialData = PersonalInfoData(
|
||||
firstName: registrationData.firstName,
|
||||
lastName: registrationData.lastName,
|
||||
phone: registrationData.phone,
|
||||
email: registrationData.email,
|
||||
address: registrationData.streetAddress,
|
||||
postalCode: registrationData.postalCode,
|
||||
city: registrationData.city,
|
||||
);
|
||||
}
|
||||
final initialData = PersonalInfoData(
|
||||
firstName: registrationData.firstName,
|
||||
lastName: registrationData.lastName,
|
||||
phone: registrationData.phone,
|
||||
email: registrationData.email,
|
||||
address: registrationData.streetAddress,
|
||||
postalCode: registrationData.postalCode,
|
||||
city: registrationData.city,
|
||||
);
|
||||
|
||||
return PersonalInfoFormScreen(
|
||||
stepText: 'Étape 1/4',
|
||||
title: 'Vos informations personnelles',
|
||||
cardColor: CardColorHorizontal.blue,
|
||||
initialData: initialData,
|
||||
minPersonNameLength: 2,
|
||||
previousRoute: '/register-choice',
|
||||
onSubmit: (data, {hasSecondPerson, sameAddress}) {
|
||||
registrationData.updateIdentityInfo(
|
||||
|
||||
@@ -1,93 +1,56 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'dart:io';
|
||||
|
||||
import '../../models/am_registration_data.dart';
|
||||
import '../../models/card_assets.dart';
|
||||
import '../../utils/data_generator.dart';
|
||||
import '../../widgets/professional_info_form_screen.dart';
|
||||
|
||||
class AmRegisterStep2Screen extends StatefulWidget {
|
||||
class AmRegisterStep2Screen extends StatelessWidget {
|
||||
const AmRegisterStep2Screen({super.key});
|
||||
|
||||
@override
|
||||
State<AmRegisterStep2Screen> createState() => _AmRegisterStep2ScreenState();
|
||||
}
|
||||
|
||||
class _AmRegisterStep2ScreenState extends State<AmRegisterStep2Screen> {
|
||||
String? _photoPathFramework;
|
||||
File? _photoFile;
|
||||
|
||||
Future<void> _pickPhoto() async {
|
||||
// TODO: Remplacer par la vraie logique ImagePicker
|
||||
// final imagePicker = ImagePicker();
|
||||
// final pickedFile = await imagePicker.pickImage(source: ImageSource.gallery);
|
||||
// if (pickedFile != null) {
|
||||
// setState(() {
|
||||
// _photoFile = File(pickedFile.path);
|
||||
// _photoPathFramework = pickedFile.path;
|
||||
// });
|
||||
// } else {
|
||||
setState(() {
|
||||
_photoPathFramework = 'assets/images/icon_assmat.png';
|
||||
_photoFile = null;
|
||||
});
|
||||
// }
|
||||
print("Photo sélectionnée: $_photoPathFramework");
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final registrationData = Provider.of<AmRegistrationData>(context, listen: false);
|
||||
|
||||
// Préparer les données initiales
|
||||
ProfessionalInfoData initialData = ProfessionalInfoData(
|
||||
|
||||
final initialData = ProfessionalInfoData(
|
||||
photoPath: registrationData.photoPath,
|
||||
photoBytes: registrationData.photoBytes,
|
||||
photoFilename: registrationData.photoFilename,
|
||||
photoConsent: registrationData.photoConsent,
|
||||
dateOfBirth: registrationData.dateOfBirth,
|
||||
birthCity: registrationData.birthCity,
|
||||
birthCountry: registrationData.birthCountry,
|
||||
nir: registrationData.nir,
|
||||
agrementNumber: registrationData.agrementNumber,
|
||||
agreementDate: registrationData.agreementDate,
|
||||
capacity: registrationData.capacity,
|
||||
placesAvailable: registrationData.placesAvailable,
|
||||
);
|
||||
|
||||
// Générer des données de test si les champs sont vides
|
||||
if (registrationData.dateOfBirth == null && registrationData.nir.isEmpty) {
|
||||
initialData = ProfessionalInfoData(
|
||||
photoPath: 'assets/images/icon_assmat.png',
|
||||
photoConsent: true,
|
||||
dateOfBirth: DateTime(1985, 3, 15),
|
||||
birthCity: DataGenerator.city(),
|
||||
birthCountry: 'France',
|
||||
nir: '${DataGenerator.randomIntInRange(1, 3)}${DataGenerator.randomIntInRange(80, 96)}${DataGenerator.randomIntInRange(1, 13).toString().padLeft(2, '0')}${DataGenerator.randomIntInRange(1, 100).toString().padLeft(2, '0')}${DataGenerator.randomIntInRange(100, 1000).toString().padLeft(3, '0')}${DataGenerator.randomIntInRange(100, 1000).toString().padLeft(3, '0')}${DataGenerator.randomIntInRange(10, 100).toString().padLeft(2, '0')}',
|
||||
agrementNumber: 'AM${DataGenerator.randomIntInRange(10000, 100000)}',
|
||||
capacity: DataGenerator.randomIntInRange(1, 5),
|
||||
);
|
||||
}
|
||||
|
||||
return ProfessionalInfoFormScreen(
|
||||
stepText: 'Étape 2/4',
|
||||
title: 'Vos informations professionnelles',
|
||||
cardColor: CardColorHorizontal.green,
|
||||
initialData: initialData,
|
||||
previousRoute: '/am-register-step1',
|
||||
onPickPhoto: _pickPhoto,
|
||||
onSubmit: (data) {
|
||||
registrationData.updateProfessionalInfo(
|
||||
photoPath: _photoPathFramework ?? data.photoPath,
|
||||
photoPath: data.photoPath,
|
||||
photoBytes: data.photoBytes,
|
||||
photoFilename: data.photoFilename,
|
||||
photoConsent: data.photoConsent,
|
||||
dateOfBirth: data.dateOfBirth,
|
||||
birthCity: data.birthCity,
|
||||
birthCountry: data.birthCountry,
|
||||
nir: data.nir,
|
||||
agrementNumber: data.agrementNumber,
|
||||
agreementDate: data.agreementDate,
|
||||
capacity: data.capacity,
|
||||
placesAvailable: data.placesAvailable,
|
||||
);
|
||||
context.go('/am-register-step3');
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,22 +13,13 @@ class AmRegisterStep3Screen extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
final data = Provider.of<AmRegistrationData>(context, listen: false);
|
||||
|
||||
// Générer un texte de test si vide
|
||||
String initialText = data.presentationText;
|
||||
bool initialCgu = data.cguAccepted;
|
||||
|
||||
if (initialText.isEmpty) {
|
||||
initialText = 'Disponible immédiatement, plus de 10 ans d\'expérience avec les tout-petits. Formation aux premiers secours à jour. Je dispose d\'un jardin sécurisé et d\'un espace de jeu adapté.';
|
||||
initialCgu = true;
|
||||
}
|
||||
|
||||
return PresentationFormScreen(
|
||||
stepText: 'Étape 3/4',
|
||||
title: 'Présentation et Conditions',
|
||||
cardColor: CardColorHorizontal.peach,
|
||||
textFieldHint: 'Ex: Disponible immédiatement, 10 ans d\'expérience, formation premiers secours...',
|
||||
initialText: initialText,
|
||||
initialCguAccepted: initialCgu,
|
||||
initialText: data.presentationText,
|
||||
initialCguAccepted: data.cguAccepted,
|
||||
previousRoute: '/am-register-step2',
|
||||
onSubmit: (text, cguAccepted) {
|
||||
data.updatePresentationAndCgu(
|
||||
|
||||
@@ -7,6 +7,7 @@ import 'dart:math' as math;
|
||||
import '../../models/am_registration_data.dart';
|
||||
import '../../models/card_assets.dart';
|
||||
import '../../config/display_config.dart';
|
||||
import '../../services/auth_service.dart';
|
||||
import '../../widgets/hover_relief_widget.dart';
|
||||
import '../../widgets/image_button.dart';
|
||||
import '../../widgets/custom_navigation_button.dart';
|
||||
@@ -22,6 +23,41 @@ class AmRegisterStep4Screen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _AmRegisterStep4ScreenState extends State<AmRegisterStep4Screen> {
|
||||
bool _isSubmitting = false;
|
||||
|
||||
Future<void> _submitAMRegistration(AmRegistrationData registrationData) async {
|
||||
if (_isSubmitting) return;
|
||||
if (!registrationData.isRegistrationComplete) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'Le dossier est incomplet. Vérifiez chaque étape (photo, consentement, lieux de naissance, etc.).',
|
||||
style: GoogleFonts.merienda(fontSize: 14),
|
||||
),
|
||||
backgroundColor: Colors.red.shade700,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
setState(() => _isSubmitting = true);
|
||||
try {
|
||||
await AuthService.registerAM(registrationData);
|
||||
if (!mounted) return;
|
||||
_showConfirmationModal(context);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(e is Exception ? e.toString().replaceFirst('Exception: ', '') : 'Erreur lors de l\'inscription'),
|
||||
backgroundColor: Colors.red.shade700,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) setState(() => _isSubmitting = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final registrationData = Provider.of<AmRegistrationData>(context);
|
||||
@@ -90,12 +126,9 @@ class _AmRegisterStep4ScreenState extends State<AmRegisterStep4Screen> {
|
||||
Expanded(
|
||||
child: HoverReliefWidget(
|
||||
child: CustomNavigationButton(
|
||||
text: 'Soumettre',
|
||||
text: _isSubmitting ? 'Envoi...' : 'Soumettre',
|
||||
style: NavigationButtonStyle.green,
|
||||
onPressed: () {
|
||||
print("Données AM finales: ${registrationData.firstName} ${registrationData.lastName}");
|
||||
_showConfirmationModal(context);
|
||||
},
|
||||
onPressed: () => _submitAMRegistration(registrationData),
|
||||
width: double.infinity,
|
||||
height: 50,
|
||||
fontSize: 16,
|
||||
@@ -106,17 +139,14 @@ class _AmRegisterStep4ScreenState extends State<AmRegisterStep4Screen> {
|
||||
),
|
||||
)
|
||||
else
|
||||
ImageButton(
|
||||
ImageButton(
|
||||
bg: 'assets/images/bg_green.png',
|
||||
text: 'Soumettre ma demande',
|
||||
text: _isSubmitting ? 'Envoi...' : 'Soumettre ma demande',
|
||||
textColor: const Color(0xFF2D6A4F),
|
||||
width: 350,
|
||||
height: 50,
|
||||
fontSize: 18,
|
||||
onPressed: () {
|
||||
print("Données AM finales: ${registrationData.firstName} ${registrationData.lastName}");
|
||||
_showConfirmationModal(context);
|
||||
},
|
||||
onPressed: () => _submitAMRegistration(registrationData),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -179,14 +209,17 @@ class _AmRegisterStep4ScreenState extends State<AmRegisterStep4Screen> {
|
||||
title: 'Informations professionnelles',
|
||||
cardColor: CardColorHorizontal.green,
|
||||
initialData: ProfessionalInfoData(
|
||||
// TODO: Gérer photoPath vs photoFile correctement
|
||||
photoPath: null, // Pas d'accès facile au fichier ici, on verra
|
||||
photoPath: data.photoPath,
|
||||
photoBytes: data.photoBytes,
|
||||
photoFilename: data.photoFilename,
|
||||
dateOfBirth: data.dateOfBirth,
|
||||
birthCity: data.birthCity,
|
||||
birthCountry: data.birthCountry,
|
||||
nir: data.nir,
|
||||
agrementNumber: data.agrementNumber,
|
||||
agreementDate: data.agreementDate,
|
||||
capacity: data.capacity,
|
||||
placesAvailable: data.placesAvailable,
|
||||
photoConsent: data.photoConsent,
|
||||
),
|
||||
onSubmit: (d) {},
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:p_tits_pas/services/bug_report_service.dart';
|
||||
import 'package:p_tits_pas/utils/email_utils.dart';
|
||||
import '../../widgets/image_button.dart';
|
||||
import '../../widgets/custom_app_text_field.dart';
|
||||
import '../../services/auth_service.dart';
|
||||
@@ -16,42 +18,72 @@ class LoginScreen extends StatefulWidget {
|
||||
State<LoginScreen> createState() => _LoginPageState();
|
||||
}
|
||||
|
||||
class _LoginPageState extends State<LoginScreen> with WidgetsBindingObserver {
|
||||
class _LoginPageState extends State<LoginScreen> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _emailController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
|
||||
final GlobalKey<FormFieldState<String>> _emailFormKey =
|
||||
GlobalKey<FormFieldState<String>>();
|
||||
late final FocusNode _emailFocus;
|
||||
late final FocusNode _passwordFocus;
|
||||
|
||||
bool _isLoading = false;
|
||||
String? _errorMessage;
|
||||
|
||||
static const double _mobileBreakpoint = 900.0;
|
||||
|
||||
/// Une seule fois : évite de relancer `_getImageDimensions()` à chaque rebuild (sinon sur web,
|
||||
/// tout événement de layout / métriques recréait un Future et pouvait provoquer des erreurs DWDS
|
||||
/// ou des comportements bizarres pendant la saisie dans les champs).
|
||||
late final Future<ImageDimensions> _desktopRiverLogoDimensionsFuture;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_desktopRiverLogoDimensionsFuture = _getImageDimensions();
|
||||
_emailFocus = FocusNode();
|
||||
_passwordFocus = FocusNode();
|
||||
_emailFocus.addListener(_onEmailFocusChange);
|
||||
}
|
||||
|
||||
void _onEmailFocusChange() {
|
||||
if (_emailFocus.hasFocus) {
|
||||
return;
|
||||
}
|
||||
// Reporter au frame suivant : une mise à jour synchrone du controller pendant
|
||||
// un transfert de focus (Tab) peut casser la navigation au clavier.
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted || _emailFocus.hasFocus) {
|
||||
return;
|
||||
}
|
||||
final normalized = normalizeEmailText(_emailController.text);
|
||||
if (normalized != _emailController.text) {
|
||||
_emailController.value = TextEditingValue(
|
||||
text: normalized,
|
||||
selection: TextSelection.collapsed(offset: normalized.length),
|
||||
);
|
||||
}
|
||||
_emailFormKey.currentState?.validate();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_emailFocus.removeListener(_onEmailFocusChange);
|
||||
_emailFocus.dispose();
|
||||
_passwordFocus.dispose();
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeMetrics() {
|
||||
super.didChangeMetrics();
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
String? _validateEmail(String? value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Veuillez entrer votre email';
|
||||
final v = value?.trim() ?? '';
|
||||
if (v.isEmpty) {
|
||||
return 'Veuillez entrer votre adresse e-mail.';
|
||||
}
|
||||
if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
|
||||
return 'Veuillez entrer un email valide';
|
||||
if (!isValidEmailFormat(v)) {
|
||||
return 'L’adresse e-mail n’est pas valide.';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -63,6 +95,11 @@ class _LoginPageState extends State<LoginScreen> with WidgetsBindingObserver {
|
||||
return null;
|
||||
}
|
||||
|
||||
void _handlePasswordSubmitted(String _) {
|
||||
if (_isLoading) return;
|
||||
_handleLogin();
|
||||
}
|
||||
|
||||
/// Gère la connexion de l'utilisateur
|
||||
Future<void> _handleLogin() async {
|
||||
// Réinitialiser le message d'erreur
|
||||
@@ -90,7 +127,7 @@ class _LoginPageState extends State<LoginScreen> with WidgetsBindingObserver {
|
||||
// Vérifier si l'utilisateur doit changer son mot de passe
|
||||
if (user.changementMdpObligatoire) {
|
||||
if (!mounted) return;
|
||||
|
||||
|
||||
// Afficher la modale de changement de mot de passe (non-dismissible)
|
||||
final result = await showDialog<bool>(
|
||||
context: context,
|
||||
@@ -106,8 +143,11 @@ class _LoginPageState extends State<LoginScreen> with WidgetsBindingObserver {
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
// Laisse au navigateur/OS la possibilité de mémoriser les identifiants.
|
||||
TextInput.finishAutofillContext(shouldSave: true);
|
||||
|
||||
// Rediriger selon le rôle de l'utilisateur
|
||||
_redirectUserByRole(user.role);
|
||||
_redirectUserByRole(user.role.isEmpty ? null : user.role);
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
@@ -117,14 +157,17 @@ class _LoginPageState extends State<LoginScreen> with WidgetsBindingObserver {
|
||||
}
|
||||
|
||||
/// Redirige l'utilisateur selon son rôle (GoRouter : context.go).
|
||||
void _redirectUserByRole(String role) {
|
||||
void _redirectUserByRole(String? role) {
|
||||
setState(() => _isLoading = false);
|
||||
switch (role.toLowerCase()) {
|
||||
final r = (role ?? '').toLowerCase();
|
||||
switch (r) {
|
||||
case 'super_admin':
|
||||
case 'administrateur':
|
||||
case 'gestionnaire':
|
||||
context.go('/admin-dashboard');
|
||||
break;
|
||||
case 'gestionnaire':
|
||||
context.go('/gestionnaire-dashboard');
|
||||
break;
|
||||
case 'parent':
|
||||
context.go('/parent-dashboard');
|
||||
break;
|
||||
@@ -151,112 +194,149 @@ class _LoginPageState extends State<LoginScreen> with WidgetsBindingObserver {
|
||||
builder: (context, constraints) {
|
||||
final w = constraints.maxWidth;
|
||||
final h = constraints.maxHeight;
|
||||
return FutureBuilder(
|
||||
future: _getImageDimensions(),
|
||||
builder: (context, snapshot) {
|
||||
if (!snapshot.hasData) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
return FutureBuilder<ImageDimensions>(
|
||||
future: _desktopRiverLogoDimensionsFuture,
|
||||
builder: (context, snapshot) {
|
||||
if (!snapshot.hasData) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
final imageDimensions = snapshot.data!;
|
||||
final imageHeight = h;
|
||||
final imageWidth = imageHeight * (imageDimensions.width / imageDimensions.height);
|
||||
final remainingWidth = w - imageWidth;
|
||||
final leftMargin = remainingWidth / 4;
|
||||
final imageDimensions = snapshot.data!;
|
||||
final imageHeight = h;
|
||||
final imageWidth = imageHeight *
|
||||
(imageDimensions.width / imageDimensions.height);
|
||||
final remainingWidth = w - imageWidth;
|
||||
final leftMargin = remainingWidth / 4;
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
// Fond en papier
|
||||
Positioned.fill(
|
||||
child: Image.asset(
|
||||
'assets/images/paper2.png',
|
||||
fit: BoxFit.cover,
|
||||
repeat: ImageRepeat.repeat,
|
||||
),
|
||||
return Stack(
|
||||
children: [
|
||||
// Fond en papier
|
||||
Positioned.fill(
|
||||
child: Image.asset(
|
||||
'assets/images/paper2.png',
|
||||
fit: BoxFit.cover,
|
||||
repeat: ImageRepeat.repeat,
|
||||
),
|
||||
// Image principale
|
||||
Positioned(
|
||||
left: leftMargin,
|
||||
top: 0,
|
||||
height: imageHeight,
|
||||
width: imageWidth,
|
||||
child: Image.asset(
|
||||
'assets/images/river_logo_desktop.png',
|
||||
fit: BoxFit.contain,
|
||||
),
|
||||
),
|
||||
// Image principale
|
||||
Positioned(
|
||||
left: leftMargin,
|
||||
top: 0,
|
||||
height: imageHeight,
|
||||
width: imageWidth,
|
||||
child: Image.asset(
|
||||
'assets/images/river_logo_desktop.png',
|
||||
fit: BoxFit.contain,
|
||||
),
|
||||
// Formulaire dans le cadran en bas à droite
|
||||
Positioned(
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
width: w * 0.6, // 60% de la largeur de l'écran
|
||||
height: h * 0.5, // 50% de la hauteur de l'écran
|
||||
),
|
||||
// Formulaire dans le cadran en bas à droite
|
||||
Positioned(
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
width: w * 0.6, // 60% de la largeur de l'écran
|
||||
height: h * 0.5, // 50% de la hauteur de l'écran
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(w * 0.02), // 2% de padding
|
||||
padding: EdgeInsets.all(w * 0.02), // 2% de padding
|
||||
child: AutofillGroup(
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// Champs côte à côte
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: CustomAppTextField(
|
||||
controller: _emailController,
|
||||
labelText: 'Email',
|
||||
hintText: 'Votre adresse email',
|
||||
validator: _validateEmail,
|
||||
style: CustomAppTextFieldStyle.lavande,
|
||||
fieldHeight: 53,
|
||||
fieldWidth: double.infinity,
|
||||
FocusTraversalGroup(
|
||||
policy: OrderedTraversalPolicy(),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: FocusTraversalOrder(
|
||||
order: const NumericFocusOrder(1),
|
||||
child: CustomAppTextField(
|
||||
formFieldKey: _emailFormKey,
|
||||
controller: _emailController,
|
||||
focusNode: _emailFocus,
|
||||
labelText: 'Email',
|
||||
hintText: 'Votre adresse email',
|
||||
keyboardType:
|
||||
TextInputType.emailAddress,
|
||||
autocorrect: false,
|
||||
enableSuggestions: false,
|
||||
autofillHints: const [
|
||||
AutofillHints.username,
|
||||
AutofillHints.email,
|
||||
],
|
||||
inputFormatters: const [
|
||||
EmailMaxLengthFormatter(),
|
||||
],
|
||||
textInputAction: TextInputAction.next,
|
||||
onFieldSubmitted: (_) =>
|
||||
_passwordFocus.requestFocus(),
|
||||
validator: _validateEmail,
|
||||
style:
|
||||
CustomAppTextFieldStyle.lavande,
|
||||
fieldHeight: 53,
|
||||
fieldWidth: double.infinity,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 20),
|
||||
Expanded(
|
||||
child: CustomAppTextField(
|
||||
controller: _passwordController,
|
||||
labelText: 'Mot de passe',
|
||||
hintText: 'Votre mot de passe',
|
||||
obscureText: true,
|
||||
validator: _validatePassword,
|
||||
style: CustomAppTextFieldStyle.jaune,
|
||||
fieldHeight: 53,
|
||||
fieldWidth: double.infinity,
|
||||
const SizedBox(width: 20),
|
||||
Expanded(
|
||||
child: FocusTraversalOrder(
|
||||
order: const NumericFocusOrder(2),
|
||||
child: CustomAppTextField(
|
||||
controller: _passwordController,
|
||||
focusNode: _passwordFocus,
|
||||
labelText: 'Mot de passe',
|
||||
hintText: 'Votre mot de passe',
|
||||
obscureText: true,
|
||||
autofillHints: const [
|
||||
AutofillHints.password,
|
||||
],
|
||||
textInputAction: TextInputAction.done,
|
||||
onFieldSubmitted:
|
||||
_handlePasswordSubmitted,
|
||||
validator: _validatePassword,
|
||||
style:
|
||||
CustomAppTextFieldStyle.jaune,
|
||||
fieldHeight: 53,
|
||||
fieldWidth: double.infinity,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
|
||||
// Message d'erreur
|
||||
if (_errorMessage != null)
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
margin: const EdgeInsets.only(bottom: 15),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red.shade50,
|
||||
color: Colors.red[50],
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: Colors.red.shade300),
|
||||
border: Border.all(color: Colors.red[300]!),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.error_outline, color: Colors.red.shade700, size: 20),
|
||||
Icon(Icons.error_outline,
|
||||
color: Colors.red[700], size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_errorMessage!,
|
||||
style: GoogleFonts.merienda(
|
||||
fontSize: 12,
|
||||
color: Colors.red.shade700,
|
||||
color: Colors.red[700],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
|
||||
// Bouton centré
|
||||
Center(
|
||||
child: _isLoading
|
||||
@@ -309,67 +389,68 @@ class _LoginPageState extends State<LoginScreen> with WidgetsBindingObserver {
|
||||
),
|
||||
),
|
||||
),
|
||||
// Pied de page (Wrap pour éviter overflow sur petite largeur)
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8.0),
|
||||
decoration: const BoxDecoration(
|
||||
color: Colors.transparent,
|
||||
),
|
||||
child: Wrap(
|
||||
alignment: WrapAlignment.center,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
_FooterLink(
|
||||
text: 'Contact support',
|
||||
onTap: () async {
|
||||
final Uri emailLaunchUri = Uri(
|
||||
scheme: 'mailto',
|
||||
path: 'support@supernounou.local',
|
||||
);
|
||||
if (await canLaunchUrl(emailLaunchUri)) {
|
||||
await launchUrl(emailLaunchUri);
|
||||
} else {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'Impossible d\'ouvrir le client mail',
|
||||
style: GoogleFonts.merienda(),
|
||||
),
|
||||
),
|
||||
// Pied de page (Wrap pour éviter overflow sur petite largeur)
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8.0),
|
||||
decoration: const BoxDecoration(
|
||||
color: Colors.transparent,
|
||||
),
|
||||
child: Wrap(
|
||||
alignment: WrapAlignment.center,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
_FooterLink(
|
||||
text: 'Contact support',
|
||||
onTap: () async {
|
||||
final Uri emailLaunchUri = Uri(
|
||||
scheme: 'mailto',
|
||||
path: 'support@supernounou.local',
|
||||
);
|
||||
if (await canLaunchUrl(emailLaunchUri)) {
|
||||
await launchUrl(emailLaunchUri);
|
||||
} else {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'Impossible d\'ouvrir le client mail',
|
||||
style: GoogleFonts.merienda(),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
_FooterLink(
|
||||
text: 'Signaler un bug',
|
||||
onTap: () {
|
||||
_showBugReportDialog(context);
|
||||
},
|
||||
),
|
||||
_FooterLink(
|
||||
text: 'Mentions légales',
|
||||
onTap: () {
|
||||
context.go('/legal');
|
||||
},
|
||||
),
|
||||
_FooterLink(
|
||||
text: 'Politique de confidentialité',
|
||||
onTap: () {
|
||||
context.go('/privacy');
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
_FooterLink(
|
||||
text: 'Signaler un bug',
|
||||
onTap: () {
|
||||
_showBugReportDialog(context);
|
||||
},
|
||||
),
|
||||
_FooterLink(
|
||||
text: 'Mentions légales',
|
||||
onTap: () {
|
||||
context.go('/legal');
|
||||
},
|
||||
),
|
||||
_FooterLink(
|
||||
text: 'Politique de confidentialité',
|
||||
onTap: () {
|
||||
context.go('/privacy');
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -378,6 +459,7 @@ class _LoginPageState extends State<LoginScreen> with WidgetsBindingObserver {
|
||||
/// Dimensions de river_logo_mobile.png (à mettre à jour si l'asset change).
|
||||
static const int _riverLogoMobileWidth = 600;
|
||||
static const int _riverLogoMobileHeight = 1080;
|
||||
|
||||
/// Fraction de la hauteur de l'image où se termine visuellement le slogan (0 = haut, 1 = bas).
|
||||
static const double _sloganEndFraction = 0.42;
|
||||
static const double _gapBelowSlogan = 12.0;
|
||||
@@ -388,7 +470,8 @@ class _LoginPageState extends State<LoginScreen> with WidgetsBindingObserver {
|
||||
final h = constraints.maxHeight;
|
||||
final w = constraints.maxWidth;
|
||||
final imageAspectRatio = _riverLogoMobileHeight / _riverLogoMobileWidth;
|
||||
final formTop = w * imageAspectRatio * _sloganEndFraction + _gapBelowSlogan;
|
||||
final formTop =
|
||||
w * imageAspectRatio * _sloganEndFraction + _gapBelowSlogan;
|
||||
return Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
@@ -428,100 +511,143 @@ class _LoginPageState extends State<LoginScreen> with WidgetsBindingObserver {
|
||||
children: [
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 24, vertical: 20),
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 400),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const SizedBox(height: 16),
|
||||
CustomAppTextField(
|
||||
controller: _emailController,
|
||||
labelText: 'Email',
|
||||
showLabel: false,
|
||||
hintText: 'Votre adresse email',
|
||||
validator: _validateEmail,
|
||||
style: CustomAppTextFieldStyle.lavande,
|
||||
fieldHeight: 48,
|
||||
fieldWidth: double.infinity,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
CustomAppTextField(
|
||||
controller: _passwordController,
|
||||
labelText: 'Mot de passe',
|
||||
showLabel: false,
|
||||
hintText: 'Votre mot de passe',
|
||||
obscureText: true,
|
||||
validator: _validatePassword,
|
||||
style: CustomAppTextFieldStyle.jaune,
|
||||
fieldHeight: 48,
|
||||
fieldWidth: double.infinity,
|
||||
),
|
||||
if (_errorMessage != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red.shade50,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: Colors.red.shade300),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.error_outline, color: Colors.red.shade700, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_errorMessage!,
|
||||
style: GoogleFonts.merienda(fontSize: 12, color: Colors.red.shade700),
|
||||
),
|
||||
child: AutofillGroup(
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: FocusTraversalGroup(
|
||||
policy: OrderedTraversalPolicy(),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const SizedBox(height: 16),
|
||||
FocusTraversalOrder(
|
||||
order: const NumericFocusOrder(1),
|
||||
child: CustomAppTextField(
|
||||
formFieldKey: _emailFormKey,
|
||||
controller: _emailController,
|
||||
focusNode: _emailFocus,
|
||||
labelText: 'Email',
|
||||
showLabel: false,
|
||||
hintText: 'Votre adresse email',
|
||||
keyboardType:
|
||||
TextInputType.emailAddress,
|
||||
autocorrect: false,
|
||||
enableSuggestions: false,
|
||||
autofillHints: const [
|
||||
AutofillHints.username,
|
||||
AutofillHints.email,
|
||||
],
|
||||
inputFormatters: const [
|
||||
EmailMaxLengthFormatter(),
|
||||
],
|
||||
textInputAction: TextInputAction.next,
|
||||
onFieldSubmitted: (_) =>
|
||||
_passwordFocus.requestFocus(),
|
||||
validator: _validateEmail,
|
||||
style:
|
||||
CustomAppTextFieldStyle.lavande,
|
||||
fieldHeight: 48,
|
||||
fieldWidth: double.infinity,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
FocusTraversalOrder(
|
||||
order: const NumericFocusOrder(2),
|
||||
child: CustomAppTextField(
|
||||
controller: _passwordController,
|
||||
focusNode: _passwordFocus,
|
||||
labelText: 'Mot de passe',
|
||||
showLabel: false,
|
||||
hintText: 'Votre mot de passe',
|
||||
obscureText: true,
|
||||
autofillHints: const [
|
||||
AutofillHints.password
|
||||
],
|
||||
textInputAction: TextInputAction.done,
|
||||
onFieldSubmitted:
|
||||
_handlePasswordSubmitted,
|
||||
validator: _validatePassword,
|
||||
style:
|
||||
CustomAppTextFieldStyle.jaune,
|
||||
fieldHeight: 48,
|
||||
fieldWidth: double.infinity,
|
||||
),
|
||||
),
|
||||
if (_errorMessage != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red.shade50,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(
|
||||
color: Colors.red.shade300),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.error_outline,
|
||||
color: Colors.red.shade700,
|
||||
size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_errorMessage!,
|
||||
style: GoogleFonts.merienda(
|
||||
fontSize: 12,
|
||||
color: Colors.red.shade700),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
_isLoading
|
||||
? const CircularProgressIndicator()
|
||||
: ImageButton(
|
||||
bg: 'assets/images/bg_green.png',
|
||||
width: double.infinity,
|
||||
height: 44,
|
||||
text: 'Se connecter',
|
||||
textColor: const Color(0xFF2D6A4F),
|
||||
onPressed: _handleLogin,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextButton(
|
||||
onPressed: () {/* TODO */},
|
||||
child: Text(
|
||||
'Mot de passe oublié ?',
|
||||
style: GoogleFonts.merienda(
|
||||
fontSize: 14,
|
||||
color: const Color(0xFF2D6A4F),
|
||||
decoration: TextDecoration.underline,
|
||||
),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
context.go('/register-choice'),
|
||||
child: Text(
|
||||
'Créer un compte',
|
||||
style: GoogleFonts.merienda(
|
||||
fontSize: 16,
|
||||
color: const Color(0xFF2D6A4F),
|
||||
decoration: TextDecoration.underline,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
_isLoading
|
||||
? const CircularProgressIndicator()
|
||||
: ImageButton(
|
||||
bg: 'assets/images/bg_green.png',
|
||||
width: double.infinity,
|
||||
height: 44,
|
||||
text: 'Se connecter',
|
||||
textColor: const Color(0xFF2D6A4F),
|
||||
onPressed: _handleLogin,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextButton(
|
||||
onPressed: () { /* TODO */ },
|
||||
child: Text(
|
||||
'Mot de passe oublié ?',
|
||||
style: GoogleFonts.merienda(
|
||||
fontSize: 14,
|
||||
color: const Color(0xFF2D6A4F),
|
||||
decoration: TextDecoration.underline,
|
||||
),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => context.go('/register-choice'),
|
||||
child: Text(
|
||||
'Créer un compte',
|
||||
style: GoogleFonts.merienda(
|
||||
fontSize: 16,
|
||||
color: const Color(0xFF2D6A4F),
|
||||
decoration: TextDecoration.underline,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12, top: 8),
|
||||
child: Wrap(
|
||||
@@ -533,12 +659,17 @@ class _LoginPageState extends State<LoginScreen> with WidgetsBindingObserver {
|
||||
text: 'Contact support',
|
||||
fontSize: 11,
|
||||
onTap: () async {
|
||||
final uri = Uri(scheme: 'mailto', path: 'support@supernounou.local');
|
||||
final uri = Uri(
|
||||
scheme: 'mailto',
|
||||
path: 'support@supernounou.local');
|
||||
if (await canLaunchUrl(uri)) {
|
||||
await launchUrl(uri);
|
||||
} else if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Impossible d\'ouvrir le client mail', style: GoogleFonts.merienda())),
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'Impossible d\'ouvrir le client mail',
|
||||
style: GoogleFonts.merienda())),
|
||||
);
|
||||
}
|
||||
},
|
||||
@@ -707,4 +838,4 @@ class _FooterLink extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import 'package:provider/provider.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../models/user_registration_data.dart';
|
||||
import '../../utils/data_generator.dart';
|
||||
import '../../widgets/personal_info_form_screen.dart';
|
||||
import '../../models/card_assets.dart';
|
||||
|
||||
@@ -15,31 +14,15 @@ class ParentRegisterStep1Screen extends StatelessWidget {
|
||||
final registrationData = Provider.of<UserRegistrationData>(context, listen: false);
|
||||
final parent1 = registrationData.parent1;
|
||||
|
||||
// Générer des données de test si vide
|
||||
PersonalInfoData initialData;
|
||||
if (parent1.firstName.isEmpty) {
|
||||
final genFirstName = DataGenerator.firstName();
|
||||
final genLastName = DataGenerator.lastName();
|
||||
initialData = PersonalInfoData(
|
||||
firstName: genFirstName,
|
||||
lastName: genLastName,
|
||||
phone: DataGenerator.phone(),
|
||||
email: DataGenerator.email(genFirstName, genLastName),
|
||||
address: DataGenerator.address(),
|
||||
postalCode: DataGenerator.postalCode(),
|
||||
city: DataGenerator.city(),
|
||||
);
|
||||
} else {
|
||||
initialData = PersonalInfoData(
|
||||
firstName: parent1.firstName,
|
||||
lastName: parent1.lastName,
|
||||
phone: parent1.phone,
|
||||
email: parent1.email,
|
||||
address: parent1.address,
|
||||
postalCode: parent1.postalCode,
|
||||
city: parent1.city,
|
||||
);
|
||||
}
|
||||
final initialData = PersonalInfoData(
|
||||
firstName: parent1.firstName,
|
||||
lastName: parent1.lastName,
|
||||
phone: parent1.phone,
|
||||
email: parent1.email,
|
||||
address: parent1.address,
|
||||
postalCode: parent1.postalCode,
|
||||
city: parent1.city,
|
||||
);
|
||||
|
||||
return PersonalInfoFormScreen(
|
||||
stepText: 'Étape 1/5',
|
||||
|
||||
@@ -3,7 +3,6 @@ import 'package:provider/provider.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../models/user_registration_data.dart';
|
||||
import '../../utils/data_generator.dart';
|
||||
import '../../widgets/personal_info_form_screen.dart';
|
||||
import '../../models/card_assets.dart';
|
||||
|
||||
@@ -19,21 +18,17 @@ class ParentRegisterStep2Screen extends StatelessWidget {
|
||||
bool hasParent2 = parent2 != null;
|
||||
bool sameAddress = false;
|
||||
|
||||
// Générer des données de test si vide
|
||||
PersonalInfoData initialData;
|
||||
if (parent2 == null || parent2.firstName.isEmpty) {
|
||||
final genFirstName = DataGenerator.firstName();
|
||||
final genLastName = DataGenerator.lastName();
|
||||
sameAddress = DataGenerator.boolean();
|
||||
|
||||
sameAddress = false;
|
||||
initialData = PersonalInfoData(
|
||||
firstName: genFirstName,
|
||||
lastName: genLastName,
|
||||
phone: DataGenerator.phone(),
|
||||
email: DataGenerator.email(genFirstName, genLastName),
|
||||
address: sameAddress ? parent1.address : DataGenerator.address(),
|
||||
postalCode: sameAddress ? parent1.postalCode : DataGenerator.postalCode(),
|
||||
city: sameAddress ? parent1.city : DataGenerator.city(),
|
||||
firstName: parent2?.firstName ?? '',
|
||||
lastName: parent2?.lastName ?? '',
|
||||
phone: parent2?.phone ?? '',
|
||||
email: parent2?.email ?? '',
|
||||
address: parent2?.address ?? '',
|
||||
postalCode: parent2?.postalCode ?? '',
|
||||
city: parent2?.city ?? '',
|
||||
);
|
||||
} else {
|
||||
sameAddress = (parent2.address == parent1.address &&
|
||||
|
||||
@@ -3,15 +3,16 @@ import 'package:google_fonts/google_fonts.dart';
|
||||
import 'dart:math' as math; // Pour la rotation du chevron
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'dart:io' show File;
|
||||
import 'package:flutter/foundation.dart' show kIsWeb;
|
||||
import '../../widgets/hover_relief_widget.dart';
|
||||
import '../../widgets/child_card_widget.dart';
|
||||
import '../../widgets/custom_navigation_button.dart';
|
||||
import '../../models/user_registration_data.dart';
|
||||
import '../../utils/data_generator.dart';
|
||||
import '../../models/card_assets.dart';
|
||||
import '../../config/display_config.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:p_tits_pas/utils/name_format_utils.dart';
|
||||
|
||||
class ParentRegisterStep3Screen extends StatefulWidget {
|
||||
// final UserRegistrationData registrationData; // Supprimé
|
||||
@@ -75,6 +76,22 @@ class _ParentRegisterStep3ScreenState extends State<ParentRegisterStep3Screen> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Même logique que nom / prénom parent : normalisation avant passage à l’étape suivante.
|
||||
void _normalizeChildrenNamesAndGoToStep4(
|
||||
BuildContext context,
|
||||
UserRegistrationData registrationData,
|
||||
) {
|
||||
for (var i = 0; i < registrationData.children.length; i++) {
|
||||
final c = registrationData.children[i];
|
||||
final fn = formatPersonNameCase(c.firstName);
|
||||
final ln = formatPersonNameCase(c.lastName);
|
||||
if (fn != c.firstName || ln != c.lastName) {
|
||||
registrationData.updateChild(i, c.copyWith(firstName: fn, lastName: ln));
|
||||
}
|
||||
}
|
||||
context.go('/parent-register-step4');
|
||||
}
|
||||
|
||||
void _scrollListener() {
|
||||
if (!_scrollController.hasClients) return;
|
||||
final position = _scrollController.position;
|
||||
@@ -92,8 +109,6 @@ class _ParentRegisterStep3ScreenState extends State<ParentRegisterStep3Screen> {
|
||||
|
||||
void _addChild(UserRegistrationData registrationData) { // Prend registrationData
|
||||
setState(() {
|
||||
bool isUnborn = DataGenerator.boolean();
|
||||
|
||||
// Trouver la première couleur non utilisée
|
||||
CardColorVertical cardColor = _childCardColors.firstWhere(
|
||||
(color) => !_usedColors.contains(color),
|
||||
@@ -102,11 +117,11 @@ class _ParentRegisterStep3ScreenState extends State<ParentRegisterStep3Screen> {
|
||||
|
||||
final newChild = ChildData(
|
||||
lastName: registrationData.parent1.lastName,
|
||||
firstName: DataGenerator.firstName(),
|
||||
dob: DataGenerator.dob(isUnborn: isUnborn),
|
||||
isUnbornChild: isUnborn,
|
||||
photoConsent: DataGenerator.boolean(),
|
||||
multipleBirth: DataGenerator.boolean(),
|
||||
firstName: '',
|
||||
dob: '',
|
||||
isUnbornChild: false,
|
||||
photoConsent: false,
|
||||
multipleBirth: false,
|
||||
cardColor: cardColor,
|
||||
);
|
||||
registrationData.addChild(newChild);
|
||||
@@ -134,23 +149,27 @@ class _ParentRegisterStep3ScreenState extends State<ParentRegisterStep3Screen> {
|
||||
final ImagePicker picker = ImagePicker();
|
||||
try {
|
||||
final XFile? pickedFile = await picker.pickImage(
|
||||
source: ImageSource.gallery, imageQuality: 70, maxWidth: 1024, maxHeight: 1024);
|
||||
source: ImageSource.gallery,
|
||||
imageQuality: 60,
|
||||
maxWidth: 900,
|
||||
maxHeight: 900,
|
||||
);
|
||||
if (pickedFile != null) {
|
||||
if (childIndex < registrationData.children.length) {
|
||||
final oldChild = registrationData.children[childIndex];
|
||||
final updatedChild = ChildData(
|
||||
firstName: oldChild.firstName,
|
||||
lastName: oldChild.lastName,
|
||||
dob: oldChild.dob,
|
||||
photoConsent: oldChild.photoConsent,
|
||||
multipleBirth: oldChild.multipleBirth,
|
||||
isUnbornChild: oldChild.isUnbornChild,
|
||||
imageFile: File(pickedFile.path),
|
||||
cardColor: oldChild.cardColor,
|
||||
);
|
||||
final bytes = await pickedFile.readAsBytes();
|
||||
if (bytes.isEmpty) return;
|
||||
File? file;
|
||||
if (!kIsWeb) {
|
||||
try {
|
||||
final f = File(pickedFile.path);
|
||||
if (await f.exists()) file = f;
|
||||
} catch (_) {}
|
||||
}
|
||||
final updatedChild = oldChild.copyWith(imageBytes: bytes, imageFile: file);
|
||||
registrationData.updateChild(childIndex, updatedChild);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) { print("Erreur image: $e"); }
|
||||
}
|
||||
|
||||
@@ -188,15 +207,8 @@ class _ParentRegisterStep3ScreenState extends State<ParentRegisterStep3Screen> {
|
||||
);
|
||||
if (picked != null) {
|
||||
final oldChild = registrationData.children[childIndex];
|
||||
final updatedChild = ChildData(
|
||||
firstName: oldChild.firstName,
|
||||
lastName: oldChild.lastName,
|
||||
dob: "${picked.day.toString().padLeft(2, '0')}/${picked.month.toString().padLeft(2, '0')}/${picked.year}",
|
||||
photoConsent: oldChild.photoConsent,
|
||||
multipleBirth: oldChild.multipleBirth,
|
||||
isUnbornChild: oldChild.isUnbornChild,
|
||||
imageFile: oldChild.imageFile,
|
||||
cardColor: oldChild.cardColor,
|
||||
final updatedChild = oldChild.copyWith(
|
||||
dob: "${picked.day.toString().padLeft(2, '0')}/${picked.month.toString().padLeft(2, '0')}/${picked.year}",
|
||||
);
|
||||
registrationData.updateChild(childIndex, updatedChild);
|
||||
}
|
||||
@@ -287,40 +299,42 @@ class _ParentRegisterStep3ScreenState extends State<ParentRegisterStep3Screen> {
|
||||
// Générer les cartes enfants
|
||||
for (int index = 0; index < registrationData.children.length; index++) ...[
|
||||
ChildCardWidget(
|
||||
key: ValueKey(registrationData.children[index].hashCode),
|
||||
key: ValueKey('parent_register_child_$index'),
|
||||
childData: registrationData.children[index],
|
||||
childIndex: index,
|
||||
onPickImage: () => _pickImage(index, registrationData),
|
||||
onClearImage: () => setState(() {
|
||||
final c = registrationData.children[index];
|
||||
registrationData.updateChild(
|
||||
index, c.copyWith(imageFile: null, imageBytes: null));
|
||||
}),
|
||||
onDateSelect: () => _selectDate(context, index, registrationData),
|
||||
onFirstNameChanged: (value) => setState(() => registrationData.updateChild(index, ChildData(
|
||||
firstName: value, lastName: registrationData.children[index].lastName, dob: registrationData.children[index].dob, photoConsent: registrationData.children[index].photoConsent,
|
||||
multipleBirth: registrationData.children[index].multipleBirth, isUnbornChild: registrationData.children[index].isUnbornChild, imageFile: registrationData.children[index].imageFile, cardColor: registrationData.children[index].cardColor
|
||||
))),
|
||||
onLastNameChanged: (value) => setState(() => registrationData.updateChild(index, ChildData(
|
||||
firstName: registrationData.children[index].firstName, lastName: value, dob: registrationData.children[index].dob, photoConsent: registrationData.children[index].photoConsent,
|
||||
multipleBirth: registrationData.children[index].multipleBirth, isUnbornChild: registrationData.children[index].isUnbornChild, imageFile: registrationData.children[index].imageFile, cardColor: registrationData.children[index].cardColor
|
||||
))),
|
||||
onFirstNameChanged: (value) => setState(() {
|
||||
final c = registrationData.children[index];
|
||||
registrationData.updateChild(index, c.copyWith(firstName: value));
|
||||
}),
|
||||
onLastNameChanged: (value) => setState(() {
|
||||
final c = registrationData.children[index];
|
||||
registrationData.updateChild(index, c.copyWith(lastName: value));
|
||||
}),
|
||||
onGenreChanged: (value) => setState(() {
|
||||
final c = registrationData.children[index];
|
||||
registrationData.updateChild(index, c.copyWith(genre: value));
|
||||
}),
|
||||
onTogglePhotoConsent: (newValue) {
|
||||
final oldChild = registrationData.children[index];
|
||||
registrationData.updateChild(index, ChildData(
|
||||
firstName: oldChild.firstName, lastName: oldChild.lastName, dob: oldChild.dob, photoConsent: newValue,
|
||||
multipleBirth: oldChild.multipleBirth, isUnbornChild: oldChild.isUnbornChild, imageFile: oldChild.imageFile, cardColor: oldChild.cardColor
|
||||
));
|
||||
},
|
||||
onToggleMultipleBirth: (newValue) {
|
||||
final oldChild = registrationData.children[index];
|
||||
registrationData.updateChild(index, ChildData(
|
||||
firstName: oldChild.firstName, lastName: oldChild.lastName, dob: oldChild.dob, photoConsent: oldChild.photoConsent,
|
||||
multipleBirth: newValue, isUnbornChild: oldChild.isUnbornChild, imageFile: oldChild.imageFile, cardColor: oldChild.cardColor
|
||||
));
|
||||
registrationData.updateChild(index, oldChild.copyWith(photoConsent: newValue));
|
||||
},
|
||||
onToggleIsUnborn: (newValue) {
|
||||
final oldChild = registrationData.children[index];
|
||||
registrationData.updateChild(index, ChildData(
|
||||
firstName: oldChild.firstName, lastName: oldChild.lastName, dob: DataGenerator.dob(isUnborn: newValue),
|
||||
photoConsent: oldChild.photoConsent, multipleBirth: oldChild.multipleBirth, isUnbornChild: newValue,
|
||||
imageFile: oldChild.imageFile, cardColor: oldChild.cardColor
|
||||
));
|
||||
var g = oldChild.genre;
|
||||
if (!newValue && g == 'Autre') {
|
||||
g = '';
|
||||
}
|
||||
registrationData.updateChild(
|
||||
index,
|
||||
oldChild.copyWith(isUnbornChild: newValue, genre: g),
|
||||
);
|
||||
},
|
||||
onRemove: () => _removeChild(index, registrationData),
|
||||
canBeRemoved: registrationData.children.length > 1,
|
||||
@@ -343,7 +357,7 @@ class _ParentRegisterStep3ScreenState extends State<ParentRegisterStep3Screen> {
|
||||
|
||||
const SizedBox(height: 30),
|
||||
// Boutons navigation en bas du scroll
|
||||
_buildMobileButtons(context, config, screenSize),
|
||||
_buildMobileButtons(context, config, screenSize, registrationData),
|
||||
const SizedBox(height: 20),
|
||||
],
|
||||
),
|
||||
@@ -393,41 +407,43 @@ class _ParentRegisterStep3ScreenState extends State<ParentRegisterStep3Screen> {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 20.0),
|
||||
child: ChildCardWidget(
|
||||
key: ValueKey(registrationData.children[index].hashCode), // Utiliser une clé basée sur les données
|
||||
key: ValueKey('parent_register_child_$index'),
|
||||
childData: registrationData.children[index],
|
||||
childIndex: index,
|
||||
onPickImage: () => _pickImage(index, registrationData),
|
||||
onClearImage: () => setState(() {
|
||||
final c = registrationData.children[index];
|
||||
registrationData.updateChild(
|
||||
index, c.copyWith(imageFile: null, imageBytes: null));
|
||||
}),
|
||||
onDateSelect: () => _selectDate(context, index, registrationData),
|
||||
onFirstNameChanged: (value) => setState(() => registrationData.updateChild(index, ChildData(
|
||||
firstName: value, lastName: registrationData.children[index].lastName, dob: registrationData.children[index].dob, photoConsent: registrationData.children[index].photoConsent,
|
||||
multipleBirth: registrationData.children[index].multipleBirth, isUnbornChild: registrationData.children[index].isUnbornChild, imageFile: registrationData.children[index].imageFile, cardColor: registrationData.children[index].cardColor
|
||||
))),
|
||||
onLastNameChanged: (value) => setState(() => registrationData.updateChild(index, ChildData(
|
||||
firstName: registrationData.children[index].firstName, lastName: value, dob: registrationData.children[index].dob, photoConsent: registrationData.children[index].photoConsent,
|
||||
multipleBirth: registrationData.children[index].multipleBirth, isUnbornChild: registrationData.children[index].isUnbornChild, imageFile: registrationData.children[index].imageFile, cardColor: registrationData.children[index].cardColor
|
||||
))),
|
||||
onFirstNameChanged: (value) => setState(() {
|
||||
final c = registrationData.children[index];
|
||||
registrationData.updateChild(index, c.copyWith(firstName: value));
|
||||
}),
|
||||
onLastNameChanged: (value) => setState(() {
|
||||
final c = registrationData.children[index];
|
||||
registrationData.updateChild(index, c.copyWith(lastName: value));
|
||||
}),
|
||||
onGenreChanged: (value) => setState(() {
|
||||
final c = registrationData.children[index];
|
||||
registrationData.updateChild(index, c.copyWith(genre: value));
|
||||
}),
|
||||
onTogglePhotoConsent: (newValue) {
|
||||
final oldChild = registrationData.children[index];
|
||||
registrationData.updateChild(index, ChildData(
|
||||
firstName: oldChild.firstName, lastName: oldChild.lastName, dob: oldChild.dob, photoConsent: newValue,
|
||||
multipleBirth: oldChild.multipleBirth, isUnbornChild: oldChild.isUnbornChild, imageFile: oldChild.imageFile, cardColor: oldChild.cardColor
|
||||
));
|
||||
},
|
||||
onToggleMultipleBirth: (newValue) {
|
||||
final oldChild = registrationData.children[index];
|
||||
registrationData.updateChild(index, ChildData(
|
||||
firstName: oldChild.firstName, lastName: oldChild.lastName, dob: oldChild.dob, photoConsent: oldChild.photoConsent,
|
||||
multipleBirth: newValue, isUnbornChild: oldChild.isUnbornChild, imageFile: oldChild.imageFile, cardColor: oldChild.cardColor
|
||||
));
|
||||
registrationData.updateChild(index, oldChild.copyWith(photoConsent: newValue));
|
||||
},
|
||||
onToggleIsUnborn: (newValue) {
|
||||
final oldChild = registrationData.children[index];
|
||||
registrationData.updateChild(index, ChildData(
|
||||
firstName: oldChild.firstName, lastName: oldChild.lastName, dob: DataGenerator.dob(isUnborn: newValue),
|
||||
photoConsent: oldChild.photoConsent, multipleBirth: oldChild.multipleBirth, isUnbornChild: newValue,
|
||||
imageFile: oldChild.imageFile, cardColor: oldChild.cardColor
|
||||
));
|
||||
},
|
||||
final oldChild = registrationData.children[index];
|
||||
var g = oldChild.genre;
|
||||
if (!newValue && g == 'Autre') {
|
||||
g = '';
|
||||
}
|
||||
registrationData.updateChild(
|
||||
index,
|
||||
oldChild.copyWith(isUnbornChild: newValue, genre: g),
|
||||
);
|
||||
},
|
||||
onRemove: () => _removeChild(index, registrationData),
|
||||
canBeRemoved: registrationData.children.length > 1,
|
||||
),
|
||||
@@ -455,7 +471,12 @@ class _ParentRegisterStep3ScreenState extends State<ParentRegisterStep3Screen> {
|
||||
}
|
||||
|
||||
/// Boutons navigation mobile
|
||||
Widget _buildMobileButtons(BuildContext context, DisplayConfig config, Size screenSize) {
|
||||
Widget _buildMobileButtons(
|
||||
BuildContext context,
|
||||
DisplayConfig config,
|
||||
Size screenSize,
|
||||
UserRegistrationData registrationData,
|
||||
) {
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
@@ -483,7 +504,7 @@ class _ParentRegisterStep3ScreenState extends State<ParentRegisterStep3Screen> {
|
||||
text: 'Suivant',
|
||||
style: NavigationButtonStyle.green,
|
||||
onPressed: () {
|
||||
context.go('/parent-register-step4');
|
||||
_normalizeChildrenNamesAndGoToStep4(context, registrationData);
|
||||
},
|
||||
width: double.infinity,
|
||||
height: 50,
|
||||
|
||||
@@ -5,7 +5,6 @@ import 'package:go_router/go_router.dart';
|
||||
import '../../models/user_registration_data.dart';
|
||||
import '../../widgets/presentation_form_screen.dart';
|
||||
import '../../models/card_assets.dart';
|
||||
import '../../utils/data_generator.dart';
|
||||
|
||||
class ParentRegisterStep4Screen extends StatelessWidget {
|
||||
const ParentRegisterStep4Screen({super.key});
|
||||
@@ -14,22 +13,13 @@ class ParentRegisterStep4Screen extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
final registrationData = Provider.of<UserRegistrationData>(context, listen: false);
|
||||
|
||||
// Générer un texte de test si vide
|
||||
String initialText = registrationData.motivationText;
|
||||
bool initialCgu = registrationData.cguAccepted;
|
||||
|
||||
if (initialText.isEmpty) {
|
||||
initialText = DataGenerator.motivation();
|
||||
initialCgu = true;
|
||||
}
|
||||
|
||||
return PresentationFormScreen(
|
||||
stepText: 'Étape 4/5',
|
||||
title: 'Motivation de votre demande',
|
||||
cardColor: CardColorHorizontal.green,
|
||||
textFieldHint: 'Écrivez ici pour motiver votre demande...',
|
||||
initialText: initialText,
|
||||
initialCguAccepted: initialCgu,
|
||||
initialText: registrationData.motivationText,
|
||||
initialCguAccepted: registrationData.cguAccepted,
|
||||
previousRoute: '/parent-register-step3',
|
||||
onSubmit: (text, cguAccepted) {
|
||||
registrationData.updateMotivation(text);
|
||||
|
||||
@@ -13,6 +13,7 @@ import '../../widgets/custom_navigation_button.dart';
|
||||
import '../../widgets/personal_info_form_screen.dart';
|
||||
import '../../widgets/child_card_widget.dart';
|
||||
import '../../widgets/presentation_form_screen.dart';
|
||||
import '../../services/auth_service.dart';
|
||||
|
||||
class ParentRegisterStep5Screen extends StatefulWidget {
|
||||
const ParentRegisterStep5Screen({super.key});
|
||||
@@ -22,6 +23,36 @@ class ParentRegisterStep5Screen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _ParentRegisterStep5ScreenState extends State<ParentRegisterStep5Screen> {
|
||||
bool _isSubmitting = false;
|
||||
|
||||
Future<void> _submitRegistration(BuildContext context, UserRegistrationData data) async {
|
||||
if (_isSubmitting) return;
|
||||
setState(() => _isSubmitting = true);
|
||||
try {
|
||||
await AuthService.registerParent(data);
|
||||
if (!context.mounted) return;
|
||||
_showSuccessModal(context);
|
||||
} catch (e) {
|
||||
if (!context.mounted) return;
|
||||
final msg = e.toString().replaceAll('Exception: ', '');
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: Text('Envoi impossible', style: GoogleFonts.merienda(fontWeight: FontWeight.bold)),
|
||||
content: Text(msg, style: GoogleFonts.merienda(fontSize: 14)),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(),
|
||||
child: Text('OK', style: GoogleFonts.merienda(fontWeight: FontWeight.bold)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) setState(() => _isSubmitting = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final registrationData = Provider.of<UserRegistrationData>(context);
|
||||
@@ -102,12 +133,11 @@ class _ParentRegisterStep5ScreenState extends State<ParentRegisterStep5Screen> {
|
||||
Expanded(
|
||||
child: HoverReliefWidget(
|
||||
child: CustomNavigationButton(
|
||||
text: 'Soumettre',
|
||||
text: _isSubmitting ? 'Envoi…' : 'Soumettre',
|
||||
style: NavigationButtonStyle.green,
|
||||
onPressed: () {
|
||||
print("Données finales: ${registrationData.parent1.firstName}, Enfant(s): ${registrationData.children.length}");
|
||||
_showConfirmationModal(context);
|
||||
},
|
||||
onPressed: _isSubmitting
|
||||
? () {}
|
||||
: () => _submitRegistration(context, registrationData),
|
||||
width: double.infinity,
|
||||
height: 50,
|
||||
fontSize: 16,
|
||||
@@ -118,18 +148,20 @@ class _ParentRegisterStep5ScreenState extends State<ParentRegisterStep5Screen> {
|
||||
),
|
||||
)
|
||||
else
|
||||
ImageButton(
|
||||
bg: 'assets/images/bg_green.png',
|
||||
text: 'Soumettre ma demande',
|
||||
textColor: const Color(0xFF2D6A4F),
|
||||
width: 350,
|
||||
height: 50,
|
||||
fontSize: 18,
|
||||
onPressed: () {
|
||||
print("Données finales: ${registrationData.parent1.firstName}, Enfant(s): ${registrationData.children.length}");
|
||||
_showConfirmationModal(context);
|
||||
},
|
||||
),
|
||||
_isSubmitting
|
||||
? const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: CircularProgressIndicator(),
|
||||
)
|
||||
: ImageButton(
|
||||
bg: 'assets/images/bg_green.png',
|
||||
text: 'Soumettre ma demande',
|
||||
textColor: const Color(0xFF2D6A4F),
|
||||
width: 350,
|
||||
height: 50,
|
||||
fontSize: 18,
|
||||
onPressed: () => _submitRegistration(context, registrationData),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -216,11 +248,12 @@ class _ParentRegisterStep5ScreenState extends State<ParentRegisterStep5Screen> {
|
||||
childIndex: index,
|
||||
mode: DisplayMode.readonly,
|
||||
onPickImage: () {},
|
||||
onClearImage: () {},
|
||||
onDateSelect: () {},
|
||||
onFirstNameChanged: (v) {},
|
||||
onLastNameChanged: (v) {},
|
||||
onGenreChanged: (v) {},
|
||||
onTogglePhotoConsent: (v) {},
|
||||
onToggleMultipleBirth: (v) {},
|
||||
onToggleIsUnborn: (v) {},
|
||||
onRemove: () {},
|
||||
canBeRemoved: false,
|
||||
@@ -239,14 +272,14 @@ class _ParentRegisterStep5ScreenState extends State<ParentRegisterStep5Screen> {
|
||||
cardColor: CardColorHorizontal.green, // Changé de pink à green
|
||||
textFieldHint: '',
|
||||
initialText: data.motivationText,
|
||||
initialCguAccepted: true, // Toujours true ici car déjà passé
|
||||
initialCguAccepted: data.cguAccepted,
|
||||
previousRoute: '',
|
||||
onSubmit: (t, c) {},
|
||||
onEdit: () => context.go('/parent-register-step4'),
|
||||
);
|
||||
}
|
||||
|
||||
void _showConfirmationModal(BuildContext context) {
|
||||
void _showSuccessModal(BuildContext context) {
|
||||
showDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:p_tits_pas/models/user.dart';
|
||||
import 'package:p_tits_pas/services/auth_service.dart';
|
||||
import 'package:p_tits_pas/widgets/admin/user_management_panel.dart';
|
||||
import 'package:p_tits_pas/widgets/app_footer.dart';
|
||||
import 'package:p_tits_pas/widgets/dashboard/dashboard_bandeau.dart';
|
||||
|
||||
/// Dashboard gestionnaire – même shell que l'admin, sans onglet Paramètres.
|
||||
/// Réutilise [UserManagementPanel].
|
||||
class GestionnaireDashboardScreen extends StatefulWidget {
|
||||
const GestionnaireDashboardScreen({super.key});
|
||||
|
||||
@override
|
||||
State<GestionnaireDashboardScreen> createState() =>
|
||||
_GestionnaireDashboardScreenState();
|
||||
}
|
||||
|
||||
class _GestionnaireDashboardScreenState extends State<GestionnaireDashboardScreen> {
|
||||
AppUser? _user;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadUser();
|
||||
}
|
||||
|
||||
Future<void> _loadUser() async {
|
||||
final user = await AuthService.getCurrentUser();
|
||||
if (mounted) setState(() => _user = user);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: PreferredSize(
|
||||
preferredSize: const Size.fromHeight(60.0),
|
||||
child: DashboardBandeau(
|
||||
tabItems: const [
|
||||
DashboardTabItem(label: 'Gestion des utilisateurs'),
|
||||
],
|
||||
selectedTabIndex: 0,
|
||||
onTabSelected: (_) {},
|
||||
userDisplayName: _user?.fullName.isNotEmpty == true
|
||||
? _user!.fullName
|
||||
: 'Gestionnaire',
|
||||
userEmail: _user?.email,
|
||||
userRole: _user?.role,
|
||||
onProfileTap: () {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Modification du profil – à venir')),
|
||||
);
|
||||
},
|
||||
onSettingsTap: () {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Paramètres – à venir')),
|
||||
);
|
||||
},
|
||||
onLogout: () {},
|
||||
showLogoutConfirmation: true,
|
||||
),
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: UserManagementPanel(showAdministrateursTab: false),
|
||||
),
|
||||
const AppFooter(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user