Compare commits
92
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
939e7777ac | ||
|
|
b474842e19 | ||
|
|
a312d9c0fa | ||
|
|
b5b32062b3 | ||
|
|
946d8edcd2 | ||
|
|
c8cb82dd24 | ||
|
|
9cd180bf6a | ||
|
|
ca07d2e111 | ||
|
|
67336c64fe | ||
|
|
97afbbcf9a | ||
|
|
e235b30140 | ||
|
|
7f23356273 | ||
|
|
c8c9cfbc4d | ||
|
|
530e896b66 | ||
|
|
0029c5ab86 | ||
|
|
2ce9e9215f | ||
|
|
3fdd913367 | ||
|
|
6708f73b06 | ||
|
|
f596f062a6 | ||
|
|
86701731e3 | ||
|
|
b4abb7d6de | ||
|
|
cb5c1a5518 | ||
|
|
30ca99fb65 | ||
|
|
8ee2ca8ea6 | ||
|
|
e3552667bc | ||
|
|
4ae334b247 | ||
|
|
471a62ddb7 | ||
|
|
59afeb0a8d | ||
|
|
d2172eafdb | ||
|
|
d247867fa0 | ||
|
|
93912d1374 | ||
|
|
925b6d5cd4 | ||
|
|
b0dddd6695 | ||
|
|
ef7512dc1e | ||
|
|
2ececa711b | ||
|
|
7a3d997ff9 | ||
|
|
6b89d7b405 | ||
|
|
f7ac628445 | ||
|
|
26e9738ec7 | ||
|
|
0ec3410457 | ||
|
|
c3acf1970d | ||
|
|
6fe2b89a61 | ||
|
|
d6a9b3fd66 | ||
|
|
134b9781c8 | ||
|
|
b936d27445 | ||
|
|
18c1d1eba7 | ||
|
|
f74b14c203 | ||
|
|
f194b5f9e8 | ||
|
|
5ab8ae3423 | ||
|
|
3277f77846 | ||
|
|
2d80ad0d7e | ||
|
|
09386f8aa6 | ||
|
|
faa50f637c | ||
|
|
267fe63aec | ||
|
|
90b185740c | ||
|
|
b903dbf60b | ||
|
|
291ea26b34 | ||
|
|
59919834b9 | ||
|
|
cf6acbae7c | ||
|
|
7951c38d4d | ||
|
|
77d952a6f7 | ||
|
|
b4b546044d | ||
|
|
6788351070 | ||
|
|
7b69f27ca5 | ||
|
|
8ed68797aa | ||
|
|
9ad371a342 | ||
|
|
18718670e9 | ||
|
|
fbf22f2540 | ||
|
|
43a2cd213b | ||
|
|
c865d11dc3 | ||
|
|
d03a8e6c8b | ||
|
|
66c7f22280 | ||
|
|
53721ffbb3 | ||
|
|
52e40d0001 | ||
|
|
4985726bc6 | ||
|
|
479a32b4bf | ||
|
|
2fd97ddecb | ||
|
|
ce474797c4 | ||
|
|
ebf794e1ac | ||
|
|
d55f240f56 | ||
|
|
966f4a9c9c | ||
|
|
8494341b56 | ||
|
|
1dddc67933 | ||
|
|
df776d8200 | ||
|
|
c26ed00374 | ||
|
|
9d54d9b19b | ||
|
|
c438009286 | ||
|
|
9b7231f1da | ||
|
|
f300505225 | ||
|
|
25c10c885a | ||
|
|
d70577b1c3 | ||
|
|
671da71752 |
@@ -89,6 +89,9 @@
|
|||||||
"transform": {
|
"transform": {
|
||||||
"^.+\\.(t|j)s$": "ts-jest"
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
},
|
},
|
||||||
|
"moduleNameMapper": {
|
||||||
|
"^src/(.*)$": "<rootDir>/$1"
|
||||||
|
},
|
||||||
"collectCoverageFrom": [
|
"collectCoverageFrom": [
|
||||||
"**/*.(t|j)s"
|
"**/*.(t|j)s"
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -33,7 +33,6 @@ model Child {
|
|||||||
dateOfBirth DateTime
|
dateOfBirth DateTime
|
||||||
photoUrl String?
|
photoUrl String?
|
||||||
photoConsent Boolean @default(false)
|
photoConsent Boolean @default(false)
|
||||||
isMultiple Boolean @default(false)
|
|
||||||
isUnborn Boolean @default(false)
|
isUnborn Boolean @default(false)
|
||||||
parentId String
|
parentId String
|
||||||
parent Parent @relation(fields: [parentId], references: [id])
|
parent Parent @relation(fields: [parentId], references: [id])
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
/**
|
||||||
|
* Crée l'issue Gitea — gestionnaire ne doit pas pouvoir se supprimer.
|
||||||
|
* Usage: node backend/scripts/create-gitea-issue-gestionnaire-self-delete.js
|
||||||
|
*/
|
||||||
|
const https = require('https');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const repoRoot = path.join(__dirname, '../..');
|
||||||
|
const MILESTONE_0_1_0 = 10;
|
||||||
|
|
||||||
|
let token = process.env.GITEA_TOKEN;
|
||||||
|
if (!token) {
|
||||||
|
try {
|
||||||
|
const tokenFile = path.join(repoRoot, '.gitea-token');
|
||||||
|
if (fs.existsSync(tokenFile)) token = fs.readFileSync(tokenFile, 'utf8').trim();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
if (!token) {
|
||||||
|
try {
|
||||||
|
const briefing = fs.readFileSync(
|
||||||
|
path.join(repoRoot, 'docs/27_BRIEFING-FRONTEND.md'),
|
||||||
|
'utf8',
|
||||||
|
);
|
||||||
|
const m = briefing.match(/Token:\s*(gitebu_[a-f0-9]+)/);
|
||||||
|
if (m) token = m[1].trim();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
if (!token) {
|
||||||
|
console.error('Token non trouvé : .gitea-token ou GITEA_TOKEN');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = `## Contexte
|
||||||
|
|
||||||
|
Quand un **gestionnaire** connecté ouvre sa propre fiche dans l'onglet **Gestionnaires** (Gestion des utilisateurs), la modale **Modifier un "Gestionnaire"** affiche le bouton **Supprimer**.
|
||||||
|
|
||||||
|
Comportement actuel : le gestionnaire voit et peut tenter de supprimer son propre compte.
|
||||||
|
|
||||||
|
## Comportement attendu
|
||||||
|
|
||||||
|
Comme pour le **super administrateur** (bouton Supprimer masqué sur la fiche super admin) :
|
||||||
|
|
||||||
|
- **Pas de bouton Supprimer** quand l'utilisateur édite **sa propre fiche**
|
||||||
|
- **Modification** des informations (prénom, nom, email, téléphone, relais, mot de passe) **toujours autorisée**
|
||||||
|
|
||||||
|
## Périmètre
|
||||||
|
|
||||||
|
- Frontend : \`AdminUserFormDialog\` (\`gestionnaires_create.dart\`)
|
||||||
|
- Comparer \`initialUser.id\` avec l'utilisateur connecté (\`AuthService.getCurrentUser\`)
|
||||||
|
- Masquer Supprimer si édition de soi-même ; conserver garde existante super admin
|
||||||
|
|
||||||
|
## Critères d'acceptation
|
||||||
|
|
||||||
|
- [ ] Gestionnaire connecté → ouvre sa fiche → **pas** de bouton Supprimer
|
||||||
|
- [ ] Gestionnaire connecté → peut **Modifier** ses informations
|
||||||
|
- [ ] Super admin / admin → peut toujours supprimer **un autre** gestionnaire (si droits API)
|
||||||
|
- [ ] Pas de régression sur fiche super administrateur (Supprimer toujours masqué)
|
||||||
|
|
||||||
|
## Fichiers clés
|
||||||
|
|
||||||
|
- \`frontend/lib/screens/administrateurs/creation/gestionnaires_create.dart\`
|
||||||
|
- \`frontend/lib/widgets/admin/gestionnaire_management_widget.dart\`
|
||||||
|
|
||||||
|
## Milestone
|
||||||
|
|
||||||
|
**0.1.0** — correction UX / sécurité gestion utilisateurs.`;
|
||||||
|
|
||||||
|
const payloadClean = JSON.stringify({
|
||||||
|
title: '[Bug] Gestionnaire peut voir Supprimer sur sa propre fiche',
|
||||||
|
body,
|
||||||
|
milestone: MILESTONE_0_1_0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const opts = {
|
||||||
|
hostname: 'git.ptits-pas.fr',
|
||||||
|
path: '/api/v1/repos/jmartin/petitspas/issues',
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
Authorization: 'token ' + token,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Content-Length': Buffer.byteLength(payloadClean),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const req = https.request(opts, (res) => {
|
||||||
|
let d = '';
|
||||||
|
res.on('data', (c) => (d += c));
|
||||||
|
res.on('end', () => {
|
||||||
|
try {
|
||||||
|
const o = JSON.parse(d);
|
||||||
|
if (o.number) {
|
||||||
|
console.log('NUMBER:', o.number);
|
||||||
|
console.log('URL:', o.html_url);
|
||||||
|
console.log('MILESTONE:', o.milestone?.title ?? '(aucun)');
|
||||||
|
} else {
|
||||||
|
console.error('Réponse:', d);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(d);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
req.on('error', (e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
req.write(payloadClean);
|
||||||
|
req.end();
|
||||||
@@ -18,6 +18,7 @@ import { AppConfigModule } from './modules/config/config.module';
|
|||||||
import { DocumentsLegauxModule } from './modules/documents-legaux';
|
import { DocumentsLegauxModule } from './modules/documents-legaux';
|
||||||
import { RelaisModule } from './routes/relais/relais.module';
|
import { RelaisModule } from './routes/relais/relais.module';
|
||||||
import { DossiersModule } from './routes/dossiers/dossiers.module';
|
import { DossiersModule } from './routes/dossiers/dossiers.module';
|
||||||
|
import { SuppressionsModule } from './routes/suppressions/suppressions.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -57,6 +58,7 @@ import { DossiersModule } from './routes/dossiers/dossiers.module';
|
|||||||
DocumentsLegauxModule,
|
DocumentsLegauxModule,
|
||||||
RelaisModule,
|
RelaisModule,
|
||||||
DossiersModule,
|
DossiersModule,
|
||||||
|
SuppressionsModule,
|
||||||
],
|
],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [
|
providers: [
|
||||||
|
|||||||
@@ -63,9 +63,6 @@ export class Children {
|
|||||||
@Column({ type: 'timestamptz', nullable: true, name: 'date_consentement_photo' })
|
@Column({ type: 'timestamptz', nullable: true, name: 'date_consentement_photo' })
|
||||||
consent_photo_at?: Date;
|
consent_photo_at?: Date;
|
||||||
|
|
||||||
@Column({ default: false, name: 'est_multiple', type: 'boolean' })
|
|
||||||
is_multiple: boolean;
|
|
||||||
|
|
||||||
// Lien via table de jointure enfants_parents
|
// Lien via table de jointure enfants_parents
|
||||||
@OneToMany(() => ParentsChildren, pc => pc.child)
|
@OneToMany(() => ParentsChildren, pc => pc.child)
|
||||||
parentLinks: ParentsChildren[];
|
parentLinks: ParentsChildren[];
|
||||||
|
|||||||
+51
-2
@@ -1,20 +1,69 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { AssistantesMaternellesController } from './assistantes_maternelles.controller';
|
import { AssistantesMaternellesController } from './assistantes_maternelles.controller';
|
||||||
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
||||||
|
import { AuthService } from '../auth/auth.service';
|
||||||
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
|
||||||
describe('AssistantesMaternellesController', () => {
|
describe('AssistantesMaternellesController', () => {
|
||||||
let controller: AssistantesMaternellesController;
|
let controller: AssistantesMaternellesController;
|
||||||
|
const authServiceMock = {
|
||||||
|
createAmDossierStaff: jest.fn(),
|
||||||
|
};
|
||||||
|
const amServiceMock = {};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
controllers: [AssistantesMaternellesController],
|
controllers: [AssistantesMaternellesController],
|
||||||
providers: [AssistantesMaternellesService],
|
providers: [
|
||||||
}).compile();
|
{ provide: AssistantesMaternellesService, useValue: amServiceMock },
|
||||||
|
{ provide: AuthService, useValue: authServiceMock },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.overrideGuard(AuthGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.overrideGuard(RolesGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.compile();
|
||||||
|
|
||||||
controller = module.get<AssistantesMaternellesController>(AssistantesMaternellesController);
|
controller = module.get<AssistantesMaternellesController>(AssistantesMaternellesController);
|
||||||
|
jest.clearAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('should be defined', () => {
|
||||||
expect(controller).toBeDefined();
|
expect(controller).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('createDossier delegates to authService.createAmDossierStaff with CGU accepted', async () => {
|
||||||
|
authServiceMock.createAmDossierStaff.mockResolvedValue({
|
||||||
|
message: 'ok',
|
||||||
|
user_id: 'u1',
|
||||||
|
statut: 'actif',
|
||||||
|
numero_dossier: '2026-000001',
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = {
|
||||||
|
email: 'am.staff@test.fr',
|
||||||
|
prenom: 'Marie',
|
||||||
|
nom: 'TEST',
|
||||||
|
telephone: '0689567890',
|
||||||
|
consentement_photo: false,
|
||||||
|
lieu_naissance_ville: 'Paris',
|
||||||
|
lieu_naissance_pays: 'France',
|
||||||
|
nir: '285017512345678',
|
||||||
|
numero_agrement: 'AGR-TEST-001',
|
||||||
|
capacite_accueil: 3,
|
||||||
|
places_disponibles: 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
const res = await controller.createDossier(body as any);
|
||||||
|
expect(authServiceMock.createAmDossierStaff).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
email: body.email,
|
||||||
|
acceptation_cgu: true,
|
||||||
|
acceptation_privacy: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(res.numero_dossier).toBe('2026-000001');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import {
|
|||||||
Param,
|
Param,
|
||||||
Delete,
|
Delete,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
||||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||||
@@ -16,17 +18,49 @@ import { RoleType, Users } from 'src/entities/users.entity';
|
|||||||
import { CreateAssistanteDto } from '../user/dto/create_assistante.dto';
|
import { CreateAssistanteDto } from '../user/dto/create_assistante.dto';
|
||||||
import { UpdateAssistanteDto } from '../user/dto/update_assistante.dto';
|
import { UpdateAssistanteDto } from '../user/dto/update_assistante.dto';
|
||||||
import { UpdateAmFicheAdminDto } from './dto/update-am-fiche-admin.dto';
|
import { UpdateAmFicheAdminDto } from './dto/update-am-fiche-admin.dto';
|
||||||
|
import { StaffCreateAmDossierDto } from './dto/staff-create-am-dossier.dto';
|
||||||
|
import { StaffCreateAmDossierResponseDto } from './dto/staff-create-am-dossier-response.dto';
|
||||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
import { User } from 'src/common/decorators/user.decorator';
|
import { User } from 'src/common/decorators/user.decorator';
|
||||||
import { mapAmForApi, mapAmsForApi } from './assistantes_maternelles.mapper';
|
import { mapAmForApi, mapAmsForApi } from './assistantes_maternelles.mapper';
|
||||||
|
import { AuthService } from '../auth/auth.service';
|
||||||
|
import { RegisterAMCompletDto } from '../auth/dto/register-am-complet.dto';
|
||||||
|
|
||||||
@ApiTags("Assistantes Maternelles")
|
@ApiTags("Assistantes Maternelles")
|
||||||
@ApiBearerAuth('access-token')
|
@ApiBearerAuth('access-token')
|
||||||
@UseGuards(AuthGuard, RolesGuard)
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
@Controller('assistantes-maternelles')
|
@Controller('assistantes-maternelles')
|
||||||
export class AssistantesMaternellesController {
|
export class AssistantesMaternellesController {
|
||||||
constructor(private readonly assistantesMaternellesService: AssistantesMaternellesService) { }
|
constructor(
|
||||||
|
private readonly assistantesMaternellesService: AssistantesMaternellesService,
|
||||||
|
private readonly authService: AuthService,
|
||||||
|
) { }
|
||||||
|
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
|
@Post('dossier')
|
||||||
|
@HttpCode(HttpStatus.CREATED)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Créer un dossier AM complet (staff) — ticket #156',
|
||||||
|
description:
|
||||||
|
'Crée user + fiche AM avec statut actif, n° dossier, et envoie l’e-mail de création de mot de passe. ' +
|
||||||
|
'Ne pas utiliser POST /auth/register/am depuis le dashboard.',
|
||||||
|
})
|
||||||
|
@ApiBody({ type: StaffCreateAmDossierDto })
|
||||||
|
@ApiResponse({ status: 201, type: StaffCreateAmDossierResponseDto })
|
||||||
|
@ApiResponse({ status: 400, description: 'Validation métier / NIR' })
|
||||||
|
@ApiResponse({ status: 403, description: 'Rôle non autorisé' })
|
||||||
|
@ApiResponse({ status: 409, description: 'Email / NIR / agrément déjà pris' })
|
||||||
|
async createDossier(
|
||||||
|
@Body() dto: StaffCreateAmDossierDto,
|
||||||
|
): Promise<StaffCreateAmDossierResponseDto> {
|
||||||
|
const registerDto = {
|
||||||
|
...dto,
|
||||||
|
acceptation_cgu: true,
|
||||||
|
acceptation_privacy: true,
|
||||||
|
} as RegisterAMCompletDto;
|
||||||
|
return this.authService.createAmDossierStaff(registerDto);
|
||||||
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE)
|
||||||
@ApiOperation({ summary: 'Créer nounou' })
|
@ApiOperation({ summary: 'Créer nounou' })
|
||||||
|
|||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
/** Réponse 201 POST /assistantes-maternelles/dossier (#156). */
|
||||||
|
export class StaffCreateAmDossierResponseDto {
|
||||||
|
@ApiProperty()
|
||||||
|
message: string;
|
||||||
|
|
||||||
|
@ApiProperty({ format: 'uuid' })
|
||||||
|
user_id: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
enum: StatutUtilisateurType,
|
||||||
|
example: StatutUtilisateurType.ACTIF,
|
||||||
|
})
|
||||||
|
statut: StatutUtilisateurType;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: '2026-000042',
|
||||||
|
description: 'Numéro de dossier attribué',
|
||||||
|
})
|
||||||
|
numero_dossier: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { ApiPropertyOptional, OmitType } from '@nestjs/swagger';
|
||||||
|
import { IsBoolean, IsOptional } from 'class-validator';
|
||||||
|
import { RegisterAMCompletDto } from 'src/routes/auth/dto/register-am-complet.dto';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Création dossier AM par staff (#156).
|
||||||
|
* Mêmes champs que l'inscription publique, sans CGU/privacy obligatoires
|
||||||
|
* (acceptées côté serveur pour le compte du gestionnaire).
|
||||||
|
*/
|
||||||
|
export class StaffCreateAmDossierDto extends OmitType(RegisterAMCompletDto, [
|
||||||
|
'acceptation_cgu',
|
||||||
|
'acceptation_privacy',
|
||||||
|
] as const) {
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Ignoré côté staff (CGU acceptées serveur). Conservé pour compat éventuelle.',
|
||||||
|
default: true,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
acceptation_cgu?: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Ignoré côté staff (privacy acceptée serveur).',
|
||||||
|
default: true,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
acceptation_privacy?: boolean;
|
||||||
|
}
|
||||||
@@ -29,7 +29,7 @@ import { ParentsChildren } from 'src/entities/parents_children.entity';
|
|||||||
ParentsChildren,
|
ParentsChildren,
|
||||||
]),
|
]),
|
||||||
forwardRef(() => UserModule),
|
forwardRef(() => UserModule),
|
||||||
ParentsModule,
|
forwardRef(() => ParentsModule),
|
||||||
DossiersModule,
|
DossiersModule,
|
||||||
AppConfigModule,
|
AppConfigModule,
|
||||||
MailModule,
|
MailModule,
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ import { MailService } from 'src/modules/mail/mail.service';
|
|||||||
import { ParentsService } from '../parents/parents.service';
|
import { ParentsService } from '../parents/parents.service';
|
||||||
import { DossiersService } from '../dossiers/dossiers.service';
|
import { DossiersService } from '../dossiers/dossiers.service';
|
||||||
import { DossierAmCompletDto } from '../dossiers/dto/dossier-am-complet.dto';
|
import { DossierAmCompletDto } from '../dossiers/dto/dossier-am-complet.dto';
|
||||||
|
import { StaffAddCoParentDto } from '../parents/dto/staff-add-co-parent.dto';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
@@ -416,11 +417,20 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Inscription Parent COMPLÈTE - Workflow CDC 6 étapes en 1 transaction
|
* Cœur partagé création dossier parent (#129).
|
||||||
* Gère : Parent 1 + Parent 2 (opt) + Enfants + Présentation + CGU
|
* - public : statut en_attente + mails pending
|
||||||
|
* - staff : statut actif + mails création MDP (pas de mail « dossier en attente »)
|
||||||
*/
|
*/
|
||||||
async inscrireParentComplet(dto: RegisterParentCompletDto) {
|
async createParentDossier(
|
||||||
if (!dto.acceptation_cgu || !dto.acceptation_privacy) {
|
dto: RegisterParentCompletDto,
|
||||||
|
options: {
|
||||||
|
statut: StatutUtilisateurType;
|
||||||
|
sendPendingEmail: boolean;
|
||||||
|
sendPasswordSetupEmail: boolean;
|
||||||
|
requireCgu: boolean;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
if (options.requireCgu && (!dto.acceptation_cgu || !dto.acceptation_privacy)) {
|
||||||
throw new BadRequestException('L\'acceptation des CGU et de la politique de confidentialité est obligatoire');
|
throw new BadRequestException('L\'acceptation des CGU et de la politique de confidentialité est obligatoire');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -471,7 +481,7 @@ export class AuthService {
|
|||||||
prenom: dto.prenom,
|
prenom: dto.prenom,
|
||||||
nom: dto.nom,
|
nom: dto.nom,
|
||||||
role: RoleType.PARENT,
|
role: RoleType.PARENT,
|
||||||
statut: StatutUtilisateurType.EN_ATTENTE,
|
statut: options.statut,
|
||||||
telephone: dto.telephone,
|
telephone: dto.telephone,
|
||||||
adresse: dto.adresse,
|
adresse: dto.adresse,
|
||||||
code_postal: dto.code_postal,
|
code_postal: dto.code_postal,
|
||||||
@@ -496,7 +506,7 @@ export class AuthService {
|
|||||||
prenom: dto.co_parent_prenom,
|
prenom: dto.co_parent_prenom,
|
||||||
nom: dto.co_parent_nom,
|
nom: dto.co_parent_nom,
|
||||||
role: RoleType.PARENT,
|
role: RoleType.PARENT,
|
||||||
statut: StatutUtilisateurType.EN_ATTENTE,
|
statut: options.statut,
|
||||||
telephone: dto.co_parent_telephone,
|
telephone: dto.co_parent_telephone,
|
||||||
adresse: dto.co_parent_meme_adresse ? dto.adresse : dto.co_parent_adresse,
|
adresse: dto.co_parent_meme_adresse ? dto.adresse : dto.co_parent_adresse,
|
||||||
code_postal: dto.co_parent_meme_adresse ? dto.code_postal : dto.co_parent_code_postal,
|
code_postal: dto.co_parent_meme_adresse ? dto.code_postal : dto.co_parent_code_postal,
|
||||||
@@ -552,8 +562,8 @@ export class AuthService {
|
|||||||
: undefined;
|
: undefined;
|
||||||
enfant.photo_url = urlPhoto || undefined;
|
enfant.photo_url = urlPhoto || undefined;
|
||||||
enfant.status = enfantDto.date_naissance ? StatutEnfantType.SANS_GARDE : StatutEnfantType.A_NAITRE;
|
enfant.status = enfantDto.date_naissance ? StatutEnfantType.SANS_GARDE : StatutEnfantType.A_NAITRE;
|
||||||
enfant.consent_photo = false;
|
enfant.consent_photo = !!enfantDto.consent_photo;
|
||||||
enfant.is_multiple = enfantDto.grossesse_multiple || false;
|
enfant.consent_photo_at = enfant.consent_photo ? new Date() : null!;
|
||||||
|
|
||||||
const enfantEnregistre = await manager.save(Children, enfant);
|
const enfantEnregistre = await manager.save(Children, enfant);
|
||||||
enfantsEnregistres.push(enfantEnregistre);
|
enfantsEnregistres.push(enfantEnregistre);
|
||||||
@@ -611,6 +621,7 @@ export class AuthService {
|
|||||||
|
|
||||||
const numeroDossier = resultat.parent1.numero_dossier ?? '';
|
const numeroDossier = resultat.parent1.numero_dossier ?? '';
|
||||||
|
|
||||||
|
if (options.sendPendingEmail) {
|
||||||
try {
|
try {
|
||||||
await this.mailService.sendRegistrationPendingEmail(
|
await this.mailService.sendRegistrationPendingEmail(
|
||||||
resultat.parent1.email,
|
resultat.parent1.email,
|
||||||
@@ -628,27 +639,269 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
"[inscrireParentComplet] Échec envoi email d'accusé de réception (inscription conservée)",
|
"[createParentDossier] Échec envoi email d'accusé de réception (inscription conservée)",
|
||||||
err instanceof Error ? err.stack : String(err),
|
err instanceof Error ? err.stack : String(err),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.sendPasswordSetupEmail) {
|
||||||
|
try {
|
||||||
|
await this.mailService.sendValidatedAccountPasswordSetupEmail(
|
||||||
|
{
|
||||||
|
email: resultat.parent1.email,
|
||||||
|
prenom: resultat.parent1.prenom ?? '',
|
||||||
|
nom: resultat.parent1.nom ?? '',
|
||||||
|
token: resultat.tokenCreationMdp,
|
||||||
|
numeroDossier,
|
||||||
|
},
|
||||||
|
'parent',
|
||||||
|
);
|
||||||
|
if (resultat.parent2 && resultat.tokenCoParent) {
|
||||||
|
await this.mailService.sendValidatedAccountPasswordSetupEmail(
|
||||||
|
{
|
||||||
|
email: resultat.parent2.email,
|
||||||
|
prenom: resultat.parent2.prenom ?? '',
|
||||||
|
nom: resultat.parent2.nom ?? '',
|
||||||
|
token: resultat.tokenCoParent,
|
||||||
|
numeroDossier,
|
||||||
|
},
|
||||||
|
'parent',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error(
|
||||||
|
'[createParentDossier] Échec envoi email création MDP (dossier conservé)',
|
||||||
|
err instanceof Error ? err.stack : String(err),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = options.sendPasswordSetupEmail
|
||||||
|
? 'Dossier famille créé et validé. Un e-mail de création de mot de passe a été envoyé.'
|
||||||
|
: 'Inscription réussie. Votre dossier est en attente de validation par un gestionnaire.';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message: 'Inscription réussie. Votre dossier est en attente de validation par un gestionnaire.',
|
message,
|
||||||
parent_id: resultat.parent1.id,
|
parent_id: resultat.parent1.id,
|
||||||
co_parent_id: resultat.parent2?.id,
|
parent_user_id: resultat.parent1.id,
|
||||||
|
co_parent_id: resultat.parent2?.id ?? null,
|
||||||
|
co_parent_user_id: resultat.parent2?.id ?? null,
|
||||||
enfants_ids: resultat.enfants.map(e => e.id),
|
enfants_ids: resultat.enfants.map(e => e.id),
|
||||||
statut: StatutUtilisateurType.EN_ATTENTE,
|
enfant_ids: resultat.enfants.map(e => e.id),
|
||||||
|
statut: options.statut,
|
||||||
numero_dossier: numeroDossier,
|
numero_dossier: numeroDossier,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Inscription Assistante Maternelle COMPLÈTE - Un seul endpoint (identité + pro + photo + CGU)
|
* Inscription Parent publique — CDC (statut en_attente + mail pending).
|
||||||
* Crée User (role AM) + entrée assistantes_maternelles, token création MDP
|
|
||||||
*/
|
*/
|
||||||
async inscrireAMComplet(dto: RegisterAMCompletDto) {
|
async inscrireParentComplet(dto: RegisterParentCompletDto) {
|
||||||
if (!dto.acceptation_cgu || !dto.acceptation_privacy) {
|
return this.createParentDossier(dto, {
|
||||||
|
statut: StatutUtilisateurType.EN_ATTENTE,
|
||||||
|
sendPendingEmail: true,
|
||||||
|
sendPasswordSetupEmail: false,
|
||||||
|
requireCgu: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Création dossier parent par le staff (#129) — actif + mail création MDP.
|
||||||
|
*/
|
||||||
|
async createParentDossierStaff(dto: RegisterParentCompletDto) {
|
||||||
|
return this.createParentDossier(dto, {
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
sendPendingEmail: false,
|
||||||
|
sendPasswordSetupEmail: true,
|
||||||
|
requireCgu: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ajoute un co-parent à un foyer existant (mono-parent) — ticket #135.
|
||||||
|
* Compte actif + mail création MDP + liens Parents bidirectionnels + enfants du foyer.
|
||||||
|
*/
|
||||||
|
async addCoParentStaff(pivotUserId: string, dto: StaffAddCoParentDto) {
|
||||||
|
const pivotParent = await this.parentsRepo.findOne({
|
||||||
|
where: { user_id: pivotUserId },
|
||||||
|
relations: ['user', 'co_parent', 'parentChildren'],
|
||||||
|
});
|
||||||
|
if (!pivotParent?.user) {
|
||||||
|
throw new NotFoundException('Parent introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pivotParent.co_parent) {
|
||||||
|
throw new BadRequestException('Ce foyer a déjà un co-parent.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const numeroDossier = pivotParent.numero_dossier?.trim() || pivotParent.user.numero_dossier?.trim();
|
||||||
|
if (!numeroDossier) {
|
||||||
|
throw new BadRequestException("Ce parent n'a pas de numéro de dossier.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const sameDossierCount = await this.parentsRepo.count({
|
||||||
|
where: { numero_dossier: numeroDossier },
|
||||||
|
});
|
||||||
|
if (sameDossierCount >= 2) {
|
||||||
|
throw new BadRequestException('Ce dossier a déjà deux responsables.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const email = dto.email.trim().toLowerCase();
|
||||||
|
if (pivotParent.user.email.trim().toLowerCase() === email) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
"L'email du co-parent doit être différent de celui du parent principal.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const emailExiste = await this.usersService.findByEmailOrNull(dto.email);
|
||||||
|
if (emailExiste) {
|
||||||
|
throw new ConflictException("L'email du co-parent est déjà utilisé");
|
||||||
|
}
|
||||||
|
|
||||||
|
const memeAdresse = dto.meme_adresse ?? true;
|
||||||
|
if (!memeAdresse) {
|
||||||
|
if (!dto.adresse?.trim() || !dto.ville?.trim() || !dto.code_postal?.trim()) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
"Adresse, code postal et ville du co-parent sont requis si meme_adresse est faux.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const joursExpirationToken = await this.appConfigService.get<number>(
|
||||||
|
'password_reset_token_expiry_days',
|
||||||
|
7,
|
||||||
|
);
|
||||||
|
const tokenCreationMdp = crypto.randomUUID();
|
||||||
|
const dateExpiration = new Date();
|
||||||
|
dateExpiration.setDate(dateExpiration.getDate() + joursExpirationToken);
|
||||||
|
|
||||||
|
let coParent: Users;
|
||||||
|
|
||||||
|
try {
|
||||||
|
coParent = await this.usersRepo.manager.transaction(async (manager) => {
|
||||||
|
const pivotUser = await manager.findOne(Users, {
|
||||||
|
where: { id: pivotUserId },
|
||||||
|
});
|
||||||
|
if (!pivotUser) {
|
||||||
|
throw new NotFoundException('Parent introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const pivotEntite = await manager.findOne(Parents, {
|
||||||
|
where: { user_id: pivotUserId },
|
||||||
|
relations: ['parentChildren'],
|
||||||
|
});
|
||||||
|
if (!pivotEntite) {
|
||||||
|
throw new NotFoundException('Parent introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const coUser = manager.create(Users, {
|
||||||
|
email: dto.email.trim(),
|
||||||
|
prenom: dto.prenom,
|
||||||
|
nom: dto.nom,
|
||||||
|
role: RoleType.PARENT,
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
telephone: dto.telephone,
|
||||||
|
adresse: memeAdresse ? pivotUser.adresse : dto.adresse,
|
||||||
|
code_postal: memeAdresse ? pivotUser.code_postal : dto.code_postal,
|
||||||
|
ville: memeAdresse ? pivotUser.ville : dto.ville,
|
||||||
|
token_creation_mdp: tokenCreationMdp,
|
||||||
|
token_creation_mdp_expire_le: dateExpiration,
|
||||||
|
numero_dossier: numeroDossier,
|
||||||
|
});
|
||||||
|
const coUserSaved = await manager.save(Users, coUser);
|
||||||
|
|
||||||
|
pivotEntite.co_parent = coUserSaved;
|
||||||
|
pivotEntite.numero_dossier = numeroDossier;
|
||||||
|
await manager.save(Parents, pivotEntite);
|
||||||
|
|
||||||
|
const coEntite = manager.create(Parents, {
|
||||||
|
user_id: coUserSaved.id,
|
||||||
|
numero_dossier: numeroDossier,
|
||||||
|
});
|
||||||
|
coEntite.user = coUserSaved;
|
||||||
|
coEntite.co_parent = pivotUser;
|
||||||
|
await manager.save(Parents, coEntite);
|
||||||
|
|
||||||
|
const enfantIds = (pivotEntite.parentChildren ?? [])
|
||||||
|
.map((pc) => pc.enfantId)
|
||||||
|
.filter(Boolean);
|
||||||
|
for (const enfantId of enfantIds) {
|
||||||
|
const existing = await manager.findOne(ParentsChildren, {
|
||||||
|
where: { parentId: coUserSaved.id, enfantId },
|
||||||
|
});
|
||||||
|
if (existing) continue;
|
||||||
|
await manager.save(
|
||||||
|
ParentsChildren,
|
||||||
|
manager.create(ParentsChildren, {
|
||||||
|
parentId: coUserSaved.id,
|
||||||
|
enfantId,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return coUserSaved;
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
if (this.isPostgresUniqueViolation(err)) {
|
||||||
|
throw new ConflictException(
|
||||||
|
'Un compte avec cet email existe déjà (contrainte unique en base).',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.mailService.sendValidatedAccountPasswordSetupEmail(
|
||||||
|
{
|
||||||
|
email: coParent.email,
|
||||||
|
prenom: coParent.prenom ?? '',
|
||||||
|
nom: coParent.nom ?? '',
|
||||||
|
token: tokenCreationMdp,
|
||||||
|
numeroDossier,
|
||||||
|
},
|
||||||
|
'parent',
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error(
|
||||||
|
'[addCoParentStaff] Échec envoi email création MDP (co-parent conservé)',
|
||||||
|
err instanceof Error ? err.stack : String(err),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
message:
|
||||||
|
'Co-parent ajouté au foyer. Un e-mail de création de mot de passe a été envoyé.',
|
||||||
|
numero_dossier: numeroDossier,
|
||||||
|
parent_user_id: pivotUserId,
|
||||||
|
co_parent_user_id: coParent.id,
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cœur partagé création dossier AM (#156).
|
||||||
|
* - public : statut en_attente + mail pending
|
||||||
|
* - staff : statut actif + mail création MDP
|
||||||
|
*/
|
||||||
|
async createAmDossier(
|
||||||
|
dto: RegisterAMCompletDto,
|
||||||
|
options: {
|
||||||
|
statut: StatutUtilisateurType;
|
||||||
|
sendPendingEmail: boolean;
|
||||||
|
sendPasswordSetupEmail: boolean;
|
||||||
|
requireCgu: boolean;
|
||||||
|
logContext?: string;
|
||||||
|
},
|
||||||
|
): Promise<{
|
||||||
|
message: string;
|
||||||
|
user_id: string;
|
||||||
|
statut: StatutUtilisateurType;
|
||||||
|
numero_dossier: string;
|
||||||
|
}> {
|
||||||
|
const logCtx = options.logContext ?? 'createAmDossier';
|
||||||
|
|
||||||
|
if (options.requireCgu && (!dto.acceptation_cgu || !dto.acceptation_privacy)) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
"L'acceptation des CGU et de la politique de confidentialité est obligatoire",
|
"L'acceptation des CGU et de la politique de confidentialité est obligatoire",
|
||||||
);
|
);
|
||||||
@@ -668,8 +921,7 @@ export class AuthService {
|
|||||||
throw new BadRequestException(nirValidation.error || 'NIR invalide');
|
throw new BadRequestException(nirValidation.error || 'NIR invalide');
|
||||||
}
|
}
|
||||||
if (nirValidation.warning) {
|
if (nirValidation.warning) {
|
||||||
// Warning uniquement : on ne bloque pas (AM souvent étrangères, DOM-TOM, Corse)
|
console.warn(`[${logCtx}] NIR warning:`, nirValidation.warning, 'email=', dto.email);
|
||||||
console.warn('[inscrireAMComplet] NIR warning:', nirValidation.warning, 'email=', dto.email);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const existe = await this.usersService.findByEmailOrNull(dto.email);
|
const existe = await this.usersService.findByEmailOrNull(dto.email);
|
||||||
@@ -720,14 +972,15 @@ export class AuthService {
|
|||||||
let resultat: { user: Users };
|
let resultat: { user: Users };
|
||||||
try {
|
try {
|
||||||
resultat = await this.usersRepo.manager.transaction(async (manager) => {
|
resultat = await this.usersRepo.manager.transaction(async (manager) => {
|
||||||
const { numero: numeroDossier } = await this.numeroDossierService.getNextNumeroDossier(manager);
|
const { numero: numeroDossier } =
|
||||||
|
await this.numeroDossierService.getNextNumeroDossier(manager);
|
||||||
|
|
||||||
const user = manager.create(Users, {
|
const user = manager.create(Users, {
|
||||||
email: dto.email,
|
email: dto.email,
|
||||||
prenom: dto.prenom,
|
prenom: dto.prenom,
|
||||||
nom: dto.nom,
|
nom: dto.nom,
|
||||||
role: RoleType.ASSISTANTE_MATERNELLE,
|
role: RoleType.ASSISTANTE_MATERNELLE,
|
||||||
statut: StatutUtilisateurType.EN_ATTENTE,
|
statut: options.statut,
|
||||||
telephone: dto.telephone,
|
telephone: dto.telephone,
|
||||||
adresse: dto.adresse,
|
adresse: dto.adresse,
|
||||||
code_postal: dto.code_postal,
|
code_postal: dto.code_postal,
|
||||||
@@ -737,7 +990,9 @@ export class AuthService {
|
|||||||
photo_url: urlPhoto ?? undefined,
|
photo_url: urlPhoto ?? undefined,
|
||||||
consentement_photo: dto.consentement_photo,
|
consentement_photo: dto.consentement_photo,
|
||||||
date_consentement_photo: dateConsentementPhoto,
|
date_consentement_photo: dateConsentementPhoto,
|
||||||
date_naissance: dto.date_naissance ? new Date(dto.date_naissance) : undefined,
|
date_naissance: dto.date_naissance
|
||||||
|
? new Date(dto.date_naissance)
|
||||||
|
: undefined,
|
||||||
lieu_naissance_ville: dto.lieu_naissance_ville,
|
lieu_naissance_ville: dto.lieu_naissance_ville,
|
||||||
lieu_naissance_pays: dto.lieu_naissance_pays,
|
lieu_naissance_pays: dto.lieu_naissance_pays,
|
||||||
numero_dossier: numeroDossier,
|
numero_dossier: numeroDossier,
|
||||||
@@ -753,7 +1008,9 @@ export class AuthService {
|
|||||||
places_available: dto.places_disponibles,
|
places_available: dto.places_disponibles,
|
||||||
biography: dto.biographie,
|
biography: dto.biographie,
|
||||||
residence_city: dto.ville ?? undefined,
|
residence_city: dto.ville ?? undefined,
|
||||||
agreement_date: dto.date_agrement ? new Date(dto.date_agrement) : undefined,
|
agreement_date: dto.date_agrement
|
||||||
|
? new Date(dto.date_agrement)
|
||||||
|
: undefined,
|
||||||
available: true,
|
available: true,
|
||||||
numero_dossier: numeroDossier,
|
numero_dossier: numeroDossier,
|
||||||
});
|
});
|
||||||
@@ -763,13 +1020,16 @@ export class AuthService {
|
|||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (this.isPostgresUniqueViolation(err)) {
|
if (this.isPostgresUniqueViolation(err)) {
|
||||||
throw new ConflictException('Un compte avec cet email existe déjà (contrainte unique en base).');
|
throw new ConflictException(
|
||||||
|
'Un compte avec cet email existe déjà (contrainte unique en base).',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
const numeroDossier = resultat.user.numero_dossier ?? '';
|
const numeroDossier = resultat.user.numero_dossier ?? '';
|
||||||
|
|
||||||
|
if (options.sendPendingEmail) {
|
||||||
try {
|
try {
|
||||||
await this.mailService.sendRegistrationPendingEmail(
|
await this.mailService.sendRegistrationPendingEmail(
|
||||||
resultat.user.email,
|
resultat.user.email,
|
||||||
@@ -779,20 +1039,75 @@ export class AuthService {
|
|||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
"[inscrireAMComplet] Échec envoi email d'accusé de réception (inscription conservée)",
|
`[${logCtx}] Échec envoi email d'accusé de réception (inscription conservée)`,
|
||||||
err instanceof Error ? err.stack : String(err),
|
err instanceof Error ? err.stack : String(err),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.sendPasswordSetupEmail) {
|
||||||
|
try {
|
||||||
|
await this.mailService.sendValidatedAccountPasswordSetupEmail(
|
||||||
|
{
|
||||||
|
email: resultat.user.email,
|
||||||
|
prenom: resultat.user.prenom ?? '',
|
||||||
|
nom: resultat.user.nom ?? '',
|
||||||
|
token: tokenCreationMdp,
|
||||||
|
numeroDossier,
|
||||||
|
},
|
||||||
|
'am',
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error(
|
||||||
|
`[${logCtx}] Échec envoi email création MDP (dossier conservé)`,
|
||||||
|
err instanceof Error ? err.stack : String(err),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const message =
|
||||||
|
options.statut === StatutUtilisateurType.ACTIF
|
||||||
|
? 'Dossier AM créé et validé. Un e-mail de création de mot de passe a été envoyé.'
|
||||||
|
: 'Inscription réussie. Votre dossier est en attente de validation par un gestionnaire.';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
message:
|
message,
|
||||||
'Inscription réussie. Votre dossier est en attente de validation par un gestionnaire.',
|
|
||||||
user_id: resultat.user.id,
|
user_id: resultat.user.id,
|
||||||
statut: StatutUtilisateurType.EN_ATTENTE,
|
statut: options.statut,
|
||||||
numero_dossier: numeroDossier,
|
numero_dossier: numeroDossier,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inscription Assistante Maternelle COMPLÈTE - Un seul endpoint (identité + pro + photo + CGU)
|
||||||
|
* Crée User (role AM) + entrée assistantes_maternelles, token création MDP
|
||||||
|
*/
|
||||||
|
async inscrireAMComplet(dto: RegisterAMCompletDto) {
|
||||||
|
return this.createAmDossier(dto, {
|
||||||
|
statut: StatutUtilisateurType.EN_ATTENTE,
|
||||||
|
sendPendingEmail: true,
|
||||||
|
sendPasswordSetupEmail: false,
|
||||||
|
requireCgu: true,
|
||||||
|
logContext: 'inscrireAMComplet',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Création dossier AM par staff (#156) — statut actif + e-mail création MDP.
|
||||||
|
*/
|
||||||
|
async createAmDossierStaff(dto: RegisterAMCompletDto) {
|
||||||
|
return this.createAmDossier(dto, {
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
sendPendingEmail: false,
|
||||||
|
sendPasswordSetupEmail: true,
|
||||||
|
requireCgu: false,
|
||||||
|
logContext: 'createAmDossierStaff',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sauvegarde une photo depuis base64 vers le système de fichiers
|
||||||
|
*/
|
||||||
/**
|
/**
|
||||||
* Sauvegarde une photo depuis base64 vers le système de fichiers
|
* Sauvegarde une photo depuis base64 vers le système de fichiers
|
||||||
*/
|
*/
|
||||||
@@ -1071,8 +1386,11 @@ export class AuthService {
|
|||||||
enfant.status = StatutEnfantType.A_NAITRE;
|
enfant.status = StatutEnfantType.A_NAITRE;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (enfantDto.grossesse_multiple !== undefined) {
|
if (enfantDto.consent_photo !== undefined) {
|
||||||
enfant.is_multiple = enfantDto.grossesse_multiple;
|
enfant.consent_photo = !!enfantDto.consent_photo;
|
||||||
|
enfant.consent_photo_at = enfant.consent_photo
|
||||||
|
? new Date()
|
||||||
|
: null!;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (enfantDto.photo_base64 && enfantDto.photo_filename) {
|
if (enfantDto.photo_base64 && enfantDto.photo_filename) {
|
||||||
|
|||||||
@@ -55,9 +55,13 @@ export class EnfantInscriptionDto {
|
|||||||
@IsString()
|
@IsString()
|
||||||
photo_filename?: string;
|
photo_filename?: string;
|
||||||
|
|
||||||
@ApiProperty({ example: false, required: false, description: 'Grossesse multiple (jumeaux, triplés, etc.)' })
|
@ApiProperty({
|
||||||
|
example: true,
|
||||||
|
required: false,
|
||||||
|
description: 'Consentement affichage / stockage photo (colonne enfants.consentement_photo)',
|
||||||
|
})
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
grossesse_multiple?: boolean;
|
consent_photo?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { DossiersController } from './dossiers.controller';
|
||||||
|
import { DossiersService } from './dossiers.service';
|
||||||
|
import { SuppressionService } from '../suppressions/suppression.service';
|
||||||
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
describe('DossiersController', () => {
|
||||||
|
let controller: DossiersController;
|
||||||
|
const dossiersServiceMock = {
|
||||||
|
listDossiers: jest.fn(),
|
||||||
|
getDossierByNumero: jest.fn(),
|
||||||
|
};
|
||||||
|
const suppressionServiceMock = {
|
||||||
|
deleteDossier: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
controllers: [DossiersController],
|
||||||
|
providers: [
|
||||||
|
{ provide: DossiersService, useValue: dossiersServiceMock },
|
||||||
|
{ provide: SuppressionService, useValue: suppressionServiceMock },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.overrideGuard(AuthGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.overrideGuard(RolesGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.compile();
|
||||||
|
|
||||||
|
controller = module.get<DossiersController>(DossiersController);
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(controller).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('list delegates to dossiersService.listDossiers with q', async () => {
|
||||||
|
dossiersServiceMock.listDossiers.mockResolvedValue([
|
||||||
|
{
|
||||||
|
type: 'famille',
|
||||||
|
numero_dossier: '2026-000043',
|
||||||
|
libelle: 'Claire MARTIN',
|
||||||
|
emails: ['claire@test.fr'],
|
||||||
|
user_ids: ['u1'],
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
a_valider: false,
|
||||||
|
date_reference: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const res = await controller.list('martin');
|
||||||
|
expect(dossiersServiceMock.listDossiers).toHaveBeenCalledWith('martin');
|
||||||
|
expect(res).toHaveLength(1);
|
||||||
|
expect(res[0].numero_dossier).toBe('2026-000043');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getDossier delegates to getDossierByNumero', async () => {
|
||||||
|
dossiersServiceMock.getDossierByNumero.mockResolvedValue({
|
||||||
|
type: 'family',
|
||||||
|
dossier: { numero_dossier: '2026-000001' },
|
||||||
|
});
|
||||||
|
const res = await controller.getDossier('2026-000001');
|
||||||
|
expect(dossiersServiceMock.getDossierByNumero).toHaveBeenCalledWith('2026-000001');
|
||||||
|
expect(res.type).toBe('family');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('remove delegates to suppressionService.deleteDossier', async () => {
|
||||||
|
const user = { id: 'u1', role: 'gestionnaire' } as never;
|
||||||
|
suppressionServiceMock.deleteDossier.mockResolvedValue({
|
||||||
|
type: 'famille',
|
||||||
|
deleted_user_ids: [],
|
||||||
|
deleted_enfant_ids: [],
|
||||||
|
message: 'ok',
|
||||||
|
});
|
||||||
|
await controller.remove('2026-000001', user);
|
||||||
|
expect(suppressionServiceMock.deleteDossier).toHaveBeenCalledWith(
|
||||||
|
'2026-000001',
|
||||||
|
user,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,17 +1,58 @@
|
|||||||
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
|
import {
|
||||||
import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiOperation,
|
||||||
|
ApiParam,
|
||||||
|
ApiQuery,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from '@nestjs/swagger';
|
||||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||||
import { RoleType } from 'src/entities/users.entity';
|
import { RoleType, Users } from 'src/entities/users.entity';
|
||||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
import { User } from 'src/common/decorators/user.decorator';
|
||||||
import { DossiersService } from './dossiers.service';
|
import { DossiersService } from './dossiers.service';
|
||||||
|
import { SuppressionService } from '../suppressions/suppression.service';
|
||||||
import { DossierUnifieDto } from './dto/dossier-unifie.dto';
|
import { DossierUnifieDto } from './dto/dossier-unifie.dto';
|
||||||
|
import { DossierListItemDto } from './dto/dossier-list-item.dto';
|
||||||
|
|
||||||
@ApiTags('Dossiers')
|
@ApiTags('Dossiers')
|
||||||
|
@ApiBearerAuth('access-token')
|
||||||
@Controller('dossiers')
|
@Controller('dossiers')
|
||||||
@UseGuards(AuthGuard, RolesGuard)
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
export class DossiersController {
|
export class DossiersController {
|
||||||
constructor(private readonly dossiersService: DossiersService) {}
|
constructor(
|
||||||
|
private readonly dossiersService: DossiersService,
|
||||||
|
private readonly suppressionService: SuppressionService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Liste unifiée des dossiers (familles + AM) — ticket #153',
|
||||||
|
description:
|
||||||
|
'1 entrée = 1 numero_dossier. Types `famille` | `assistante_maternelle`. ' +
|
||||||
|
'Filtre optionnel `q` (n°, nom, email). Tri : à valider d’abord, puis n° décroissant. ' +
|
||||||
|
'`sans_enfant` (#159) pour dossiers famille sans enfant.',
|
||||||
|
})
|
||||||
|
@ApiQuery({
|
||||||
|
name: 'q',
|
||||||
|
required: false,
|
||||||
|
description: 'Recherche libre : n° dossier, libellé, email…',
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: 200, type: [DossierListItemDto] })
|
||||||
|
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||||
|
list(@Query('q') q?: string): Promise<DossierListItemDto[]> {
|
||||||
|
return this.dossiersService.listDossiers(q);
|
||||||
|
}
|
||||||
|
|
||||||
@Get(':numeroDossier')
|
@Get(':numeroDossier')
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
@@ -23,4 +64,21 @@ export class DossiersController {
|
|||||||
getDossier(@Param('numeroDossier') numeroDossier: string): Promise<DossierUnifieDto> {
|
getDossier(@Param('numeroDossier') numeroDossier: string): Promise<DossierUnifieDto> {
|
||||||
return this.dossiersService.getDossierByNumero(numeroDossier);
|
return this.dossiersService.getDossierByNumero(numeroDossier);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Delete(':numeroDossier')
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Supprimer un dossier (famille ou AM) — #159',
|
||||||
|
description:
|
||||||
|
'Famille : parents + enfants. AM : compte AM + dossier AM (enfants conservés, placements clos).',
|
||||||
|
})
|
||||||
|
@ApiParam({ name: 'numeroDossier', description: 'Numéro de dossier' })
|
||||||
|
@ApiResponse({ status: 200, description: 'Résultat de suppression' })
|
||||||
|
@ApiResponse({ status: 404, description: 'Dossier introuvable' })
|
||||||
|
remove(
|
||||||
|
@Param('numeroDossier') numeroDossier: string,
|
||||||
|
@User() currentUser: Users,
|
||||||
|
) {
|
||||||
|
return this.suppressionService.deleteDossier(numeroDossier, currentUser);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { JwtModule } from '@nestjs/jwt';
|
|||||||
import { Parents } from 'src/entities/parents.entity';
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
import { ParentsModule } from '../parents/parents.module';
|
import { ParentsModule } from '../parents/parents.module';
|
||||||
|
import { SuppressionsModule } from '../suppressions/suppressions.module';
|
||||||
import { DossiersController } from './dossiers.controller';
|
import { DossiersController } from './dossiers.controller';
|
||||||
import { DossiersService } from './dossiers.service';
|
import { DossiersService } from './dossiers.service';
|
||||||
|
|
||||||
@@ -12,6 +13,7 @@ import { DossiersService } from './dossiers.service';
|
|||||||
imports: [
|
imports: [
|
||||||
TypeOrmModule.forFeature([Parents, AssistanteMaternelle]),
|
TypeOrmModule.forFeature([Parents, AssistanteMaternelle]),
|
||||||
ParentsModule,
|
ParentsModule,
|
||||||
|
SuppressionsModule,
|
||||||
JwtModule.registerAsync({
|
JwtModule.registerAsync({
|
||||||
imports: [ConfigModule],
|
imports: [ConfigModule],
|
||||||
useFactory: (config: ConfigService) => ({
|
useFactory: (config: ConfigService) => ({
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
|
import { DossiersService } from './dossiers.service';
|
||||||
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
|
import { ParentsService } from '../parents/parents.service';
|
||||||
|
import { SuppressionService } from '../suppressions/suppression.service';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
describe('DossiersService.listDossiers', () => {
|
||||||
|
let service: DossiersService;
|
||||||
|
const parentsQb = {
|
||||||
|
innerJoinAndSelect: jest.fn().mockReturnThis(),
|
||||||
|
leftJoinAndSelect: jest.fn().mockReturnThis(),
|
||||||
|
where: jest.fn().mockReturnThis(),
|
||||||
|
andWhere: jest.fn().mockReturnThis(),
|
||||||
|
getMany: jest.fn(),
|
||||||
|
};
|
||||||
|
const amQb = {
|
||||||
|
innerJoinAndSelect: jest.fn().mockReturnThis(),
|
||||||
|
where: jest.fn().mockReturnThis(),
|
||||||
|
andWhere: jest.fn().mockReturnThis(),
|
||||||
|
getMany: jest.fn(),
|
||||||
|
};
|
||||||
|
const parentsRepo = {
|
||||||
|
createQueryBuilder: jest.fn(() => parentsQb),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
const amRepo = {
|
||||||
|
createQueryBuilder: jest.fn(() => amQb),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
const parentsService = {
|
||||||
|
getDossierFamilleByNumero: jest.fn(),
|
||||||
|
};
|
||||||
|
const suppressionService = {
|
||||||
|
countEnfantsForNumero: jest.fn().mockResolvedValue(1),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
DossiersService,
|
||||||
|
{ provide: getRepositoryToken(Parents), useValue: parentsRepo },
|
||||||
|
{ provide: getRepositoryToken(AssistanteMaternelle), useValue: amRepo },
|
||||||
|
{ provide: ParentsService, useValue: parentsService },
|
||||||
|
{ provide: SuppressionService, useValue: suppressionService },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get(DossiersService);
|
||||||
|
jest.clearAllMocks();
|
||||||
|
parentsRepo.createQueryBuilder.mockReturnValue(parentsQb);
|
||||||
|
amRepo.createQueryBuilder.mockReturnValue(amQb);
|
||||||
|
suppressionService.countEnfantsForNumero.mockResolvedValue(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('aggregates famille (pivot+co-parent) and AM, sorts a_valider first', async () => {
|
||||||
|
parentsQb.getMany.mockResolvedValue([
|
||||||
|
{
|
||||||
|
user_id: 'p1',
|
||||||
|
numero_dossier: '2026-000010',
|
||||||
|
user: {
|
||||||
|
id: 'p1',
|
||||||
|
email: 'claire@test.fr',
|
||||||
|
prenom: 'Claire',
|
||||||
|
nom: 'Martin',
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
cree_le: new Date('2026-01-01'),
|
||||||
|
},
|
||||||
|
co_parent: {
|
||||||
|
id: 'p2',
|
||||||
|
email: 'thomas@test.fr',
|
||||||
|
prenom: 'Thomas',
|
||||||
|
nom: 'Martin',
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
cree_le: new Date('2026-01-02'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
user_id: 'p3',
|
||||||
|
numero_dossier: '2026-000020',
|
||||||
|
user: {
|
||||||
|
id: 'p3',
|
||||||
|
email: 'pending@test.fr',
|
||||||
|
prenom: 'Paul',
|
||||||
|
nom: 'Pending',
|
||||||
|
statut: StatutUtilisateurType.EN_ATTENTE,
|
||||||
|
cree_le: new Date('2026-02-01'),
|
||||||
|
},
|
||||||
|
co_parent: undefined,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
amQb.getMany.mockResolvedValue([
|
||||||
|
{
|
||||||
|
user_id: 'am1',
|
||||||
|
numero_dossier: '2026-000015',
|
||||||
|
user: {
|
||||||
|
id: 'am1',
|
||||||
|
email: 'am@test.fr',
|
||||||
|
prenom: 'Marie',
|
||||||
|
nom: 'Dupont',
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
cree_le: new Date('2026-01-15'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const list = await service.listDossiers();
|
||||||
|
expect(list).toHaveLength(3);
|
||||||
|
expect(list[0].a_valider).toBe(true);
|
||||||
|
expect(list[0].type).toBe('famille');
|
||||||
|
expect(list[0].numero_dossier).toBe('2026-000020');
|
||||||
|
|
||||||
|
const famille = list.find((i) => i.numero_dossier === '2026-000010')!;
|
||||||
|
expect(famille.type).toBe('famille');
|
||||||
|
expect(famille.user_ids).toEqual(expect.arrayContaining(['p1', 'p2']));
|
||||||
|
expect(famille.emails).toHaveLength(2);
|
||||||
|
expect(famille.libelle).toContain('MARTIN');
|
||||||
|
|
||||||
|
const am = list.find((i) => i.type === 'assistante_maternelle')!;
|
||||||
|
expect(am.numero_dossier).toBe('2026-000015');
|
||||||
|
expect(am.libelle).toContain('Marie');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters with q', async () => {
|
||||||
|
parentsQb.getMany.mockResolvedValue([]);
|
||||||
|
amQb.getMany.mockResolvedValue([
|
||||||
|
{
|
||||||
|
user_id: 'am1',
|
||||||
|
numero_dossier: '2026-000015',
|
||||||
|
user: {
|
||||||
|
id: 'am1',
|
||||||
|
email: 'am@test.fr',
|
||||||
|
prenom: 'Marie',
|
||||||
|
nom: 'Dupont',
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
cree_le: new Date('2026-01-15'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const hit = await service.listDossiers('dupont');
|
||||||
|
expect(hit).toHaveLength(1);
|
||||||
|
const miss = await service.listDossiers('zzz');
|
||||||
|
expect(miss).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -3,12 +3,15 @@ import { InjectRepository } from '@nestjs/typeorm';
|
|||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { Parents } from 'src/entities/parents.entity';
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
|
import { StatutUtilisateurType, Users } from 'src/entities/users.entity';
|
||||||
import { ParentsService } from '../parents/parents.service';
|
import { ParentsService } from '../parents/parents.service';
|
||||||
|
import { SuppressionService } from '../suppressions/suppression.service';
|
||||||
import { DossierUnifieDto } from './dto/dossier-unifie.dto';
|
import { DossierUnifieDto } from './dto/dossier-unifie.dto';
|
||||||
import { DossierAmCompletDto, DossierAmUserDto } from './dto/dossier-am-complet.dto';
|
import { DossierAmCompletDto, DossierAmUserDto } from './dto/dossier-am-complet.dto';
|
||||||
|
import { DossierListItemDto } from './dto/dossier-list-item.dto';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Endpoint unifié GET /dossiers/:numeroDossier – AM ou famille. Ticket #119.
|
* Dossiers unifiés — détail (#119) + liste (#153) + sans_enfant (#159).
|
||||||
*/
|
*/
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class DossiersService {
|
export class DossiersService {
|
||||||
@@ -18,8 +21,173 @@ export class DossiersService {
|
|||||||
@InjectRepository(AssistanteMaternelle)
|
@InjectRepository(AssistanteMaternelle)
|
||||||
private readonly amRepository: Repository<AssistanteMaternelle>,
|
private readonly amRepository: Repository<AssistanteMaternelle>,
|
||||||
private readonly parentsService: ParentsService,
|
private readonly parentsService: ParentsService,
|
||||||
|
private readonly suppressionService: SuppressionService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Liste unifiée tous dossiers (familles + AM) ayant un numero_dossier.
|
||||||
|
* Ticket #153 — optionnel `q` filtre n° / nom / prénom / email (côté serveur).
|
||||||
|
*/
|
||||||
|
async listDossiers(q?: string): Promise<DossierListItemDto[]> {
|
||||||
|
const items: DossierListItemDto[] = [
|
||||||
|
...(await this.listFamilleItems()),
|
||||||
|
...(await this.listAmItems()),
|
||||||
|
];
|
||||||
|
|
||||||
|
const needle = (q ?? '').trim().toLowerCase();
|
||||||
|
const filtered = needle
|
||||||
|
? items.filter((item) => this.matchesQuery(item, needle))
|
||||||
|
: items;
|
||||||
|
|
||||||
|
filtered.sort((a, b) => {
|
||||||
|
// À valider d'abord, puis n° dossier décroissant
|
||||||
|
if (a.a_valider !== b.a_valider) return a.a_valider ? -1 : 1;
|
||||||
|
return b.numero_dossier.localeCompare(a.numero_dossier, 'fr');
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const item of filtered) {
|
||||||
|
if (item.type === 'famille') {
|
||||||
|
const n = await this.suppressionService.countEnfantsForNumero(
|
||||||
|
item.numero_dossier,
|
||||||
|
);
|
||||||
|
item.sans_enfant = n === 0;
|
||||||
|
} else {
|
||||||
|
item.sans_enfant = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return filtered;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async listFamilleItems(): Promise<DossierListItemDto[]> {
|
||||||
|
const parents = await this.parentsRepository
|
||||||
|
.createQueryBuilder('p')
|
||||||
|
.innerJoinAndSelect('p.user', 'u')
|
||||||
|
.leftJoinAndSelect('p.co_parent', 'cp')
|
||||||
|
.where('p.numero_dossier IS NOT NULL')
|
||||||
|
.andWhere("TRIM(p.numero_dossier) <> ''")
|
||||||
|
.getMany();
|
||||||
|
|
||||||
|
const byNum = new Map<string, Parents[]>();
|
||||||
|
for (const p of parents) {
|
||||||
|
const num = (p.numero_dossier ?? '').trim();
|
||||||
|
if (!num) continue;
|
||||||
|
const group = byNum.get(num) ?? [];
|
||||||
|
group.push(p);
|
||||||
|
byNum.set(num, group);
|
||||||
|
}
|
||||||
|
|
||||||
|
const items: DossierListItemDto[] = [];
|
||||||
|
for (const [numero_dossier, group] of byNum) {
|
||||||
|
const usersMap = new Map<string, Users>();
|
||||||
|
for (const p of group) {
|
||||||
|
if (p.user) usersMap.set(p.user.id, p.user);
|
||||||
|
if (p.co_parent) usersMap.set(p.co_parent.id, p.co_parent);
|
||||||
|
}
|
||||||
|
const users = [...usersMap.values()].sort((a, b) => {
|
||||||
|
const an = `${a.nom ?? ''} ${a.prenom ?? ''}`.toLowerCase();
|
||||||
|
const bn = `${b.nom ?? ''} ${b.prenom ?? ''}`.toLowerCase();
|
||||||
|
return an.localeCompare(bn, 'fr') || a.id.localeCompare(b.id);
|
||||||
|
});
|
||||||
|
if (users.length === 0) continue;
|
||||||
|
|
||||||
|
const names = users.map((u) => this.formatPersonName(u)).filter(Boolean);
|
||||||
|
const libelle =
|
||||||
|
names.length === 0
|
||||||
|
? `Dossier ${numero_dossier}`
|
||||||
|
: names.length === 1
|
||||||
|
? names[0]
|
||||||
|
: names.join(' & ');
|
||||||
|
|
||||||
|
const emails = users.map((u) => u.email).filter(Boolean);
|
||||||
|
const user_ids = users.map((u) => u.id);
|
||||||
|
const a_valider = users.some((u) => u.statut === StatutUtilisateurType.EN_ATTENTE);
|
||||||
|
const statut = a_valider
|
||||||
|
? StatutUtilisateurType.EN_ATTENTE
|
||||||
|
: (users[0].statut ?? StatutUtilisateurType.ACTIF);
|
||||||
|
const date_reference = this.minCreeLeIso(users);
|
||||||
|
|
||||||
|
items.push({
|
||||||
|
type: 'famille',
|
||||||
|
numero_dossier,
|
||||||
|
libelle,
|
||||||
|
emails,
|
||||||
|
user_ids,
|
||||||
|
statut,
|
||||||
|
a_valider,
|
||||||
|
date_reference,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async listAmItems(): Promise<DossierListItemDto[]> {
|
||||||
|
const ams = await this.amRepository
|
||||||
|
.createQueryBuilder('am')
|
||||||
|
.innerJoinAndSelect('am.user', 'u')
|
||||||
|
.where('am.numero_dossier IS NOT NULL')
|
||||||
|
.andWhere("TRIM(am.numero_dossier) <> ''")
|
||||||
|
.getMany();
|
||||||
|
|
||||||
|
const byNum = new Map<string, AssistanteMaternelle>();
|
||||||
|
for (const am of ams) {
|
||||||
|
const num = (am.numero_dossier ?? '').trim();
|
||||||
|
if (!num || !am.user) continue;
|
||||||
|
// Un n° = une AM ; garder le premier
|
||||||
|
if (!byNum.has(num)) byNum.set(num, am);
|
||||||
|
}
|
||||||
|
|
||||||
|
const items: DossierListItemDto[] = [];
|
||||||
|
for (const [numero_dossier, am] of byNum) {
|
||||||
|
const u = am.user!;
|
||||||
|
const libelle = this.formatPersonName(u) || `AM ${numero_dossier}`;
|
||||||
|
const a_valider = u.statut === StatutUtilisateurType.EN_ATTENTE;
|
||||||
|
items.push({
|
||||||
|
type: 'assistante_maternelle',
|
||||||
|
numero_dossier,
|
||||||
|
libelle,
|
||||||
|
emails: u.email ? [u.email] : [],
|
||||||
|
user_ids: [u.id],
|
||||||
|
statut: u.statut ?? StatutUtilisateurType.ACTIF,
|
||||||
|
a_valider,
|
||||||
|
date_reference: this.minCreeLeIso([u]),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
private matchesQuery(item: DossierListItemDto, needle: string): boolean {
|
||||||
|
const hay = [
|
||||||
|
item.numero_dossier,
|
||||||
|
item.libelle,
|
||||||
|
...item.emails,
|
||||||
|
item.statut,
|
||||||
|
item.type,
|
||||||
|
]
|
||||||
|
.join(' ')
|
||||||
|
.toLowerCase();
|
||||||
|
return hay.includes(needle);
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatPersonName(u: Users): string {
|
||||||
|
const prenom = (u.prenom ?? '').trim();
|
||||||
|
const nom = (u.nom ?? '').trim();
|
||||||
|
const nomFmt = nom ? nom.toUpperCase() : '';
|
||||||
|
return [prenom, nomFmt].filter(Boolean).join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
private minCreeLeIso(users: Users[]): string | null {
|
||||||
|
let min: Date | null = null;
|
||||||
|
for (const u of users) {
|
||||||
|
const d = u.cree_le;
|
||||||
|
if (!d) continue;
|
||||||
|
const date = d instanceof Date ? d : new Date(d);
|
||||||
|
if (Number.isNaN(date.getTime())) continue;
|
||||||
|
if (!min || date < min) min = date;
|
||||||
|
}
|
||||||
|
return min ? min.toISOString() : null;
|
||||||
|
}
|
||||||
|
|
||||||
async getDossierByNumero(numeroDossier: string): Promise<DossierUnifieDto> {
|
async getDossierByNumero(numeroDossier: string): Promise<DossierUnifieDto> {
|
||||||
const num = numeroDossier?.trim();
|
const num = numeroDossier?.trim();
|
||||||
if (!num) {
|
if (!num) {
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
/** Ligne de liste GET /dossiers (#153). */
|
||||||
|
export class DossierListItemDto {
|
||||||
|
@ApiProperty({
|
||||||
|
enum: ['famille', 'assistante_maternelle'],
|
||||||
|
description: 'Type de dossier',
|
||||||
|
})
|
||||||
|
type: 'famille' | 'assistante_maternelle';
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2026-000043' })
|
||||||
|
numero_dossier: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'Claire MARTIN & Thomas MARTIN',
|
||||||
|
description: 'Libellé affiché (noms)',
|
||||||
|
})
|
||||||
|
libelle: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
type: [String],
|
||||||
|
example: ['claire@example.com', 'thomas@example.com'],
|
||||||
|
})
|
||||||
|
emails: string[];
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
type: [String],
|
||||||
|
format: 'uuid',
|
||||||
|
description: 'IDs utilisateur liés au dossier (parents du foyer ou AM)',
|
||||||
|
})
|
||||||
|
user_ids: string[];
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
enum: StatutUtilisateurType,
|
||||||
|
description:
|
||||||
|
'Statut agrégé : en_attente si au moins un user en_attente, sinon statut du premier',
|
||||||
|
})
|
||||||
|
statut: StatutUtilisateurType;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'True si le dossier est en attente de validation (section haute UI)',
|
||||||
|
})
|
||||||
|
a_valider: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
nullable: true,
|
||||||
|
example: '2026-01-12T10:00:00.000Z',
|
||||||
|
description: 'Date de référence (MIN cree_le des users du dossier)',
|
||||||
|
})
|
||||||
|
date_reference: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description:
|
||||||
|
'True si dossier famille sans enfant lié (#159). Omis ou false pour AM.',
|
||||||
|
})
|
||||||
|
sans_enfant?: boolean;
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { Transform } from 'class-transformer';
|
||||||
import {
|
import {
|
||||||
IsBoolean,
|
IsBoolean,
|
||||||
IsDateString,
|
IsDateString,
|
||||||
@@ -6,11 +7,23 @@ import {
|
|||||||
IsNotEmpty,
|
IsNotEmpty,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
|
IsUUID,
|
||||||
MaxLength,
|
MaxLength,
|
||||||
ValidateIf,
|
ValidateIf,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
import { GenreType, StatutEnfantType } from 'src/entities/children.entity';
|
import { GenreType, StatutEnfantType } from 'src/entities/children.entity';
|
||||||
|
|
||||||
|
/** Multipart envoie des strings ("true"/"false") — JSON envoie déjà des booleans. */
|
||||||
|
function toBoolean({ value }: { value: unknown }): boolean | unknown {
|
||||||
|
if (typeof value === 'boolean') return value;
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const v = value.trim().toLowerCase();
|
||||||
|
if (v === 'true' || v === '1') return true;
|
||||||
|
if (v === 'false' || v === '0' || v === '') return false;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
export class CreateEnfantsDto {
|
export class CreateEnfantsDto {
|
||||||
@ApiProperty({ enum: StatutEnfantType, example: StatutEnfantType.SANS_GARDE })
|
@ApiProperty({ enum: StatutEnfantType, example: StatutEnfantType.SANS_GARDE })
|
||||||
@IsEnum(StatutEnfantType)
|
@IsEnum(StatutEnfantType)
|
||||||
@@ -52,6 +65,7 @@ export class CreateEnfantsDto {
|
|||||||
photo_url?: string;
|
photo_url?: string;
|
||||||
|
|
||||||
@ApiProperty({ default: false })
|
@ApiProperty({ default: false })
|
||||||
|
@Transform(toBoolean)
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
consent_photo: boolean;
|
consent_photo: boolean;
|
||||||
|
|
||||||
@@ -60,7 +74,16 @@ export class CreateEnfantsDto {
|
|||||||
@IsDateString()
|
@IsDateString()
|
||||||
consent_photo_at?: string;
|
consent_photo_at?: string;
|
||||||
|
|
||||||
@ApiProperty({ default: false })
|
/**
|
||||||
@IsBoolean()
|
* Parent pivot du foyer — obligatoire pour staff (gestionnaire/admin).
|
||||||
is_multiple: boolean;
|
* Ignoré / interdit en externe pour un PARENT (ticket #132).
|
||||||
|
*/
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description:
|
||||||
|
'UUID du parent pivot (staff only). Obligatoire pour GESTIONNAIRE / ADMIN / SUPER_ADMIN.',
|
||||||
|
format: 'uuid',
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsUUID('4')
|
||||||
|
parent_user_id?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ export class EnfantResponseDto {
|
|||||||
@ApiProperty({ example: false })
|
@ApiProperty({ example: false })
|
||||||
consent_photo: boolean;
|
consent_photo: boolean;
|
||||||
|
|
||||||
@ApiProperty({ example: false })
|
|
||||||
is_multiple: boolean;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'UUID-parent' })
|
@ApiProperty({ example: 'UUID-parent' })
|
||||||
parent_id: string;
|
parent_id: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,35 @@
|
|||||||
import {
|
import {
|
||||||
Body,
|
Body,
|
||||||
|
CallHandler,
|
||||||
Controller,
|
Controller,
|
||||||
Delete,
|
Delete,
|
||||||
|
ExecutionContext,
|
||||||
Get,
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
|
Injectable,
|
||||||
|
NestInterceptor,
|
||||||
Param,
|
Param,
|
||||||
ParseUUIDPipe,
|
ParseUUIDPipe,
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
|
Query,
|
||||||
|
UploadedFile,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
UseInterceptors,
|
UseInterceptors,
|
||||||
UploadedFile,
|
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { FileInterceptor } from '@nestjs/platform-express';
|
import { FileInterceptor } from '@nestjs/platform-express';
|
||||||
import { ApiBearerAuth, ApiTags, ApiConsumes } from '@nestjs/swagger';
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiBody,
|
||||||
|
ApiConsumes,
|
||||||
|
ApiOperation,
|
||||||
|
ApiQuery,
|
||||||
|
ApiTags,
|
||||||
|
} from '@nestjs/swagger';
|
||||||
import { diskStorage } from 'multer';
|
import { diskStorage } from 'multer';
|
||||||
import { extname } from 'path';
|
import { extname } from 'path';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
import { EnfantsService } from './enfants.service';
|
import { EnfantsService } from './enfants.service';
|
||||||
import { CreateEnfantsDto } from './dto/create_enfants.dto';
|
import { CreateEnfantsDto } from './dto/create_enfants.dto';
|
||||||
import { UpdateEnfantsDto } from './dto/update_enfants.dto';
|
import { UpdateEnfantsDto } from './dto/update_enfants.dto';
|
||||||
@@ -23,19 +38,9 @@ import { User } from 'src/common/decorators/user.decorator';
|
|||||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
import { SuppressionService } from '../suppressions/suppression.service';
|
||||||
|
|
||||||
@ApiBearerAuth('access-token')
|
const photoMulterOptions = {
|
||||||
@ApiTags('Enfants')
|
|
||||||
@UseGuards(AuthGuard, RolesGuard)
|
|
||||||
@Controller('enfants')
|
|
||||||
export class EnfantsController {
|
|
||||||
constructor(private readonly enfantsService: EnfantsService) { }
|
|
||||||
|
|
||||||
@Roles(RoleType.PARENT)
|
|
||||||
@Post()
|
|
||||||
@ApiConsumes('multipart/form-data')
|
|
||||||
@UseInterceptors(
|
|
||||||
FileInterceptor('photo', {
|
|
||||||
storage: diskStorage({
|
storage: diskStorage({
|
||||||
destination: './uploads/photos',
|
destination: './uploads/photos',
|
||||||
filename: (req, file, cb) => {
|
filename: (req, file, cb) => {
|
||||||
@@ -53,8 +58,60 @@ export class EnfantsController {
|
|||||||
limits: {
|
limits: {
|
||||||
fileSize: 5 * 1024 * 1024,
|
fileSize: 5 * 1024 * 1024,
|
||||||
},
|
},
|
||||||
}),
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Multer uniquement si Content-Type multipart (parent ou staff + photo).
|
||||||
|
* JSON sans photo (#132) passe sans interceptor fichier.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
class OptionalEnfantPhotoInterceptor implements NestInterceptor {
|
||||||
|
private readonly multipart = new (FileInterceptor(
|
||||||
|
'photo',
|
||||||
|
photoMulterOptions,
|
||||||
|
))();
|
||||||
|
|
||||||
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> | Promise<Observable<unknown>> {
|
||||||
|
const req = context.switchToHttp().getRequest();
|
||||||
|
const ct = String(req.headers['content-type'] ?? '');
|
||||||
|
if (!ct.includes('multipart/form-data')) {
|
||||||
|
return next.handle();
|
||||||
|
}
|
||||||
|
return this.multipart.intercept(context, next);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiBearerAuth('access-token')
|
||||||
|
@ApiTags('Enfants')
|
||||||
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
|
@Controller('enfants')
|
||||||
|
export class EnfantsController {
|
||||||
|
constructor(
|
||||||
|
private readonly enfantsService: EnfantsService,
|
||||||
|
private readonly suppressionService: SuppressionService,
|
||||||
|
) { }
|
||||||
|
|
||||||
|
@Roles(
|
||||||
|
RoleType.PARENT,
|
||||||
|
RoleType.GESTIONNAIRE,
|
||||||
|
RoleType.ADMINISTRATEUR,
|
||||||
|
RoleType.SUPER_ADMIN,
|
||||||
)
|
)
|
||||||
|
@Post()
|
||||||
|
@HttpCode(HttpStatus.CREATED)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Créer un enfant',
|
||||||
|
description:
|
||||||
|
'PARENT : multipart éventuel, rattache au compte connecté. ' +
|
||||||
|
'Staff : parent_user_id obligatoire ; JSON sans photo OK ; avec photo → multipart (champ fichier `photo`, max 5 Mo). Ticket #132.',
|
||||||
|
})
|
||||||
|
@ApiConsumes('application/json', 'multipart/form-data')
|
||||||
|
@ApiBody({
|
||||||
|
description:
|
||||||
|
'Champs métier (+ parent_user_id côté staff). Fichier optionnel `photo` en multipart.',
|
||||||
|
type: CreateEnfantsDto,
|
||||||
|
})
|
||||||
|
@UseInterceptors(OptionalEnfantPhotoInterceptor)
|
||||||
create(
|
create(
|
||||||
@Body() dto: CreateEnfantsDto,
|
@Body() dto: CreateEnfantsDto,
|
||||||
@UploadedFile() photo: Express.Multer.File,
|
@UploadedFile() photo: Express.Multer.File,
|
||||||
@@ -90,17 +147,47 @@ export class EnfantsController {
|
|||||||
RoleType.GESTIONNAIRE,
|
RoleType.GESTIONNAIRE,
|
||||||
)
|
)
|
||||||
@Patch(':id')
|
@Patch(':id')
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Mettre à jour un enfant',
|
||||||
|
description:
|
||||||
|
'JSON sans photo OK ; avec nouvelle photo → multipart (champ fichier `photo`, max 5 Mo).',
|
||||||
|
})
|
||||||
|
@ApiConsumes('application/json', 'multipart/form-data')
|
||||||
|
@UseInterceptors(OptionalEnfantPhotoInterceptor)
|
||||||
update(
|
update(
|
||||||
@Param('id', new ParseUUIDPipe()) id: string,
|
@Param('id', new ParseUUIDPipe()) id: string,
|
||||||
@Body() dto: UpdateEnfantsDto,
|
@Body() dto: UpdateEnfantsDto,
|
||||||
|
@UploadedFile() photo: Express.Multer.File,
|
||||||
@User() currentUser: Users,
|
@User() currentUser: Users,
|
||||||
) {
|
) {
|
||||||
return this.enfantsService.update(id, dto, currentUser);
|
return this.enfantsService.update(id, dto, currentUser, photo);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN)
|
@Roles(
|
||||||
|
RoleType.SUPER_ADMIN,
|
||||||
|
RoleType.ADMINISTRATEUR,
|
||||||
|
RoleType.GESTIONNAIRE,
|
||||||
|
)
|
||||||
@Delete(':id')
|
@Delete(':id')
|
||||||
remove(@Param('id', new ParseUUIDPipe()) id: string) {
|
@ApiOperation({
|
||||||
return this.enfantsService.remove(id);
|
summary: 'Supprimer un enfant (#159)',
|
||||||
|
description:
|
||||||
|
'Query `deleteDossier=true` si dernier enfant et suppression du dossier famille souhaitée.',
|
||||||
|
})
|
||||||
|
@ApiQuery({
|
||||||
|
name: 'deleteDossier',
|
||||||
|
required: false,
|
||||||
|
description: 'Si true et dernier enfant : cascade dossier famille',
|
||||||
|
})
|
||||||
|
remove(
|
||||||
|
@Param('id', new ParseUUIDPipe()) id: string,
|
||||||
|
@Query('deleteDossier') deleteDossier: string | undefined,
|
||||||
|
@User() currentUser: Users,
|
||||||
|
) {
|
||||||
|
const flag =
|
||||||
|
deleteDossier === 'true' ||
|
||||||
|
deleteDossier === '1' ||
|
||||||
|
deleteDossier === 'yes';
|
||||||
|
return this.suppressionService.deleteEnfant(id, flag, currentUser);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,13 +6,16 @@ import { Children } from 'src/entities/children.entity';
|
|||||||
import { Parents } from 'src/entities/parents.entity';
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
import { AuthModule } from '../auth/auth.module';
|
import { AuthModule } from '../auth/auth.module';
|
||||||
|
import { SuppressionsModule } from '../suppressions/suppressions.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([Children, Parents, ParentsChildren]),
|
imports: [
|
||||||
AuthModule
|
TypeOrmModule.forFeature([Children, Parents, ParentsChildren]),
|
||||||
|
AuthModule,
|
||||||
|
SuppressionsModule,
|
||||||
],
|
],
|
||||||
controllers: [EnfantsController],
|
controllers: [EnfantsController],
|
||||||
providers: [EnfantsService]
|
providers: [EnfantsService],
|
||||||
|
exports: [EnfantsService],
|
||||||
})
|
})
|
||||||
export class EnfantsModule { }
|
export class EnfantsModule { }
|
||||||
|
|||||||
@@ -13,6 +13,12 @@ import { ParentsChildren } from 'src/entities/parents_children.entity';
|
|||||||
import { RoleType, Users } from 'src/entities/users.entity';
|
import { RoleType, Users } from 'src/entities/users.entity';
|
||||||
import { CreateEnfantsDto } from './dto/create_enfants.dto';
|
import { CreateEnfantsDto } from './dto/create_enfants.dto';
|
||||||
|
|
||||||
|
const STAFF_ROLES: RoleType[] = [
|
||||||
|
RoleType.GESTIONNAIRE,
|
||||||
|
RoleType.ADMINISTRATEUR,
|
||||||
|
RoleType.SUPER_ADMIN,
|
||||||
|
];
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class EnfantsService {
|
export class EnfantsService {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -24,20 +30,35 @@ export class EnfantsService {
|
|||||||
private readonly parentsChildrenRepository: Repository<ParentsChildren>,
|
private readonly parentsChildrenRepository: Repository<ParentsChildren>,
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
// Création d'un enfant
|
private isStaff(user: Users): boolean {
|
||||||
async create(dto: CreateEnfantsDto, currentUser: Users, photoFile?: Express.Multer.File): Promise<Children> {
|
return STAFF_ROLES.includes(user.role);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Création d'un enfant.
|
||||||
|
* - PARENT : rattache au parent connecté (multipart photo optionnel).
|
||||||
|
* - Staff : `parent_user_id` obligatoire ; JSON sans photo OK ;
|
||||||
|
* avec photo → multipart (même stockage `/uploads/photos/...`). Ticket #132.
|
||||||
|
*/
|
||||||
|
async create(
|
||||||
|
dto: CreateEnfantsDto,
|
||||||
|
currentUser: Users,
|
||||||
|
photoFile?: Express.Multer.File,
|
||||||
|
): Promise<Children> {
|
||||||
|
const pivotUserId = this.resolvePivotParentUserId(dto, currentUser);
|
||||||
|
|
||||||
const parent = await this.parentsRepository.findOne({
|
const parent = await this.parentsRepository.findOne({
|
||||||
where: { user_id: currentUser.id },
|
where: { user_id: pivotUserId },
|
||||||
relations: ['co_parent'],
|
relations: ['co_parent'],
|
||||||
});
|
});
|
||||||
if (!parent) throw new NotFoundException('Parent introuvable');
|
if (!parent) throw new NotFoundException('Parent introuvable');
|
||||||
|
|
||||||
// Vérif métier simple
|
// Vérif métier simple (aligné comportement historique parent)
|
||||||
if (dto.status !== StatutEnfantType.A_NAITRE && !dto.birth_date) {
|
if (dto.status !== StatutEnfantType.A_NAITRE && !dto.birth_date) {
|
||||||
throw new BadRequestException('Un enfant né doit avoir une date de naissance');
|
throw new BadRequestException('Un enfant né doit avoir une date de naissance');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Vérif doublon éventuel (ex: même prénom + date de naissance pour ce parent)
|
// Vérif doublon éventuel (ex: même prénom + date de naissance)
|
||||||
const exist = await this.childrenRepository.findOne({
|
const exist = await this.childrenRepository.findOne({
|
||||||
where: {
|
where: {
|
||||||
first_name: dto.first_name,
|
first_name: dto.first_name,
|
||||||
@@ -47,50 +68,107 @@ export class EnfantsService {
|
|||||||
});
|
});
|
||||||
if (exist) throw new ConflictException('Cet enfant existe déjà');
|
if (exist) throw new ConflictException('Cet enfant existe déjà');
|
||||||
|
|
||||||
// Gestion de la photo uploadée
|
// Gestion de la photo uploadée (multipart parent ou staff)
|
||||||
|
let photoUrl = dto.photo_url;
|
||||||
|
let consentAt: Date | undefined;
|
||||||
if (photoFile) {
|
if (photoFile) {
|
||||||
dto.photo_url = `/uploads/photos/${photoFile.filename}`;
|
photoUrl = `/uploads/photos/${photoFile.filename}`;
|
||||||
if (dto.consent_photo) {
|
if (dto.consent_photo) {
|
||||||
dto.consent_photo_at = new Date().toISOString();
|
consentAt = new Date();
|
||||||
}
|
}
|
||||||
|
} else if (dto.consent_photo) {
|
||||||
|
consentAt = dto.consent_photo_at
|
||||||
|
? new Date(dto.consent_photo_at)
|
||||||
|
: new Date();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Création
|
const child = this.childrenRepository.create({
|
||||||
const child = this.childrenRepository.create(dto);
|
status: dto.status,
|
||||||
|
first_name: dto.first_name,
|
||||||
|
last_name: dto.last_name,
|
||||||
|
gender: dto.gender,
|
||||||
|
birth_date: dto.birth_date ? new Date(dto.birth_date) : undefined,
|
||||||
|
due_date: dto.due_date ? new Date(dto.due_date) : undefined,
|
||||||
|
photo_url: photoUrl,
|
||||||
|
consent_photo: !!dto.consent_photo,
|
||||||
|
consent_photo_at: consentAt,
|
||||||
|
});
|
||||||
await this.childrenRepository.save(child);
|
await this.childrenRepository.save(child);
|
||||||
|
|
||||||
// Lien parent-enfant (Parent 1)
|
// Lien parent-enfant (pivot)
|
||||||
const parentLink = this.parentsChildrenRepository.create({
|
await this.parentsChildrenRepository.save(
|
||||||
|
this.parentsChildrenRepository.create({
|
||||||
parentId: parent.user_id,
|
parentId: parent.user_id,
|
||||||
enfantId: child.id,
|
enfantId: child.id,
|
||||||
});
|
}),
|
||||||
await this.parentsChildrenRepository.save(parentLink);
|
);
|
||||||
|
|
||||||
// Rattachement automatique au co-parent s'il existe
|
// Rattachement automatique au co-parent s'il existe
|
||||||
if (parent.co_parent) {
|
if (parent.co_parent) {
|
||||||
const coParentLink = this.parentsChildrenRepository.create({
|
await this.parentsChildrenRepository.save(
|
||||||
|
this.parentsChildrenRepository.create({
|
||||||
parentId: parent.co_parent.id,
|
parentId: parent.co_parent.id,
|
||||||
enfantId: child.id,
|
enfantId: child.id,
|
||||||
});
|
}),
|
||||||
await this.parentsChildrenRepository.save(coParentLink);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.findOne(child.id, currentUser);
|
return this.findOne(child.id, currentUser);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Liste des enfants (admin/gestionnaire)
|
private resolvePivotParentUserId(
|
||||||
async findAll(): Promise<Children[]> {
|
dto: CreateEnfantsDto,
|
||||||
return this.childrenRepository.find({
|
currentUser: Users,
|
||||||
relations: ['parentLinks', 'parentLinks.parent', 'parentLinks.parent.user'],
|
): string {
|
||||||
order: { last_name: 'ASC', first_name: 'ASC' },
|
if (this.isStaff(currentUser)) {
|
||||||
|
const id = dto.parent_user_id?.trim();
|
||||||
|
if (!id) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'parent_user_id est obligatoire pour créer un enfant (staff)',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentUser.role === RoleType.PARENT) {
|
||||||
|
if (
|
||||||
|
dto.parent_user_id &&
|
||||||
|
dto.parent_user_id.trim() !== currentUser.id
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Un parent ne peut pas créer un enfant pour un autre compte',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return currentUser.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new ForbiddenException('Accès interdit');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Flag API #157 — true si aucun lien enfants_parents. */
|
||||||
|
private withSansResponsable(child: Children): Children & { sans_responsable: boolean } {
|
||||||
|
return Object.assign(child, {
|
||||||
|
sans_responsable: !child.parentLinks || child.parentLinks.length === 0,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Liste des enfants (admin/gestionnaire) — inclut les orphelins (parentLinks: [])
|
||||||
|
async findAll(): Promise<Array<Children & { sans_responsable: boolean }>> {
|
||||||
|
const children = await this.childrenRepository.find({
|
||||||
|
relations: ['parentLinks', 'parentLinks.parent', 'parentLinks.parent.user'],
|
||||||
|
order: { last_name: 'ASC', first_name: 'ASC' },
|
||||||
|
});
|
||||||
|
return children.map((c) => this.withSansResponsable(c));
|
||||||
|
}
|
||||||
|
|
||||||
// Récupérer un enfant par id
|
// Récupérer un enfant par id
|
||||||
async findOne(id: string, currentUser: Users): Promise<Children> {
|
async findOne(
|
||||||
|
id: string,
|
||||||
|
currentUser: Users,
|
||||||
|
): Promise<Children & { sans_responsable: boolean }> {
|
||||||
const child = await this.childrenRepository.findOne({
|
const child = await this.childrenRepository.findOne({
|
||||||
where: { id },
|
where: { id },
|
||||||
relations: ['parentLinks'],
|
relations: ['parentLinks', 'parentLinks.parent', 'parentLinks.parent.user'],
|
||||||
});
|
});
|
||||||
if (!child) throw new NotFoundException('Enfant introuvable');
|
if (!child) throw new NotFoundException('Enfant introuvable');
|
||||||
|
|
||||||
@@ -104,23 +182,42 @@ export class EnfantsService {
|
|||||||
case RoleType.ADMINISTRATEUR:
|
case RoleType.ADMINISTRATEUR:
|
||||||
case RoleType.SUPER_ADMIN:
|
case RoleType.SUPER_ADMIN:
|
||||||
case RoleType.GESTIONNAIRE:
|
case RoleType.GESTIONNAIRE:
|
||||||
// accès complet
|
// accès complet (y compris orphelins)
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
throw new ForbiddenException('Accès interdit');
|
throw new ForbiddenException('Accès interdit');
|
||||||
}
|
}
|
||||||
|
|
||||||
return child;
|
return this.withSansResponsable(child);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Mise à jour
|
// Mise à jour
|
||||||
async update(id: string, dto: Partial<CreateEnfantsDto>, currentUser: Users): Promise<Children> {
|
async update(
|
||||||
|
id: string,
|
||||||
|
dto: Partial<CreateEnfantsDto>,
|
||||||
|
currentUser: Users,
|
||||||
|
photoFile?: Express.Multer.File,
|
||||||
|
): Promise<Children> {
|
||||||
const child = await this.childrenRepository.findOne({ where: { id } });
|
const child = await this.childrenRepository.findOne({ where: { id } });
|
||||||
if (!child) throw new NotFoundException('Enfant introuvable');
|
if (!child) throw new NotFoundException('Enfant introuvable');
|
||||||
|
|
||||||
await this.childrenRepository.update(id, dto);
|
const { parent_user_id: _ignored, ...rest } = dto;
|
||||||
|
const patch: Partial<Children> = { ...rest } as Partial<Children>;
|
||||||
|
if (dto.consent_photo !== undefined) {
|
||||||
|
patch.consent_photo = dto.consent_photo;
|
||||||
|
patch.consent_photo_at = dto.consent_photo ? new Date() : null!;
|
||||||
|
}
|
||||||
|
if (photoFile) {
|
||||||
|
patch.photo_url = `/uploads/photos/${photoFile.filename}`;
|
||||||
|
if (dto.consent_photo !== false) {
|
||||||
|
patch.consent_photo = true;
|
||||||
|
patch.consent_photo_at = new Date();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.childrenRepository.update(id, patch);
|
||||||
return this.findOne(id, currentUser);
|
return this.findOne(id, currentUser);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -54,9 +54,6 @@ export class DossierFamilleEnfantDto {
|
|||||||
description: 'Consentement affichage photo (colonne consentement_photo)',
|
description: 'Consentement affichage photo (colonne consentement_photo)',
|
||||||
})
|
})
|
||||||
consent_photo?: boolean;
|
consent_photo?: boolean;
|
||||||
|
|
||||||
@ApiProperty({ required: false, description: 'Grossesse multiple (est_multiple)' })
|
|
||||||
est_multiple?: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Réponse GET /parents/dossier-famille/:numeroDossier – dossier famille complet. Ticket #119 */
|
/** Réponse GET /parents/dossier-famille/:numeroDossier – dossier famille complet. Ticket #119 */
|
||||||
|
|||||||
@@ -7,6 +7,12 @@ export class ParentPendingSummaryDto {
|
|||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
email: string;
|
email: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ nullable: true })
|
||||||
|
nom?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ nullable: true })
|
||||||
|
prenom?: string | null;
|
||||||
|
|
||||||
@ApiPropertyOptional({ nullable: true })
|
@ApiPropertyOptional({ nullable: true })
|
||||||
telephone?: string | null;
|
telephone?: string | null;
|
||||||
|
|
||||||
@@ -18,7 +24,10 @@ export class ParentPendingSummaryDto {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class PendingFamilyDto {
|
export class PendingFamilyDto {
|
||||||
@ApiProperty({ example: 'Famille Dupont', description: 'Libellé affiché pour la famille' })
|
@ApiProperty({
|
||||||
|
example: 'MARTIN Claire - MARTIN Thomas',
|
||||||
|
description: 'Libellé affiché : NOM Prénom (séparés par « - » si co-parent)',
|
||||||
|
})
|
||||||
libelle: string;
|
libelle: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
/** Réponse 201 POST /parents/:id/co-parent (#135). */
|
||||||
|
export class StaffAddCoParentResponseDto {
|
||||||
|
@ApiProperty()
|
||||||
|
message: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2026-000043' })
|
||||||
|
numero_dossier: string;
|
||||||
|
|
||||||
|
@ApiProperty({ format: 'uuid', description: 'UUID du parent pivot' })
|
||||||
|
parent_user_id: string;
|
||||||
|
|
||||||
|
@ApiProperty({ format: 'uuid', description: 'UUID du co-parent créé' })
|
||||||
|
co_parent_user_id: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
enum: StatutUtilisateurType,
|
||||||
|
example: StatutUtilisateurType.ACTIF,
|
||||||
|
})
|
||||||
|
statut: StatutUtilisateurType;
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import {
|
||||||
|
IsBoolean,
|
||||||
|
IsEmail,
|
||||||
|
IsNotEmpty,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
Matches,
|
||||||
|
MaxLength,
|
||||||
|
MinLength,
|
||||||
|
} from 'class-validator';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ajout d’un co-parent sur un foyer existant (staff) — ticket #135.
|
||||||
|
* Corps sans préfixe `co_parent_*` (l’URL cible déjà le pivot).
|
||||||
|
*/
|
||||||
|
export class StaffAddCoParentDto {
|
||||||
|
@ApiProperty({ example: 'thomas.martin@ptits-pas.fr' })
|
||||||
|
@IsEmail({}, { message: 'Email invalide' })
|
||||||
|
@IsNotEmpty({ message: "L'email est requis" })
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'Thomas' })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty({ message: 'Le prénom est requis' })
|
||||||
|
@MinLength(2)
|
||||||
|
@MaxLength(100)
|
||||||
|
prenom: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'MARTIN' })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty({ message: 'Le nom est requis' })
|
||||||
|
@MinLength(2)
|
||||||
|
@MaxLength(100)
|
||||||
|
nom: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '0678456789' })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty({ message: 'Le téléphone est requis' })
|
||||||
|
@Matches(/^(\+33|0)[1-9](\d{2}){4}$/, {
|
||||||
|
message: 'Le numéro de téléphone doit être valide (ex: 0689567890 ou +33689567890)',
|
||||||
|
})
|
||||||
|
telephone: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
example: true,
|
||||||
|
description: 'Si true, copie l’adresse du parent pivot',
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
meme_adresse?: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
adresse?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(10)
|
||||||
|
code_postal?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(150)
|
||||||
|
ville?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
/** Réponse 201 POST /parents/dossier (#129). */
|
||||||
|
export class StaffCreateParentDossierResponseDto {
|
||||||
|
@ApiProperty()
|
||||||
|
message: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: '2026-000043',
|
||||||
|
description: 'Numéro de dossier famille attribué',
|
||||||
|
})
|
||||||
|
numero_dossier: string;
|
||||||
|
|
||||||
|
@ApiProperty({ format: 'uuid', description: 'UUID user du parent pivot' })
|
||||||
|
parent_user_id: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
format: 'uuid',
|
||||||
|
nullable: true,
|
||||||
|
description: 'UUID user du co-parent, ou null',
|
||||||
|
})
|
||||||
|
co_parent_user_id: string | null;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
enum: StatutUtilisateurType,
|
||||||
|
example: StatutUtilisateurType.ACTIF,
|
||||||
|
})
|
||||||
|
statut: StatutUtilisateurType;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
type: [String],
|
||||||
|
format: 'uuid',
|
||||||
|
description: 'IDs des enfants créés',
|
||||||
|
})
|
||||||
|
enfant_ids: string[];
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { ApiPropertyOptional, OmitType } from '@nestjs/swagger';
|
||||||
|
import { IsBoolean, IsOptional } from 'class-validator';
|
||||||
|
import { RegisterParentCompletDto } from 'src/routes/auth/dto/register-parent-complet.dto';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Création dossier parent/famille par staff (#129).
|
||||||
|
* Mêmes champs que l'inscription publique, sans CGU/privacy obligatoires
|
||||||
|
* (acceptées côté serveur pour le compte du gestionnaire).
|
||||||
|
*/
|
||||||
|
export class StaffCreateParentDossierDto extends OmitType(RegisterParentCompletDto, [
|
||||||
|
'acceptation_cgu',
|
||||||
|
'acceptation_privacy',
|
||||||
|
] as const) {
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Ignoré côté staff (CGU acceptées serveur). Conservé pour compat éventuelle.',
|
||||||
|
default: true,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
acceptation_cgu?: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Ignoré côté staff (privacy acceptée serveur).',
|
||||||
|
default: true,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
acceptation_privacy?: boolean;
|
||||||
|
}
|
||||||
@@ -1,18 +1,104 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { ParentsController } from './parents.controller';
|
import { ParentsController } from './parents.controller';
|
||||||
|
import { ParentsService } from './parents.service';
|
||||||
|
import { UserService } from '../user/user.service';
|
||||||
|
import { AuthService } from '../auth/auth.service';
|
||||||
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
import { StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
describe('ParentsController', () => {
|
describe('ParentsController', () => {
|
||||||
let controller: ParentsController;
|
let controller: ParentsController;
|
||||||
|
const authServiceMock = {
|
||||||
|
createParentDossierStaff: jest.fn(),
|
||||||
|
addCoParentStaff: jest.fn(),
|
||||||
|
};
|
||||||
|
const parentsServiceMock = {};
|
||||||
|
const userServiceMock = {};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
controllers: [ParentsController],
|
controllers: [ParentsController],
|
||||||
}).compile();
|
providers: [
|
||||||
|
{ provide: ParentsService, useValue: parentsServiceMock },
|
||||||
|
{ provide: UserService, useValue: userServiceMock },
|
||||||
|
{ provide: AuthService, useValue: authServiceMock },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.overrideGuard(AuthGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.overrideGuard(RolesGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.compile();
|
||||||
|
|
||||||
controller = module.get<ParentsController>(ParentsController);
|
controller = module.get<ParentsController>(ParentsController);
|
||||||
|
jest.clearAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('should be defined', () => {
|
||||||
expect(controller).toBeDefined();
|
expect(controller).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('createDossier delegates to authService.createParentDossierStaff with CGU accepted', async () => {
|
||||||
|
authServiceMock.createParentDossierStaff.mockResolvedValue({
|
||||||
|
message: 'Dossier famille créé et validé. Un e-mail de création de mot de passe a été envoyé.',
|
||||||
|
parent_user_id: 'p1',
|
||||||
|
co_parent_user_id: 'p2',
|
||||||
|
enfant_ids: ['e1'],
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
numero_dossier: '2026-000043',
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = {
|
||||||
|
email: 'parent.staff@test.fr',
|
||||||
|
prenom: 'Claire',
|
||||||
|
nom: 'MARTIN',
|
||||||
|
telephone: '0689567890',
|
||||||
|
enfants: [
|
||||||
|
{
|
||||||
|
prenom: 'Emma',
|
||||||
|
nom: 'MARTIN',
|
||||||
|
date_naissance: '2023-02-15',
|
||||||
|
genre: 'F',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const res = await controller.createDossier(body as any);
|
||||||
|
expect(authServiceMock.createParentDossierStaff).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
email: body.email,
|
||||||
|
acceptation_cgu: true,
|
||||||
|
acceptation_privacy: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(res.numero_dossier).toBe('2026-000043');
|
||||||
|
expect(res.parent_user_id).toBe('p1');
|
||||||
|
expect(res.co_parent_user_id).toBe('p2');
|
||||||
|
expect(res.enfant_ids).toEqual(['e1']);
|
||||||
|
expect(res.statut).toBe(StatutUtilisateurType.ACTIF);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('addCoParent delegates to authService.addCoParentStaff', async () => {
|
||||||
|
authServiceMock.addCoParentStaff.mockResolvedValue({
|
||||||
|
message: 'ok',
|
||||||
|
numero_dossier: '2026-000043',
|
||||||
|
parent_user_id: 'p1',
|
||||||
|
co_parent_user_id: 'p2',
|
||||||
|
statut: StatutUtilisateurType.ACTIF,
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = {
|
||||||
|
email: 'coparent@test.fr',
|
||||||
|
prenom: 'Thomas',
|
||||||
|
nom: 'MARTIN',
|
||||||
|
telephone: '0678456789',
|
||||||
|
meme_adresse: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const res = await controller.addCoParent('p1', body as any);
|
||||||
|
expect(authServiceMock.addCoParentStaff).toHaveBeenCalledWith('p1', body);
|
||||||
|
expect(res.co_parent_user_id).toBe('p2');
|
||||||
|
expect(res.statut).toBe(StatutUtilisateurType.ACTIF);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import {
|
|||||||
Controller,
|
Controller,
|
||||||
Delete,
|
Delete,
|
||||||
Get,
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
Param,
|
Param,
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
@@ -10,14 +12,27 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ParentsService } from './parents.service';
|
import { ParentsService } from './parents.service';
|
||||||
import { UserService } from '../user/user.service';
|
import { UserService } from '../user/user.service';
|
||||||
|
import { AuthService } from '../auth/auth.service';
|
||||||
import { Parents } from 'src/entities/parents.entity';
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
import { Users } from 'src/entities/users.entity';
|
import { Users } from 'src/entities/users.entity';
|
||||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||||
import { RoleType, StatutUtilisateurType } from 'src/entities/users.entity';
|
import { RoleType, StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
import { ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiBody,
|
||||||
|
ApiOperation,
|
||||||
|
ApiParam,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from '@nestjs/swagger';
|
||||||
import { CreateParentDto } from '../user/dto/create_parent.dto';
|
import { CreateParentDto } from '../user/dto/create_parent.dto';
|
||||||
import { UpdateParentsDto } from '../user/dto/update_parent.dto';
|
import { UpdateParentsDto } from '../user/dto/update_parent.dto';
|
||||||
import { UpdateParentFicheAdminDto } from './dto/update-parent-fiche-admin.dto';
|
import { UpdateParentFicheAdminDto } from './dto/update-parent-fiche-admin.dto';
|
||||||
|
import { StaffCreateParentDossierDto } from './dto/staff-create-parent-dossier.dto';
|
||||||
|
import { StaffCreateParentDossierResponseDto } from './dto/staff-create-parent-dossier-response.dto';
|
||||||
|
import { StaffAddCoParentDto } from './dto/staff-add-co-parent.dto';
|
||||||
|
import { StaffAddCoParentResponseDto } from './dto/staff-add-co-parent-response.dto';
|
||||||
|
import { RegisterParentCompletDto } from '../auth/dto/register-parent-complet.dto';
|
||||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
import { User } from 'src/common/decorators/user.decorator';
|
import { User } from 'src/common/decorators/user.decorator';
|
||||||
@@ -26,14 +41,50 @@ import { DossierFamilleCompletDto } from './dto/dossier-famille-complet.dto';
|
|||||||
import { mapParentForApi, mapParentsForApi } from './parents.mapper';
|
import { mapParentForApi, mapParentsForApi } from './parents.mapper';
|
||||||
|
|
||||||
@ApiTags('Parents')
|
@ApiTags('Parents')
|
||||||
|
@ApiBearerAuth('access-token')
|
||||||
@Controller('parents')
|
@Controller('parents')
|
||||||
@UseGuards(AuthGuard, RolesGuard)
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
export class ParentsController {
|
export class ParentsController {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly parentsService: ParentsService,
|
private readonly parentsService: ParentsService,
|
||||||
private readonly userService: UserService,
|
private readonly userService: UserService,
|
||||||
|
private readonly authService: AuthService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
|
@Post('dossier')
|
||||||
|
@HttpCode(HttpStatus.CREATED)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Créer un dossier famille/parent complet (staff) — ticket #129',
|
||||||
|
description:
|
||||||
|
'Crée parent (+ co-parent optionnel) + enfants + n° dossier avec statut actif, ' +
|
||||||
|
'et envoie l’e-mail de création de mot de passe. ' +
|
||||||
|
'Ne pas utiliser POST /auth/register/parent depuis le dashboard.',
|
||||||
|
})
|
||||||
|
@ApiBody({ type: StaffCreateParentDossierDto })
|
||||||
|
@ApiResponse({ status: 201, type: StaffCreateParentDossierResponseDto })
|
||||||
|
@ApiResponse({ status: 400, description: 'Validation DTO / métier' })
|
||||||
|
@ApiResponse({ status: 403, description: 'Rôle non autorisé' })
|
||||||
|
@ApiResponse({ status: 409, description: 'Email pivot et/ou co-parent déjà pris' })
|
||||||
|
async createDossier(
|
||||||
|
@Body() dto: StaffCreateParentDossierDto,
|
||||||
|
): Promise<StaffCreateParentDossierResponseDto> {
|
||||||
|
const registerDto = {
|
||||||
|
...dto,
|
||||||
|
acceptation_cgu: true,
|
||||||
|
acceptation_privacy: true,
|
||||||
|
} as RegisterParentCompletDto;
|
||||||
|
const result = await this.authService.createParentDossierStaff(registerDto);
|
||||||
|
return {
|
||||||
|
message: result.message,
|
||||||
|
numero_dossier: result.numero_dossier,
|
||||||
|
parent_user_id: result.parent_user_id,
|
||||||
|
co_parent_user_id: result.co_parent_user_id ?? null,
|
||||||
|
statut: result.statut,
|
||||||
|
enfant_ids: result.enfant_ids,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
@Get('pending-families')
|
@Get('pending-families')
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
@ApiOperation({ summary: 'Liste des familles en attente (une entrée par famille)' })
|
@ApiOperation({ summary: 'Liste des familles en attente (une entrée par famille)' })
|
||||||
@@ -127,6 +178,28 @@ export class ParentsController {
|
|||||||
return mapParentForApi(parent);
|
return mapParentForApi(parent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
|
@Post(':id/co-parent')
|
||||||
|
@HttpCode(HttpStatus.CREATED)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Ajouter un co-parent à un foyer existant (staff) — ticket #135',
|
||||||
|
description:
|
||||||
|
'Foyer mono-parent uniquement. Crée le co-parent actif, liens foyer + enfants, ' +
|
||||||
|
'e-mail de création de mot de passe. Ne pas utiliser POST /auth/register/parent.',
|
||||||
|
})
|
||||||
|
@ApiParam({ name: 'id', description: 'UUID utilisateur du parent pivot' })
|
||||||
|
@ApiBody({ type: StaffAddCoParentDto })
|
||||||
|
@ApiResponse({ status: 201, type: StaffAddCoParentResponseDto })
|
||||||
|
@ApiResponse({ status: 400, description: 'Foyer déjà à 2 parents / validation' })
|
||||||
|
@ApiResponse({ status: 404, description: 'Parent introuvable' })
|
||||||
|
@ApiResponse({ status: 409, description: 'Email déjà pris' })
|
||||||
|
async addCoParent(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() dto: StaffAddCoParentDto,
|
||||||
|
): Promise<StaffAddCoParentResponseDto> {
|
||||||
|
return this.authService.addCoParentStaff(id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||||
@Post(':id/enfants/:enfantId')
|
@Post(':id/enfants/:enfantId')
|
||||||
@ApiOperation({ summary: 'Rattacher un enfant à un parent — ticket #115' })
|
@ApiOperation({ summary: 'Rattacher un enfant à un parent — ticket #115' })
|
||||||
|
|||||||
@@ -9,11 +9,13 @@ import { ParentsController } from './parents.controller';
|
|||||||
import { ParentsService } from './parents.service';
|
import { ParentsService } from './parents.service';
|
||||||
import { Users } from 'src/entities/users.entity';
|
import { Users } from 'src/entities/users.entity';
|
||||||
import { UserModule } from '../user/user.module';
|
import { UserModule } from '../user/user.module';
|
||||||
|
import { AuthModule } from '../auth/auth.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
TypeOrmModule.forFeature([Parents, Users, DossierFamille, DossierFamilleEnfant, ParentsChildren]),
|
TypeOrmModule.forFeature([Parents, Users, DossierFamille, DossierFamilleEnfant, ParentsChildren]),
|
||||||
forwardRef(() => UserModule),
|
forwardRef(() => UserModule),
|
||||||
|
forwardRef(() => AuthModule),
|
||||||
JwtModule.registerAsync({
|
JwtModule.registerAsync({
|
||||||
imports: [ConfigModule],
|
imports: [ConfigModule],
|
||||||
useFactory: (config: ConfigService) => ({
|
useFactory: (config: ConfigService) => ({
|
||||||
|
|||||||
@@ -114,34 +114,86 @@ export class ParentsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Rattacher un enfant existant à un parent (enfants_parents). Ticket #115 / doc 28 §6.2.
|
* Membres du foyer (user ids) pour affiliation enfant.
|
||||||
|
* Pivot + co-parent (A→B et B→A) + même numero_dossier. Ticket #158.
|
||||||
*/
|
*/
|
||||||
async attachEnfant(parentUserId: string, enfantId: string): Promise<Parents> {
|
private async resolveFoyerParentUserIds(parent: Parents): Promise<string[]> {
|
||||||
await this.findOne(parentUserId);
|
const ids = new Set<string>([parent.user_id]);
|
||||||
|
|
||||||
const existing = await this.parentsChildrenRepository.findOne({
|
if (parent.co_parent?.id) {
|
||||||
where: { parentId: parentUserId, enfantId },
|
ids.add(parent.co_parent.id);
|
||||||
});
|
|
||||||
if (existing) {
|
|
||||||
throw new ConflictException('Cet enfant est déjà rattaché à ce parent');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const child = await this.parentsRepository.manager.findOne(Children, { where: { id: enfantId } });
|
// Sens inverse : parents qui déclarent ce user comme co-parent
|
||||||
|
const reverseLinks = await this.parentsRepository.find({
|
||||||
|
where: { co_parent: { id: parent.user_id } },
|
||||||
|
relations: ['co_parent'],
|
||||||
|
});
|
||||||
|
for (const p of reverseLinks) {
|
||||||
|
ids.add(p.user_id);
|
||||||
|
if (p.co_parent?.id) ids.add(p.co_parent.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const dossier = parent.numero_dossier?.trim();
|
||||||
|
if (dossier) {
|
||||||
|
const sameDossier = await this.parentsRepository.find({
|
||||||
|
where: { numero_dossier: dossier },
|
||||||
|
relations: ['co_parent'],
|
||||||
|
});
|
||||||
|
for (const p of sameDossier) {
|
||||||
|
ids.add(p.user_id);
|
||||||
|
if (p.co_parent?.id) ids.add(p.co_parent.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...ids];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rattacher un enfant au foyer du parent (tous les responsables). Ticket #158.
|
||||||
|
* Un seul POST suffit : liens créés pour pivot + co-parent / même dossier.
|
||||||
|
*/
|
||||||
|
async attachEnfant(parentUserId: string, enfantId: string): Promise<Parents> {
|
||||||
|
const parent = await this.findOne(parentUserId);
|
||||||
|
|
||||||
|
const child = await this.parentsRepository.manager.findOne(Children, {
|
||||||
|
where: { id: enfantId },
|
||||||
|
});
|
||||||
if (!child) {
|
if (!child) {
|
||||||
throw new NotFoundException('Enfant introuvable');
|
throw new NotFoundException('Enfant introuvable');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const foyerIds = await this.resolveFoyerParentUserIds(parent);
|
||||||
|
let created = 0;
|
||||||
|
|
||||||
|
for (const memberId of foyerIds) {
|
||||||
|
const existing = await this.parentsChildrenRepository.findOne({
|
||||||
|
where: { parentId: memberId, enfantId },
|
||||||
|
});
|
||||||
|
if (existing) continue;
|
||||||
|
|
||||||
await this.parentsChildrenRepository.save(
|
await this.parentsChildrenRepository.save(
|
||||||
this.parentsChildrenRepository.create({ parentId: parentUserId, enfantId }),
|
this.parentsChildrenRepository.create({
|
||||||
|
parentId: memberId,
|
||||||
|
enfantId,
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
|
created += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (created === 0) {
|
||||||
|
throw new ConflictException('Cet enfant est déjà rattaché à ce foyer');
|
||||||
|
}
|
||||||
|
|
||||||
return this.findOne(parentUserId);
|
return this.findOne(parentUserId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Détacher un enfant d'un parent sans supprimer l'enfant. Ticket #115 / doc 28 §6.2.
|
* Détacher un enfant du foyer du parent (tous les responsables). Ticket #158.
|
||||||
|
* Si plus aucun lien ensuite → enfant orphelin (#157).
|
||||||
*/
|
*/
|
||||||
async detachEnfant(parentUserId: string, enfantId: string): Promise<Parents> {
|
async detachEnfant(parentUserId: string, enfantId: string): Promise<Parents> {
|
||||||
await this.findOne(parentUserId);
|
const parent = await this.findOne(parentUserId);
|
||||||
|
|
||||||
const link = await this.parentsChildrenRepository.findOne({
|
const link = await this.parentsChildrenRepository.findOne({
|
||||||
where: { parentId: parentUserId, enfantId },
|
where: { parentId: parentUserId, enfantId },
|
||||||
@@ -150,12 +202,12 @@ export class ParentsService {
|
|||||||
throw new NotFoundException('Lien parent-enfant introuvable');
|
throw new NotFoundException('Lien parent-enfant introuvable');
|
||||||
}
|
}
|
||||||
|
|
||||||
const totalLinks = await this.parentsChildrenRepository.count({ where: { enfantId } });
|
const foyerIds = await this.resolveFoyerParentUserIds(parent);
|
||||||
if (totalLinks <= 1) {
|
await this.parentsChildrenRepository.delete({
|
||||||
throw new BadRequestException('Un enfant doit rester rattaché à au moins un responsable');
|
parentId: In(foyerIds),
|
||||||
}
|
enfantId,
|
||||||
|
});
|
||||||
|
|
||||||
await this.parentsChildrenRepository.delete({ parentId: parentUserId, enfantId });
|
|
||||||
return this.findOne(parentUserId);
|
return this.findOne(parentUserId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,7 +251,15 @@ export class ParentsService {
|
|||||||
SELECT id, (MIN(rep::text))::uuid AS rep FROM rec GROUP BY id
|
SELECT id, (MIN(rep::text))::uuid AS rep FROM rec GROUP BY id
|
||||||
)
|
)
|
||||||
SELECT
|
SELECT
|
||||||
'Famille ' || string_agg(u.nom, ' - ' ORDER BY u.nom, u.prenom) AS libelle,
|
string_agg(
|
||||||
|
UPPER(TRIM(u.nom))
|
||||||
|
|| CASE
|
||||||
|
WHEN u.prenom IS NOT NULL AND TRIM(u.prenom) <> ''
|
||||||
|
THEN ' ' || INITCAP(TRIM(u.prenom))
|
||||||
|
ELSE ''
|
||||||
|
END,
|
||||||
|
' - ' ORDER BY u.nom, u.prenom, u.id
|
||||||
|
) AS libelle,
|
||||||
array_agg(p.id_utilisateur ORDER BY u.nom, u.prenom, u.id) AS "parentIds",
|
array_agg(p.id_utilisateur ORDER BY u.nom, u.prenom, u.id) AS "parentIds",
|
||||||
(array_agg(p.numero_dossier))[1] AS numero_dossier,
|
(array_agg(p.numero_dossier))[1] AS numero_dossier,
|
||||||
MIN(u.cree_le) AS date_soumission,
|
MIN(u.cree_le) AS date_soumission,
|
||||||
@@ -215,6 +275,8 @@ export class ParentsService {
|
|||||||
json_build_object(
|
json_build_object(
|
||||||
'id', u.id::text,
|
'id', u.id::text,
|
||||||
'email', u.email,
|
'email', u.email,
|
||||||
|
'nom', u.nom,
|
||||||
|
'prenom', u.prenom,
|
||||||
'telephone', u.telephone,
|
'telephone', u.telephone,
|
||||||
'code_postal', u.code_postal,
|
'code_postal', u.code_postal,
|
||||||
'ville', u.ville
|
'ville', u.ville
|
||||||
@@ -265,11 +327,21 @@ export class ParentsService {
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeParents(parents: unknown): { id: string; email: string; telephone: string | null; code_postal: string | null; ville: string | null }[] {
|
private normalizeParents(parents: unknown): {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
nom: string | null;
|
||||||
|
prenom: string | null;
|
||||||
|
telephone: string | null;
|
||||||
|
code_postal: string | null;
|
||||||
|
ville: string | null;
|
||||||
|
}[] {
|
||||||
if (Array.isArray(parents)) {
|
if (Array.isArray(parents)) {
|
||||||
return parents.map((p: any) => ({
|
return parents.map((p: any) => ({
|
||||||
id: String(p?.id ?? ''),
|
id: String(p?.id ?? ''),
|
||||||
email: String(p?.email ?? ''),
|
email: String(p?.email ?? ''),
|
||||||
|
nom: p?.nom != null ? String(p.nom) : null,
|
||||||
|
prenom: p?.prenom != null ? String(p.prenom) : null,
|
||||||
telephone: p?.telephone != null ? String(p.telephone) : null,
|
telephone: p?.telephone != null ? String(p.telephone) : null,
|
||||||
code_postal: p?.code_postal != null ? String(p.code_postal) : null,
|
code_postal: p?.code_postal != null ? String(p.code_postal) : null,
|
||||||
ville: p?.ville != null ? String(p.ville) : null,
|
ville: p?.ville != null ? String(p.ville) : null,
|
||||||
@@ -298,7 +370,6 @@ export class ParentsService {
|
|||||||
status: child.status,
|
status: child.status,
|
||||||
photo_url: child.photo_url ?? undefined,
|
photo_url: child.photo_url ?? undefined,
|
||||||
consent_photo: child.consent_photo,
|
consent_photo: child.consent_photo,
|
||||||
est_multiple: child.is_multiple,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,15 +24,19 @@ export class RelaisController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
@ApiOperation({ summary: 'Lister tous les relais' })
|
@ApiOperation({
|
||||||
|
summary: 'Lister tous les relais',
|
||||||
|
description:
|
||||||
|
'Lecture ouverte aux gestionnaires (combobox fiches). CRUD write reste admin-only. Ticket #151.',
|
||||||
|
})
|
||||||
@ApiResponse({ status: 200, description: 'Liste des relais.' })
|
@ApiResponse({ status: 200, description: 'Liste des relais.' })
|
||||||
findAll() {
|
findAll() {
|
||||||
return this.relaisService.findAll();
|
return this.relaisService.findAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':id')
|
@Get(':id')
|
||||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||||
@ApiOperation({ summary: 'Récupérer un relais par ID' })
|
@ApiOperation({ summary: 'Récupérer un relais par ID' })
|
||||||
@ApiResponse({ status: 200, description: 'Le relais trouvé.' })
|
@ApiResponse({ status: 200, description: 'Le relais trouvé.' })
|
||||||
findOne(@Param('id') id: string) {
|
findOne(@Param('id') id: string) {
|
||||||
|
|||||||
@@ -0,0 +1,175 @@
|
|||||||
|
import { ForbiddenException, NotFoundException } from '@nestjs/common';
|
||||||
|
import { SuppressionService } from './suppression.service';
|
||||||
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
describe('SuppressionService (#159)', () => {
|
||||||
|
const dataSource = {
|
||||||
|
transaction: jest.fn(async (cb: (m: unknown) => Promise<unknown>) =>
|
||||||
|
cb({
|
||||||
|
delete: jest.fn(),
|
||||||
|
query: jest.fn(),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
const usersRepository = {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
count: jest.fn(),
|
||||||
|
};
|
||||||
|
const parentsRepository = {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
find: jest.fn(),
|
||||||
|
query: jest.fn(),
|
||||||
|
};
|
||||||
|
const amRepository = {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
const childrenRepository = {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
save: jest.fn(),
|
||||||
|
};
|
||||||
|
const parentsChildrenRepository = {
|
||||||
|
find: jest.fn(),
|
||||||
|
};
|
||||||
|
const amChildrenRepository = {
|
||||||
|
find: jest.fn(),
|
||||||
|
save: jest.fn(),
|
||||||
|
count: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let service: SuppressionService;
|
||||||
|
|
||||||
|
const staff = {
|
||||||
|
id: 'staff-1',
|
||||||
|
role: RoleType.GESTIONNAIRE,
|
||||||
|
} as never;
|
||||||
|
|
||||||
|
const admin = {
|
||||||
|
id: 'admin-1',
|
||||||
|
role: RoleType.ADMINISTRATEUR,
|
||||||
|
} as never;
|
||||||
|
|
||||||
|
const superAdmin = {
|
||||||
|
id: 'sa-1',
|
||||||
|
role: RoleType.SUPER_ADMIN,
|
||||||
|
} as never;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
service = new SuppressionService(
|
||||||
|
dataSource as never,
|
||||||
|
usersRepository as never,
|
||||||
|
parentsRepository as never,
|
||||||
|
amRepository as never,
|
||||||
|
childrenRepository as never,
|
||||||
|
parentsChildrenRepository as never,
|
||||||
|
amChildrenRepository as never,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse self-delete', async () => {
|
||||||
|
usersRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'admin-1',
|
||||||
|
role: RoleType.ADMINISTRATEUR,
|
||||||
|
});
|
||||||
|
await expect(service.deleteUser('admin-1', admin)).rejects.toBeInstanceOf(
|
||||||
|
ForbiddenException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse gestionnaire deleting another gestionnaire', async () => {
|
||||||
|
usersRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'g2',
|
||||||
|
role: RoleType.GESTIONNAIRE,
|
||||||
|
});
|
||||||
|
await expect(service.deleteUser('g2', staff)).rejects.toBeInstanceOf(
|
||||||
|
ForbiddenException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dernier admin : refus si pas super_admin', async () => {
|
||||||
|
usersRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'admin-2',
|
||||||
|
role: RoleType.ADMINISTRATEUR,
|
||||||
|
});
|
||||||
|
usersRepository.count.mockResolvedValue(1);
|
||||||
|
await expect(service.deleteUser('admin-2', admin)).rejects.toBeInstanceOf(
|
||||||
|
ForbiddenException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dernier admin : OK pour super_admin', async () => {
|
||||||
|
usersRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'admin-2',
|
||||||
|
role: RoleType.ADMINISTRATEUR,
|
||||||
|
});
|
||||||
|
usersRepository.count.mockResolvedValue(1);
|
||||||
|
usersRepository.delete.mockResolvedValue({ affected: 1 });
|
||||||
|
const res = await service.deleteUser('admin-2', superAdmin);
|
||||||
|
expect(res.deleted_user_ids).toEqual(['admin-2']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('delete AM : clos placements, pas d’enfants deleted', async () => {
|
||||||
|
usersRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'am-1',
|
||||||
|
role: RoleType.ASSISTANTE_MATERNELLE,
|
||||||
|
});
|
||||||
|
amRepository.findOne.mockResolvedValue({
|
||||||
|
user_id: 'am-1',
|
||||||
|
numero_dossier: '2026-000015',
|
||||||
|
});
|
||||||
|
amChildrenRepository.find.mockResolvedValue([
|
||||||
|
{
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e1',
|
||||||
|
child: { id: 'e1', status: 'garde' },
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
amChildrenRepository.count.mockResolvedValue(0);
|
||||||
|
amChildrenRepository.save.mockImplementation(async (x) => x);
|
||||||
|
childrenRepository.save.mockResolvedValue({});
|
||||||
|
usersRepository.delete.mockResolvedValue({ affected: 1 });
|
||||||
|
|
||||||
|
const res = await service.deleteUser('am-1', staff);
|
||||||
|
expect(res.deleted_enfant_ids).toEqual([]);
|
||||||
|
expect(res.deleted_user_ids).toEqual(['am-1']);
|
||||||
|
expect(res.type).toBe('assistante_maternelle');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('delete dossier famille introuvable', async () => {
|
||||||
|
parentsRepository.findOne.mockResolvedValue(null);
|
||||||
|
amRepository.findOne.mockResolvedValue(null);
|
||||||
|
await expect(
|
||||||
|
service.deleteDossier('2026-999999', staff),
|
||||||
|
).rejects.toBeInstanceOf(NotFoundException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('co-parent : delete user seul', async () => {
|
||||||
|
usersRepository.findOne.mockResolvedValue({
|
||||||
|
id: 'p2',
|
||||||
|
role: RoleType.PARENT,
|
||||||
|
});
|
||||||
|
parentsRepository.findOne.mockResolvedValue({
|
||||||
|
user_id: 'p2',
|
||||||
|
numero_dossier: '2026-000010',
|
||||||
|
co_parent: { id: 'p1' },
|
||||||
|
});
|
||||||
|
parentsRepository.query.mockResolvedValue([
|
||||||
|
{ id: 'p1' },
|
||||||
|
{ id: 'p2' },
|
||||||
|
]);
|
||||||
|
dataSource.transaction.mockImplementation(async (cb) =>
|
||||||
|
cb({
|
||||||
|
delete: jest.fn(),
|
||||||
|
query: jest.fn(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const res = await service.deleteUser('p2', staff);
|
||||||
|
expect(res.deleted_enfant_ids).toEqual([]);
|
||||||
|
expect(res.deleted_user_ids).toEqual(['p2']);
|
||||||
|
expect(res.message).toMatch(/co-parent/i);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
ForbiddenException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { DataSource, In, IsNull, Repository } from 'typeorm';
|
||||||
|
import { RoleType, Users } from 'src/entities/users.entity';
|
||||||
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
|
import { Children, StatutEnfantType } from 'src/entities/children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
|
||||||
|
export type SuppressionResult = {
|
||||||
|
type?: 'famille' | 'assistante_maternelle';
|
||||||
|
numero_dossier?: string;
|
||||||
|
deleted_user_ids: string[];
|
||||||
|
deleted_enfant_ids: string[];
|
||||||
|
dossier_supprime?: boolean;
|
||||||
|
message: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const STAFF_METIER: RoleType[] = [
|
||||||
|
RoleType.GESTIONNAIRE,
|
||||||
|
RoleType.ADMINISTRATEUR,
|
||||||
|
RoleType.SUPER_ADMIN,
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cascades de suppression métier — tickets #154 / #159.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class SuppressionService {
|
||||||
|
constructor(
|
||||||
|
private readonly dataSource: DataSource,
|
||||||
|
@InjectRepository(Users)
|
||||||
|
private readonly usersRepository: Repository<Users>,
|
||||||
|
@InjectRepository(Parents)
|
||||||
|
private readonly parentsRepository: Repository<Parents>,
|
||||||
|
@InjectRepository(AssistanteMaternelle)
|
||||||
|
private readonly amRepository: Repository<AssistanteMaternelle>,
|
||||||
|
@InjectRepository(Children)
|
||||||
|
private readonly childrenRepository: Repository<Children>,
|
||||||
|
@InjectRepository(ParentsChildren)
|
||||||
|
private readonly parentsChildrenRepository: Repository<ParentsChildren>,
|
||||||
|
@InjectRepository(AmChildren)
|
||||||
|
private readonly amChildrenRepository: Repository<AmChildren>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
assertStaffMetier(currentUser: Users): void {
|
||||||
|
if (!STAFF_METIER.includes(currentUser.role)) {
|
||||||
|
throw new ForbiddenException('Accès refusé');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteDossier(
|
||||||
|
numeroDossier: string,
|
||||||
|
currentUser: Users,
|
||||||
|
): Promise<SuppressionResult> {
|
||||||
|
this.assertStaffMetier(currentUser);
|
||||||
|
const num = numeroDossier?.trim();
|
||||||
|
if (!num) {
|
||||||
|
throw new BadRequestException('Numéro de dossier requis.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const parentHit = await this.parentsRepository.findOne({
|
||||||
|
where: { numero_dossier: num },
|
||||||
|
});
|
||||||
|
if (parentHit) {
|
||||||
|
return this.deleteFamilleByNumero(num);
|
||||||
|
}
|
||||||
|
|
||||||
|
const amHit = await this.amRepository.findOne({
|
||||||
|
where: { numero_dossier: num },
|
||||||
|
relations: ['user'],
|
||||||
|
});
|
||||||
|
if (amHit?.user) {
|
||||||
|
return this.deleteAmUser(amHit.user.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new NotFoundException('Aucun dossier trouvé pour ce numéro.');
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteUser(
|
||||||
|
id: string,
|
||||||
|
currentUser: Users,
|
||||||
|
): Promise<SuppressionResult> {
|
||||||
|
const target = await this.usersRepository.findOne({ where: { id } });
|
||||||
|
if (!target) {
|
||||||
|
throw new NotFoundException('Utilisateur introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target.id === currentUser.id) {
|
||||||
|
throw new ForbiddenException('Vous ne pouvez pas supprimer votre propre compte.');
|
||||||
|
}
|
||||||
|
if (target.role === RoleType.SUPER_ADMIN) {
|
||||||
|
throw new ForbiddenException('Le super administrateur ne peut pas être supprimé.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target.role === RoleType.PARENT) {
|
||||||
|
this.assertStaffMetier(currentUser);
|
||||||
|
return this.deleteParentUser(target.id);
|
||||||
|
}
|
||||||
|
if (target.role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
this.assertStaffMetier(currentUser);
|
||||||
|
return this.deleteAmUser(target.id);
|
||||||
|
}
|
||||||
|
if (target.role === RoleType.GESTIONNAIRE) {
|
||||||
|
if (
|
||||||
|
currentUser.role !== RoleType.ADMINISTRATEUR &&
|
||||||
|
currentUser.role !== RoleType.SUPER_ADMIN
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Seul un administrateur peut supprimer un gestionnaire.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await this.usersRepository.delete(target.id);
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [target.id],
|
||||||
|
deleted_enfant_ids: [],
|
||||||
|
message: 'Gestionnaire supprimé.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (target.role === RoleType.ADMINISTRATEUR) {
|
||||||
|
await this.assertCanDeleteAdministrateur(target, currentUser);
|
||||||
|
await this.usersRepository.delete(target.id);
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [target.id],
|
||||||
|
deleted_enfant_ids: [],
|
||||||
|
message: 'Administrateur supprimé.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new BadRequestException('Type d’utilisateur non supprimable via cet endpoint.');
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteEnfant(
|
||||||
|
enfantId: string,
|
||||||
|
deleteDossier: boolean,
|
||||||
|
currentUser: Users,
|
||||||
|
): Promise<SuppressionResult> {
|
||||||
|
this.assertStaffMetier(currentUser);
|
||||||
|
|
||||||
|
const child = await this.childrenRepository.findOne({
|
||||||
|
where: { id: enfantId },
|
||||||
|
relations: ['parentLinks', 'parentLinks.parent'],
|
||||||
|
});
|
||||||
|
if (!child) {
|
||||||
|
throw new NotFoundException('Enfant introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const parentIds = (child.parentLinks ?? [])
|
||||||
|
.map((l) => l.parentId ?? l.parent?.user_id)
|
||||||
|
.filter(Boolean) as string[];
|
||||||
|
|
||||||
|
let numero: string | undefined;
|
||||||
|
if (parentIds.length > 0) {
|
||||||
|
const parents = await this.parentsRepository.find({
|
||||||
|
where: { user_id: In(parentIds) },
|
||||||
|
});
|
||||||
|
numero = parents.map((p) => p.numero_dossier?.trim()).find((n) => !!n);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!numero) {
|
||||||
|
await this.closePlacementsForEnfants([enfantId]);
|
||||||
|
await this.childrenRepository.delete(enfantId);
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [],
|
||||||
|
deleted_enfant_ids: [enfantId],
|
||||||
|
dossier_supprime: false,
|
||||||
|
message: 'Enfant supprimé.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const siblingIds = await this.listEnfantIdsForNumero(numero);
|
||||||
|
const isLast = siblingIds.length <= 1;
|
||||||
|
|
||||||
|
if (isLast && deleteDossier) {
|
||||||
|
const result = await this.deleteFamilleByNumero(numero);
|
||||||
|
return {
|
||||||
|
...result,
|
||||||
|
dossier_supprime: true,
|
||||||
|
message: 'Dernier enfant et dossier famille supprimés.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.closePlacementsForEnfants([enfantId]);
|
||||||
|
await this.childrenRepository.delete(enfantId);
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [],
|
||||||
|
deleted_enfant_ids: [enfantId],
|
||||||
|
dossier_supprime: false,
|
||||||
|
numero_dossier: numero,
|
||||||
|
type: 'famille',
|
||||||
|
message: isLast
|
||||||
|
? 'Dernier enfant supprimé. Le dossier famille reste sans enfant.'
|
||||||
|
: 'Enfant supprimé du dossier famille.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Compte enfants liés à un numero_dossier famille (pour flag sans_enfant). */
|
||||||
|
async countEnfantsForNumero(numeroDossier: string): Promise<number> {
|
||||||
|
const ids = await this.listEnfantIdsForNumero(numeroDossier);
|
||||||
|
return ids.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertCanDeleteAdministrateur(
|
||||||
|
target: Users,
|
||||||
|
currentUser: Users,
|
||||||
|
): Promise<void> {
|
||||||
|
if (
|
||||||
|
currentUser.role !== RoleType.ADMINISTRATEUR &&
|
||||||
|
currentUser.role !== RoleType.SUPER_ADMIN
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Seul un administrateur peut supprimer un administrateur.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const adminCount = await this.usersRepository.count({
|
||||||
|
where: { role: RoleType.ADMINISTRATEUR },
|
||||||
|
});
|
||||||
|
if (adminCount <= 1) {
|
||||||
|
if (currentUser.role !== RoleType.SUPER_ADMIN) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Seul le super administrateur peut supprimer le dernier administrateur.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async deleteParentUser(userId: string): Promise<SuppressionResult> {
|
||||||
|
const parent = await this.parentsRepository.findOne({
|
||||||
|
where: { user_id: userId },
|
||||||
|
relations: ['co_parent'],
|
||||||
|
});
|
||||||
|
if (!parent) {
|
||||||
|
// Compte parent sans fiche — hard delete user
|
||||||
|
await this.usersRepository.delete(userId);
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [userId],
|
||||||
|
deleted_enfant_ids: [],
|
||||||
|
message: 'Parent supprimé.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const numero = parent.numero_dossier?.trim();
|
||||||
|
const foyerIds = numero
|
||||||
|
? await this.listParentUserIdsForNumero(numero)
|
||||||
|
: [userId];
|
||||||
|
|
||||||
|
const isLast = foyerIds.filter((id) => id !== userId).length === 0;
|
||||||
|
|
||||||
|
if (!isLast) {
|
||||||
|
// Co-parent : retirer liens enfants de ce parent, clear co_parent refs, delete user
|
||||||
|
await this.dataSource.transaction(async (manager) => {
|
||||||
|
await manager.delete(ParentsChildren, { parentId: userId });
|
||||||
|
await manager.query(
|
||||||
|
`UPDATE parents SET id_co_parent = NULL WHERE id_co_parent = $1 OR id_utilisateur = $1`,
|
||||||
|
[userId],
|
||||||
|
);
|
||||||
|
await manager.delete(Users, { id: userId });
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [userId],
|
||||||
|
deleted_enfant_ids: [],
|
||||||
|
numero_dossier: numero,
|
||||||
|
type: 'famille',
|
||||||
|
message: 'Parent retiré du dossier (co-parent).',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dernier parent : + enfants
|
||||||
|
const enfantIds = numero
|
||||||
|
? await this.listEnfantIdsForNumero(numero)
|
||||||
|
: await this.listEnfantIdsForParent(userId);
|
||||||
|
await this.closePlacementsForEnfants(enfantIds);
|
||||||
|
await this.dataSource.transaction(async (manager) => {
|
||||||
|
if (enfantIds.length) {
|
||||||
|
await manager.delete(Children, { id: In(enfantIds) });
|
||||||
|
}
|
||||||
|
await manager.query(
|
||||||
|
`UPDATE parents SET id_co_parent = NULL WHERE id_utilisateur = $1 OR id_co_parent = $1`,
|
||||||
|
[userId],
|
||||||
|
);
|
||||||
|
await manager.delete(Users, { id: userId });
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
deleted_user_ids: [userId],
|
||||||
|
deleted_enfant_ids: enfantIds,
|
||||||
|
numero_dossier: numero,
|
||||||
|
type: 'famille',
|
||||||
|
message: 'Dernier parent et enfants rattachés supprimés.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async deleteFamilleByNumero(numero: string): Promise<SuppressionResult> {
|
||||||
|
const parentIds = await this.listParentUserIdsForNumero(numero);
|
||||||
|
if (parentIds.length === 0) {
|
||||||
|
throw new NotFoundException('Aucun parent pour ce dossier.');
|
||||||
|
}
|
||||||
|
const enfantIds = await this.listEnfantIdsForNumero(numero);
|
||||||
|
await this.closePlacementsForEnfants(enfantIds);
|
||||||
|
|
||||||
|
await this.dataSource.transaction(async (manager) => {
|
||||||
|
if (enfantIds.length) {
|
||||||
|
await manager.delete(Children, { id: In(enfantIds) });
|
||||||
|
}
|
||||||
|
await manager.query(
|
||||||
|
`UPDATE parents SET id_co_parent = NULL WHERE id_utilisateur = ANY($1::uuid[]) OR id_co_parent = ANY($1::uuid[])`,
|
||||||
|
[parentIds],
|
||||||
|
);
|
||||||
|
await manager.delete(Users, { id: In(parentIds) });
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'famille',
|
||||||
|
numero_dossier: numero,
|
||||||
|
deleted_user_ids: parentIds,
|
||||||
|
deleted_enfant_ids: enfantIds,
|
||||||
|
message: 'Dossier famille supprimé.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async deleteAmUser(userId: string): Promise<SuppressionResult> {
|
||||||
|
const am = await this.amRepository.findOne({ where: { user_id: userId } });
|
||||||
|
const numero = am?.numero_dossier?.trim();
|
||||||
|
|
||||||
|
const active = await this.amChildrenRepository.find({
|
||||||
|
where: { amId: userId, date_fin: IsNull() },
|
||||||
|
relations: ['child'],
|
||||||
|
});
|
||||||
|
const now = new Date();
|
||||||
|
for (const link of active) {
|
||||||
|
link.date_fin = now;
|
||||||
|
await this.amChildrenRepository.save(link);
|
||||||
|
if (link.child) {
|
||||||
|
await this.applySansGarde(link.child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.usersRepository.delete(userId);
|
||||||
|
return {
|
||||||
|
type: 'assistante_maternelle',
|
||||||
|
numero_dossier: numero,
|
||||||
|
deleted_user_ids: [userId],
|
||||||
|
deleted_enfant_ids: [],
|
||||||
|
message: 'Dossier assistante maternelle supprimé.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async applySansGarde(child: Children): Promise<void> {
|
||||||
|
if (
|
||||||
|
child.status === StatutEnfantType.A_NAITRE ||
|
||||||
|
child.status === StatutEnfantType.SCOLARISE
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const remaining = await this.amChildrenRepository.count({
|
||||||
|
where: { enfantId: child.id, date_fin: IsNull() },
|
||||||
|
});
|
||||||
|
if (remaining === 0) {
|
||||||
|
child.status = StatutEnfantType.SANS_GARDE;
|
||||||
|
await this.childrenRepository.save(child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async closePlacementsForEnfants(enfantIds: string[]): Promise<void> {
|
||||||
|
if (!enfantIds.length) return;
|
||||||
|
const links = await this.amChildrenRepository.find({
|
||||||
|
where: { enfantId: In(enfantIds), date_fin: IsNull() },
|
||||||
|
relations: ['child'],
|
||||||
|
});
|
||||||
|
const now = new Date();
|
||||||
|
for (const link of links) {
|
||||||
|
link.date_fin = now;
|
||||||
|
await this.amChildrenRepository.save(link);
|
||||||
|
if (link.child) {
|
||||||
|
await this.applySansGarde(link.child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async listParentUserIdsForNumero(numero: string): Promise<string[]> {
|
||||||
|
const rows: Array<{ id: string }> = await this.parentsRepository.query(
|
||||||
|
`
|
||||||
|
SELECT DISTINCT x.id::text AS id FROM (
|
||||||
|
SELECT id_utilisateur AS id FROM parents WHERE TRIM(numero_dossier) = $1
|
||||||
|
UNION
|
||||||
|
SELECT id_co_parent AS id FROM parents
|
||||||
|
WHERE TRIM(numero_dossier) = $1 AND id_co_parent IS NOT NULL
|
||||||
|
UNION
|
||||||
|
SELECT p2.id_utilisateur AS id FROM parents p1
|
||||||
|
JOIN parents p2 ON p2.id_utilisateur = p1.id_co_parent
|
||||||
|
WHERE TRIM(p1.numero_dossier) = $1
|
||||||
|
) x WHERE x.id IS NOT NULL
|
||||||
|
`,
|
||||||
|
[numero],
|
||||||
|
);
|
||||||
|
return rows.map((r) => r.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async listEnfantIdsForNumero(numero: string): Promise<string[]> {
|
||||||
|
const parentIds = await this.listParentUserIdsForNumero(numero);
|
||||||
|
if (!parentIds.length) return [];
|
||||||
|
return this.listEnfantIdsForParents(parentIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async listEnfantIdsForParent(parentId: string): Promise<string[]> {
|
||||||
|
return this.listEnfantIdsForParents([parentId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async listEnfantIdsForParents(parentIds: string[]): Promise<string[]> {
|
||||||
|
const links = await this.parentsChildrenRepository.find({
|
||||||
|
where: { parentId: In(parentIds) },
|
||||||
|
});
|
||||||
|
return [...new Set(links.map((l) => l.enfantId))];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { Users } from 'src/entities/users.entity';
|
||||||
|
import { Parents } from 'src/entities/parents.entity';
|
||||||
|
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||||
|
import { Children } from 'src/entities/children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { SuppressionService } from './suppression.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
TypeOrmModule.forFeature([
|
||||||
|
Users,
|
||||||
|
Parents,
|
||||||
|
AssistanteMaternelle,
|
||||||
|
Children,
|
||||||
|
ParentsChildren,
|
||||||
|
AmChildren,
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
providers: [SuppressionService],
|
||||||
|
exports: [SuppressionService],
|
||||||
|
})
|
||||||
|
export class SuppressionsModule {}
|
||||||
@@ -1,20 +1,21 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import 'reflect-metadata';
|
||||||
import { GestionnairesController } from './gestionnaires.controller';
|
import { GestionnairesController } from './gestionnaires.controller';
|
||||||
import { GestionnairesService } from './gestionnaires.service';
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
describe('GestionnairesController', () => {
|
describe('GestionnairesController roles (#161)', () => {
|
||||||
let controller: GestionnairesController;
|
it('POST /gestionnaires autorise SUPER_ADMIN et ADMINISTRATEUR', () => {
|
||||||
|
const roles = Reflect.getMetadata('roles', GestionnairesController.prototype.create);
|
||||||
beforeEach(async () => {
|
expect(roles).toEqual(
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
expect.arrayContaining([RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR]),
|
||||||
controllers: [GestionnairesController],
|
);
|
||||||
providers: [GestionnairesService],
|
expect(roles).not.toContain(RoleType.GESTIONNAIRE);
|
||||||
}).compile();
|
|
||||||
|
|
||||||
controller = module.get<GestionnairesController>(GestionnairesController);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('PATCH /gestionnaires/:id autorise SUPER_ADMIN et ADMINISTRATEUR', () => {
|
||||||
expect(controller).toBeDefined();
|
const roles = Reflect.getMetadata('roles', GestionnairesController.prototype.update);
|
||||||
|
expect(roles).toEqual(
|
||||||
|
expect.arrayContaining([RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR]),
|
||||||
|
);
|
||||||
|
expect(roles).not.toContain(RoleType.GESTIONNAIRE);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -25,10 +25,10 @@ import { AuthGuard } from 'src/common/guards/auth.guard';
|
|||||||
export class GestionnairesController {
|
export class GestionnairesController {
|
||||||
constructor(private readonly gestionnairesService: GestionnairesService) { }
|
constructor(private readonly gestionnairesService: GestionnairesService) { }
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||||
@ApiResponse({ status: 201, description: 'Le gestionnaire a été créé avec succès.', type: Users })
|
@ApiResponse({ status: 201, description: 'Le gestionnaire a été créé avec succès.', type: Users })
|
||||||
@ApiResponse({ status: 409, description: 'Conflit. L\'email est déjà utilisé.' })
|
@ApiResponse({ status: 409, description: 'Conflit. L\'email est déjà utilisé.' })
|
||||||
@ApiOperation({ summary: 'Création d\'un gestionnaire' })
|
@ApiOperation({ summary: 'Création d\'un gestionnaire (admin / super admin)' })
|
||||||
@ApiBody({ type: CreateGestionnaireDto })
|
@ApiBody({ type: CreateGestionnaireDto })
|
||||||
@Post()
|
@Post()
|
||||||
create(@Body() dto: CreateGestionnaireDto): Promise<Users> {
|
create(@Body() dto: CreateGestionnaireDto): Promise<Users> {
|
||||||
@@ -43,7 +43,7 @@ export class GestionnairesController {
|
|||||||
return this.gestionnairesService.findAll();
|
return this.gestionnairesService.findAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.GESTIONNAIRE, RoleType.SUPER_ADMIN)
|
@Roles(RoleType.GESTIONNAIRE, RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||||
@ApiOperation({ summary: 'Récupérer un gestionnaire par ID' })
|
@ApiOperation({ summary: 'Récupérer un gestionnaire par ID' })
|
||||||
@ApiResponse({ status: 400, description: 'ID invalide' })
|
@ApiResponse({ status: 400, description: 'ID invalide' })
|
||||||
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||||
@@ -56,8 +56,8 @@ export class GestionnairesController {
|
|||||||
return this.gestionnairesService.findOne(id);
|
return this.gestionnairesService.findOne(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Roles(RoleType.SUPER_ADMIN)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||||
@ApiOperation({ summary: 'Mettre à jour un gestionnaire' })
|
@ApiOperation({ summary: 'Mettre à jour un gestionnaire (admin / super admin)' })
|
||||||
@ApiResponse({ status: 200, description: 'Le gestionnaire a été mis à jour avec succès.', type: Users })
|
@ApiResponse({ status: 200, description: 'Le gestionnaire a été mis à jour avec succès.', type: Users })
|
||||||
@ApiResponse({ status: 404, description: 'Gestionnaire non trouvé' })
|
@ApiResponse({ status: 404, description: 'Gestionnaire non trouvé' })
|
||||||
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||||
|
|||||||
@@ -1,20 +1,13 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import 'reflect-metadata';
|
||||||
import { UserController } from './user.controller';
|
import { UserController } from './user.controller';
|
||||||
import { UserService } from './user.service';
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
describe('UserController', () => {
|
describe('UserController roles (#161)', () => {
|
||||||
let controller: UserController;
|
it('POST /users/admin autorise SUPER_ADMIN et ADMINISTRATEUR', () => {
|
||||||
|
const roles = Reflect.getMetadata('roles', UserController.prototype.createAdmin);
|
||||||
beforeEach(async () => {
|
expect(roles).toEqual(
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
expect.arrayContaining([RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR]),
|
||||||
controllers: [UserController],
|
);
|
||||||
providers: [UserService],
|
expect(roles).not.toContain(RoleType.GESTIONNAIRE);
|
||||||
}).compile();
|
|
||||||
|
|
||||||
controller = module.get<UserController>(UserController);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should be defined', () => {
|
|
||||||
expect(controller).toBeDefined();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -10,18 +10,22 @@ import { CreateUserDto } from './dto/create_user.dto';
|
|||||||
import { CreateAdminDto } from './dto/create_admin.dto';
|
import { CreateAdminDto } from './dto/create_admin.dto';
|
||||||
import { UpdateUserDto } from './dto/update_user.dto';
|
import { UpdateUserDto } from './dto/update_user.dto';
|
||||||
import { AffecterNumeroDossierDto } from './dto/affecter-numero-dossier.dto';
|
import { AffecterNumeroDossierDto } from './dto/affecter-numero-dossier.dto';
|
||||||
|
import { SuppressionService } from '../suppressions/suppression.service';
|
||||||
|
|
||||||
@ApiTags('Utilisateurs')
|
@ApiTags('Utilisateurs')
|
||||||
@ApiBearerAuth('access-token')
|
@ApiBearerAuth('access-token')
|
||||||
@UseGuards(AuthGuard, RolesGuard)
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
@Controller('users')
|
@Controller('users')
|
||||||
export class UserController {
|
export class UserController {
|
||||||
constructor(private readonly userService: UserService) { }
|
constructor(
|
||||||
|
private readonly userService: UserService,
|
||||||
|
private readonly suppressionService: SuppressionService,
|
||||||
|
) { }
|
||||||
|
|
||||||
// Création d'un administrateur (réservée aux super admins)
|
// Création d'un administrateur (admin + super admin) — #161
|
||||||
@Post('admin')
|
@Post('admin')
|
||||||
@Roles(RoleType.SUPER_ADMIN)
|
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||||
@ApiOperation({ summary: 'Créer un nouvel administrateur (super admin seulement)' })
|
@ApiOperation({ summary: 'Créer un nouvel administrateur (admin / super admin)' })
|
||||||
createAdmin(
|
createAdmin(
|
||||||
@Body() dto: CreateAdminDto,
|
@Body() dto: CreateAdminDto,
|
||||||
@User() currentUser: Users
|
@User() currentUser: Users
|
||||||
@@ -146,12 +150,20 @@ export class UserController {
|
|||||||
return this.userService.suspendUser(id, currentUser, comment);
|
return this.userService.suspendUser(id, currentUser, comment);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Supprimer un utilisateur (super_admin uniquement)
|
// Supprimer un utilisateur — cascades métier #159
|
||||||
@Delete(':id')
|
@Delete(':id')
|
||||||
@Roles(RoleType.SUPER_ADMIN)
|
@Roles(
|
||||||
@ApiOperation({ summary: 'Supprimer un utilisateur' })
|
RoleType.SUPER_ADMIN,
|
||||||
|
RoleType.ADMINISTRATEUR,
|
||||||
|
RoleType.GESTIONNAIRE,
|
||||||
|
)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Supprimer un utilisateur (cascades métier #159)',
|
||||||
|
description:
|
||||||
|
'Parent / AM / staff selon matrice. Gestionnaire ne peut pas supprimer un autre gestionnaire. Self interdit.',
|
||||||
|
})
|
||||||
@ApiParam({ name: 'id', description: "UUID de l'utilisateur" })
|
@ApiParam({ name: 'id', description: "UUID de l'utilisateur" })
|
||||||
remove(@Param('id') id: string, @User() currentUser: Users) {
|
remove(@Param('id') id: string, @User() currentUser: Users) {
|
||||||
return this.userService.remove(id, currentUser);
|
return this.suppressionService.deleteUser(id, currentUser);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { Parents } from 'src/entities/parents.entity';
|
|||||||
import { GestionnairesModule } from './gestionnaires/gestionnaires.module';
|
import { GestionnairesModule } from './gestionnaires/gestionnaires.module';
|
||||||
import { MailModule } from 'src/modules/mail/mail.module';
|
import { MailModule } from 'src/modules/mail/mail.module';
|
||||||
import { AppConfigModule } from 'src/modules/config/config.module';
|
import { AppConfigModule } from 'src/modules/config/config.module';
|
||||||
|
import { SuppressionsModule } from '../suppressions/suppressions.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature(
|
imports: [TypeOrmModule.forFeature(
|
||||||
@@ -26,6 +27,7 @@ import { AppConfigModule } from 'src/modules/config/config.module';
|
|||||||
GestionnairesModule,
|
GestionnairesModule,
|
||||||
MailModule,
|
MailModule,
|
||||||
AppConfigModule,
|
AppConfigModule,
|
||||||
|
SuppressionsModule,
|
||||||
],
|
],
|
||||||
controllers: [UserController],
|
controllers: [UserController],
|
||||||
providers: [UserService],
|
providers: [UserService],
|
||||||
|
|||||||
@@ -1,18 +1,87 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { BadRequestException, ForbiddenException } from '@nestjs/common';
|
||||||
import { UserService } from './user.service';
|
import { UserService } from './user.service';
|
||||||
|
import { RoleType, StatutUtilisateurType } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
describe('UserService.createAdmin (#161)', () => {
|
||||||
|
const usersRepository = {
|
||||||
|
findOneBy: jest.fn(),
|
||||||
|
create: jest.fn(),
|
||||||
|
save: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
describe('UserService', () => {
|
|
||||||
let service: UserService;
|
let service: UserService;
|
||||||
|
|
||||||
beforeEach(async () => {
|
const dto = {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
email: 'nouveau.admin@ptits-pas.fr',
|
||||||
providers: [UserService],
|
password: 'Password1!',
|
||||||
}).compile();
|
prenom: 'Nina',
|
||||||
|
nom: 'Admin',
|
||||||
|
telephone: '0601020304',
|
||||||
|
};
|
||||||
|
|
||||||
service = module.get<UserService>(UserService);
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
service = new UserService(
|
||||||
|
usersRepository as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
{} as never,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('autorise un administrateur à créer un admin', async () => {
|
||||||
expect(service).toBeDefined();
|
usersRepository.findOneBy.mockResolvedValue(null);
|
||||||
|
usersRepository.create.mockImplementation((data) => data);
|
||||||
|
usersRepository.save.mockImplementation(async (entity) => ({
|
||||||
|
id: 'new-admin',
|
||||||
|
...entity,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const result = await service.createAdmin(dto as never, {
|
||||||
|
id: 'admin-1',
|
||||||
|
role: RoleType.ADMINISTRATEUR,
|
||||||
|
} as never);
|
||||||
|
|
||||||
|
expect(result.role).toBe(RoleType.ADMINISTRATEUR);
|
||||||
|
expect(result.statut).toBe(StatutUtilisateurType.ACTIF);
|
||||||
|
expect(usersRepository.save).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('autorise un super_admin à créer un admin', async () => {
|
||||||
|
usersRepository.findOneBy.mockResolvedValue(null);
|
||||||
|
usersRepository.create.mockImplementation((data) => data);
|
||||||
|
usersRepository.save.mockImplementation(async (entity) => ({
|
||||||
|
id: 'new-admin',
|
||||||
|
...entity,
|
||||||
|
}));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.createAdmin(dto as never, {
|
||||||
|
id: 'sa-1',
|
||||||
|
role: RoleType.SUPER_ADMIN,
|
||||||
|
} as never),
|
||||||
|
).resolves.toMatchObject({ role: RoleType.ADMINISTRATEUR });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse un gestionnaire (403 métier)', async () => {
|
||||||
|
await expect(
|
||||||
|
service.createAdmin(dto as never, {
|
||||||
|
id: 'gest-1',
|
||||||
|
role: RoleType.GESTIONNAIRE,
|
||||||
|
} as never),
|
||||||
|
).rejects.toBeInstanceOf(ForbiddenException);
|
||||||
|
expect(usersRepository.save).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse un email déjà utilisé', async () => {
|
||||||
|
usersRepository.findOneBy.mockResolvedValue({ id: 'exists' });
|
||||||
|
await expect(
|
||||||
|
service.createAdmin(dto as never, {
|
||||||
|
id: 'admin-1',
|
||||||
|
role: RoleType.ADMINISTRATEUR,
|
||||||
|
} as never),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -117,8 +117,14 @@ export class UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async createAdmin(dto: CreateAdminDto, currentUser: Users): Promise<Users> {
|
async createAdmin(dto: CreateAdminDto, currentUser: Users): Promise<Users> {
|
||||||
if (currentUser.role !== RoleType.SUPER_ADMIN) {
|
// #161 — admin et super_admin peuvent créer un administrateur
|
||||||
throw new ForbiddenException('Seuls les super administrateurs peuvent créer un administrateur');
|
if (
|
||||||
|
currentUser.role !== RoleType.SUPER_ADMIN &&
|
||||||
|
currentUser.role !== RoleType.ADMINISTRATEUR
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Seuls les administrateurs et super administrateurs peuvent créer un administrateur',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const exist = await this.usersRepository.findOneBy({ email: dto.email });
|
const exist = await this.usersRepository.findOneBy({ email: dto.email });
|
||||||
@@ -520,6 +526,7 @@ export class UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async remove(id: string, currentUser: Users): Promise<void> {
|
async remove(id: string, currentUser: Users): Promise<void> {
|
||||||
|
// Délégué historiquement ; préférer SuppressionService via controller (#159).
|
||||||
if (currentUser.role !== RoleType.SUPER_ADMIN) {
|
if (currentUser.role !== RoleType.SUPER_ADMIN) {
|
||||||
throw new ForbiddenException('Accès réservé aux super admins');
|
throw new ForbiddenException('Accès réservé aux super admins');
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-2
@@ -174,8 +174,7 @@ CREATE TABLE enfants (
|
|||||||
date_prevue_naissance DATE,
|
date_prevue_naissance DATE,
|
||||||
photo_url TEXT,
|
photo_url TEXT,
|
||||||
consentement_photo BOOLEAN DEFAULT false,
|
consentement_photo BOOLEAN DEFAULT false,
|
||||||
date_consentement_photo TIMESTAMPTZ,
|
date_consentement_photo TIMESTAMPTZ
|
||||||
est_multiple BOOLEAN DEFAULT false
|
|
||||||
);
|
);
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
"id","statut","prenom","nom","genre","date_naissance","date_prevue_naissance","photo_url","consentement_photo","date_consentement_photo","est_multiple"
|
"id","statut","prenom","nom","genre","date_naissance","date_prevue_naissance","photo_url","consentement_photo","date_consentement_photo"
|
||||||
"5e8574b7-63e6-4d48-9af3-8d3bf7a6a6cf","sans_garde","Emma","Dupont","F","2020-06-01",,,False,,False
|
"5e8574b7-63e6-4d48-9af3-8d3bf7a6a6cf","sans_garde","Emma","Dupont","F","2020-06-01",,,False,
|
||||||
"a5c3268e-07eb-41a4-9f6c-2f9f16f37c3d","sans_garde",,,,"2020-01-01","2025-01-01",,False,,False
|
"a5c3268e-07eb-41a4-9f6c-2f9f16f37c3d","sans_garde",,,,"2020-01-01","2025-01-01",,False,
|
||||||
"e1a2b3c4-d5e6-4f7a-8b9c-1d2e3f4a5b6c","sans_garde","Emma","Martin",,"2023-02-15",,,False,,False
|
"e1a2b3c4-d5e6-4f7a-8b9c-1d2e3f4a5b6c","sans_garde","Emma","Martin",,"2023-02-15",,,False,
|
||||||
"e2b3c4d5-e6f7-4a8b-9c1d-2e3f4a5b6c7d","sans_garde","Noah","Martin",,"2023-02-15",,,False,,False
|
"e2b3c4d5-e6f7-4a8b-9c1d-2e3f4a5b6c7d","sans_garde","Noah","Martin",,"2023-02-15",,,False,
|
||||||
"e3c4d5e6-f7a8-4b9c-1d2e-3f4a5b6c7d8e","sans_garde","Léa","Martin",,"2023-02-15",,,False,,False
|
"e3c4d5e6-f7a8-4b9c-1d2e-3f4a5b6c7d8e","sans_garde","Léa","Martin",,"2023-02-15",,,False,
|
||||||
"e4d5e6f7-a8b9-4c1d-2e3f-4a5b6c7d8e9f","sans_garde","Chloé","Rousseau",,"2022-04-20",,,False,,False
|
"e4d5e6f7-a8b9-4c1d-2e3f-4a5b6c7d8e9f","sans_garde","Chloé","Rousseau",,"2022-04-20",,,False,
|
||||||
"e5e6f7a8-b9c1-4d2e-3f4a-5b6c7d8e9f1a","sans_garde","Hugo","Rousseau",,"2024-03-10",,,False,,False
|
"e5e6f7a8-b9c1-4d2e-3f4a-5b6c7d8e9f1a","sans_garde","Hugo","Rousseau",,"2024-03-10",,,False,
|
||||||
"e6f7a8b9-c1d2-4e3f-5a6b-7c8d9e0f1a2b","sans_garde","Maxime","Lecomte",,"2023-04-15",,,False,,False
|
"e6f7a8b9-c1d2-4e3f-5a6b-7c8d9e0f1a2b","sans_garde","Maxime","Lecomte",,"2023-04-15",,,False,
|
||||||
"edd19cd1-bb67-4f14-8a37-c66b75c94537","scolarise","Lucas","Durand","H","2018-09-15",,,False,,False
|
"edd19cd1-bb67-4f14-8a37-c66b75c94537","scolarise","Lucas","Durand","H","2018-09-15",,,False,
|
||||||
|
|||||||
|
@@ -0,0 +1,2 @@
|
|||||||
|
-- #152 — Suppression grossesse multiple / est_multiple
|
||||||
|
ALTER TABLE enfants DROP COLUMN IF EXISTS est_multiple;
|
||||||
@@ -69,12 +69,12 @@ ON CONFLICT (id_utilisateur) DO NOTHING;
|
|||||||
-- - child B : à naître (statut = 'a_naitre' et date_prevue_naissance requise)
|
-- - child B : à naître (statut = 'a_naitre' et date_prevue_naissance requise)
|
||||||
-- ------------------------------------------------------------
|
-- ------------------------------------------------------------
|
||||||
|
|
||||||
INSERT INTO enfants (id, prenom, nom, statut, date_naissance, jumeau_multiple)
|
INSERT INTO enfants (id, prenom, nom, statut, date_naissance)
|
||||||
VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Léo', 'Parent', 'sans_garde', '2022-04-12', false)
|
VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Léo', 'Parent', 'sans_garde', '2022-04-12')
|
||||||
ON CONFLICT (id) DO NOTHING;
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
|
||||||
INSERT INTO enfants (id, prenom, nom, statut, date_prevue_naissance, jumeau_multiple)
|
INSERT INTO enfants (id, prenom, nom, statut, date_prevue_naissance)
|
||||||
VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Mila', 'Parent', 'a_naitre', '2026-02-15', false)
|
VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Mila', 'Parent', 'a_naitre', '2026-02-15')
|
||||||
ON CONFLICT (id) DO NOTHING;
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
|
||||||
-- ------------------------------------------------------------
|
-- ------------------------------------------------------------
|
||||||
|
|||||||
@@ -49,14 +49,14 @@ VALUES
|
|||||||
ON CONFLICT (id_utilisateur) DO NOTHING;
|
ON CONFLICT (id_utilisateur) DO NOTHING;
|
||||||
|
|
||||||
-- ========== ENFANTS ==========
|
-- ========== ENFANTS ==========
|
||||||
INSERT INTO enfants (id, prenom, nom, genre, date_naissance, statut, est_multiple)
|
INSERT INTO enfants (id, prenom, nom, genre, date_naissance, statut)
|
||||||
VALUES
|
VALUES
|
||||||
('e0000001-0001-0001-0001-000000000001', 'Emma', 'MARTIN', 'F', '2023-02-15', 'sans_garde', true),
|
('e0000001-0001-0001-0001-000000000001', 'Emma', 'MARTIN', 'F', '2023-02-15', 'sans_garde'),
|
||||||
('e0000002-0002-0002-0002-000000000002', 'Noah', 'MARTIN', 'H', '2023-02-15', 'sans_garde', true),
|
('e0000002-0002-0002-0002-000000000002', 'Noah', 'MARTIN', 'H', '2023-02-15', 'sans_garde'),
|
||||||
('e0000003-0003-0003-0003-000000000003', 'Léa', 'MARTIN', 'F', '2023-02-15', 'sans_garde', true),
|
('e0000003-0003-0003-0003-000000000003', 'Léa', 'MARTIN', 'F', '2023-02-15', 'sans_garde'),
|
||||||
('e0000004-0004-0004-0004-000000000004', 'Chloé', 'ROUSSEAU', 'F', '2022-04-20', 'sans_garde', false),
|
('e0000004-0004-0004-0004-000000000004', 'Chloé', 'ROUSSEAU', 'F', '2022-04-20', 'sans_garde'),
|
||||||
('e0000005-0005-0005-0005-000000000005', 'Hugo', 'ROUSSEAU', 'H', '2024-03-10', 'sans_garde', false),
|
('e0000005-0005-0005-0005-000000000005', 'Hugo', 'ROUSSEAU', 'H', '2024-03-10', 'sans_garde'),
|
||||||
('e0000006-0006-0006-0006-000000000006', 'Maxime', 'LECOMTE', 'H', '2023-04-15', 'sans_garde', false)
|
('e0000006-0006-0006-0006-000000000006', 'Maxime', 'LECOMTE', 'H', '2023-04-15', 'sans_garde')
|
||||||
ON CONFLICT (id) DO NOTHING;
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
|
||||||
-- ========== ENFANTS_PARENTS (liaison N:N) ==========
|
-- ========== ENFANTS_PARENTS (liaison N:N) ==========
|
||||||
|
|||||||
@@ -117,7 +117,6 @@ Table des enfants pris en charge.
|
|||||||
| `photo_url` | TEXT | | URL de la photo |
|
| `photo_url` | TEXT | | URL de la photo |
|
||||||
| `consentement_photo` | BOOLEAN | DEFAULT false | Consentement photo |
|
| `consentement_photo` | BOOLEAN | DEFAULT false | Consentement photo |
|
||||||
| `date_consentement_photo` | TIMESTAMPTZ | | Date du consentement |
|
| `date_consentement_photo` | TIMESTAMPTZ | | Date du consentement |
|
||||||
| `est_multiple` | BOOLEAN | DEFAULT false | Indique si grossesse multiple |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -276,9 +276,6 @@ export class Enfants {
|
|||||||
@Column({ name: 'consentement_photo', type: 'boolean', default: false })
|
@Column({ name: 'consentement_photo', type: 'boolean', default: false })
|
||||||
consentementPhoto: boolean;
|
consentementPhoto: boolean;
|
||||||
|
|
||||||
@Column({ name: 'est_multiple', type: 'boolean', default: false })
|
|
||||||
estMultiple: boolean;
|
|
||||||
|
|
||||||
@Column({
|
@Column({
|
||||||
type: 'enum',
|
type: 'enum',
|
||||||
enum: StatutEnfantType,
|
enum: StatutEnfantType,
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
# Analyse d’empreinte — P'titsPas
|
||||||
|
|
||||||
|
**Date :** 2026-07-22
|
||||||
|
**Contexte :** snapshot pour mémoire (après alerte disque plein + purge cache Gitea)
|
||||||
|
**Périmètre :** application `jmartin/petitspas` déployée sur le VPS (`/home/deploy/dev/ptitspas-app`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Lignes de code
|
||||||
|
|
||||||
|
Comptage brut (`wc -l`), hors `node_modules` / builds / `.dart_tool`.
|
||||||
|
|
||||||
|
| Zone | Lignes | Fichiers |
|
||||||
|
|------|--------|----------|
|
||||||
|
| **Frontend** (Dart `frontend/lib/`) | ~29 800 | 141 |
|
||||||
|
| **Backend** (TypeScript `backend/src/`) | ~10 000 | 141 |
|
||||||
|
| **BDD** (SQL sous `database/`) | ~1 250 | ~15 |
|
||||||
|
| **Total** | **~41 000** | |
|
||||||
|
|
||||||
|
### Frontend (détail)
|
||||||
|
|
||||||
|
| Dossier | Lignes |
|
||||||
|
|---------|--------|
|
||||||
|
| `widgets/` | ~18 400 |
|
||||||
|
| `screens/` | ~5 000 |
|
||||||
|
| `services/` | ~2 300 |
|
||||||
|
| `models/` | ~2 200 |
|
||||||
|
| `utils/` | ~1 400 |
|
||||||
|
| reste | ~500 |
|
||||||
|
|
||||||
|
### Backend (détail)
|
||||||
|
|
||||||
|
| Dossier | Lignes |
|
||||||
|
|---------|--------|
|
||||||
|
| `routes/` | ~6 500 |
|
||||||
|
| `modules/` | ~1 700 |
|
||||||
|
| `entities/` | ~1 000 |
|
||||||
|
| `common/` + `config/` | ~400 |
|
||||||
|
|
||||||
|
### BDD (détail)
|
||||||
|
|
||||||
|
| Élément | Lignes |
|
||||||
|
|---------|--------|
|
||||||
|
| `BDD.sql` (schéma) | ~470 |
|
||||||
|
| seeds | ~300 |
|
||||||
|
| migrations / patches | ~280 |
|
||||||
|
| tests SQL | ~205 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Empreinte disque — runtime (Docker)
|
||||||
|
|
||||||
|
| Composant | Taille | Notes |
|
||||||
|
|-----------|--------|--------|
|
||||||
|
| Image `ptitspas-app-backend` | ~300 Mo | NestJS |
|
||||||
|
| Image `ptitspas-app-frontend` | ~122 Mo | Flutter web + Nginx |
|
||||||
|
| Image `postgres:17` | ~454 Mo | |
|
||||||
|
| Image `dpage/pgadmin4` | ~534 Mo | optionnel |
|
||||||
|
| Volume `postgres_data` | ~49 Mo | données BDD live |
|
||||||
|
| Volume `backend_uploads` | ~20 Mo | photos |
|
||||||
|
| Volume `backend_documents_legaux` | ~0 | |
|
||||||
|
| **Stack complète (avec pgAdmin)** | **~1,5 Go** | |
|
||||||
|
| **Stack prod sans pgAdmin** | **~945 Mo** | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Empreinte disque — code source
|
||||||
|
|
||||||
|
| Élément | Taille |
|
||||||
|
|---------|--------|
|
||||||
|
| Clone `/home/deploy/dev/ptitspas-app` | ~701 Mo |
|
||||||
|
| dont `backend/node_modules` | ~354 Mo |
|
||||||
|
| dont `frontend` (+ `.dart_tool`) | ~114 Mo |
|
||||||
|
| **Code utile** (hors deps / `.git` / builds) | **~51 Mo** |
|
||||||
|
| Repo Gitea `petitspas.git` | ~109 Mo |
|
||||||
|
| Dump `database/BDD.sql` | ~19 Ko |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Pour (re)déployer
|
||||||
|
|
||||||
|
Minimum requis :
|
||||||
|
|
||||||
|
1. Images custom backend + frontend (~422 Mo), ou code + build Docker
|
||||||
|
2. Image `postgres:17` (~454 Mo)
|
||||||
|
3. Volumes persistants (~70 Mo au snapshot)
|
||||||
|
4. Optionnel : pgAdmin (~534 Mo)
|
||||||
|
|
||||||
|
**Ordre de grandeur :** ~1 Go pour faire tourner l’app en prod (sans pgAdmin).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Notes infra du jour (lié)
|
||||||
|
|
||||||
|
- Disque VPS passé de **100 %** à ~**44 %** après :
|
||||||
|
- purge cache Docker / journals
|
||||||
|
- purge officielle Gitea `delete_repo_archives` (~24 Go de zip/bundle `petitspas`)
|
||||||
|
- Crons Gitea activés :
|
||||||
|
- `archive_cleanup` @midnight (`OLDER_THAN = 24h`)
|
||||||
|
- `delete_repo_archives` @weekly
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Fichier généré pour historique projet — ne pas considérer comme métrique CI automatisée.*
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# Mini-spec API — POST /parents/dossier (#129)
|
||||||
|
|
||||||
|
Contrat pour le **plan front** (wizard création dossier famille staff).
|
||||||
|
|
||||||
|
Miroir de **#156** (`POST /assistantes-maternelles/dossier`).
|
||||||
|
|
||||||
|
## Endpoint
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|--|--|
|
||||||
|
| **Méthode** | `POST` |
|
||||||
|
| **URL** | `{base}/parents/dossier` |
|
||||||
|
| **Auth** | Bearer JWT |
|
||||||
|
| **Rôles** | `gestionnaire`, `administrateur`, `super_admin` |
|
||||||
|
| **Content-Type** | `application/json` |
|
||||||
|
|
||||||
|
Ne **pas** appeler `POST /auth/register/parent` depuis le dashboard.
|
||||||
|
|
||||||
|
## Body (JSON)
|
||||||
|
|
||||||
|
Aligné `RegisterParentCompletDto`, **sans** CGU/privacy obligatoires (acceptées serveur).
|
||||||
|
|
||||||
|
### Parent 1 (obligatoire)
|
||||||
|
|
||||||
|
| Champ | Type | Obligatoire | Notes |
|
||||||
|
|-------|------|-------------|--------|
|
||||||
|
| `email` | string | oui | unique |
|
||||||
|
| `prenom` | string | oui | |
|
||||||
|
| `nom` | string | oui | |
|
||||||
|
| `telephone` | string | oui | `0X…` ou `+33…` |
|
||||||
|
| `adresse` | string | non | |
|
||||||
|
| `code_postal` | string | non | |
|
||||||
|
| `ville` | string | non | |
|
||||||
|
|
||||||
|
### Co-parent (optionnel)
|
||||||
|
|
||||||
|
`co_parent_email`, `co_parent_prenom`, `co_parent_nom`, `co_parent_telephone`,
|
||||||
|
`co_parent_meme_adresse`, `co_parent_adresse`, `co_parent_code_postal`, `co_parent_ville`.
|
||||||
|
|
||||||
|
Si co-parent fourni : e-mail distinct ; mêmes règles téléphone / adresse que register.
|
||||||
|
|
||||||
|
### Enfants (≥ 1)
|
||||||
|
|
||||||
|
| Champ | Type | Notes |
|
||||||
|
|-------|------|--------|
|
||||||
|
| `enfants` | `EnfantInscriptionDto[]` | `prenom`, `nom`, `date_naissance` / `date_previsionnelle_naissance`, `genre`, `photo_base64`, `photo_filename`, etc. |
|
||||||
|
|
||||||
|
### Présentation
|
||||||
|
|
||||||
|
| Champ | Type | Obligatoire |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| `presentation_dossier` | string | non (max 2000) |
|
||||||
|
|
||||||
|
## Réponses
|
||||||
|
|
||||||
|
### 201 Created
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"message": "Dossier famille créé et validé. Un e-mail de création de mot de passe a été envoyé.",
|
||||||
|
"numero_dossier": "2026-000043",
|
||||||
|
"parent_user_id": "uuid-pivot",
|
||||||
|
"co_parent_user_id": "uuid-ou-null",
|
||||||
|
"statut": "actif",
|
||||||
|
"enfant_ids": ["uuid", "..."]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Effets serveur : user(s) parent **actif**, fiches `parents`, enfants + foyer, n° dossier,
|
||||||
|
**e-mail création MDP** pour chaque compte sans MDP (pas d’accusé « en attente »).
|
||||||
|
|
||||||
|
### Erreurs
|
||||||
|
|
||||||
|
| Code | Cas |
|
||||||
|
|------|-----|
|
||||||
|
| 400 | Validation DTO / métier (enfants vides, dates, etc.) |
|
||||||
|
| 401 | Token manquant / invalide |
|
||||||
|
| 403 | Rôle non staff |
|
||||||
|
| 409 | Conflit e-mail (pivot et/ou co-parent) |
|
||||||
|
|
||||||
|
## Front
|
||||||
|
|
||||||
|
- `UserService.createParentDossier(body)` → cet endpoint
|
||||||
|
- Wizard create basé sur `ValidationFamilyWizard`
|
||||||
|
- Ne pas envoyer `acceptation_cgu` / `acceptation_privacy` (optionnels)
|
||||||
|
|
||||||
|
## Branche
|
||||||
|
|
||||||
|
`feature/129-creation-dossier-parent`
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# Mini-spec API — POST /parents/:id/co-parent (#135)
|
||||||
|
|
||||||
|
Contrat back pour l’ajout d’un **2ᵉ parent** sur un foyer mono-parent (staff).
|
||||||
|
|
||||||
|
## Endpoint
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|--|--|
|
||||||
|
| **Méthode** | `POST` |
|
||||||
|
| **URL** | `{base}/api/v1/parents/{parentUserId}/co-parent` |
|
||||||
|
| **Auth** | Bearer JWT |
|
||||||
|
| **Rôles** | `gestionnaire`, `administrateur`, `super_admin` |
|
||||||
|
| **Succès** | **201** |
|
||||||
|
|
||||||
|
`parentUserId` = UUID du **parent pivot** (déjà dans le dossier).
|
||||||
|
|
||||||
|
Ne **pas** appeler `POST /auth/register/parent` ni `POST /parents/dossier`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Body (JSON)
|
||||||
|
|
||||||
|
| Champ | Type | Obligatoire | Notes |
|
||||||
|
|-------|------|-------------|--------|
|
||||||
|
| `email` | string | oui | unique |
|
||||||
|
| `prenom` | string | oui | |
|
||||||
|
| `nom` | string | oui | |
|
||||||
|
| `telephone` | string | oui | `0X…` ou `+33…` |
|
||||||
|
| `meme_adresse` | bool | non | défaut **true** → copie adresse du pivot |
|
||||||
|
| `adresse` | string | si `meme_adresse=false` | |
|
||||||
|
| `code_postal` | string | si `meme_adresse=false` | |
|
||||||
|
| `ville` | string | si `meme_adresse=false` | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Comportement 201
|
||||||
|
|
||||||
|
- User co-parent **actif** + token création MDP
|
||||||
|
- Fiche `parents` + liens pivot ↔ co-parent + même `numero_dossier`
|
||||||
|
- Enfants du foyer rattachés au co-parent
|
||||||
|
- E-mail **création MDP** (pas mail « en attente »)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"message": "Co-parent ajouté au foyer. Un e-mail de création de mot de passe a été envoyé.",
|
||||||
|
"numero_dossier": "2026-000043",
|
||||||
|
"parent_user_id": "uuid-pivot",
|
||||||
|
"co_parent_user_id": "uuid-co",
|
||||||
|
"statut": "actif"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Erreurs
|
||||||
|
|
||||||
|
| Code | Cas |
|
||||||
|
|------|-----|
|
||||||
|
| 400 | Déjà un co-parent / 2 responsables / validation adresse |
|
||||||
|
| 401 | Token invalide |
|
||||||
|
| 403 | Rôle non staff |
|
||||||
|
| 404 | Pivot introuvable |
|
||||||
|
| 409 | Email déjà pris |
|
||||||
|
|
||||||
|
## Réemploi édition identité
|
||||||
|
|
||||||
|
| Endpoint | Usage |
|
||||||
|
|----------|--------|
|
||||||
|
| `GET /dossiers/:numero` | Préremplir wizard edit |
|
||||||
|
| `PATCH /parents/:id/fiche` | Sauver identité pivot / co-parent existant |
|
||||||
|
| `PATCH /assistantes-maternelles/:id/fiche` | Édition AM |
|
||||||
|
|
||||||
|
## Branche
|
||||||
|
|
||||||
|
`feature/135-edition-dossier`
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# Mini-spec front — Mode édition dossier + ajout 2ᵉ parent (#135)
|
||||||
|
|
||||||
|
Branche : `feature/135-edition-dossier`
|
||||||
|
Ticket : **#135** (full-stack)
|
||||||
|
|
||||||
|
Prérequis : **#153** (liste Dossiers) livré.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Objectif
|
||||||
|
|
||||||
|
1. Clic sur un dossier (liste #153) → ouvrir le wizard en mode **`edit`**
|
||||||
|
2. Foyer **mono-parent** : page co-parent → **switch** ajouter un 2ᵉ parent
|
||||||
|
3. Sauvegarder les champs via APIs existantes + nouvel endpoint co-parent
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Modes wizard
|
||||||
|
|
||||||
|
| Mode | Famille | AM |
|
||||||
|
|------|---------|-----|
|
||||||
|
| `review` | déjà | déjà |
|
||||||
|
| `create` | déjà (#129) | déjà (#156) |
|
||||||
|
| **`edit`** | **à faire** | **à faire** |
|
||||||
|
|
||||||
|
Factories : `ParentDossierWizard.edit(...)` / `AmDossierWizard.edit(...)`
|
||||||
|
Préremplir via `UserService.getDossierByNumero(numero)`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## APIs
|
||||||
|
|
||||||
|
| Action | Endpoint |
|
||||||
|
|--------|----------|
|
||||||
|
| Charger | `GET /dossiers/:numero` |
|
||||||
|
| Sauver parent | `PATCH /parents/:id/fiche` |
|
||||||
|
| Sauver AM | `PATCH /assistantes-maternelles/:id/fiche` |
|
||||||
|
| **Ajouter co-parent** | **`POST /parents/:pivotUserId/co-parent`** — voir `docs/tmp/135-contrat-api-ajout-co-parent.md` |
|
||||||
|
|
||||||
|
Body co-parent :
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"email": "thomas@…",
|
||||||
|
"prenom": "Thomas",
|
||||||
|
"nom": "MARTIN",
|
||||||
|
"telephone": "0678456789",
|
||||||
|
"meme_adresse": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`UserService.addCoParent(pivotUserId, body)` → cet endpoint.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## UX
|
||||||
|
|
||||||
|
- Depuis `DossiersManagementWidget` / carte liste : clic → edit (plus seulement review pending)
|
||||||
|
- Pending : garder validation (review) ; dossiers actifs → edit
|
||||||
|
- Mono-parent : switch « Ajouter un co-parent » (comme create) → au save, `POST …/co-parent` si nouveau
|
||||||
|
- Déjà 2 parents : éditer les deux fiches ; pas de 3ᵉ
|
||||||
|
- Pas de bouton créer dans l’onglet Dossiers
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hors scope
|
||||||
|
|
||||||
|
- Famille N responsables (#139)
|
||||||
|
- Suppressions (#154)
|
||||||
|
- Création dossier initial (#129 / #156)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Critères d’acceptation
|
||||||
|
|
||||||
|
- [ ] Clic dossier actif → wizard edit prérempli
|
||||||
|
- [ ] PATCH fiche enregistre les modifs
|
||||||
|
- [ ] Mono-parent + switch → co-parent créé (actif + mail MDP)
|
||||||
|
- [ ] review / create inchangés
|
||||||
|
|
||||||
|
## Branche
|
||||||
|
|
||||||
|
`feature/135-edition-dossier`
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# Mini-spec — Suppression complète grossesse multiple / `est_multiple`
|
||||||
|
|
||||||
|
**Ticket** : **#152** — https://git.ptits-pas.fr/jmartin/petitspas/issues/152
|
||||||
|
**Branche** : `feature/152-remove-est-multiple` (depuis `develop`)
|
||||||
|
**Périmètre** : **full stack** — BDD + back + front + scripts + docs. **Aucun fantôme.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Décision
|
||||||
|
|
||||||
|
On **supprime tout**. Pas de DTO « ignorés », pas de compat payload.
|
||||||
|
|
||||||
|
`forbidNonWhitelisted: true` ⇒ back et front **partent ensemble** (même feature / même déploiement).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Alias retirés
|
||||||
|
|
||||||
|
`est_multiple` · `is_multiple` · `grossesse_multiple` · `multipleBirth` · `estMultiple` · `isMultiple` · `jumeau_multiple`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Back / BDD (fait sur la branche)
|
||||||
|
|
||||||
|
- [x] Migration `database/migrations/2026_drop_enfants_est_multiple.sql`
|
||||||
|
- [x] `BDD.sql`, seeds, CSV test
|
||||||
|
- [x] Entity `Children` sans colonne
|
||||||
|
- [x] DTO create/inscription/réponse/dossier famille **sans** le champ
|
||||||
|
- [x] Services auth / enfants / parents : plus de mapping
|
||||||
|
- [x] Prisma legacy `isMultiple` retiré
|
||||||
|
|
||||||
|
## Front (fait sur la branche)
|
||||||
|
|
||||||
|
- [x] Modèles admin / dossier / inscription
|
||||||
|
- [x] Payloads inscription + reprise
|
||||||
|
- [x] Modale enfant + wizard dossier famille
|
||||||
|
- [x] Step3 inscription parent
|
||||||
|
|
||||||
|
## Scripts / docs
|
||||||
|
|
||||||
|
- [x] `tests/scripts/register-parent-*.mjs`
|
||||||
|
- [x] `docs/10_DATABASE.md`, `docs/99_REGLES-CODAGE.md`
|
||||||
|
- Docs tmp/archive #112 : mentions historiques OK (archive)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Déploiement
|
||||||
|
|
||||||
|
1. Appliquer la migration SQL sur la BDD vivante
|
||||||
|
2. Deploy back **et** front de cette branche
|
||||||
|
3. Smoke : création enfant staff, inscription parent, reprise, wizard famille
|
||||||
|
|
||||||
|
## Vérif
|
||||||
|
|
||||||
|
```bash
|
||||||
|
rg -n 'est_multiple|is_multiple|grossesse_multiple|multipleBirth|estMultiple|isMultiple|jumeau_multiple' \
|
||||||
|
backend/src frontend/lib database tests/scripts docs/10_DATABASE.md docs/99_REGLES-CODAGE.md
|
||||||
|
```
|
||||||
|
→ **0** hit (hors ce fichier mini-spec / archives).
|
||||||
|
|
||||||
|
## Hors scope
|
||||||
|
|
||||||
|
- Métier futur « fratrie / jumeaux » → nouveau ticket
|
||||||
|
- #155 rename Admin*
|
||||||
|
- Ticket modales staff
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# Mini-spec API — GET /dossiers (#153)
|
||||||
|
|
||||||
|
Contrat pour le **plan front** (onglet permanent Dossiers).
|
||||||
|
|
||||||
|
## Endpoint
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|--|--|
|
||||||
|
| **Méthode** | `GET` |
|
||||||
|
| **URL** | `{base}/api/v1/dossiers` |
|
||||||
|
| **Auth** | Bearer JWT |
|
||||||
|
| **Rôles** | `gestionnaire`, `administrateur`, `super_admin` |
|
||||||
|
| **Query** | `q` (optionnel) — recherche n° / libellé / email |
|
||||||
|
|
||||||
|
Complète `GET /dossiers/:numeroDossier` (#119) déjà existant.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Réponse 200
|
||||||
|
|
||||||
|
Tableau de lignes (1 entrée = 1 `numero_dossier`) :
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"type": "famille",
|
||||||
|
"numero_dossier": "2026-000043",
|
||||||
|
"libelle": "Claire MARTIN & Thomas MARTIN",
|
||||||
|
"emails": ["claire@test.fr", "thomas@test.fr"],
|
||||||
|
"user_ids": ["uuid-pivot", "uuid-co"],
|
||||||
|
"statut": "actif",
|
||||||
|
"a_valider": false,
|
||||||
|
"date_reference": "2026-01-12T10:00:00.000Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "assistante_maternelle",
|
||||||
|
"numero_dossier": "2026-000042",
|
||||||
|
"libelle": "Marie DUPONT",
|
||||||
|
"emails": ["marie@test.fr"],
|
||||||
|
"user_ids": ["uuid-am"],
|
||||||
|
"statut": "en_attente",
|
||||||
|
"a_valider": true,
|
||||||
|
"date_reference": "2026-02-01T08:00:00.000Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Champs
|
||||||
|
|
||||||
|
| Champ | Notes |
|
||||||
|
|-------|--------|
|
||||||
|
| `type` | `famille` \| `assistante_maternelle` |
|
||||||
|
| `numero_dossier` | Clé d’unité |
|
||||||
|
| `libelle` | Noms formatés (foyer : `A & B`) |
|
||||||
|
| `emails` / `user_ids` | Membres du foyer ou AM |
|
||||||
|
| `statut` | Agrégé : `en_attente` si au moins un user pending |
|
||||||
|
| `a_valider` | `true` si pending → section haute UI |
|
||||||
|
| `date_reference` | `MIN(cree_le)` des users |
|
||||||
|
|
||||||
|
**Tri** : `a_valider` d’abord, puis `numero_dossier` décroissant.
|
||||||
|
|
||||||
|
**Famille** : dédupliquée par `numero_dossier` (pivot + co-parent = 1 ligne).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Front
|
||||||
|
|
||||||
|
- `UserService.getDossiers({ q? })` → cet endpoint
|
||||||
|
- Section haute : filtrer `a_valider == true` **ou** continuer pending APIs existantes
|
||||||
|
- Section basse : liste complète (ou hors pending selon règle UX)
|
||||||
|
- Clic → `GET /dossiers/:numero` (détail) / validation review
|
||||||
|
|
||||||
|
Composition client `getParents`+`getAM` **plus nécessaire** si cet endpoint est déployé.
|
||||||
|
|
||||||
|
## Branche
|
||||||
|
|
||||||
|
`feature/153-onglet-dossiers`
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
# Mini-spec front — Onglet permanent « Dossiers » (#153)
|
||||||
|
|
||||||
|
Branche Git (front + back) : `feature/153-onglet-dossiers`
|
||||||
|
Ticket Gitea : **#153** (ticket normal, plus epic)
|
||||||
|
|
||||||
|
> Suite prévue : **#135** = au clic, mode **édition** wizard + ajout 2ᵉ parent.
|
||||||
|
> **#153** = onglet + listes + navigation / validation pending. **Pas** de création, **pas** d’édition complète.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contexte / objectif
|
||||||
|
|
||||||
|
Remplacer l’onglet conditionnel **« À valider »** (apparaît/disparaît selon pending) par un onglet **permanent « Dossiers »** dans le dashboard admin/gestionnaire.
|
||||||
|
|
||||||
|
Quand on ouvre **Dossiers** :
|
||||||
|
|
||||||
|
1. **En haut** — section **Dossiers à valider** (AM + familles pending)
|
||||||
|
2. **En dessous** — liste de **tous les dossiers** (familles **et** AM), 1 ligne = 1 `numero_dossier`
|
||||||
|
3. Différenciation visuelle famille vs AM : **couleur + icône**
|
||||||
|
4. **Barre de recherche** (n° dossier, nom, email…)
|
||||||
|
|
||||||
|
**Pas** de bouton « Créer un dossier » ici (création via **+ Parents** #129 / **+ Asmat** #156).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## UX cible
|
||||||
|
|
||||||
|
### Onglets dashboard (`UserManagementPanel`)
|
||||||
|
|
||||||
|
| Avant (#107) | Après (#153) |
|
||||||
|
|--------------|--------------|
|
||||||
|
| « À valider » **conditionnel** si pending | **« Dossiers » toujours visible** (admin + gestionnaire) |
|
||||||
|
| Contenu = seulement pending | Pending **en haut** + liste complète **en bas** |
|
||||||
|
|
||||||
|
Ordre suggéré des onglets :
|
||||||
|
|
||||||
|
`Dossiers` | `Parents` | `Enfants` | `Assistantes maternelles` | `Gestionnaires` | (`Administrateurs`)
|
||||||
|
|
||||||
|
### Section haute — À valider
|
||||||
|
|
||||||
|
- Réutiliser / adapter `PendingValidationWidget` (ou extraire la liste dans un sous-widget).
|
||||||
|
- Sources déjà branchées :
|
||||||
|
- `UserService.getPendingUsers(role: 'assistante_maternelle')`
|
||||||
|
- `UserService.getPendingFamilies()`
|
||||||
|
- Clic ligne pending → **`ValidationDossierModal`** / wizards `.review` (inchangé).
|
||||||
|
- Si section vide : ne pas afficher de gros vide ; masquer la section ou message court « Aucun dossier en attente ».
|
||||||
|
|
||||||
|
### Section basse — Tous les dossiers
|
||||||
|
|
||||||
|
1 ligne = **1 dossier** (`numero_dossier`), type :
|
||||||
|
|
||||||
|
| Type | Libellé UI | Couleur (suggestion) |
|
||||||
|
|------|------------|----------------------|
|
||||||
|
| `famille` | Famille / Parents | teinte existante parents (ex. violet / rose dashboard) |
|
||||||
|
| `assistante_maternelle` | AM | teinte existante AM (ex. teal / bleu) |
|
||||||
|
|
||||||
|
Colonnes / infos utiles (cartes style `AdminUserCard` ou lignes type pending) :
|
||||||
|
|
||||||
|
- n° dossier
|
||||||
|
- type (pastille couleur + icône)
|
||||||
|
- libellé (noms parents ou AM)
|
||||||
|
- email(s) principal(aux)
|
||||||
|
- statut user / dossier si dispo (`actif`, `en_attente`, …)
|
||||||
|
- date utile si dispo
|
||||||
|
|
||||||
|
**Déduplication** : un foyer (pivot + co-parent) = **une** ligne famille (même `numero_dossier`). Idem AM.
|
||||||
|
|
||||||
|
### Recherche
|
||||||
|
|
||||||
|
- La search bar du panel (aujourd’hui désactivée / hint « pas de recherche » sur À valider) doit **filtrer la liste unifiée** (et idéalement aussi le pending affiché).
|
||||||
|
- Critères **minimum** : `numero_dossier`, nom, prénom, email.
|
||||||
|
- Harmoniser le hint : `Rechercher un dossier (n°, nom, email)…`
|
||||||
|
|
||||||
|
### État vide liste complète
|
||||||
|
|
||||||
|
Aide optionnelle : *« Pour créer un dossier → onglet Parents (+ Parents) ou Assistantes maternelles (+ Asmat) »*.
|
||||||
|
|
||||||
|
### Clic sur un dossier de la liste complète (#153)
|
||||||
|
|
||||||
|
| Cas | Comportement #153 |
|
||||||
|
|-----|-------------------|
|
||||||
|
| Pending | Ouvrir validation (review) — déjà en place |
|
||||||
|
| Dossier **actif** / non pending | Ouvrir consultation via `GET /dossiers/:numeroDossier` (`UserService.getDossierByNumero`) en **lecture / review** si possible **sans** save édition |
|
||||||
|
|
||||||
|
**Ne pas** implémenter le mode `edit` ni le switch 2ᵉ parent → **#135**.
|
||||||
|
|
||||||
|
Si l’ouverture « review » d’un dossier actif est trop lourde pour ce ticket : clic peut temporairement no-op / snackbar *« Édition dossier : prochainement (#135) »* — **à éviter** si `getDossierByNumero` + wizard review marche déjà pour les deux types.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Données / APIs (front)
|
||||||
|
|
||||||
|
### Déjà disponibles (préférer composer côté front pour #153)
|
||||||
|
|
||||||
|
| Besoin | API / service |
|
||||||
|
|--------|----------------|
|
||||||
|
| Pending AM | `getPendingUsers(role: assistante_maternelle)` |
|
||||||
|
| Pending familles | `getPendingFamilies()` |
|
||||||
|
| Parents (avec `numero_dossier`) | `getParents()` |
|
||||||
|
| AM (avec `numero_dossier`) | `getAssistantesMaternelles()` |
|
||||||
|
| Détail unifié | `getDossierByNumero(numero)` → `GET /dossiers/:numeroDossier` |
|
||||||
|
|
||||||
|
**Pas d’endpoint `GET /dossiers` liste** aujourd’hui. Pour #153 :
|
||||||
|
|
||||||
|
- Construire la liste unifiée **côté client** à partir de `getParents()` + `getAssistantesMaternelles()` (group by `numero_dossier`).
|
||||||
|
- Exclure ou marquer les pending déjà dans la section haute (éviter doublons visuels, ou les laisser dans les deux avec badge « à valider » — **préférence** : pending **uniquement** en haut ; liste basse = tous **hors** pending **ou** tous avec badge ; choisir une règle claire et documenter dans le PR).
|
||||||
|
|
||||||
|
**Règle recommandée** :
|
||||||
|
- Haut = pending only
|
||||||
|
- Bas = **tous** les dossiers ayant un `numero_dossier` (y compris pending) **OU** bas = non-pending only
|
||||||
|
→ **Recommandation produit** : bas = **tous** (vision complète), pending aussi en haut pour action rapide. Si doublon gênant : bas = non-pending only.
|
||||||
|
|
||||||
|
### Si le back ajoute plus tard `GET /dossiers`
|
||||||
|
|
||||||
|
Brancher `UserService.getDossiers()` — hors scope bloquant #153 front si composition client OK.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fichiers front probables
|
||||||
|
|
||||||
|
| Fichier | Rôle |
|
||||||
|
|---------|------|
|
||||||
|
| `frontend/lib/widgets/admin/user_management_panel.dart` | Onglet permanent **Dossiers** ; retirer logique conditionnelle À valider ; search sur cet onglet |
|
||||||
|
| `frontend/lib/widgets/admin/pending_validation_widget.dart` | Réemploi section haute (ou refactor léger) |
|
||||||
|
| **Nouveau** `…/dossiers_management_widget.dart` (nom libre) | Shell onglet : pending + liste unifiée + refresh |
|
||||||
|
| **Nouveau** modèle léger `DossierListItem` (type, numero, libelle, emails, statut…) | Mapping parents/AM → ligne |
|
||||||
|
| `user_service.dart` / `api_config.dart` | Seulement si helper `getDossiersUnified()` côté client (pas forcément nouvel endpoint) |
|
||||||
|
| `validation_dossier_modal.dart` | Réemploi ouverture pending / détail |
|
||||||
|
|
||||||
|
Réutiliser look & feel cartes / hover « Ouvrir » de `_PendingValidationRow` / `AdminUserCard`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hors scope (#153)
|
||||||
|
|
||||||
|
- Bouton créer dossier
|
||||||
|
- Mode `edit` wizard + ajout 2ᵉ parent → **#135**
|
||||||
|
- Suppressions → **#154**
|
||||||
|
- Famille N responsables → **#139**
|
||||||
|
- Changer les onglets Parents / AM / Enfants (restent)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Critères d’acceptation front
|
||||||
|
|
||||||
|
- [ ] Onglet **Dossiers** toujours visible (même 0 pending)
|
||||||
|
- [ ] Plus d’onglet conditionnel **« À valider »**
|
||||||
|
- [ ] Section haute pending si non vide ; validation au clic OK
|
||||||
|
- [ ] Liste unifiée familles + AM en dessous ; 1 ligne / `numero_dossier`
|
||||||
|
- [ ] Couleur + icône différencient famille / AM
|
||||||
|
- [ ] Recherche filtre (n° + nom + email minimum)
|
||||||
|
- [ ] **Aucun** bouton créer dans cet onglet
|
||||||
|
- [ ] Pas de régression validation pending (valider / refuser)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Back (info — Cursor back séparé si besoin)
|
||||||
|
|
||||||
|
- Liste unifiée : **pas bloquante** si composition front
|
||||||
|
- Optionnel : `GET /api/v1/dossiers` (liste) pour perf / pagination plus tard
|
||||||
|
- `GET /dossiers/:numero` déjà là (#119)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Branche
|
||||||
|
|
||||||
|
`feature/153-onglet-dossiers` (depuis `develop`)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Matrice suppression — #154 / back **#159** / front **#160**
|
||||||
|
|
||||||
|
**Statut** : cadrage PO validé (sept. 2026)
|
||||||
|
**Milestone** : 0.1.0
|
||||||
|
**Email** : pas d’email de suppression (cas rare)
|
||||||
|
|
||||||
|
## Droits
|
||||||
|
|
||||||
|
| Cible | Qui peut supprimer |
|
||||||
|
|-------|-------------------|
|
||||||
|
| Dossier / parent / enfant / AM | `GESTIONNAIRE`, `ADMINISTRATEUR`, `SUPER_ADMIN` |
|
||||||
|
| Gestionnaire (user) | `ADMINISTRATEUR`, `SUPER_ADMIN` |
|
||||||
|
| Administrateur (user) | Autre admin OK ; **self interdit** ; **dernier admin** = `SUPER_ADMIN` only ; `SUPER_ADMIN` non supprimable |
|
||||||
|
|
||||||
|
## Matrice métier
|
||||||
|
|
||||||
|
| Point d’entrée | Action | Effet |
|
||||||
|
|----------------|--------|--------|
|
||||||
|
| Dossiers | Delete dossier **famille** | Tous **parents** + tous **enfants** ; clore placements AM des enfants |
|
||||||
|
| Dossiers / AM | Delete dossier **AM** ou compte AM | **Compte AM + dossier AM** ; enfants **conservés** ; placements **clos** |
|
||||||
|
| Parents | Co-parent (autre parent reste) | Compte parent seul ; dossier + enfants restent |
|
||||||
|
| Parents | Dernier parent | Parent + **enfants** rattachés |
|
||||||
|
| Enfants | Pas dernier | Enfant seul (retiré du dossier) |
|
||||||
|
| Enfants | Dernier + `deleteDossier=true` | Cascade dossier famille (parents + enfants) |
|
||||||
|
| Enfants | Dernier + `deleteDossier=false` | Enfant seul ; dossier peut apparaître **`sans_enfant`** |
|
||||||
|
| Pending / validé | — | **Mêmes règles** (pas de différenciation) |
|
||||||
|
|
||||||
|
## Warning
|
||||||
|
|
||||||
|
- `sans_enfant` sur liste `GET /dossiers` (dossier famille sans enfant lié).
|
||||||
|
- Miroir de `sans_responsable` (#157) côté enfants.
|
||||||
|
|
||||||
|
## Hors scope
|
||||||
|
|
||||||
|
Soft-delete RGPD, audit (#128), famille N (#139), restriction admin-only métier (plus tard).
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
# Mini-spec front — Suppressions dashboard
|
||||||
|
|
||||||
|
**Ticket front** : **#160** — https://git.ptits-pas.fr/jmartin/petitspas/issues/160
|
||||||
|
**Ticket back** : **#159** — https://git.ptits-pas.fr/jmartin/petitspas/issues/159
|
||||||
|
**Epic** : #154 (complète #133)
|
||||||
|
**Branche back** : `feature/159-suppressions-backend`
|
||||||
|
**Doc matrice** : [154-matrice-suppression.md](./154-matrice-suppression.md)
|
||||||
|
|
||||||
|
Travail **en parallèle** : ce contrat est la source de vérité UI ↔ API.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## UX commune
|
||||||
|
|
||||||
|
Sur chaque ligne / carte des listes :
|
||||||
|
|
||||||
|
- Icône **poubelle** en bout de ligne
|
||||||
|
- Clic → **dialog de confirmation** (texte d’impact) → DELETE → **refresh** liste
|
||||||
|
- Pending = **mêmes** règles que validés
|
||||||
|
- **Pas** d’email
|
||||||
|
|
||||||
|
| Liste | Poubelle visible si |
|
||||||
|
|-------|---------------------|
|
||||||
|
| Dossiers, Parents, Enfants, AM | gestionnaire **ou** admin |
|
||||||
|
| Gestionnaires | **admin** only |
|
||||||
|
| Administrateurs | admin+ ; **pas** sur sa propre ligne ; dernier admin : UI warning + réservé super_admin |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contrat API
|
||||||
|
|
||||||
|
Base : auth Bearer. Erreurs : `400` / `403` / `404` / `409` avec `message` FR.
|
||||||
|
|
||||||
|
### 1. `DELETE /dossiers/:numeroDossier`
|
||||||
|
|
||||||
|
- **Famille** → supprime tous parents + enfants du n° ; clos placements AM des enfants.
|
||||||
|
- **AM** → compte AM + dossier AM ; enfants gardés ; placements clos.
|
||||||
|
|
||||||
|
**Réponse 200** (exemple) :
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "famille",
|
||||||
|
"numero_dossier": "2026-000043",
|
||||||
|
"deleted_user_ids": ["…"],
|
||||||
|
"deleted_enfant_ids": ["…"],
|
||||||
|
"message": "Dossier famille supprimé."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
ou
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "assistante_maternelle",
|
||||||
|
"numero_dossier": "2026-000015",
|
||||||
|
"deleted_user_ids": ["…"],
|
||||||
|
"deleted_enfant_ids": [],
|
||||||
|
"message": "Dossier assistante maternelle supprimé."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Dialog UI** : lister libellé + n° + « X parent(s), Y enfant(s) » (ou « compte AM, enfants conservés »).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2. `DELETE /users/:id`
|
||||||
|
|
||||||
|
Comportement selon le **rôle** de la cible :
|
||||||
|
|
||||||
|
| Cible | Effet |
|
||||||
|
|-------|--------|
|
||||||
|
| Parent **co-parent** | Delete ce user seul |
|
||||||
|
| Parent **dernier** du dossier | Delete user + enfants du foyer |
|
||||||
|
| AM | Delete user AM + dossier AM ; enfants conservés ; placements clos |
|
||||||
|
| Gestionnaire | Admin only ; self → 403 |
|
||||||
|
| Administrateur | Self → 403 ; dernier admin → super_admin only sinon 403 ; super_admin → 403 |
|
||||||
|
|
||||||
|
**Réponse 200** :
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"deleted_user_ids": ["…"],
|
||||||
|
"deleted_enfant_ids": ["…"],
|
||||||
|
"message": "…"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Dialogs** :
|
||||||
|
|
||||||
|
- Co-parent : « Ce parent sera retiré / supprimé du dossier {n°}. Les enfants restent avec le co-parent. »
|
||||||
|
- Dernier parent : « Dernier parent du dossier {n°}. Les enfants rattachés seront aussi supprimés. »
|
||||||
|
- AM : « Le compte et le dossier AM seront supprimés. Les enfants accueillis ne seront pas supprimés. »
|
||||||
|
|
||||||
|
Optionnel (si exposé) : `GET /users/:id/suppression-impact` — sinon calculer depuis données déjà en liste / détail dossier.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3. `DELETE /enfants/:id?deleteDossier=true|false`
|
||||||
|
|
||||||
|
- Pas dernier enfant → delete enfant (`deleteDossier` ignoré ou false).
|
||||||
|
- Dernier enfant + `deleteDossier=false` → delete enfant ; dossier famille peut passer `sans_enfant`.
|
||||||
|
- Dernier enfant + `deleteDossier=true` → cascade dossier famille (parents + enfants).
|
||||||
|
|
||||||
|
**Réponse 200** :
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"deleted_enfant_ids": ["…"],
|
||||||
|
"deleted_user_ids": ["…"],
|
||||||
|
"dossier_supprime": false,
|
||||||
|
"message": "…"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Dialog** :
|
||||||
|
|
||||||
|
- Standard : « L’enfant sera supprimé du dossier de {famille} ({n°}). »
|
||||||
|
- Dernier : proposer **deux actions** :
|
||||||
|
1. Supprimer l’enfant seulement (`deleteDossier=false`)
|
||||||
|
2. Supprimer aussi le dossier / parents (`deleteDossier=true`)
|
||||||
|
|
||||||
|
Pour savoir si dernier : compter enfants du `numero_dossier` (détail dossier ou champ impact API).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4. `GET /dossiers` — flag `sans_enfant`
|
||||||
|
|
||||||
|
Chaque item famille peut exposer :
|
||||||
|
|
||||||
|
```json
|
||||||
|
"sans_enfant": true
|
||||||
|
```
|
||||||
|
|
||||||
|
- `true` si dossier **famille** sans enfant lié.
|
||||||
|
- AM : `false` ou omis.
|
||||||
|
|
||||||
|
**UI** : badge / warning vigilance (comme `sans_responsable` / alertes AM).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## UserService (Flutter) — signatures cibles
|
||||||
|
|
||||||
|
```dart
|
||||||
|
Future<void> deleteDossier(String numeroDossier);
|
||||||
|
Future<Map<String, dynamic>> deleteUser(String userId);
|
||||||
|
Future<Map<String, dynamic>> deleteEnfant(String enfantId, {bool deleteDossier = false});
|
||||||
|
```
|
||||||
|
|
||||||
|
(Adapter le parsing au JSON réel une fois le back mergé ; en parallèle, stubber sur ce contrat.)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fichiers front probables
|
||||||
|
|
||||||
|
- Cartes listes : `admin_user_card.dart`, `admin_enfant_user_card.dart`, cartes dossiers
|
||||||
|
- Listes : `dossiers_management_widget.dart`, `parent_managmant_widget.dart`, `enfant_management_widget.dart`, `assistante_maternelle_management_widget.dart`, `gestionnaire_management_widget.dart`, `admin_management_widget.dart`
|
||||||
|
- `user_service.dart`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Critères front (#160)
|
||||||
|
|
||||||
|
- [ ] Poubelle selon droits
|
||||||
|
- [ ] Confirmations avec impact
|
||||||
|
- [ ] Refresh après succès
|
||||||
|
- [ ] Dernier enfant : choix dossier oui/non
|
||||||
|
- [ ] Warning `sans_enfant`
|
||||||
|
- [ ] Self-admin / dernier admin gérés côté UI (masquer ou message 403)
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# Mini-spec — Rename préfixe `Admin*` dashboard partagé (#155)
|
||||||
|
|
||||||
|
**Ticket** : **#155**
|
||||||
|
**Branche** : `feature/155-rename-admin-prefix-dashboard` (depuis `develop`)
|
||||||
|
**Décision naming** : **option C** — dossier neutre `widgets/dashboard/` + noms **sans** préfixe `Admin`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Principe
|
||||||
|
|
||||||
|
Les widgets partagés **admin + gestionnaire** ne doivent plus s’appeler `Admin*`.
|
||||||
|
On garde `Admin*` seulement là où c’est vraiment le rôle administrateur.
|
||||||
|
|
||||||
|
## Gardé `Admin*` (hors rename)
|
||||||
|
|
||||||
|
| Élément | Raison |
|
||||||
|
|---------|--------|
|
||||||
|
| `AdminManagementWidget` | Onglet **Administrateurs** |
|
||||||
|
| `screens/administrateurs/*` | `AdminDashboardScreen`, `AdminCreateDialog`, `AdminUserFormDialog` |
|
||||||
|
| `EnfantAdminModel` | Modèle API (pas un widget) — hors scope ticket |
|
||||||
|
|
||||||
|
## Renames faits
|
||||||
|
|
||||||
|
| Avant | Après |
|
||||||
|
|-------|--------|
|
||||||
|
| `widgets/admin/common/admin_child_detail_modal.dart` → `AdminChildDetailModal` | `widgets/dashboard/child_detail_modal.dart` → `ChildDetailModal` |
|
||||||
|
| `admin_am_edit_modal` → `AdminAmEditModal` | `am_edit_modal` → `AmEditModal` |
|
||||||
|
| `admin_parent_edit_modal` → `AdminParentEditModal` | `parent_edit_modal` → `ParentEditModal` |
|
||||||
|
| `admin_user_card` → `AdminUserCard` | `user_card` → `UserCard` |
|
||||||
|
| `admin_enfant_user_card` → `AdminEnfantUserCard` | `enfant_user_card` → `EnfantUserCard` |
|
||||||
|
| `admin_am_photo_frame` → `AdminAmPhotoFrame` | `am_photo_frame` → `AmPhotoFrame` |
|
||||||
|
| `admin_am_children_capacity_grid` | `am_children_capacity_grid` → `AmChildrenCapacityGrid` |
|
||||||
|
| `admin_children_affiliation_panel` | `children_affiliation_panel` → `ChildrenAffiliationPanel` |
|
||||||
|
| `admin_select_*` / `AdminSelect*` / `AdminFamilleFoyer` | `select_*` / `Select*` / `FamilleFoyer` |
|
||||||
|
| `admin_status_capsule` | `status_capsule` → `StatusCapsule` |
|
||||||
|
| `admin_list_state` → `AdminListState` | `user_list_state` → `UserListState` |
|
||||||
|
| `admin_detail_modal` → `AdminDetailModal` / `AdminDetailField` | `detail_modal` → `DetailModal` / `DetailField` |
|
||||||
|
| `dashboard_admin.dart` | `user_management_sub_bar.dart` (`DashboardUserManagementSubBar` inchangé) |
|
||||||
|
|
||||||
|
Dossier `widgets/admin/` conserve encore les panels métier (`user_management_panel`, wizards, etc.) + `AdminManagementWidget`.
|
||||||
|
|
||||||
|
**Phase 2** (même ticket #155) : déplacer ces panels → `widgets/dashboard/` — voir [155-suite-move-admin-panels-to-dashboard.md](./155-suite-move-admin-panels-to-dashboard.md).
|
||||||
|
|
||||||
|
## Hors scope
|
||||||
|
|
||||||
|
- Refonte UX modales (ticket dédié)
|
||||||
|
- Rename API / back
|
||||||
|
- Déplacer tout `widgets/admin/` → `widgets/dashboard/` (panels) — possible follow-up
|
||||||
|
|
||||||
|
## Critères
|
||||||
|
|
||||||
|
- [x] Plus de préfixe `Admin` sur les composants **partagés** listés
|
||||||
|
- [ ] Build Flutter / recette dashboard admin + gestionnaire OK
|
||||||
|
- [x] Pas de changement comportemental (rename mécanique)
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
# Mini-spec — Déplacer les panels `widgets/admin/` → `widgets/dashboard/`
|
||||||
|
|
||||||
|
**Ticket** : **#155** (phase 2 — même ticket que le rename `Admin*`)
|
||||||
|
**Phase 1** : widgets `Admin*` → `widgets/dashboard/` (déjà sur `feature/155-rename-admin-prefix-dashboard`)
|
||||||
|
**Branche** : poursuivre / rebaser `feature/155-rename-admin-prefix-dashboard` (ou nouvelle branche depuis `develop` après merge phase 1)
|
||||||
|
**Nature** : rename / move mécanique — **zéro** changement UX / métier
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contexte
|
||||||
|
|
||||||
|
Après la phase 1 (#155), la situation est **hybride** :
|
||||||
|
|
||||||
|
| Emplacement | Contenu |
|
||||||
|
|-------------|---------|
|
||||||
|
| `widgets/dashboard/` | Composants partagés sans préfixe `Admin*` (modales, cartes, selects, sub-bar…) |
|
||||||
|
| `widgets/admin/` | **Panels** du dashboard staff (listes, wizards, validation, shell `UserManagementPanel`…) + `AdminManagementWidget` |
|
||||||
|
|
||||||
|
Le dossier `admin/` laisse encore croire « réservé administrateur », alors que **gestionnaire** consomme les mêmes panels (`GestionnaireDashboardScreen` → `UserManagementPanel`).
|
||||||
|
|
||||||
|
Ce ticket **termine l’option C** au niveau dossier : tout le dashboard staff vit sous `widgets/dashboard/`, sauf ce qui est **vraiment** rôle admin.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Objectif
|
||||||
|
|
||||||
|
```
|
||||||
|
frontend/lib/widgets/admin/<panels & common partagés>
|
||||||
|
↓ git mv + update imports
|
||||||
|
frontend/lib/widgets/dashboard/…
|
||||||
|
```
|
||||||
|
|
||||||
|
Critère : un nouveau dev ne doit plus ouvrir `widgets/admin/` pour du code partagé admin+gestionnaire.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cible d’arborescence (proposée)
|
||||||
|
|
||||||
|
```
|
||||||
|
widgets/dashboard/
|
||||||
|
├── (déjà là #155) child_detail_modal.dart, am_edit_modal.dart, user_card.dart, …
|
||||||
|
├── user_management_panel.dart ← shell onglets
|
||||||
|
├── user_management_sub_bar.dart ← déjà déplacé #155
|
||||||
|
├── dossiers_management_widget.dart
|
||||||
|
├── dossier_list_card.dart
|
||||||
|
├── parent_management_widget.dart ← corriger le typo managmant au passage ?
|
||||||
|
├── enfant_management_widget.dart
|
||||||
|
├── assistante_maternelle_management_widget.dart
|
||||||
|
├── gestionnaire_management_widget.dart
|
||||||
|
├── pending_validation_widget.dart
|
||||||
|
├── parent_dossier_create_modal.dart
|
||||||
|
├── parent_dossier_wizard.dart
|
||||||
|
├── am_dossier_create_modal.dart
|
||||||
|
├── am_dossier_wizard.dart
|
||||||
|
├── validation_*.dart ← family/am wizards, refus, theme, confirm
|
||||||
|
├── parametres_panel.dart ← utilisé par écran admin (OK dans dashboard)
|
||||||
|
├── relais_management_panel.dart
|
||||||
|
├── common/ ← sous-dossier optionnel
|
||||||
|
│ ├── suppression_confirm_dialog.dart
|
||||||
|
│ ├── user_list.dart
|
||||||
|
│ └── validation_detail_section.dart
|
||||||
|
└── …
|
||||||
|
|
||||||
|
widgets/admin/ ← mince, rôle admin seulement
|
||||||
|
└── admin_management_widget.dart ← onglet Administrateurs
|
||||||
|
```
|
||||||
|
|
||||||
|
### Variante B (plus stricte)
|
||||||
|
|
||||||
|
`AdminManagementWidget` + éventuels helpers purement admin →
|
||||||
|
`screens/administrateurs/widgets/`
|
||||||
|
et **suppression** du dossier `widgets/admin/`.
|
||||||
|
|
||||||
|
**Reco** : **variante A** (garder `widgets/admin/` minimal avec seulement `AdminManagementWidget`) — moins de churn screens, clair.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Inventaire à déplacer (état actuel)
|
||||||
|
|
||||||
|
### Racine `widgets/admin/` → `widgets/dashboard/`
|
||||||
|
|
||||||
|
| Fichier actuel | Notes |
|
||||||
|
|----------------|--------|
|
||||||
|
| `user_management_panel.dart` | Shell partagé admin + gestionnaire |
|
||||||
|
| `dossiers_management_widget.dart` | |
|
||||||
|
| `dossier_list_card.dart` | |
|
||||||
|
| `parent_managmant_widget.dart` | Typo historique `managmant` — **option** : renommer → `parent_management_widget.dart` dans le même ticket ou ticket typo séparé |
|
||||||
|
| `enfant_management_widget.dart` | |
|
||||||
|
| `assistante_maternelle_management_widget.dart` | |
|
||||||
|
| `gestionnaire_management_widget.dart` | |
|
||||||
|
| `pending_validation_widget.dart` | |
|
||||||
|
| `parent_dossier_create_modal.dart` | |
|
||||||
|
| `parent_dossier_wizard.dart` | |
|
||||||
|
| `am_dossier_create_modal.dart` | |
|
||||||
|
| `am_dossier_wizard.dart` | |
|
||||||
|
| `validation_am_wizard.dart` | |
|
||||||
|
| `validation_family_wizard.dart` | |
|
||||||
|
| `validation_dossier_modal.dart` | |
|
||||||
|
| `validation_modal_theme.dart` | |
|
||||||
|
| `validation_refus_form.dart` | |
|
||||||
|
| `validation_valider_confirm_dialog.dart` | |
|
||||||
|
| `parametres_panel.dart` | Écran admin seulement, mais pas préfixé Admin — OK dashboard |
|
||||||
|
| `relais_management_panel.dart` | |
|
||||||
|
|
||||||
|
### `widgets/admin/common/` → `widgets/dashboard/common/` (ou plat)
|
||||||
|
|
||||||
|
| Fichier | Notes |
|
||||||
|
|---------|--------|
|
||||||
|
| `suppression_confirm_dialog.dart` | Partagé (y compris `screens/administrateurs/creation/*`) |
|
||||||
|
| `user_list.dart` | |
|
||||||
|
| `validation_detail_section.dart` | |
|
||||||
|
|
||||||
|
### **Ne pas** déplacer
|
||||||
|
|
||||||
|
| Fichier | Destination |
|
||||||
|
|---------|-------------|
|
||||||
|
| `admin_management_widget.dart` | Reste `widgets/admin/` (ou variante B → screens) |
|
||||||
|
|
||||||
|
### Déjà fait (#155) — ne pas retraiter
|
||||||
|
|
||||||
|
Tout ce qui est déjà sous `widgets/dashboard/` (`child_detail_modal`, `am_edit_modal`, `user_card`, `select_*`, `user_management_sub_bar`, …).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Consommateurs d’imports (à mettre à jour)
|
||||||
|
|
||||||
|
### Screens
|
||||||
|
- `screens/administrateurs/admin_dashboardScreen.dart` — `UserManagementPanel`, `ParametresPanel`
|
||||||
|
- `screens/gestionnaire/gestionnaire_dashboard_screen.dart` — `UserManagementPanel`
|
||||||
|
- `screens/administrateurs/creation/admin_create.dart` — `suppression_confirm_dialog`
|
||||||
|
- `screens/administrateurs/creation/gestionnaires_create.dart` — idem
|
||||||
|
|
||||||
|
### Widgets déjà en `dashboard/`
|
||||||
|
- `am_edit_modal`, `child_detail_modal`, `parent_edit_modal`, `select_*` — imports vers `widgets/admin/common/*` ou panels
|
||||||
|
|
||||||
|
### Divers
|
||||||
|
- `widgets/common/identity_block.dart` (si import admin)
|
||||||
|
- Tous les fichiers **déplacés** entre eux (imports relatifs / package)
|
||||||
|
|
||||||
|
### Hors scope rename classes
|
||||||
|
Sauf décision explicite sur le typo `parent_managmant_widget` → pas de rename de **classes** métier dans ce ticket (seulement chemins de fichiers + imports).
|
||||||
|
`AdminManagementWidget` **conserve** son nom.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Plan d’exécution
|
||||||
|
|
||||||
|
1. Partir de `feature/155-rename-admin-prefix-dashboard` (phase 1) **ou** `develop` si phase 1 déjà mergée
|
||||||
|
2. `git mv` fichiers selon inventaire
|
||||||
|
3. Remplacer globalement
|
||||||
|
`package:p_tits_pas/widgets/admin/` → `package:p_tits_pas/widgets/dashboard/`
|
||||||
|
**sauf** `…/widgets/admin/admin_management_widget.dart`
|
||||||
|
4. Corriger imports relatifs cassés
|
||||||
|
5. Grep de contrôle (ci-dessous)
|
||||||
|
6. Build Flutter web (Docker) + smoke dashboard admin **et** gestionnaire
|
||||||
|
7. Merge → squash master si flux habituel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Vérifs
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Plus de panels partagés sous admin (seul AdminManagement attendu)
|
||||||
|
find frontend/lib/widgets/admin -name '*.dart'
|
||||||
|
|
||||||
|
# Plus d’imports panels vers l’ancien chemin (sauf AdminManagement)
|
||||||
|
rg -n "widgets/admin/(user_management|dossiers_|parent_|enfant_|assistante|gestionnaire|pending|validation_|parametres|relais|am_dossier|parent_dossier|dossier_list|common/)" frontend/lib
|
||||||
|
|
||||||
|
# Screens OK
|
||||||
|
rg -n "widgets/admin/" frontend/lib/screens
|
||||||
|
```
|
||||||
|
|
||||||
|
Attendu screens : **0** hit vers panels ; éventuellement plus aucun hit `widgets/admin/` sauf si import explicite `AdminManagementWidget` depuis `user_management_panel` (chemin `widgets/admin/admin_management_widget.dart`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hors scope
|
||||||
|
|
||||||
|
- Refonte UX des modales / panels (ticket dédié annoncé)
|
||||||
|
- Rename `EnfantAdminModel`
|
||||||
|
- Rename `screens/administrateurs/`
|
||||||
|
- Rename `AdminUserFormDialog` / `AdminCreateDialog`
|
||||||
|
- Changement API / back
|
||||||
|
- #152 (`est_multiple`) — autre branche
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Critères d’acceptation
|
||||||
|
|
||||||
|
- [ ] Inventaire déplacé selon tableau
|
||||||
|
- [ ] `widgets/admin/` ne contient plus que `admin_management_widget.dart` (variante A)
|
||||||
|
- [ ] Imports screens + widgets à jour
|
||||||
|
- [ ] Build Flutter OK
|
||||||
|
- [ ] Recette : dashboard **administrateur** et **gestionnaire** (listes, ouverture fiches, validation, création dossier) sans régression
|
||||||
|
- [ ] Aucun changement comportemental volontaire
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Risques / notes
|
||||||
|
|
||||||
|
- **Conflits de merge** si d’autres features touchent les panels → faire ce ticket quand la surface dashboard est calme (fin 0.1.0 OK)
|
||||||
|
- Typo `parent_managmant_widget` : soit inclus (bonus), soit ticket cleanup 1-ligne séparé
|
||||||
|
- Docs d’archive citant `widgets/admin/…` : pas obligatoire de mettre à jour ; `docs/27_BRIEFING-FRONTEND.md` oui si encore listé
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# Mini-spec API — POST /assistantes-maternelles/dossier (#156)
|
||||||
|
|
||||||
|
Contrat pour le **plan front** (wizard création AM staff).
|
||||||
|
|
||||||
|
## Endpoint
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|--|--|
|
||||||
|
| **Méthode** | `POST` |
|
||||||
|
| **URL** | `{base}/assistantes-maternelles/dossier` |
|
||||||
|
| **Auth** | Bearer JWT |
|
||||||
|
| **Rôles** | `gestionnaire`, `administrateur`, `super_admin` |
|
||||||
|
| **Content-Type** | `application/json` |
|
||||||
|
|
||||||
|
Ne **pas** appeler `POST /auth/register/am` depuis le dashboard.
|
||||||
|
|
||||||
|
## Body (JSON)
|
||||||
|
|
||||||
|
Aligné inscription AM publique, **sans** CGU/privacy obligatoires (acceptées serveur).
|
||||||
|
|
||||||
|
| Champ | Type | Obligatoire | Notes |
|
||||||
|
|-------|------|-------------|--------|
|
||||||
|
| `email` | string | oui | unique |
|
||||||
|
| `prenom` | string | oui | |
|
||||||
|
| `nom` | string | oui | |
|
||||||
|
| `telephone` | string | oui | `0X…` ou `+33…` |
|
||||||
|
| `adresse` | string | non | |
|
||||||
|
| `code_postal` | string | non | |
|
||||||
|
| `ville` | string | non | |
|
||||||
|
| `photo_base64` | string | non | data-URL `data:image/…;base64,…` |
|
||||||
|
| `photo_filename` | string | non | hint nom fichier |
|
||||||
|
| `consentement_photo` | bool | oui | |
|
||||||
|
| `date_naissance` | date ISO | non | `YYYY-MM-DD` |
|
||||||
|
| `lieu_naissance_ville` | string | oui | |
|
||||||
|
| `lieu_naissance_pays` | string | oui | |
|
||||||
|
| `nir` | string | oui | 15 car. (Corse 2A/2B OK) |
|
||||||
|
| `numero_agrement` | string | oui | unique |
|
||||||
|
| `date_agrement` | date ISO | non | |
|
||||||
|
| `capacite_accueil` | int | oui | 1–10 |
|
||||||
|
| `places_disponibles` | int | oui | 0–10, ≤ capacité |
|
||||||
|
| `biographie` | string | non | max 2000 |
|
||||||
|
|
||||||
|
## Réponses
|
||||||
|
|
||||||
|
### 201 Created
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"message": "Dossier AM créé et validé. Un e-mail de création de mot de passe a été envoyé.",
|
||||||
|
"user_id": "uuid",
|
||||||
|
"statut": "actif",
|
||||||
|
"numero_dossier": "2026-000042"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Effets serveur : user AM **actif**, fiche `assistantes_maternelles`, n° dossier, **e-mail création MDP** (pas d’accusé « en attente »).
|
||||||
|
|
||||||
|
### Erreurs
|
||||||
|
|
||||||
|
| Code | Cas |
|
||||||
|
|------|-----|
|
||||||
|
| 400 | Validation / NIR / places > capacité |
|
||||||
|
| 403 | Rôle non staff |
|
||||||
|
| 409 | Email, NIR ou agrément déjà pris |
|
||||||
|
| 401 | Token manquant / invalide |
|
||||||
|
|
||||||
|
## Front
|
||||||
|
|
||||||
|
- `UserService.createAmDossier(body)` → cet endpoint
|
||||||
|
- Après 201 : refresh liste AM ; snackbar OK
|
||||||
|
- Wizard create : ne pas envoyer `acceptation_cgu` / `acceptation_privacy` (optionnels)
|
||||||
|
|
||||||
|
## Branche
|
||||||
|
|
||||||
|
`feature/156-creation-dossier-am`
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
import 'package:p_tits_pas/models/assistante_maternelle_model.dart';
|
||||||
|
import 'package:p_tits_pas/models/parent_model.dart';
|
||||||
|
import 'package:p_tits_pas/utils/name_format_utils.dart';
|
||||||
|
|
||||||
|
/// Ligne de liste unifiée dossiers (famille ou AM) — ticket #153.
|
||||||
|
enum DossierListType { famille, assistanteMaternelle }
|
||||||
|
|
||||||
|
class DossierListItem {
|
||||||
|
final DossierListType type;
|
||||||
|
final String numeroDossier;
|
||||||
|
final String libelle;
|
||||||
|
final List<String> emails;
|
||||||
|
final String? statut;
|
||||||
|
/// Photo profil (AM) — affichée à la place de l’icône si présente.
|
||||||
|
final String? photoUrl;
|
||||||
|
/// Dossier famille sans enfant lié (#159 / #160).
|
||||||
|
final bool sansEnfant;
|
||||||
|
/// Nombre d’enfants du foyer (famille uniquement ; null pour AM).
|
||||||
|
final int? enfantsCount;
|
||||||
|
|
||||||
|
const DossierListItem({
|
||||||
|
required this.type,
|
||||||
|
required this.numeroDossier,
|
||||||
|
required this.libelle,
|
||||||
|
this.emails = const [],
|
||||||
|
this.statut,
|
||||||
|
this.photoUrl,
|
||||||
|
this.sansEnfant = false,
|
||||||
|
this.enfantsCount,
|
||||||
|
});
|
||||||
|
|
||||||
|
DossierListItem copyWith({
|
||||||
|
DossierListType? type,
|
||||||
|
String? numeroDossier,
|
||||||
|
String? libelle,
|
||||||
|
List<String>? emails,
|
||||||
|
String? statut,
|
||||||
|
String? photoUrl,
|
||||||
|
bool? sansEnfant,
|
||||||
|
int? enfantsCount,
|
||||||
|
}) {
|
||||||
|
return DossierListItem(
|
||||||
|
type: type ?? this.type,
|
||||||
|
numeroDossier: numeroDossier ?? this.numeroDossier,
|
||||||
|
libelle: libelle ?? this.libelle,
|
||||||
|
emails: emails ?? this.emails,
|
||||||
|
statut: statut ?? this.statut,
|
||||||
|
photoUrl: photoUrl ?? this.photoUrl,
|
||||||
|
sansEnfant: sansEnfant ?? this.sansEnfant,
|
||||||
|
enfantsCount: enfantsCount ?? this.enfantsCount,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get isFamille => type == DossierListType.famille;
|
||||||
|
bool get isAm => type == DossierListType.assistanteMaternelle;
|
||||||
|
|
||||||
|
String get typeLabel => isFamille ? 'Famille' : 'AM';
|
||||||
|
|
||||||
|
/// Sous-titre carte : `NOM Prénom` ou `NOM Prénom - NOM Prénom`.
|
||||||
|
String get namesLine => libelle;
|
||||||
|
|
||||||
|
String get emailsLine => emails.where((e) => e.trim().isNotEmpty).join(' · ');
|
||||||
|
|
||||||
|
/// Titre carte : numéro de dossier seul.
|
||||||
|
String get titleLine => numeroDossier;
|
||||||
|
|
||||||
|
bool matchesQuery(String query) {
|
||||||
|
final q = query.trim().toLowerCase();
|
||||||
|
if (q.isEmpty) return true;
|
||||||
|
if (numeroDossier.toLowerCase().contains(q)) return true;
|
||||||
|
if (libelle.toLowerCase().contains(q)) return true;
|
||||||
|
for (final e in emails) {
|
||||||
|
if (e.toLowerCase().contains(q)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Une ligne par `numero_dossier` (foyer dédupliqué).
|
||||||
|
static List<DossierListItem> fromParents(List<ParentModel> parents) {
|
||||||
|
final byDossier = <String, List<ParentModel>>{};
|
||||||
|
for (final p in parents) {
|
||||||
|
final num = (p.user.numeroDossier ?? '').trim();
|
||||||
|
if (num.isEmpty) continue;
|
||||||
|
byDossier.putIfAbsent(num, () => []).add(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
final items = <DossierListItem>[];
|
||||||
|
for (final entry in byDossier.entries) {
|
||||||
|
final seenIds = <String>{};
|
||||||
|
final names = <String>[];
|
||||||
|
final emails = <String>[];
|
||||||
|
final statuts = <String>[];
|
||||||
|
|
||||||
|
void consider(
|
||||||
|
String? id,
|
||||||
|
String? nom,
|
||||||
|
String? prenom,
|
||||||
|
String? email,
|
||||||
|
String? statut,
|
||||||
|
) {
|
||||||
|
final uid = (id ?? '').trim();
|
||||||
|
if (uid.isEmpty || !seenIds.add(uid)) return;
|
||||||
|
final label = formatDossierPersonLabel(
|
||||||
|
nom: nom,
|
||||||
|
prenom: prenom,
|
||||||
|
email: email,
|
||||||
|
);
|
||||||
|
if (label.isNotEmpty) names.add(label);
|
||||||
|
final e = (email ?? '').trim();
|
||||||
|
if (e.isNotEmpty) emails.add(e);
|
||||||
|
final s = (statut ?? '').trim();
|
||||||
|
if (s.isNotEmpty) statuts.add(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (final p in entry.value) {
|
||||||
|
consider(
|
||||||
|
p.user.id,
|
||||||
|
p.user.nom,
|
||||||
|
p.user.prenom,
|
||||||
|
p.user.email,
|
||||||
|
p.user.statut,
|
||||||
|
);
|
||||||
|
final co = p.coParent;
|
||||||
|
if (co != null) {
|
||||||
|
consider(co.id, co.nom, co.prenom, co.email, co.statut);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final childIds = <String>{};
|
||||||
|
var maxCountFallback = 0;
|
||||||
|
for (final p in entry.value) {
|
||||||
|
for (final c in p.children) {
|
||||||
|
final id = c.id.trim();
|
||||||
|
if (id.isNotEmpty) childIds.add(id);
|
||||||
|
}
|
||||||
|
final n = p.children.isNotEmpty ? p.children.length : p.childrenCount;
|
||||||
|
if (n > maxCountFallback) maxCountFallback = n;
|
||||||
|
}
|
||||||
|
final enfantsCount =
|
||||||
|
childIds.isNotEmpty ? childIds.length : maxCountFallback;
|
||||||
|
|
||||||
|
items.add(
|
||||||
|
DossierListItem(
|
||||||
|
type: DossierListType.famille,
|
||||||
|
numeroDossier: entry.key,
|
||||||
|
libelle: names.isNotEmpty ? names.join(' - ') : 'Famille',
|
||||||
|
emails: emails,
|
||||||
|
statut: _preferStatut(statuts),
|
||||||
|
enfantsCount: enfantsCount,
|
||||||
|
sansEnfant: enfantsCount == 0,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
static List<DossierListItem> fromAssistantes(
|
||||||
|
List<AssistanteMaternelleModel> ams,
|
||||||
|
) {
|
||||||
|
final byDossier = <String, AssistanteMaternelleModel>{};
|
||||||
|
for (final am in ams) {
|
||||||
|
final num = (am.user.numeroDossier ?? '').trim();
|
||||||
|
if (num.isEmpty) continue;
|
||||||
|
byDossier.putIfAbsent(num, () => am);
|
||||||
|
}
|
||||||
|
|
||||||
|
return byDossier.entries.map((e) {
|
||||||
|
final u = e.value.user;
|
||||||
|
final name = formatDossierPersonLabel(
|
||||||
|
nom: u.nom,
|
||||||
|
prenom: u.prenom,
|
||||||
|
email: u.email,
|
||||||
|
);
|
||||||
|
final photo = (u.photoUrl ?? '').trim();
|
||||||
|
return DossierListItem(
|
||||||
|
type: DossierListType.assistanteMaternelle,
|
||||||
|
numeroDossier: e.key,
|
||||||
|
libelle: name.isNotEmpty ? name : 'AM',
|
||||||
|
emails: u.email.trim().isEmpty ? const [] : [u.email.trim()],
|
||||||
|
statut: u.statut?.trim(),
|
||||||
|
photoUrl: photo.isEmpty ? null : photo,
|
||||||
|
);
|
||||||
|
}).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Priorité affichage : en_attente > suspendu > refuse > actif > autre.
|
||||||
|
static String? _preferStatut(List<String> raw) {
|
||||||
|
if (raw.isEmpty) return null;
|
||||||
|
const order = ['en_attente', 'suspendu', 'refuse', 'actif'];
|
||||||
|
for (final wanted in order) {
|
||||||
|
for (final s in raw) {
|
||||||
|
if (s.toLowerCase() == wanted) return s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return raw.first;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Affichage carte dossier : `NOM Prénom` (repli email).
|
||||||
|
String formatDossierPersonLabel({
|
||||||
|
String? nom,
|
||||||
|
String? prenom,
|
||||||
|
String? email,
|
||||||
|
}) {
|
||||||
|
final n = (nom ?? '').trim().toUpperCase();
|
||||||
|
final p = formatPersonNameCase(prenom ?? '');
|
||||||
|
if (n.isNotEmpty && p.isNotEmpty) return '$n $p';
|
||||||
|
if (n.isNotEmpty) return n;
|
||||||
|
if (p.isNotEmpty) return p;
|
||||||
|
return (email ?? '').trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reformate un libellé famille API (`A & B` / `Famille …`) en `NOM Prénom - …`.
|
||||||
|
String formatDossierFamilyNamesLine(String libelle) {
|
||||||
|
var raw = libelle.trim();
|
||||||
|
if (raw.isEmpty) return '';
|
||||||
|
raw = raw.replaceFirst(RegExp(r'^famille\s+', caseSensitive: false), '');
|
||||||
|
raw = raw
|
||||||
|
.replaceAll(RegExp(r'\s+&\s+'), ' - ')
|
||||||
|
.replaceAll(RegExp(r'\s+et\s+', caseSensitive: false), ' - ');
|
||||||
|
final parts = raw
|
||||||
|
.split(RegExp(r'\s+-\s+'))
|
||||||
|
.map((part) => _formatLoosePersonSegment(part.trim()))
|
||||||
|
.where((s) => s.isNotEmpty)
|
||||||
|
.toList();
|
||||||
|
return parts.join(' - ');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Segment libre type « martin sophie » ou « DURAND Amélie » → `NOM Prénom`.
|
||||||
|
String _formatLoosePersonSegment(String segment) {
|
||||||
|
final words =
|
||||||
|
segment.split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();
|
||||||
|
if (words.isEmpty) return '';
|
||||||
|
if (words.length == 1) return words.first.toUpperCase();
|
||||||
|
// Convention affichage : premier mot = NOM, reste = prénom(s).
|
||||||
|
final nom = words.first.toUpperCase();
|
||||||
|
final prenom = formatPersonNameCase(words.sublist(1).join(' '));
|
||||||
|
return '$nom $prenom';
|
||||||
|
}
|
||||||
@@ -185,7 +185,6 @@ class EnfantDossier {
|
|||||||
final String? dueDate;
|
final String? dueDate;
|
||||||
final String? photoUrl;
|
final String? photoUrl;
|
||||||
final bool consentPhoto;
|
final bool consentPhoto;
|
||||||
final bool estMultiple;
|
|
||||||
|
|
||||||
EnfantDossier({
|
EnfantDossier({
|
||||||
required this.id,
|
required this.id,
|
||||||
@@ -197,7 +196,6 @@ class EnfantDossier {
|
|||||||
this.dueDate,
|
this.dueDate,
|
||||||
this.photoUrl,
|
this.photoUrl,
|
||||||
this.consentPhoto = false,
|
this.consentPhoto = false,
|
||||||
this.estMultiple = false,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
String get fullName => '${firstName ?? ''} ${lastName ?? ''}'.trim();
|
String get fullName => '${firstName ?? ''} ${lastName ?? ''}'.trim();
|
||||||
@@ -215,8 +213,13 @@ class EnfantDossier {
|
|||||||
factory EnfantDossier.fromJson(Map<String, dynamic> json) {
|
factory EnfantDossier.fromJson(Map<String, dynamic> json) {
|
||||||
final rawPhoto = json['photo_url'] ?? json['photoUrl'];
|
final rawPhoto = json['photo_url'] ?? json['photoUrl'];
|
||||||
final resolvedPhoto = _optionalPhotoUrl(rawPhoto);
|
final resolvedPhoto = _optionalPhotoUrl(rawPhoto);
|
||||||
|
final rawId = json['id'] ??
|
||||||
|
json['enfant_id'] ??
|
||||||
|
json['enfantId'] ??
|
||||||
|
json['child_id'] ??
|
||||||
|
json['childId'];
|
||||||
return EnfantDossier(
|
return EnfantDossier(
|
||||||
id: json['id']?.toString() ?? '',
|
id: rawId?.toString().trim() ?? '',
|
||||||
firstName: (json['first_name'] ?? json['prenom'])?.toString(),
|
firstName: (json['first_name'] ?? json['prenom'])?.toString(),
|
||||||
lastName: (json['last_name'] ?? json['nom'])?.toString(),
|
lastName: (json['last_name'] ?? json['nom'])?.toString(),
|
||||||
birthDate: json['birth_date']?.toString(),
|
birthDate: json['birth_date']?.toString(),
|
||||||
@@ -226,8 +229,6 @@ class EnfantDossier {
|
|||||||
photoUrl: resolvedPhoto,
|
photoUrl: resolvedPhoto,
|
||||||
consentPhoto:
|
consentPhoto:
|
||||||
json['consent_photo'] == true || json['consentPhoto'] == true,
|
json['consent_photo'] == true || json['consentPhoto'] == true,
|
||||||
estMultiple:
|
|
||||||
json['est_multiple'] == true || json['estMultiple'] == true,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,8 +12,9 @@ class EnfantAdminModel {
|
|||||||
final String status;
|
final String status;
|
||||||
final String? photoUrl;
|
final String? photoUrl;
|
||||||
final bool consentPhoto;
|
final bool consentPhoto;
|
||||||
final bool isMultiple;
|
|
||||||
final List<EnfantParentLink> parentLinks;
|
final List<EnfantParentLink> parentLinks;
|
||||||
|
/// Flag API #157 (sinon déduit de [parentLinks]).
|
||||||
|
final bool? sansResponsable;
|
||||||
|
|
||||||
EnfantAdminModel({
|
EnfantAdminModel({
|
||||||
required this.id,
|
required this.id,
|
||||||
@@ -25,8 +26,8 @@ class EnfantAdminModel {
|
|||||||
required this.status,
|
required this.status,
|
||||||
this.photoUrl,
|
this.photoUrl,
|
||||||
this.consentPhoto = false,
|
this.consentPhoto = false,
|
||||||
this.isMultiple = false,
|
|
||||||
this.parentLinks = const [],
|
this.parentLinks = const [],
|
||||||
|
this.sansResponsable,
|
||||||
});
|
});
|
||||||
|
|
||||||
String get fullName {
|
String get fullName {
|
||||||
@@ -37,6 +38,40 @@ class EnfantAdminModel {
|
|||||||
return '$fn $ln';
|
return '$fn $ln';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Aucun lien parent valide — ticket #157.
|
||||||
|
bool get hasNoResponsable {
|
||||||
|
if (sansResponsable != null) return sansResponsable!;
|
||||||
|
return !parentLinks.any((l) => l.parentId.trim().isNotEmpty);
|
||||||
|
}
|
||||||
|
|
||||||
|
EnfantAdminModel copyWith({
|
||||||
|
String? id,
|
||||||
|
String? firstName,
|
||||||
|
String? lastName,
|
||||||
|
String? gender,
|
||||||
|
String? birthDate,
|
||||||
|
String? dueDate,
|
||||||
|
String? status,
|
||||||
|
String? photoUrl,
|
||||||
|
bool? consentPhoto,
|
||||||
|
List<EnfantParentLink>? parentLinks,
|
||||||
|
bool? sansResponsable,
|
||||||
|
}) {
|
||||||
|
return EnfantAdminModel(
|
||||||
|
id: id ?? this.id,
|
||||||
|
firstName: firstName ?? this.firstName,
|
||||||
|
lastName: lastName ?? this.lastName,
|
||||||
|
gender: gender ?? this.gender,
|
||||||
|
birthDate: birthDate ?? this.birthDate,
|
||||||
|
dueDate: dueDate ?? this.dueDate,
|
||||||
|
status: status ?? this.status,
|
||||||
|
photoUrl: photoUrl ?? this.photoUrl,
|
||||||
|
consentPhoto: consentPhoto ?? this.consentPhoto,
|
||||||
|
parentLinks: parentLinks ?? this.parentLinks,
|
||||||
|
sansResponsable: sansResponsable ?? this.sansResponsable,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
factory EnfantAdminModel.fromJson(Map<String, dynamic> json) {
|
factory EnfantAdminModel.fromJson(Map<String, dynamic> json) {
|
||||||
final linksRaw = json['parentLinks'] as List?;
|
final linksRaw = json['parentLinks'] as List?;
|
||||||
final links = <EnfantParentLink>[];
|
final links = <EnfantParentLink>[];
|
||||||
@@ -48,18 +83,32 @@ class EnfantAdminModel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final photoUrl = json['photo_url'] as String? ?? json['photoUrl'] as String?;
|
||||||
|
final consentPhoto = _parseBool(json['consent_photo']) ||
|
||||||
|
_parseBool(json['consentement_photo']) ||
|
||||||
|
_parseBool(json['consentPhoto']);
|
||||||
|
|
||||||
|
bool? sansResponsable;
|
||||||
|
if (json.containsKey('sans_responsable') ||
|
||||||
|
json.containsKey('sansResponsable')) {
|
||||||
|
sansResponsable = _parseBool(json['sans_responsable']) ||
|
||||||
|
_parseBool(json['sansResponsable']);
|
||||||
|
}
|
||||||
|
|
||||||
return EnfantAdminModel(
|
return EnfantAdminModel(
|
||||||
id: (json['id'] ?? '').toString(),
|
id: (json['id'] ?? '').toString(),
|
||||||
firstName: json['first_name'] as String?,
|
firstName: json['first_name'] as String? ?? json['prenom'] as String?,
|
||||||
lastName: json['last_name'] as String?,
|
lastName: json['last_name'] as String? ?? json['nom'] as String?,
|
||||||
gender: json['gender'] as String?,
|
gender: json['gender'] as String? ?? json['genre'] as String?,
|
||||||
birthDate: _dateString(json['birth_date']),
|
birthDate: _dateString(json['birth_date'] ?? json['date_naissance']),
|
||||||
dueDate: _dateString(json['due_date']),
|
dueDate: _dateString(json['due_date'] ?? json['date_prevue_naissance']),
|
||||||
status: normalizeEnfantStatus(json['status']?.toString()),
|
status: normalizeEnfantStatus(
|
||||||
photoUrl: json['photo_url'] as String?,
|
(json['status'] ?? json['statut'])?.toString(),
|
||||||
consentPhoto: json['consent_photo'] == true,
|
),
|
||||||
isMultiple: json['is_multiple'] == true,
|
photoUrl: photoUrl,
|
||||||
|
consentPhoto: consentPhoto,
|
||||||
parentLinks: links,
|
parentLinks: links,
|
||||||
|
sansResponsable: sansResponsable,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,10 +121,18 @@ class EnfantAdminModel {
|
|||||||
if (birthDate != null && birthDate!.isNotEmpty) 'birth_date': birthDate,
|
if (birthDate != null && birthDate!.isNotEmpty) 'birth_date': birthDate,
|
||||||
if (dueDate != null && dueDate!.isNotEmpty) 'due_date': dueDate,
|
if (dueDate != null && dueDate!.isNotEmpty) 'due_date': dueDate,
|
||||||
'consent_photo': consentPhoto,
|
'consent_photo': consentPhoto,
|
||||||
'is_multiple': isMultiple,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static bool _parseBool(dynamic value) {
|
||||||
|
if (value == true || value == 1) return true;
|
||||||
|
if (value is String) {
|
||||||
|
final s = value.trim().toLowerCase();
|
||||||
|
return s == 'true' || s == '1' || s == 't' || s == 'yes';
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
static String? _dateString(dynamic v) {
|
static String? _dateString(dynamic v) {
|
||||||
if (v == null) return null;
|
if (v == null) return null;
|
||||||
if (v is String) return v.split('T').first;
|
if (v is String) return v.split('T').first;
|
||||||
@@ -89,6 +146,13 @@ class EnfantParentLink {
|
|||||||
|
|
||||||
EnfantParentLink({required this.parentId, this.parentName});
|
EnfantParentLink({required this.parentId, this.parentName});
|
||||||
|
|
||||||
|
EnfantParentLink copyWith({String? parentId, String? parentName}) {
|
||||||
|
return EnfantParentLink(
|
||||||
|
parentId: parentId ?? this.parentId,
|
||||||
|
parentName: parentName ?? this.parentName,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
factory EnfantParentLink.fromJson(Map<String, dynamic> json) {
|
factory EnfantParentLink.fromJson(Map<String, dynamic> json) {
|
||||||
final parentId =
|
final parentId =
|
||||||
(json['parentId'] ?? json['id_parent'] ?? '').toString();
|
(json['parentId'] ?? json['id_parent'] ?? '').toString();
|
||||||
@@ -99,6 +163,12 @@ class EnfantParentLink {
|
|||||||
if (user is Map<String, dynamic>) {
|
if (user is Map<String, dynamic>) {
|
||||||
final u = AppUser.fromJson(user);
|
final u = AppUser.fromJson(user);
|
||||||
name = u.fullName.isNotEmpty ? u.fullName : u.email;
|
name = u.fullName.isNotEmpty ? u.fullName : u.email;
|
||||||
|
} else {
|
||||||
|
// Parfois le parent est aplati (prenom/nom) sans nested user.
|
||||||
|
final prenom = (parent['prenom'] ?? parent['first_name'] ?? '').toString().trim();
|
||||||
|
final nom = (parent['nom'] ?? parent['last_name'] ?? '').toString().trim();
|
||||||
|
final flat = '$prenom $nom'.trim();
|
||||||
|
if (flat.isNotEmpty) name = flat;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return EnfantParentLink(
|
return EnfantParentLink(
|
||||||
|
|||||||
@@ -62,4 +62,56 @@ class ParentModel {
|
|||||||
|
|
||||||
return children;
|
return children;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Nombre d’enfants distincts du foyer (ce parent + co-parent / même dossier).
|
||||||
|
/// Évite Claire=7 / Thomas=6 quand un lien n’est que sur un des deux (#157).
|
||||||
|
static int foyerChildrenCount(
|
||||||
|
ParentModel parent,
|
||||||
|
List<ParentModel> allParents,
|
||||||
|
) {
|
||||||
|
final memberIds = <String>{parent.user.id};
|
||||||
|
final coId = parent.coParent?.id.trim();
|
||||||
|
if (coId != null && coId.isNotEmpty) memberIds.add(coId);
|
||||||
|
|
||||||
|
final dossier = (parent.user.numeroDossier ?? '').trim();
|
||||||
|
|
||||||
|
for (final other in allParents) {
|
||||||
|
if (memberIds.contains(other.user.id)) continue;
|
||||||
|
final otherCo = other.coParent?.id.trim();
|
||||||
|
if (otherCo != null && memberIds.contains(otherCo)) {
|
||||||
|
memberIds.add(other.user.id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (dossier.isNotEmpty &&
|
||||||
|
(other.user.numeroDossier ?? '').trim() == dossier) {
|
||||||
|
memberIds.add(other.user.id);
|
||||||
|
final oc = other.coParent?.id.trim();
|
||||||
|
if (oc != null && oc.isNotEmpty) memberIds.add(oc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final childIds = <String>{};
|
||||||
|
for (final p in allParents) {
|
||||||
|
if (!memberIds.contains(p.user.id)) continue;
|
||||||
|
for (final c in p.children) {
|
||||||
|
final id = c.id.trim();
|
||||||
|
if (id.isNotEmpty) childIds.add(id);
|
||||||
|
}
|
||||||
|
// Repli si la liste enfants n’est pas hydratée.
|
||||||
|
if (p.children.isEmpty && p.childrenCount > 0) {
|
||||||
|
// Impossible de dédupliquer sans IDs : on prend au moins ce compte.
|
||||||
|
// (évite d’afficher 0 si l’API n’envoie que childrenCount)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (childIds.isNotEmpty) return childIds.length;
|
||||||
|
|
||||||
|
var maxCount = 0;
|
||||||
|
for (final p in allParents) {
|
||||||
|
if (!memberIds.contains(p.user.id)) continue;
|
||||||
|
final n = p.children.isNotEmpty ? p.children.length : p.childrenCount;
|
||||||
|
if (n > maxCount) maxCount = n;
|
||||||
|
}
|
||||||
|
return maxCount;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,7 +30,6 @@ class ChildData {
|
|||||||
String lastName;
|
String lastName;
|
||||||
String dob; // Date de naissance ou prévisionnelle
|
String dob; // Date de naissance ou prévisionnelle
|
||||||
bool photoConsent;
|
bool photoConsent;
|
||||||
bool multipleBirth;
|
|
||||||
bool isUnbornChild;
|
bool isUnbornChild;
|
||||||
File? imageFile;
|
File? imageFile;
|
||||||
CardColorVertical cardColor; // Nouveau champ pour la couleur de la carte
|
CardColorVertical cardColor; // Nouveau champ pour la couleur de la carte
|
||||||
@@ -40,7 +39,6 @@ class ChildData {
|
|||||||
this.lastName = '',
|
this.lastName = '',
|
||||||
this.dob = '',
|
this.dob = '',
|
||||||
this.photoConsent = false,
|
this.photoConsent = false,
|
||||||
this.multipleBirth = false,
|
|
||||||
this.isUnbornChild = false,
|
this.isUnbornChild = false,
|
||||||
this.imageFile,
|
this.imageFile,
|
||||||
required this.cardColor, // Rendre requis dans le constructeur
|
required this.cardColor, // Rendre requis dans le constructeur
|
||||||
|
|||||||
@@ -38,7 +38,6 @@ class ChildData {
|
|||||||
/// Valeurs API : `H`, `F`, `Autre` (GenreType backend). Vide tant que non choisi.
|
/// Valeurs API : `H`, `F`, `Autre` (GenreType backend). Vide tant que non choisi.
|
||||||
String genre;
|
String genre;
|
||||||
bool photoConsent;
|
bool photoConsent;
|
||||||
bool multipleBirth;
|
|
||||||
bool isUnbornChild;
|
bool isUnbornChild;
|
||||||
File? imageFile;
|
File? imageFile;
|
||||||
/// Octets de la photo (fiable à l’envoi API ; [imageFile] peut être absent sur le web).
|
/// Octets de la photo (fiable à l’envoi API ; [imageFile] peut être absent sur le web).
|
||||||
@@ -55,7 +54,6 @@ class ChildData {
|
|||||||
this.dob = '',
|
this.dob = '',
|
||||||
this.genre = '',
|
this.genre = '',
|
||||||
this.photoConsent = false,
|
this.photoConsent = false,
|
||||||
this.multipleBirth = false,
|
|
||||||
this.isUnbornChild = false,
|
this.isUnbornChild = false,
|
||||||
this.imageFile,
|
this.imageFile,
|
||||||
this.imageBytes,
|
this.imageBytes,
|
||||||
@@ -70,7 +68,6 @@ class ChildData {
|
|||||||
String? dob,
|
String? dob,
|
||||||
String? genre,
|
String? genre,
|
||||||
bool? photoConsent,
|
bool? photoConsent,
|
||||||
bool? multipleBirth,
|
|
||||||
bool? isUnbornChild,
|
bool? isUnbornChild,
|
||||||
Object? imageFile = _unsetImage,
|
Object? imageFile = _unsetImage,
|
||||||
Object? imageBytes = _unsetImageBytes,
|
Object? imageBytes = _unsetImageBytes,
|
||||||
@@ -84,7 +81,6 @@ class ChildData {
|
|||||||
dob: dob ?? this.dob,
|
dob: dob ?? this.dob,
|
||||||
genre: genre ?? this.genre,
|
genre: genre ?? this.genre,
|
||||||
photoConsent: photoConsent ?? this.photoConsent,
|
photoConsent: photoConsent ?? this.photoConsent,
|
||||||
multipleBirth: multipleBirth ?? this.multipleBirth,
|
|
||||||
isUnbornChild: isUnbornChild ?? this.isUnbornChild,
|
isUnbornChild: isUnbornChild ?? this.isUnbornChild,
|
||||||
imageFile: identical(imageFile, _unsetImage) ? this.imageFile : imageFile as File?,
|
imageFile: identical(imageFile, _unsetImage) ? this.imageFile : imageFile as File?,
|
||||||
imageBytes:
|
imageBytes:
|
||||||
|
|||||||
@@ -2,9 +2,9 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:p_tits_pas/models/user.dart';
|
import 'package:p_tits_pas/models/user.dart';
|
||||||
import 'package:p_tits_pas/services/auth_service.dart';
|
import 'package:p_tits_pas/services/auth_service.dart';
|
||||||
import 'package:p_tits_pas/services/configuration_service.dart';
|
import 'package:p_tits_pas/services/configuration_service.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/dashboard_admin.dart';
|
import 'package:p_tits_pas/widgets/dashboard/user_management_sub_bar.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/parametres_panel.dart';
|
import 'package:p_tits_pas/widgets/dashboard/parametres_panel.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/user_management_panel.dart';
|
import 'package:p_tits_pas/widgets/dashboard/user_management_panel.dart';
|
||||||
import 'package:p_tits_pas/widgets/app_footer.dart';
|
import 'package:p_tits_pas/widgets/app_footer.dart';
|
||||||
import 'package:p_tits_pas/widgets/dashboard/dashboard_bandeau.dart';
|
import 'package:p_tits_pas/widgets/dashboard/dashboard_bandeau.dart';
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import 'package:p_tits_pas/utils/phone_utils.dart';
|
|||||||
import 'package:p_tits_pas/models/user.dart';
|
import 'package:p_tits_pas/models/user.dart';
|
||||||
import 'package:p_tits_pas/services/user_service.dart';
|
import 'package:p_tits_pas/services/user_service.dart';
|
||||||
import 'package:p_tits_pas/utils/email_utils.dart';
|
import 'package:p_tits_pas/utils/email_utils.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/dashboard/common/suppression_confirm_dialog.dart';
|
||||||
import 'package:p_tits_pas/widgets/email_text_field.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/widgets/french_phone_field.dart';
|
||||||
|
|
||||||
@@ -151,30 +152,19 @@ class _AdminCreateDialogState extends State<AdminCreateDialog> {
|
|||||||
Future<void> _delete() async {
|
Future<void> _delete() async {
|
||||||
if (!_isEditMode || _isSubmitting) return;
|
if (!_isEditMode || _isSubmitting) return;
|
||||||
|
|
||||||
final confirmed = await showDialog<bool>(
|
final name = widget.initialUser!.fullName.isEmpty
|
||||||
context: context,
|
? widget.initialUser!.email
|
||||||
builder: (ctx) {
|
: widget.initialUser!.fullName;
|
||||||
return AlertDialog(
|
final confirmed = await showSuppressionConfirmDialog(
|
||||||
title: const Text('Confirmer la suppression'),
|
context,
|
||||||
content: Text(
|
title: 'Supprimer l\'administrateur',
|
||||||
'Supprimer ${widget.initialUser!.fullName.isEmpty ? widget.initialUser!.email : widget.initialUser!.fullName} ?',
|
people: [SuppressionPersonLine.administrateur(name)],
|
||||||
),
|
footnotes: const [
|
||||||
actions: [
|
'Le compte sera définitivement supprimé.',
|
||||||
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;
|
if (!confirmed) return;
|
||||||
|
|
||||||
setState(() {
|
setState(() {
|
||||||
_isSubmitting = true;
|
_isSubmitting = true;
|
||||||
|
|||||||
@@ -5,8 +5,11 @@ 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/email_text_field.dart';
|
||||||
import 'package:p_tits_pas/widgets/french_phone_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/models/user.dart';
|
||||||
|
import 'package:p_tits_pas/services/auth_service.dart';
|
||||||
import 'package:p_tits_pas/services/relais_service.dart';
|
import 'package:p_tits_pas/services/relais_service.dart';
|
||||||
import 'package:p_tits_pas/services/user_service.dart';
|
import 'package:p_tits_pas/services/user_service.dart';
|
||||||
|
import 'package:p_tits_pas/utils/staff_deletion_rights.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/dashboard/common/suppression_confirm_dialog.dart';
|
||||||
|
|
||||||
class AdminUserFormDialog extends StatefulWidget {
|
class AdminUserFormDialog extends StatefulWidget {
|
||||||
final AppUser? initialUser;
|
final AppUser? initialUser;
|
||||||
@@ -41,9 +44,21 @@ class _AdminUserFormDialogState extends State<AdminUserFormDialog> {
|
|||||||
bool _isLoadingRelais = true;
|
bool _isLoadingRelais = true;
|
||||||
List<RelaisModel> _relais = [];
|
List<RelaisModel> _relais = [];
|
||||||
String? _selectedRelaisId;
|
String? _selectedRelaisId;
|
||||||
|
String? _currentUserId;
|
||||||
|
String? _currentUserRole;
|
||||||
bool get _isEditMode => widget.initialUser != null;
|
bool get _isEditMode => widget.initialUser != null;
|
||||||
bool get _isSuperAdminTarget =>
|
bool get _isSuperAdminTarget =>
|
||||||
(widget.initialUser?.role ?? '').toLowerCase() == 'super_admin';
|
(widget.initialUser?.role ?? '').toLowerCase() == 'super_admin';
|
||||||
|
bool get _isSelfTarget =>
|
||||||
|
_isEditMode &&
|
||||||
|
_currentUserId != null &&
|
||||||
|
widget.initialUser!.id == _currentUserId;
|
||||||
|
/// Gestionnaire : pas de delete staff. Admin+ seulement (#154 / #160).
|
||||||
|
bool get _canDeleteTarget {
|
||||||
|
if (!_isEditMode || widget.readOnly) return false;
|
||||||
|
if (_isSelfTarget || _isSuperAdminTarget) return false;
|
||||||
|
return canDeleteGestionnaire(_currentUserRole);
|
||||||
|
}
|
||||||
bool get _isLockedAdminIdentity =>
|
bool get _isLockedAdminIdentity =>
|
||||||
_isEditMode && widget.adminMode && _isSuperAdminTarget;
|
_isEditMode && widget.adminMode && _isSuperAdminTarget;
|
||||||
String get _targetRoleKey {
|
String get _targetRoleKey {
|
||||||
@@ -109,6 +124,25 @@ class _AdminUserFormDialogState extends State<AdminUserFormDialog> {
|
|||||||
} else {
|
} else {
|
||||||
_isLoadingRelais = false;
|
_isLoadingRelais = false;
|
||||||
}
|
}
|
||||||
|
_loadCurrentUserId();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _loadCurrentUserId() async {
|
||||||
|
final cached = await AuthService.getCurrentUser();
|
||||||
|
if (!mounted) return;
|
||||||
|
if (cached != null) {
|
||||||
|
setState(() {
|
||||||
|
_currentUserId = cached.id;
|
||||||
|
_currentUserRole = cached.role;
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final refreshed = await AuthService.refreshCurrentUser();
|
||||||
|
if (!mounted || refreshed == null) return;
|
||||||
|
setState(() {
|
||||||
|
_currentUserId = refreshed.id;
|
||||||
|
_currentUserRole = refreshed.role;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -122,6 +156,21 @@ class _AdminUserFormDialogState extends State<AdminUserFormDialog> {
|
|||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Fallback si GET /relais échoue : conserve le relais déjà connu sur l'utilisateur.
|
||||||
|
List<RelaisModel> _fallbackRelaisFromUser() {
|
||||||
|
final id = _selectedRelaisId?.trim();
|
||||||
|
if (id == null || id.isEmpty) return const [];
|
||||||
|
final nom = (widget.initialUser?.relaisNom ?? '').trim();
|
||||||
|
return [
|
||||||
|
RelaisModel(
|
||||||
|
id: id,
|
||||||
|
nom: nom.isNotEmpty ? nom : 'Relais actuel',
|
||||||
|
adresse: '',
|
||||||
|
actif: true,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _loadRelais() async {
|
Future<void> _loadRelais() async {
|
||||||
try {
|
try {
|
||||||
final list = await RelaisService.getRelais();
|
final list = await RelaisService.getRelais();
|
||||||
@@ -138,7 +187,8 @@ class _AdminUserFormDialogState extends State<AdminUserFormDialog> {
|
|||||||
if (selected != null) {
|
if (selected != null) {
|
||||||
filtered.add(selected);
|
filtered.add(selected);
|
||||||
} else {
|
} else {
|
||||||
_selectedRelaisId = null;
|
// Garder l'id sélectionné et afficher un item de secours (nom carte).
|
||||||
|
filtered.addAll(_fallbackRelaisFromUser());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,9 +198,9 @@ class _AdminUserFormDialogState extends State<AdminUserFormDialog> {
|
|||||||
});
|
});
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
|
// Ne pas nullifier _selectedRelaisId (#151) — la carte a déjà le bon libellé.
|
||||||
setState(() {
|
setState(() {
|
||||||
_selectedRelaisId = null;
|
_relais = _fallbackRelaisFromUser();
|
||||||
_relais = [];
|
|
||||||
_isLoadingRelais = false;
|
_isLoadingRelais = false;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -335,33 +385,28 @@ class _AdminUserFormDialogState extends State<AdminUserFormDialog> {
|
|||||||
|
|
||||||
Future<void> _delete() async {
|
Future<void> _delete() async {
|
||||||
if (widget.readOnly) return;
|
if (widget.readOnly) return;
|
||||||
if (_isSuperAdminTarget) return;
|
if (!_canDeleteTarget) return;
|
||||||
if (!_isEditMode || _isSubmitting) return;
|
if (!_isEditMode || _isSubmitting) return;
|
||||||
|
|
||||||
final confirmed = await showDialog<bool>(
|
final name = widget.initialUser!.fullName.isEmpty
|
||||||
context: context,
|
? widget.initialUser!.email
|
||||||
builder: (ctx) {
|
: widget.initialUser!.fullName;
|
||||||
return AlertDialog(
|
final confirmed = await showSuppressionConfirmDialog(
|
||||||
title: const Text('Confirmer la suppression'),
|
context,
|
||||||
content: Text(
|
title: widget.adminMode
|
||||||
'Supprimer ${widget.initialUser!.fullName.isEmpty ? widget.initialUser!.email : widget.initialUser!.fullName} ?',
|
? 'Supprimer l\'administrateur'
|
||||||
),
|
: 'Supprimer le gestionnaire',
|
||||||
actions: [
|
people: [
|
||||||
TextButton(
|
widget.adminMode
|
||||||
onPressed: () => Navigator.of(ctx).pop(false),
|
? SuppressionPersonLine.administrateur(name)
|
||||||
child: const Text('Annuler'),
|
: SuppressionPersonLine.gestionnaire(name),
|
||||||
),
|
],
|
||||||
FilledButton(
|
footnotes: const [
|
||||||
onPressed: () => Navigator.of(ctx).pop(true),
|
'Le compte sera définitivement supprimé.',
|
||||||
style: FilledButton.styleFrom(backgroundColor: Colors.red.shade700),
|
|
||||||
child: const Text('Supprimer'),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
if (confirmed != true) return;
|
if (!confirmed) return;
|
||||||
|
|
||||||
setState(() {
|
setState(() {
|
||||||
_isSubmitting = true;
|
_isSubmitting = true;
|
||||||
@@ -462,7 +507,7 @@ class _AdminUserFormDialogState extends State<AdminUserFormDialog> {
|
|||||||
child: const Text('Fermer'),
|
child: const Text('Fermer'),
|
||||||
),
|
),
|
||||||
] else if (_isEditMode) ...[
|
] else if (_isEditMode) ...[
|
||||||
if (!_isSuperAdminTarget)
|
if (_canDeleteTarget)
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
onPressed: _isSubmitting ? null : _delete,
|
onPressed: _isSubmitting ? null : _delete,
|
||||||
style: OutlinedButton.styleFrom(foregroundColor: Colors.red.shade700),
|
style: OutlinedButton.styleFrom(foregroundColor: Colors.red.shade700),
|
||||||
|
|||||||
@@ -121,7 +121,6 @@ class _ParentRegisterStep3ScreenState extends State<ParentRegisterStep3Screen> {
|
|||||||
dob: '',
|
dob: '',
|
||||||
isUnbornChild: false,
|
isUnbornChild: false,
|
||||||
photoConsent: false,
|
photoConsent: false,
|
||||||
multipleBirth: false,
|
|
||||||
cardColor: cardColor,
|
cardColor: cardColor,
|
||||||
);
|
);
|
||||||
registrationData.addChild(newChild);
|
registrationData.addChild(newChild);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:p_tits_pas/models/user.dart';
|
import 'package:p_tits_pas/models/user.dart';
|
||||||
import 'package:p_tits_pas/services/auth_service.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/dashboard/user_management_panel.dart';
|
||||||
import 'package:p_tits_pas/widgets/app_footer.dart';
|
import 'package:p_tits_pas/widgets/app_footer.dart';
|
||||||
import 'package:p_tits_pas/widgets/dashboard/dashboard_bandeau.dart';
|
import 'package:p_tits_pas/widgets/dashboard/dashboard_bandeau.dart';
|
||||||
|
|
||||||
@@ -62,7 +62,10 @@ class _GestionnaireDashboardScreenState extends State<GestionnaireDashboardScree
|
|||||||
body: Column(
|
body: Column(
|
||||||
children: [
|
children: [
|
||||||
Expanded(
|
Expanded(
|
||||||
child: UserManagementPanel(showAdministrateursTab: false),
|
child: UserManagementPanel(
|
||||||
|
showAdministrateursTab: false,
|
||||||
|
allowStaffAccountCreation: false,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const AppFooter(),
|
const AppFooter(),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -60,7 +60,12 @@ class ApiConfig {
|
|||||||
static const String userChildren = '/users/children';
|
static const String userChildren = '/users/children';
|
||||||
static const String gestionnaires = '/gestionnaires';
|
static const String gestionnaires = '/gestionnaires';
|
||||||
static const String parents = '/parents';
|
static const String parents = '/parents';
|
||||||
|
/// Création dossier famille actif par le staff (#129) — body type register parent.
|
||||||
|
static const String parentsDossier = '/parents/dossier';
|
||||||
static const String assistantesMaternelles = '/assistantes-maternelles';
|
static const String assistantesMaternelles = '/assistantes-maternelles';
|
||||||
|
/// Création dossier AM actif par le staff (#156) — body type register AM.
|
||||||
|
static const String assistantesMaternellesDossier =
|
||||||
|
'/assistantes-maternelles/dossier';
|
||||||
static const String enfants = '/enfants';
|
static const String enfants = '/enfants';
|
||||||
static const String relais = '/relais';
|
static const String relais = '/relais';
|
||||||
static const String dossiers = '/dossiers';
|
static const String dossiers = '/dossiers';
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http_parser/http_parser.dart';
|
||||||
import 'package:p_tits_pas/models/user.dart';
|
import 'package:p_tits_pas/models/user.dart';
|
||||||
import 'package:p_tits_pas/models/enfant_admin_model.dart';
|
import 'package:p_tits_pas/models/enfant_admin_model.dart';
|
||||||
import 'package:p_tits_pas/models/parent_model.dart';
|
import 'package:p_tits_pas/models/parent_model.dart';
|
||||||
@@ -8,6 +9,7 @@ import 'package:p_tits_pas/models/pending_family.dart';
|
|||||||
import 'package:p_tits_pas/models/dossier_unifie.dart';
|
import 'package:p_tits_pas/models/dossier_unifie.dart';
|
||||||
import 'package:p_tits_pas/services/api/api_config.dart';
|
import 'package:p_tits_pas/services/api/api_config.dart';
|
||||||
import 'package:p_tits_pas/services/api/tokenService.dart';
|
import 'package:p_tits_pas/services/api/tokenService.dart';
|
||||||
|
import 'package:p_tits_pas/utils/am_vigilance.dart';
|
||||||
|
|
||||||
class DocumentActifInfo {
|
class DocumentActifInfo {
|
||||||
final String id;
|
final String id;
|
||||||
@@ -56,6 +58,33 @@ class UserService {
|
|||||||
return v.toString();
|
return v.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// MIME pour upload photo enfant (filtre Nest : jpg/jpeg/png/gif).
|
||||||
|
static MediaType _imageMediaType(String filename, List<int> bytes) {
|
||||||
|
if (bytes.length >= 3 &&
|
||||||
|
bytes[0] == 0xFF &&
|
||||||
|
bytes[1] == 0xD8 &&
|
||||||
|
bytes[2] == 0xFF) {
|
||||||
|
return MediaType('image', 'jpeg');
|
||||||
|
}
|
||||||
|
if (bytes.length >= 8 &&
|
||||||
|
bytes[0] == 0x89 &&
|
||||||
|
bytes[1] == 0x50 &&
|
||||||
|
bytes[2] == 0x4E &&
|
||||||
|
bytes[3] == 0x47) {
|
||||||
|
return MediaType('image', 'png');
|
||||||
|
}
|
||||||
|
if (bytes.length >= 6 &&
|
||||||
|
bytes[0] == 0x47 &&
|
||||||
|
bytes[1] == 0x49 &&
|
||||||
|
bytes[2] == 0x46) {
|
||||||
|
return MediaType('image', 'gif');
|
||||||
|
}
|
||||||
|
final lower = filename.toLowerCase();
|
||||||
|
if (lower.endsWith('.png')) return MediaType('image', 'png');
|
||||||
|
if (lower.endsWith('.gif')) return MediaType('image', 'gif');
|
||||||
|
return MediaType('image', 'jpeg');
|
||||||
|
}
|
||||||
|
|
||||||
static String _errMessage(dynamic err) {
|
static String _errMessage(dynamic err) {
|
||||||
if (err == null) return 'Erreur inconnue';
|
if (err == null) return 'Erreur inconnue';
|
||||||
if (err is String) return err;
|
if (err is String) return err;
|
||||||
@@ -460,22 +489,259 @@ class UserService {
|
|||||||
if (response.statusCode != 200) {
|
if (response.statusCode != 200) {
|
||||||
throw Exception(_extractErrorMessage(response.body, 'Erreur chargement enfant'));
|
throw Exception(_extractErrorMessage(response.body, 'Erreur chargement enfant'));
|
||||||
}
|
}
|
||||||
return EnfantAdminModel.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
|
final enfant = EnfantAdminModel.fromJson(
|
||||||
|
jsonDecode(response.body) as Map<String, dynamic>,
|
||||||
|
);
|
||||||
|
// GET /enfants/:id ne joint pas toujours parent.user → noms manquants.
|
||||||
|
return enrichEnfantParentNames(enfant);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Complète [parentName] via GET parent quand l'API n'a pas fourni le nested user.
|
||||||
|
static Future<EnfantAdminModel> enrichEnfantParentNames(
|
||||||
|
EnfantAdminModel enfant,
|
||||||
|
) async {
|
||||||
|
final links = enfant.parentLinks;
|
||||||
|
if (links.isEmpty) return enfant;
|
||||||
|
if (links.every((l) => (l.parentName ?? '').trim().isNotEmpty)) {
|
||||||
|
return enfant;
|
||||||
|
}
|
||||||
|
|
||||||
|
final enriched = await Future.wait(
|
||||||
|
links.map((link) async {
|
||||||
|
if ((link.parentName ?? '').trim().isNotEmpty) return link;
|
||||||
|
final id = link.parentId.trim();
|
||||||
|
if (id.isEmpty) return link;
|
||||||
|
try {
|
||||||
|
final parent = await getParent(id);
|
||||||
|
final name = parent.user.fullName.trim();
|
||||||
|
if (name.isEmpty) return link;
|
||||||
|
return link.copyWith(parentName: name);
|
||||||
|
} catch (_) {
|
||||||
|
return link;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
return enfant.copyWith(parentLinks: enriched);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mise à jour enfant. Avec [photoBytes] : multipart (champ `photo`), sinon JSON.
|
||||||
static Future<EnfantAdminModel> updateEnfant({
|
static Future<EnfantAdminModel> updateEnfant({
|
||||||
required String enfantId,
|
required String enfantId,
|
||||||
required Map<String, dynamic> body,
|
required Map<String, dynamic> body,
|
||||||
|
List<int>? photoBytes,
|
||||||
|
String? photoFilename,
|
||||||
}) async {
|
}) async {
|
||||||
final response = await http.patch(
|
final id = enfantId.trim();
|
||||||
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.enfants}/$enfantId'),
|
if (id.isEmpty) {
|
||||||
|
throw Exception('Identifiant enfant manquant.');
|
||||||
|
}
|
||||||
|
final hasPhoto = photoBytes != null && photoBytes.isNotEmpty;
|
||||||
|
final http.Response response;
|
||||||
|
if (hasPhoto) {
|
||||||
|
final token = await TokenService.getToken();
|
||||||
|
final req = http.MultipartRequest(
|
||||||
|
'PATCH',
|
||||||
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.enfants}/$id'),
|
||||||
|
);
|
||||||
|
req.headers['Accept'] = 'application/json';
|
||||||
|
if (token != null) {
|
||||||
|
req.headers['Authorization'] = 'Bearer $token';
|
||||||
|
}
|
||||||
|
body.forEach((key, value) {
|
||||||
|
if (value == null) return;
|
||||||
|
req.fields[key] = value is bool
|
||||||
|
? (value ? 'true' : 'false')
|
||||||
|
: value.toString();
|
||||||
|
});
|
||||||
|
final name = (photoFilename ?? '').trim();
|
||||||
|
final filename = name.isNotEmpty ? name : 'photo.jpg';
|
||||||
|
req.files.add(
|
||||||
|
http.MultipartFile.fromBytes(
|
||||||
|
'photo',
|
||||||
|
photoBytes,
|
||||||
|
filename: filename,
|
||||||
|
contentType: _imageMediaType(filename, photoBytes),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
final streamed = await req.send();
|
||||||
|
response = await http.Response.fromStream(streamed);
|
||||||
|
} else {
|
||||||
|
response = await http.patch(
|
||||||
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.enfants}/$id'),
|
||||||
headers: await _headers(),
|
headers: await _headers(),
|
||||||
body: jsonEncode(body),
|
body: jsonEncode(body),
|
||||||
);
|
);
|
||||||
if (response.statusCode != 200) {
|
|
||||||
throw Exception(_extractErrorMessage(response.body, 'Erreur mise à jour enfant'));
|
|
||||||
}
|
}
|
||||||
return EnfantAdminModel.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
|
if (response.statusCode != 200) {
|
||||||
|
throw Exception(
|
||||||
|
_extractErrorMessage(response.body, 'Erreur mise à jour enfant'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final enfant = EnfantAdminModel.fromJson(
|
||||||
|
jsonDecode(response.body) as Map<String, dynamic>,
|
||||||
|
);
|
||||||
|
return enrichEnfantParentNames(enfant);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Création enfant côté staff (#132) — nécessite `POST /enfants` étendu (voir mini-spec).
|
||||||
|
/// [parentUserId] : parent pivot du foyer (`parent_user_id`).
|
||||||
|
/// Avec [photoBytes] : `multipart/form-data` (champ fichier `photo`), sinon JSON.
|
||||||
|
static Future<EnfantAdminModel> createEnfant({
|
||||||
|
required String parentUserId,
|
||||||
|
required Map<String, dynamic> body,
|
||||||
|
List<int>? photoBytes,
|
||||||
|
String? photoFilename,
|
||||||
|
}) async {
|
||||||
|
final hasPhoto = photoBytes != null && photoBytes.isNotEmpty;
|
||||||
|
final http.Response response;
|
||||||
|
if (hasPhoto) {
|
||||||
|
final token = await TokenService.getToken();
|
||||||
|
final req = http.MultipartRequest(
|
||||||
|
'POST',
|
||||||
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.enfants}'),
|
||||||
|
);
|
||||||
|
req.headers['Accept'] = 'application/json';
|
||||||
|
if (token != null) {
|
||||||
|
req.headers['Authorization'] = 'Bearer $token';
|
||||||
|
}
|
||||||
|
body.forEach((key, value) {
|
||||||
|
if (value == null) return;
|
||||||
|
req.fields[key] = value is bool
|
||||||
|
? (value ? 'true' : 'false')
|
||||||
|
: value.toString();
|
||||||
|
});
|
||||||
|
req.fields['parent_user_id'] = parentUserId;
|
||||||
|
final name = (photoFilename ?? '').trim();
|
||||||
|
final filename = name.isNotEmpty ? name : 'photo.jpg';
|
||||||
|
req.files.add(
|
||||||
|
http.MultipartFile.fromBytes(
|
||||||
|
'photo',
|
||||||
|
photoBytes,
|
||||||
|
filename: filename,
|
||||||
|
contentType: _imageMediaType(filename, photoBytes),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
final streamed = await req.send();
|
||||||
|
response = await http.Response.fromStream(streamed);
|
||||||
|
} else {
|
||||||
|
final payload = <String, dynamic>{
|
||||||
|
...body,
|
||||||
|
'parent_user_id': parentUserId,
|
||||||
|
};
|
||||||
|
response = await http.post(
|
||||||
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.enfants}'),
|
||||||
|
headers: await _headers(),
|
||||||
|
body: jsonEncode(payload),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (response.statusCode != 200 && response.statusCode != 201) {
|
||||||
|
throw Exception(
|
||||||
|
_extractErrorMessage(response.body, 'Erreur création enfant'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final enfant = EnfantAdminModel.fromJson(
|
||||||
|
jsonDecode(response.body) as Map<String, dynamic>,
|
||||||
|
);
|
||||||
|
return enrichEnfantParentNames(enfant);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// DELETE /enfants/:id?deleteDossier= — ticket #159 / #160.
|
||||||
|
static Future<Map<String, dynamic>> deleteEnfant(
|
||||||
|
String enfantId, {
|
||||||
|
bool deleteDossier = false,
|
||||||
|
}) async {
|
||||||
|
final uri = Uri.parse(
|
||||||
|
'${ApiConfig.baseUrl}${ApiConfig.enfants}/$enfantId',
|
||||||
|
).replace(
|
||||||
|
queryParameters: {
|
||||||
|
'deleteDossier': deleteDossier ? 'true' : 'false',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
final response = await http.delete(uri, headers: await _headers());
|
||||||
|
if (response.statusCode != 200 && response.statusCode != 204) {
|
||||||
|
throw Exception(
|
||||||
|
_extractErrorMessage(response.body, 'Erreur suppression enfant'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return _parseSuppressionBody(response.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// DELETE /dossiers/:numeroDossier — ticket #159 / #160.
|
||||||
|
static Future<Map<String, dynamic>> deleteDossier(
|
||||||
|
String numeroDossier,
|
||||||
|
) async {
|
||||||
|
final num = numeroDossier.trim();
|
||||||
|
if (num.isEmpty) {
|
||||||
|
throw Exception('Numéro de dossier manquant.');
|
||||||
|
}
|
||||||
|
final encoded = Uri.encodeComponent(num);
|
||||||
|
final response = await http.delete(
|
||||||
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.dossiers}/$encoded'),
|
||||||
|
headers: await _headers(),
|
||||||
|
);
|
||||||
|
if (response.statusCode != 200 && response.statusCode != 204) {
|
||||||
|
throw Exception(
|
||||||
|
_extractErrorMessage(response.body, 'Erreur suppression dossier'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return _parseSuppressionBody(response.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Liste unifiée GET /dossiers — flags `sans_enfant` (#159).
|
||||||
|
static Future<List<Map<String, dynamic>>> listDossiers({String? q}) async {
|
||||||
|
final uri = Uri.parse('${ApiConfig.baseUrl}${ApiConfig.dossiers}')
|
||||||
|
.replace(
|
||||||
|
queryParameters: (q != null && q.trim().isNotEmpty)
|
||||||
|
? {'q': q.trim()}
|
||||||
|
: null,
|
||||||
|
);
|
||||||
|
final response = await http.get(uri, headers: await _headers());
|
||||||
|
if (response.statusCode != 200) {
|
||||||
|
throw Exception(
|
||||||
|
_extractErrorMessage(response.body, 'Erreur chargement dossiers'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final decoded = jsonDecode(response.body);
|
||||||
|
if (decoded is! List) return const [];
|
||||||
|
return decoded
|
||||||
|
.whereType<Map>()
|
||||||
|
.map((e) => Map<String, dynamic>.from(e))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Map `numero_dossier` → `sans_enfant` (familles uniquement).
|
||||||
|
static Future<Map<String, bool>> getSansEnfantByNumero() async {
|
||||||
|
final rows = await listDossiers();
|
||||||
|
final out = <String, bool>{};
|
||||||
|
for (final row in rows) {
|
||||||
|
final num = (row['numero_dossier'] ?? '').toString().trim();
|
||||||
|
if (num.isEmpty) continue;
|
||||||
|
final type = (row['type'] ?? '').toString().toLowerCase();
|
||||||
|
if (type != 'famille') continue;
|
||||||
|
out[num] = row['sans_enfant'] == true;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Map<String, dynamic> _parseSuppressionBody(String body) {
|
||||||
|
if (body.trim().isEmpty) return <String, dynamic>{};
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(body);
|
||||||
|
if (decoded is Map) {
|
||||||
|
return Map<String, dynamic>.from(decoded);
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
return <String, dynamic>{};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AM dont la liste d'enfants actifs contient [enfantId] (API actuelle).
|
||||||
|
static Future<AssistanteMaternelleModel?> findAmForEnfant(String enfantId) async {
|
||||||
|
final ams = await getAssistantesMaternelles();
|
||||||
|
for (final am in ams) {
|
||||||
|
if (am.children.any((c) => c.id == enfantId)) return am;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
static ParentModel _parentModelFromBody(String body) {
|
static ParentModel _parentModelFromBody(String body) {
|
||||||
@@ -499,6 +765,155 @@ class UserService {
|
|||||||
return fallback;
|
return fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ajout d’un co-parent sur foyer mono-parent (staff, #135).
|
||||||
|
/// `POST /parents/:pivotUserId/co-parent` — succès 201.
|
||||||
|
static Future<Map<String, dynamic>> addCoParent(
|
||||||
|
String pivotUserId, {
|
||||||
|
required Map<String, dynamic> body,
|
||||||
|
}) async {
|
||||||
|
final id = pivotUserId.trim();
|
||||||
|
if (id.isEmpty) {
|
||||||
|
throw Exception('Identifiant du parent pivot manquant.');
|
||||||
|
}
|
||||||
|
final http.Response response;
|
||||||
|
try {
|
||||||
|
response = await http.post(
|
||||||
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.parents}/$id/co-parent'),
|
||||||
|
headers: await _headers(),
|
||||||
|
body: jsonEncode(body),
|
||||||
|
);
|
||||||
|
} on http.ClientException {
|
||||||
|
throw Exception(
|
||||||
|
'Connexion au serveur impossible. Vérifiez votre réseau puis réessayez.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||||
|
if (response.body.trim().isEmpty) return <String, dynamic>{};
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(response.body);
|
||||||
|
if (decoded is Map) {
|
||||||
|
return Map<String, dynamic>.from(decoded);
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
return <String, dynamic>{};
|
||||||
|
}
|
||||||
|
|
||||||
|
final message = _extractErrorMessage(
|
||||||
|
response.body,
|
||||||
|
'Erreur ajout co-parent',
|
||||||
|
);
|
||||||
|
if (response.statusCode == 409) {
|
||||||
|
throw Exception(
|
||||||
|
message.isNotEmpty ? message : 'Conflit : e-mail déjà utilisé.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (response.statusCode == 400) {
|
||||||
|
throw Exception(
|
||||||
|
message.isNotEmpty ? message : 'Données invalides (400).',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw Exception(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Création dossier famille actif côté staff (#129).
|
||||||
|
/// `POST /parents/dossier` — body aligné sur register parent complet.
|
||||||
|
/// Succès 201 : dossier actif + `numero_dossier` (mail MDP côté serveur, par parent créé).
|
||||||
|
/// Ne pas utiliser `POST /auth/register/parent` (public / en_attente).
|
||||||
|
static Future<Map<String, dynamic>> createParentDossier(
|
||||||
|
Map<String, dynamic> body,
|
||||||
|
) async {
|
||||||
|
final http.Response response;
|
||||||
|
try {
|
||||||
|
response = await http.post(
|
||||||
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.parentsDossier}'),
|
||||||
|
headers: await _headers(),
|
||||||
|
body: jsonEncode(body),
|
||||||
|
);
|
||||||
|
} on http.ClientException {
|
||||||
|
throw Exception(
|
||||||
|
'Connexion au serveur impossible. Vérifiez votre réseau puis réessayez.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||||
|
if (response.body.trim().isEmpty) return <String, dynamic>{};
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(response.body);
|
||||||
|
if (decoded is Map) {
|
||||||
|
return Map<String, dynamic>.from(decoded);
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
return <String, dynamic>{};
|
||||||
|
}
|
||||||
|
|
||||||
|
final message = _extractErrorMessage(
|
||||||
|
response.body,
|
||||||
|
'Erreur création dossier famille',
|
||||||
|
);
|
||||||
|
if (response.statusCode == 409) {
|
||||||
|
throw Exception(
|
||||||
|
message.isNotEmpty ? message : 'Conflit : e-mail déjà utilisé.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (response.statusCode == 400) {
|
||||||
|
throw Exception(
|
||||||
|
message.isNotEmpty ? message : 'Données invalides (400).',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw Exception(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Création dossier AM actif côté staff (#156).
|
||||||
|
/// `POST /assistantes-maternelles/dossier` — body aligné sur register AM.
|
||||||
|
/// Succès 201 : dossier actif + `numero_dossier` (mail MDP côté serveur).
|
||||||
|
/// Ne pas utiliser `POST /auth/register/am` (public / en_attente).
|
||||||
|
static Future<Map<String, dynamic>> createAmDossier(
|
||||||
|
Map<String, dynamic> body,
|
||||||
|
) async {
|
||||||
|
final http.Response response;
|
||||||
|
try {
|
||||||
|
response = await http.post(
|
||||||
|
Uri.parse(
|
||||||
|
'${ApiConfig.baseUrl}${ApiConfig.assistantesMaternellesDossier}',
|
||||||
|
),
|
||||||
|
headers: await _headers(),
|
||||||
|
body: jsonEncode(body),
|
||||||
|
);
|
||||||
|
} on http.ClientException {
|
||||||
|
throw Exception(
|
||||||
|
'Connexion au serveur impossible. Vérifiez votre réseau puis réessayez.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||||
|
if (response.body.trim().isEmpty) return <String, dynamic>{};
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(response.body);
|
||||||
|
if (decoded is Map) {
|
||||||
|
return Map<String, dynamic>.from(decoded);
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
return <String, dynamic>{};
|
||||||
|
}
|
||||||
|
|
||||||
|
final message = _extractErrorMessage(
|
||||||
|
response.body,
|
||||||
|
'Erreur création dossier AM',
|
||||||
|
);
|
||||||
|
if (response.statusCode == 409) {
|
||||||
|
throw Exception(message.isNotEmpty
|
||||||
|
? message
|
||||||
|
: 'Conflit : e-mail, NIR ou agrément déjà utilisé.');
|
||||||
|
}
|
||||||
|
if (response.statusCode == 400) {
|
||||||
|
throw Exception(
|
||||||
|
message.isNotEmpty ? message : 'Données invalides (400).',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw Exception(message);
|
||||||
|
}
|
||||||
|
|
||||||
// Récupérer la liste des assistantes maternelles
|
// Récupérer la liste des assistantes maternelles
|
||||||
static Future<List<AssistanteMaternelleModel>>
|
static Future<List<AssistanteMaternelleModel>>
|
||||||
getAssistantesMaternelles() async {
|
getAssistantesMaternelles() async {
|
||||||
@@ -633,7 +1048,24 @@ class UserService {
|
|||||||
if (response.statusCode != 200 && response.statusCode != 201) {
|
if (response.statusCode != 200 && response.statusCode != 201) {
|
||||||
throw Exception(_extractErrorMessage(response.body, 'Erreur rattachement enfant'));
|
throw Exception(_extractErrorMessage(response.body, 'Erreur rattachement enfant'));
|
||||||
}
|
}
|
||||||
return _amModelFromBody(response.body);
|
final am = _amModelFromBody(response.body);
|
||||||
|
// Recalcule toujours places_available (capacité − enfants) après attachement.
|
||||||
|
return syncAmPlacesAvailable(am);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Aligne `places_available` sur capacité − enfants rattachés.
|
||||||
|
static Future<AssistanteMaternelleModel> syncAmPlacesAvailable(
|
||||||
|
AssistanteMaternelleModel am,
|
||||||
|
) async {
|
||||||
|
final expected = amExpectedPlacesAvailable(
|
||||||
|
maxChildren: am.maxChildren,
|
||||||
|
childrenCount: am.children.length,
|
||||||
|
);
|
||||||
|
if (expected == null || am.placesAvailable == expected) return am;
|
||||||
|
return updateAmFiche(
|
||||||
|
amUserId: am.user.id,
|
||||||
|
body: {'places_available': expected},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
static Future<AssistanteMaternelleModel> detachEnfantFromAm({
|
static Future<AssistanteMaternelleModel> detachEnfantFromAm({
|
||||||
@@ -871,22 +1303,18 @@ class UserService {
|
|||||||
return AppUser.fromJson(data);
|
return AppUser.fromJson(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
static Future<void> deleteUser(String userId) async {
|
/// DELETE /users/:id — cascades métier #159 / #160.
|
||||||
|
static Future<Map<String, dynamic>> deleteUser(String userId) async {
|
||||||
final response = await http.delete(
|
final response = await http.delete(
|
||||||
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.users}/$userId'),
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.users}/$userId'),
|
||||||
headers: await _headers(),
|
headers: await _headers(),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (response.statusCode != 200 && response.statusCode != 204) {
|
if (response.statusCode != 200 && response.statusCode != 204) {
|
||||||
final decoded = jsonDecode(response.body);
|
throw Exception(
|
||||||
if (decoded is Map<String, dynamic>) {
|
_extractErrorMessage(response.body, 'Erreur suppression utilisateur'),
|
||||||
final message = decoded['message'];
|
);
|
||||||
if (message is List && message.isNotEmpty) {
|
|
||||||
throw Exception(message.join(' - '));
|
|
||||||
}
|
|
||||||
throw Exception(_toStr(message) ?? 'Erreur suppression utilisateur');
|
|
||||||
}
|
|
||||||
throw Exception('Erreur suppression utilisateur');
|
|
||||||
}
|
}
|
||||||
|
return _parseSuppressionBody(response.body);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,18 @@ int? amExpectedPlacesAvailable({
|
|||||||
return (maxChildren - childrenCount).clamp(0, maxChildren);
|
return (maxChildren - childrenCount).clamp(0, maxChildren);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// True s'il reste au moins une place d'accueil (capacité − enfants).
|
||||||
|
bool amHasFreePlace(AssistanteMaternelleModel am) {
|
||||||
|
final expected = amExpectedPlacesAvailable(
|
||||||
|
maxChildren: am.maxChildren,
|
||||||
|
childrenCount: am.children.length,
|
||||||
|
);
|
||||||
|
if (expected != null) return expected > 0;
|
||||||
|
final places = am.placesAvailable;
|
||||||
|
if (places != null) return places > 0;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/// True si la valeur déclarée par l'AM ne correspond pas au calcul métier.
|
/// True si la valeur déclarée par l'AM ne correspond pas au calcul métier.
|
||||||
bool amHasPlacesInconsistency({
|
bool amHasPlacesInconsistency({
|
||||||
required int? maxChildren,
|
required int? maxChildren,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import 'package:flutter/services.dart';
|
||||||
import 'package:intl/intl.dart';
|
import 'package:intl/intl.dart';
|
||||||
import 'package:p_tits_pas/utils/enfant_status_utils.dart';
|
import 'package:p_tits_pas/utils/enfant_status_utils.dart';
|
||||||
|
|
||||||
@@ -11,10 +12,50 @@ String formatIsoDateFr(String? s, {String ifEmpty = '–'}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convertit `dd/MM/yyyy` (ou ISO) en `yyyy-MM-dd` pour l'API.
|
/// Affiche une date ISO en saisie guidée `jj / mm / aaaa`.
|
||||||
|
String formatIsoDateFrInput(String? s, {String ifEmpty = ''}) {
|
||||||
|
if (s == null || s.trim().isEmpty) return ifEmpty;
|
||||||
|
try {
|
||||||
|
final dt = DateTime.parse(s.trim());
|
||||||
|
return formatFrenchDateDigits(
|
||||||
|
DateFormat('ddMMyyyy').format(dt),
|
||||||
|
);
|
||||||
|
} catch (_) {
|
||||||
|
return formatFrenchDateDigits(s.replaceAll(RegExp(r'\D'), ''));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Formate jusqu’à 8 chiffres en `jj / mm / aaaa`.
|
||||||
|
String formatFrenchDateDigits(String digits) {
|
||||||
|
final d = digits.replaceAll(RegExp(r'\D'), '');
|
||||||
|
final limited = d.length > 8 ? d.substring(0, 8) : d;
|
||||||
|
final buf = StringBuffer();
|
||||||
|
for (var i = 0; i < limited.length; i++) {
|
||||||
|
if (i == 2 || i == 4) buf.write(' / ');
|
||||||
|
buf.write(limited[i]);
|
||||||
|
}
|
||||||
|
return buf.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convertit `dd/MM/yyyy`, `dd / MM / yyyy`, 8 chiffres ou ISO en `yyyy-MM-dd`.
|
||||||
String? parseFrDateToIso(String text) {
|
String? parseFrDateToIso(String text) {
|
||||||
final t = text.trim();
|
final t = text.trim();
|
||||||
if (t.isEmpty) return null;
|
if (t.isEmpty) return null;
|
||||||
|
|
||||||
|
final digits = t.replaceAll(RegExp(r'\D'), '');
|
||||||
|
if (digits.length == 8) {
|
||||||
|
final dd = digits.substring(0, 2);
|
||||||
|
final mm = digits.substring(2, 4);
|
||||||
|
final yyyy = digits.substring(4, 8);
|
||||||
|
try {
|
||||||
|
return DateFormat('dd/MM/yyyy')
|
||||||
|
.parseStrict('$dd/$mm/$yyyy')
|
||||||
|
.toIso8601String()
|
||||||
|
.split('T')
|
||||||
|
.first;
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return DateFormat('dd/MM/yyyy')
|
return DateFormat('dd/MM/yyyy')
|
||||||
.parseStrict(t)
|
.parseStrict(t)
|
||||||
@@ -96,3 +137,43 @@ String formatChildAgeLabel({
|
|||||||
return 'Né le ${formatIsoDateFr(birthDate)}';
|
return 'Né le ${formatIsoDateFr(birthDate)}';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Saisie date FR : 8 chiffres → `jj / mm / aaaa`.
|
||||||
|
class FrenchDateInputFormatter extends TextInputFormatter {
|
||||||
|
const FrenchDateInputFormatter();
|
||||||
|
|
||||||
|
@override
|
||||||
|
TextEditingValue formatEditUpdate(
|
||||||
|
TextEditingValue oldValue,
|
||||||
|
TextEditingValue newValue,
|
||||||
|
) {
|
||||||
|
final digits = newValue.text.replaceAll(RegExp(r'\D'), '');
|
||||||
|
final limited = digits.length > 8 ? digits.substring(0, 8) : digits;
|
||||||
|
final formatted = formatFrenchDateDigits(limited);
|
||||||
|
|
||||||
|
final digitsBeforeCursor = newValue.text
|
||||||
|
.substring(0, newValue.selection.start.clamp(0, newValue.text.length))
|
||||||
|
.replaceAll(RegExp(r'\D'), '')
|
||||||
|
.length
|
||||||
|
.clamp(0, limited.length);
|
||||||
|
|
||||||
|
return TextEditingValue(
|
||||||
|
text: formatted,
|
||||||
|
selection: TextSelection.collapsed(
|
||||||
|
offset: _cursorOffset(formatted, digitsBeforeCursor),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int _cursorOffset(String formatted, int digitsBeforeCursor) {
|
||||||
|
if (digitsBeforeCursor <= 0) return 0;
|
||||||
|
var seen = 0;
|
||||||
|
for (var i = 0; i < formatted.length; i++) {
|
||||||
|
if (RegExp(r'\d').hasMatch(formatted[i])) {
|
||||||
|
seen++;
|
||||||
|
if (seen >= digitsBeforeCursor) return i + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return formatted.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,10 +14,10 @@ String normalizeEnfantStatus(String? raw) {
|
|||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
String _scolariseAccordeAuGenre(String? gender) {
|
String _accordeAuGenre(String masculin, String feminin, String? gender) {
|
||||||
final g = (gender ?? '').trim().toUpperCase();
|
final g = (gender ?? '').trim().toUpperCase();
|
||||||
if (g == 'F') return 'Scolarisée';
|
if (g == 'F') return feminin;
|
||||||
return 'Scolarisé';
|
return masculin;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Libellé affiché pour un statut enfant.
|
/// Libellé affiché pour un statut enfant.
|
||||||
@@ -28,9 +28,9 @@ String enfantStatusLabel(String? status, {String? gender}) {
|
|||||||
case 'sans_garde':
|
case 'sans_garde':
|
||||||
return 'Sans garde';
|
return 'Sans garde';
|
||||||
case 'garde':
|
case 'garde':
|
||||||
return 'En garde';
|
return _accordeAuGenre('Gardé', 'Gardée', gender);
|
||||||
case 'scolarise':
|
case 'scolarise':
|
||||||
return _scolariseAccordeAuGenre(gender);
|
return _accordeAuGenre('Scolarisé', 'Scolarisée', gender);
|
||||||
default:
|
default:
|
||||||
return status?.trim().isNotEmpty == true ? status!.trim() : '–';
|
return status?.trim().isNotEmpty == true ? status!.trim() : '–';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import 'package:p_tits_pas/models/enfant_admin_model.dart';
|
||||||
|
|
||||||
|
/// Enfant sans lien parent (orphelins d’affiliation) — ticket #157.
|
||||||
|
bool enfantHasNoResponsable(EnfantAdminModel enfant) => enfant.hasNoResponsable;
|
||||||
|
|
||||||
|
/// Message vigilance liste Enfants (même usage que [amPlacesVigilanceMessage]).
|
||||||
|
String? enfantSansResponsableVigilanceMessage(EnfantAdminModel enfant) {
|
||||||
|
if (!enfantHasNoResponsable(enfant)) return null;
|
||||||
|
return 'Aucun responsable rattaché — à rattacher à un foyer';
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
/// Formatage affichage prénom / nom (capitalisation par mot et segments après `-` ou `'`).
|
/// Formatage affichage prénom / nom (capitalisation par mot et segments après `-` ou `'`).
|
||||||
|
|
||||||
String formatPersonNameCase(String raw) {
|
String formatPersonNameCase(String raw) {
|
||||||
@@ -9,6 +11,22 @@ String formatPersonNameCase(String raw) {
|
|||||||
return words.map(_capitalizeComposedWord).join(' ');
|
return words.map(_capitalizeComposedWord).join(' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Variante saisie live : pas de majuscule tant que le mot n’a qu’une lettre ;
|
||||||
|
/// dès la 2ᵉ lettre, capitalisation comme [formatPersonNameCase].
|
||||||
|
String formatPersonNameCaseTyping(String raw) {
|
||||||
|
if (raw.isEmpty) return raw;
|
||||||
|
final trailingMatch = RegExp(r'(\s*)$').firstMatch(raw);
|
||||||
|
final trailing = trailingMatch?.group(1) ?? '';
|
||||||
|
final core = raw.substring(0, raw.length - trailing.length);
|
||||||
|
if (core.isEmpty) return raw;
|
||||||
|
final words = core.split(RegExp(r'\s+'));
|
||||||
|
final formatted = words.map((w) {
|
||||||
|
if (w.length < 2) return w;
|
||||||
|
return _capitalizeComposedWord(w);
|
||||||
|
}).join(' ');
|
||||||
|
return formatted + trailing;
|
||||||
|
}
|
||||||
|
|
||||||
String _capitalizeComposedWord(String word) {
|
String _capitalizeComposedWord(String word) {
|
||||||
if (word.isEmpty) {
|
if (word.isEmpty) {
|
||||||
return word;
|
return word;
|
||||||
@@ -30,3 +48,26 @@ String _capitalizeComposedWord(String word) {
|
|||||||
}
|
}
|
||||||
return buffer.toString();
|
return buffer.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Formateur de saisie prénom / nom (capitalisation progressive).
|
||||||
|
class PersonNameInputFormatter extends TextInputFormatter {
|
||||||
|
const PersonNameInputFormatter();
|
||||||
|
|
||||||
|
@override
|
||||||
|
TextEditingValue formatEditUpdate(
|
||||||
|
TextEditingValue oldValue,
|
||||||
|
TextEditingValue newValue,
|
||||||
|
) {
|
||||||
|
final formatted = formatPersonNameCaseTyping(newValue.text);
|
||||||
|
if (formatted == newValue.text) return newValue;
|
||||||
|
|
||||||
|
final sel = newValue.selection;
|
||||||
|
final offset = sel.isValid
|
||||||
|
? sel.baseOffset.clamp(0, formatted.length)
|
||||||
|
: formatted.length;
|
||||||
|
return TextEditingValue(
|
||||||
|
text: formatted,
|
||||||
|
selection: TextSelection.collapsed(offset: offset),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -49,12 +49,21 @@ String nirToRaw(String normalized) {
|
|||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Formate pour affichage : 1 12 34 56 789 012 - 34 ou 1 12 34 2A 789 012 - 34 (Corse).
|
/// Formate pour affichage (complet ou en cours de saisie) :
|
||||||
|
/// `1 12 34 56 789 012 - 34` ou `1 12 34 2A 789 012 - 34` (Corse).
|
||||||
String formatNir(String raw) {
|
String formatNir(String raw) {
|
||||||
final r = nirToRaw(raw);
|
final r = nirToRaw(raw).toUpperCase();
|
||||||
if (r.length < 15) return r;
|
if (r.isEmpty) return '';
|
||||||
// Même structure pour tous : sexe + année + mois + département + commune + ordre-clé.
|
final buf = StringBuffer();
|
||||||
return '${r.substring(0, 1)} ${r.substring(1, 3)} ${r.substring(3, 5)} ${r.substring(5, 7)} ${r.substring(7, 10)} ${r.substring(10, 13)} - ${r.substring(13, 15)}';
|
for (var i = 0; i < r.length && i < 15; i++) {
|
||||||
|
if (i == 1 || i == 3 || i == 5 || i == 7 || i == 10) {
|
||||||
|
buf.write(' ');
|
||||||
|
} else if (i == 13) {
|
||||||
|
buf.write(' - ');
|
||||||
|
}
|
||||||
|
buf.write(r[i]);
|
||||||
|
}
|
||||||
|
return buf.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Aligné sur le backend (NIR côté API / nir.util.ts) : sexe 1–3, département 2A ou 2B pour la Corse.
|
/// Aligné sur le backend (NIR côté API / nir.util.ts) : sexe 1–3, département 2A ou 2B pour la Corse.
|
||||||
@@ -92,20 +101,39 @@ String? validateNir(String? value) {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Formateur de saisie : affiche le NIR formaté (1 12 34 56 789 012 - 34) et limite à 15 caractères utiles.
|
/// Validation pendant la saisie : pas d’erreur si incomplet encore plausible ;
|
||||||
|
/// dès 15 caractères, même contrôles que [validateNir].
|
||||||
|
String? validateNirTyping(String? value) {
|
||||||
|
if (value == null || value.trim().isEmpty) return null;
|
||||||
|
final raw = nirToRaw(value).toUpperCase();
|
||||||
|
if (raw.isEmpty) return null;
|
||||||
|
if (raw[0] != '1' && raw[0] != '2' && raw[0] != '3') {
|
||||||
|
return 'Format NIR invalide (ex. 1 12 34 56 789 012 - 34 ou 2A pour la Corse)';
|
||||||
|
}
|
||||||
|
if (raw.length < 15) return null;
|
||||||
|
return validateNir(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Formateur de saisie : affiche le NIR formaté au fil de la frappe et limite à 15 caractères utiles.
|
||||||
class NirInputFormatter extends TextInputFormatter {
|
class NirInputFormatter extends TextInputFormatter {
|
||||||
|
const NirInputFormatter();
|
||||||
|
|
||||||
@override
|
@override
|
||||||
TextEditingValue formatEditUpdate(
|
TextEditingValue formatEditUpdate(
|
||||||
TextEditingValue oldValue,
|
TextEditingValue oldValue,
|
||||||
TextEditingValue newValue,
|
TextEditingValue newValue,
|
||||||
) {
|
) {
|
||||||
final raw = normalizeNir(newValue.text);
|
final raw = normalizeNir(newValue.text);
|
||||||
if (raw.isEmpty) return newValue;
|
if (raw.isEmpty) {
|
||||||
|
return const TextEditingValue(
|
||||||
|
text: '',
|
||||||
|
selection: TextSelection.collapsed(offset: 0),
|
||||||
|
);
|
||||||
|
}
|
||||||
final formatted = formatNir(raw);
|
final formatted = formatNir(raw);
|
||||||
final offset = formatted.length;
|
|
||||||
return TextEditingValue(
|
return TextEditingValue(
|
||||||
text: formatted,
|
text: formatted,
|
||||||
selection: TextSelection.collapsed(offset: offset),
|
selection: TextSelection.collapsed(offset: formatted.length),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -166,7 +166,7 @@ class ParentRegistrationPayload {
|
|||||||
static Map<String, dynamic> _childToJson(ChildData c, int index, String parentNom) {
|
static Map<String, dynamic> _childToJson(ChildData c, int index, String parentNom) {
|
||||||
final map = <String, dynamic>{
|
final map = <String, dynamic>{
|
||||||
'genre': apiGenres.contains(c.genre) ? c.genre : 'Autre',
|
'genre': apiGenres.contains(c.genre) ? c.genre : 'Autre',
|
||||||
'grossesse_multiple': c.multipleBirth,
|
'consent_photo': c.photoConsent,
|
||||||
};
|
};
|
||||||
|
|
||||||
final prenom = c.firstName.trim();
|
final prenom = c.firstName.trim();
|
||||||
|
|||||||
@@ -38,16 +38,12 @@ class RepriseMapper {
|
|||||||
? isoToDdMmYyyy(e.dueDate)
|
? isoToDdMmYyyy(e.dueDate)
|
||||||
: isoToDdMmYyyy(e.birthDate);
|
: isoToDdMmYyyy(e.birthDate);
|
||||||
final photo = e.photoUrl?.trim();
|
final photo = e.photoUrl?.trim();
|
||||||
final hasPhoto = photo != null && photo.isNotEmpty;
|
|
||||||
return ChildData(
|
return ChildData(
|
||||||
firstName: e.firstName ?? '',
|
firstName: e.firstName ?? '',
|
||||||
lastName: e.lastName ?? '',
|
lastName: e.lastName ?? '',
|
||||||
dob: dob,
|
dob: dob,
|
||||||
genre: e.gender ?? '',
|
genre: e.gender ?? '',
|
||||||
// Inscription initiale exigeait la coche pour envoyer la photo ; le back
|
photoConsent: e.consentPhoto,
|
||||||
// ne persistait pas toujours consent_photo — on pré-coche si photo en base.
|
|
||||||
photoConsent: e.consentPhoto || hasPhoto,
|
|
||||||
multipleBirth: e.estMultiple,
|
|
||||||
isUnbornChild: isUnborn,
|
isUnbornChild: isUnborn,
|
||||||
cardColor: _childCardColors[index % _childCardColors.length],
|
cardColor: _childCardColors[index % _childCardColors.length],
|
||||||
repriseChildId: e.id,
|
repriseChildId: e.id,
|
||||||
@@ -200,7 +196,7 @@ class RepriseMapper {
|
|||||||
postalCode: dossier.codePostal ?? '',
|
postalCode: dossier.codePostal ?? '',
|
||||||
city: dossier.ville ?? '',
|
city: dossier.ville ?? '',
|
||||||
existingPhotoUrl: displayPhoto,
|
existingPhotoUrl: displayPhoto,
|
||||||
consentementPhoto: dossier.consentementPhoto || hasPhoto,
|
consentementPhoto: dossier.consentementPhoto,
|
||||||
dateOfBirth: parseIsoDate(dossier.dateNaissance),
|
dateOfBirth: parseIsoDate(dossier.dateNaissance),
|
||||||
birthCity: dossier.lieuNaissanceVille ?? '',
|
birthCity: dossier.lieuNaissanceVille ?? '',
|
||||||
birthCountry: dossier.lieuNaissancePays ?? '',
|
birthCountry: dossier.lieuNaissancePays ?? '',
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
/// Création comptes staff (gestionnaire / admin) — ticket #161.
|
||||||
|
bool canCreateStaffAccounts(String? role) {
|
||||||
|
final r = (role ?? '').trim().toLowerCase();
|
||||||
|
return r == 'administrateur' || r == 'super_admin';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Droits d’affichage poubelle — tickets #154 / #160.
|
||||||
|
bool canDeleteMetier(String? role) {
|
||||||
|
final r = (role ?? '').trim().toLowerCase();
|
||||||
|
return r == 'gestionnaire' ||
|
||||||
|
r == 'administrateur' ||
|
||||||
|
r == 'super_admin';
|
||||||
|
}
|
||||||
|
|
||||||
|
bool canDeleteGestionnaire(String? role) {
|
||||||
|
final r = (role ?? '').trim().toLowerCase();
|
||||||
|
return r == 'administrateur' || r == 'super_admin';
|
||||||
|
}
|
||||||
|
|
||||||
|
bool canDeleteAdministrateur({
|
||||||
|
required String? currentRole,
|
||||||
|
required String? currentUserId,
|
||||||
|
required String targetUserId,
|
||||||
|
required String targetRole,
|
||||||
|
required int adminCount,
|
||||||
|
}) {
|
||||||
|
final me = (currentRole ?? '').trim().toLowerCase();
|
||||||
|
if (me != 'administrateur' && me != 'super_admin') return false;
|
||||||
|
if (targetUserId.trim().isEmpty) return false;
|
||||||
|
if (currentUserId != null &&
|
||||||
|
currentUserId.trim() == targetUserId.trim()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
final target = targetRole.trim().toLowerCase();
|
||||||
|
if (target == 'super_admin') return false;
|
||||||
|
if (adminCount <= 1 && me != 'super_admin') return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
String? adminDeleteBlockedReason({
|
||||||
|
required String? currentRole,
|
||||||
|
required String? currentUserId,
|
||||||
|
required String targetUserId,
|
||||||
|
required String targetRole,
|
||||||
|
required int adminCount,
|
||||||
|
}) {
|
||||||
|
if (currentUserId != null &&
|
||||||
|
currentUserId.trim() == targetUserId.trim()) {
|
||||||
|
return 'Vous ne pouvez pas supprimer votre propre compte.';
|
||||||
|
}
|
||||||
|
if (targetRole.trim().toLowerCase() == 'super_admin') {
|
||||||
|
return 'Le super administrateur ne peut pas être supprimé.';
|
||||||
|
}
|
||||||
|
if (adminCount <= 1 &&
|
||||||
|
(currentRole ?? '').trim().toLowerCase() != 'super_admin') {
|
||||||
|
return 'Seul un super administrateur peut supprimer le dernier administrateur.';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -4,8 +4,10 @@ import 'package:p_tits_pas/utils/phone_utils.dart';
|
|||||||
import 'package:p_tits_pas/screens/administrateurs/creation/gestionnaires_create.dart';
|
import 'package:p_tits_pas/screens/administrateurs/creation/gestionnaires_create.dart';
|
||||||
import 'package:p_tits_pas/services/auth_service.dart';
|
import 'package:p_tits_pas/services/auth_service.dart';
|
||||||
import 'package:p_tits_pas/services/user_service.dart';
|
import 'package:p_tits_pas/services/user_service.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/common/admin_user_card.dart';
|
import 'package:p_tits_pas/utils/staff_deletion_rights.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/common/user_list.dart';
|
import 'package:p_tits_pas/widgets/dashboard/user_card.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/dashboard/common/suppression_confirm_dialog.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/dashboard/common/user_list.dart';
|
||||||
|
|
||||||
class AdminManagementWidget extends StatefulWidget {
|
class AdminManagementWidget extends StatefulWidget {
|
||||||
final String searchQuery;
|
final String searchQuery;
|
||||||
@@ -24,6 +26,7 @@ class _AdminManagementWidgetState extends State<AdminManagementWidget> {
|
|||||||
String? _error;
|
String? _error;
|
||||||
List<AppUser> _admins = [];
|
List<AppUser> _admins = [];
|
||||||
String? _currentUserRole;
|
String? _currentUserRole;
|
||||||
|
String? _currentUserId;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@@ -62,6 +65,7 @@ class _AdminManagementWidgetState extends State<AdminManagementWidget> {
|
|||||||
if (cached != null) {
|
if (cached != null) {
|
||||||
setState(() {
|
setState(() {
|
||||||
_currentUserRole = (cached.role).toLowerCase();
|
_currentUserRole = (cached.role).toLowerCase();
|
||||||
|
_currentUserId = cached.id;
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -69,6 +73,7 @@ class _AdminManagementWidgetState extends State<AdminManagementWidget> {
|
|||||||
if (!mounted || refreshed == null) return;
|
if (!mounted || refreshed == null) return;
|
||||||
setState(() {
|
setState(() {
|
||||||
_currentUserRole = (refreshed.role).toLowerCase();
|
_currentUserRole = (refreshed.role).toLowerCase();
|
||||||
|
_currentUserId = refreshed.id;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,6 +84,16 @@ class _AdminManagementWidgetState extends State<AdminManagementWidget> {
|
|||||||
return _currentUserRole == 'super_admin';
|
return _currentUserRole == 'super_admin';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool _canDeleteAdmin(AppUser target) {
|
||||||
|
return canDeleteAdministrateur(
|
||||||
|
currentRole: _currentUserRole,
|
||||||
|
currentUserId: _currentUserId,
|
||||||
|
targetUserId: target.id,
|
||||||
|
targetRole: target.role,
|
||||||
|
adminCount: _admins.length,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _openAdminEditDialog(AppUser user) async {
|
Future<void> _openAdminEditDialog(AppUser user) async {
|
||||||
final canEdit = _canEditAdmin(user);
|
final canEdit = _canEditAdmin(user);
|
||||||
final changed = await showDialog<bool>(
|
final changed = await showDialog<bool>(
|
||||||
@@ -98,6 +113,56 @@ class _AdminManagementWidgetState extends State<AdminManagementWidget> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _confirmDelete(AppUser user) async {
|
||||||
|
final blocked = adminDeleteBlockedReason(
|
||||||
|
currentRole: _currentUserRole,
|
||||||
|
currentUserId: _currentUserId,
|
||||||
|
targetUserId: user.id,
|
||||||
|
targetRole: user.role,
|
||||||
|
adminCount: _admins.length,
|
||||||
|
);
|
||||||
|
if (blocked != null) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text(blocked)),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final name = user.fullName.isNotEmpty ? user.fullName : user.email;
|
||||||
|
final isLast = _admins.length <= 1;
|
||||||
|
final confirmed = await showSuppressionConfirmDialog(
|
||||||
|
context,
|
||||||
|
title: 'Supprimer l\'administrateur',
|
||||||
|
people: [SuppressionPersonLine.administrateur(name)],
|
||||||
|
footnotes: [
|
||||||
|
if (isLast)
|
||||||
|
'Attention : c’est le dernier administrateur.',
|
||||||
|
'Le compte sera définitivement supprimé.',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
if (!confirmed || !mounted) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
final result = await UserService.deleteUser(user.id);
|
||||||
|
if (!mounted) return;
|
||||||
|
final msg =
|
||||||
|
(result['message'] ?? 'Administrateur supprimé.').toString();
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(msg)));
|
||||||
|
await _loadAdmins();
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(
|
||||||
|
e is Exception
|
||||||
|
? e.toString().replaceFirst('Exception: ', '')
|
||||||
|
: 'Erreur suppression',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final query = widget.searchQuery.toLowerCase();
|
final query = widget.searchQuery.toLowerCase();
|
||||||
@@ -117,7 +182,8 @@ class _AdminManagementWidgetState extends State<AdminManagementWidget> {
|
|||||||
final user = filteredAdmins[index];
|
final user = filteredAdmins[index];
|
||||||
final isSuperAdmin = _isSuperAdmin(user);
|
final isSuperAdmin = _isSuperAdmin(user);
|
||||||
final canEdit = _canEditAdmin(user);
|
final canEdit = _canEditAdmin(user);
|
||||||
return AdminUserCard(
|
final canDelete = _canDeleteAdmin(user);
|
||||||
|
return UserCard(
|
||||||
title: user.fullName,
|
title: user.fullName,
|
||||||
fallbackIcon: isSuperAdmin
|
fallbackIcon: isSuperAdmin
|
||||||
? Icons.verified_user_outlined
|
? Icons.verified_user_outlined
|
||||||
@@ -148,6 +214,8 @@ class _AdminManagementWidgetState extends State<AdminManagementWidget> {
|
|||||||
_openAdminEditDialog(user);
|
_openAdminEditDialog(user);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
if (canDelete)
|
||||||
|
suppressionIconButton(onPressed: () => _confirmDelete(user)),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,411 +0,0 @@
|
|||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:p_tits_pas/models/enfant_admin_model.dart';
|
|
||||||
import 'package:p_tits_pas/services/user_service.dart';
|
|
||||||
import 'package:p_tits_pas/utils/enfant_status_utils.dart';
|
|
||||||
|
|
||||||
/// Fiche enfant consultation / édition (ticket #138).
|
|
||||||
class AdminChildDetailModal extends StatefulWidget {
|
|
||||||
final EnfantAdminModel enfant;
|
|
||||||
final VoidCallback? onSaved;
|
|
||||||
|
|
||||||
const AdminChildDetailModal({
|
|
||||||
super.key,
|
|
||||||
required this.enfant,
|
|
||||||
this.onSaved,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<AdminChildDetailModal> createState() => _AdminChildDetailModalState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _AdminChildDetailModalState extends State<AdminChildDetailModal> {
|
|
||||||
late final TextEditingController _prenomCtrl;
|
|
||||||
late final TextEditingController _nomCtrl;
|
|
||||||
late final TextEditingController _birthCtrl;
|
|
||||||
late final TextEditingController _dueCtrl;
|
|
||||||
late String _status;
|
|
||||||
late String _gender;
|
|
||||||
late bool _consentPhoto;
|
|
||||||
late bool _isMultiple;
|
|
||||||
bool _dirty = false;
|
|
||||||
bool _saving = false;
|
|
||||||
|
|
||||||
static const _genders = ['H', 'F', 'Autre'];
|
|
||||||
|
|
||||||
static const _labelStyle = TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
color: Colors.black87,
|
|
||||||
);
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
final e = widget.enfant;
|
|
||||||
_prenomCtrl = TextEditingController(text: e.firstName ?? '');
|
|
||||||
_nomCtrl = TextEditingController(text: e.lastName ?? '');
|
|
||||||
_birthCtrl = TextEditingController(text: e.birthDate ?? '');
|
|
||||||
_dueCtrl = TextEditingController(text: e.dueDate ?? '');
|
|
||||||
_status = normalizeEnfantStatus(e.status);
|
|
||||||
if (!enfantStatusValues.contains(_status)) {
|
|
||||||
_status = 'sans_garde';
|
|
||||||
}
|
|
||||||
_gender = _normalizeGender(e.gender);
|
|
||||||
_consentPhoto = e.consentPhoto;
|
|
||||||
_isMultiple = e.isMultiple;
|
|
||||||
for (final c in [_prenomCtrl, _nomCtrl, _birthCtrl, _dueCtrl]) {
|
|
||||||
c.addListener(_markDirty);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
for (final c in [_prenomCtrl, _nomCtrl, _birthCtrl, _dueCtrl]) {
|
|
||||||
c.dispose();
|
|
||||||
}
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
static String _normalizeGender(String? raw) {
|
|
||||||
final g = (raw ?? '').trim();
|
|
||||||
if (g == 'M') return 'H';
|
|
||||||
if (_genders.contains(g)) return g;
|
|
||||||
return 'H';
|
|
||||||
}
|
|
||||||
|
|
||||||
void _markDirty() {
|
|
||||||
if (!_dirty) setState(() => _dirty = true);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _save() async {
|
|
||||||
if (!_dirty) return;
|
|
||||||
setState(() => _saving = true);
|
|
||||||
try {
|
|
||||||
await UserService.updateEnfant(
|
|
||||||
enfantId: widget.enfant.id,
|
|
||||||
body: {
|
|
||||||
'first_name': _prenomCtrl.text.trim(),
|
|
||||||
'last_name': _nomCtrl.text.trim(),
|
|
||||||
'status': _status,
|
|
||||||
'gender': _gender,
|
|
||||||
if (_birthCtrl.text.trim().isNotEmpty)
|
|
||||||
'birth_date': _birthCtrl.text.trim(),
|
|
||||||
if (_dueCtrl.text.trim().isNotEmpty) 'due_date': _dueCtrl.text.trim(),
|
|
||||||
'consent_photo': _consentPhoto,
|
|
||||||
'is_multiple': _isMultiple,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
_dirty = false;
|
|
||||||
_saving = false;
|
|
||||||
});
|
|
||||||
widget.onSaved?.call();
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(content: Text('Fiche enfant enregistrée')),
|
|
||||||
);
|
|
||||||
} catch (e) {
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() => _saving = false);
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(content: Text(e.toString().replaceFirst('Exception: ', ''))),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String _parentsLine() {
|
|
||||||
final names = widget.enfant.parentLinks
|
|
||||||
.map((l) {
|
|
||||||
final n = (l.parentName ?? '').trim();
|
|
||||||
return n.isNotEmpty ? n : 'Parent rattaché';
|
|
||||||
})
|
|
||||||
.where((s) => s.isNotEmpty)
|
|
||||||
.toList();
|
|
||||||
if (names.isEmpty) return '';
|
|
||||||
return names.join(', ');
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final parents = _parentsLine();
|
|
||||||
final showDueDate = _status == 'a_naitre';
|
|
||||||
|
|
||||||
return Dialog(
|
|
||||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
|
||||||
child: SizedBox(
|
|
||||||
width: 480,
|
|
||||||
child: ConstrainedBox(
|
|
||||||
constraints: const BoxConstraints(maxHeight: 640),
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(20),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
widget.enfant.fullName,
|
|
||||||
style: const TextStyle(
|
|
||||||
fontSize: 18,
|
|
||||||
fontWeight: FontWeight.w700,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (parents.isNotEmpty) ...[
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
'Responsables : $parents',
|
|
||||||
style: const TextStyle(
|
|
||||||
fontSize: 13,
|
|
||||||
color: Colors.black54,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
IconButton(
|
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
|
||||||
icon: const Icon(Icons.close),
|
|
||||||
tooltip: 'Fermer',
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
const Divider(height: 1),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Flexible(
|
|
||||||
child: SingleChildScrollView(
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
Row(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: _labeledField(
|
|
||||||
'Prénom',
|
|
||||||
TextField(
|
|
||||||
controller: _prenomCtrl,
|
|
||||||
decoration: _decoration(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
Expanded(
|
|
||||||
child: _labeledField(
|
|
||||||
'Nom',
|
|
||||||
TextField(
|
|
||||||
controller: _nomCtrl,
|
|
||||||
decoration: _decoration(),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Row(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: _labeledDropdown(
|
|
||||||
'Statut',
|
|
||||||
_status,
|
|
||||||
enfantStatusValues
|
|
||||||
.map(
|
|
||||||
(s) => MapEntry(
|
|
||||||
s,
|
|
||||||
enfantStatusLabel(s, gender: _gender),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.toList(),
|
|
||||||
(v) => setState(() {
|
|
||||||
_status = v;
|
|
||||||
_dirty = true;
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
Expanded(
|
|
||||||
child: _labeledDropdown(
|
|
||||||
'Genre',
|
|
||||||
_gender,
|
|
||||||
_genders
|
|
||||||
.map((g) => MapEntry(g, _genderLabel(g)))
|
|
||||||
.toList(),
|
|
||||||
(v) => setState(() {
|
|
||||||
_gender = v;
|
|
||||||
_dirty = true;
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
if (showDueDate)
|
|
||||||
Row(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: _labeledField(
|
|
||||||
'Date de naissance',
|
|
||||||
TextField(
|
|
||||||
controller: _birthCtrl,
|
|
||||||
decoration:
|
|
||||||
_decoration(hint: 'AAAA-MM-JJ'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
Expanded(
|
|
||||||
child: _labeledField(
|
|
||||||
'Date prévue',
|
|
||||||
TextField(
|
|
||||||
controller: _dueCtrl,
|
|
||||||
decoration:
|
|
||||||
_decoration(hint: 'AAAA-MM-JJ'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
else
|
|
||||||
_labeledField(
|
|
||||||
'Date de naissance',
|
|
||||||
TextField(
|
|
||||||
controller: _birthCtrl,
|
|
||||||
decoration: _decoration(hint: 'AAAA-MM-JJ'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
_switchRow(
|
|
||||||
'Consentement photo',
|
|
||||||
_consentPhoto,
|
|
||||||
(v) => setState(() {
|
|
||||||
_consentPhoto = v;
|
|
||||||
_dirty = true;
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
_switchRow(
|
|
||||||
'Naissance multiple',
|
|
||||||
_isMultiple,
|
|
||||||
(v) => setState(() {
|
|
||||||
_isMultiple = v;
|
|
||||||
_dirty = true;
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Row(
|
|
||||||
mainAxisAlignment: MainAxisAlignment.end,
|
|
||||||
children: [
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => Navigator.of(context).pop(),
|
|
||||||
child: const Text('Fermer'),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
ElevatedButton.icon(
|
|
||||||
onPressed: !_dirty || _saving ? null : _save,
|
|
||||||
icon: _saving
|
|
||||||
? const SizedBox(
|
|
||||||
width: 16,
|
|
||||||
height: 16,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
|
||||||
)
|
|
||||||
: const Icon(Icons.save),
|
|
||||||
label: const Text('Sauvegarder'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
InputDecoration _decoration({String? hint}) {
|
|
||||||
return InputDecoration(
|
|
||||||
isDense: true,
|
|
||||||
border: const OutlineInputBorder(),
|
|
||||||
hintText: hint,
|
|
||||||
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _labeledField(String label, Widget field) {
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
Text(label, style: _labelStyle),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
field,
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _labeledDropdown(
|
|
||||||
String label,
|
|
||||||
String value,
|
|
||||||
List<MapEntry<String, String>> items,
|
|
||||||
ValueChanged<String> onChanged,
|
|
||||||
) {
|
|
||||||
final safeValue =
|
|
||||||
items.any((e) => e.key == value) ? value : items.first.key;
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
Text(label, style: _labelStyle),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
DropdownButtonFormField<String>(
|
|
||||||
value: safeValue,
|
|
||||||
isExpanded: true,
|
|
||||||
decoration: _decoration(),
|
|
||||||
items: items
|
|
||||||
.map((e) => DropdownMenuItem(value: e.key, child: Text(e.value)))
|
|
||||||
.toList(),
|
|
||||||
onChanged: (v) {
|
|
||||||
if (v != null) onChanged(v);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _switchRow(String label, bool value, ValueChanged<bool> onChanged) {
|
|
||||||
return Padding(
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Expanded(child: Text(label, style: _labelStyle)),
|
|
||||||
Switch(
|
|
||||||
value: value,
|
|
||||||
onChanged: onChanged,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
String _genderLabel(String gender) {
|
|
||||||
switch (gender) {
|
|
||||||
case 'H':
|
|
||||||
return 'Garçon';
|
|
||||||
case 'F':
|
|
||||||
return 'Fille';
|
|
||||||
case 'Autre':
|
|
||||||
return 'Autre';
|
|
||||||
default:
|
|
||||||
return gender;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,406 +0,0 @@
|
|||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
|
||||||
import 'admin_detail_modal.dart';
|
|
||||||
|
|
||||||
/// Bloc type formulaire (titre de section + champs read-only) pour les modales de validation.
|
|
||||||
/// [rowLayout] : même disposition que la création de compte, ex. [2, 2, 1, 2] = ligne de 2, ligne de 2, plein largeur, ligne de 2.
|
|
||||||
/// [rowFlex] : flex par index de ligne (optionnel). Ex. {3: [2, 5]} = 4e ligne : code postal étroit (2), ville large (5).
|
|
||||||
class ValidationDetailSection extends StatelessWidget {
|
|
||||||
/// Si null ou vide, pas de bandeau titre (gain de place vertical, ex. wizard AM).
|
|
||||||
final String? title;
|
|
||||||
final List<AdminDetailField> fields;
|
|
||||||
|
|
||||||
/// Nombre de champs par ligne (1 = plein largeur, 2 = deux côte à côte). Ex. [2, 2, 1, 2] pour identité.
|
|
||||||
final List<int>? rowLayout;
|
|
||||||
|
|
||||||
/// Flex par ligne (index de ligne -> [flex1, flex2, ...]). Ex. {3: [2, 5]} pour Code postal | Ville.
|
|
||||||
final Map<int, List<int>>? rowFlex;
|
|
||||||
|
|
||||||
const ValidationDetailSection({
|
|
||||||
super.key,
|
|
||||||
this.title,
|
|
||||||
required this.fields,
|
|
||||||
this.rowLayout,
|
|
||||||
this.rowFlex,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return ValidationFormGrid(
|
|
||||||
title: title,
|
|
||||||
rowLayout: rowLayout,
|
|
||||||
rowFlex: rowFlex,
|
|
||||||
fields: fields
|
|
||||||
.map(
|
|
||||||
(f) => ValidationLabeledField(
|
|
||||||
label: f.label,
|
|
||||||
field: ValidationReadOnlyField(value: f.value),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.toList(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Grille label/champ réutilisable (validation, fiches admin).
|
|
||||||
class ValidationFormGrid extends StatelessWidget {
|
|
||||||
final String? title;
|
|
||||||
final List<ValidationLabeledField> fields;
|
|
||||||
final List<int>? rowLayout;
|
|
||||||
final Map<int, List<int>>? rowFlex;
|
|
||||||
final bool compact;
|
|
||||||
|
|
||||||
const ValidationFormGrid({
|
|
||||||
super.key,
|
|
||||||
this.title,
|
|
||||||
required this.fields,
|
|
||||||
this.rowLayout,
|
|
||||||
this.rowFlex,
|
|
||||||
this.compact = false,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final layout = rowLayout ?? List.filled(fields.length, 1);
|
|
||||||
int index = 0;
|
|
||||||
int rowIndex = 0;
|
|
||||||
final rows = <Widget>[];
|
|
||||||
for (final count in layout) {
|
|
||||||
if (index >= fields.length) break;
|
|
||||||
final rowFields = fields.skip(index).take(count).toList();
|
|
||||||
index += count;
|
|
||||||
if (rowFields.isEmpty) continue;
|
|
||||||
final flexForRow = rowFlex?[rowIndex];
|
|
||||||
rowIndex++;
|
|
||||||
if (count == 1) {
|
|
||||||
rows.add(Padding(
|
|
||||||
padding: EdgeInsets.only(bottom: compact ? 8 : 12),
|
|
||||||
child: rowFields.first,
|
|
||||||
));
|
|
||||||
} else {
|
|
||||||
rows.add(Padding(
|
|
||||||
padding: EdgeInsets.only(bottom: compact ? 8 : 12),
|
|
||||||
child: Row(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
for (int i = 0; i < rowFields.length; i++) ...[
|
|
||||||
if (i > 0) SizedBox(width: compact ? 12 : 16),
|
|
||||||
Expanded(
|
|
||||||
flex: (flexForRow != null && i < flexForRow.length)
|
|
||||||
? flexForRow[i]
|
|
||||||
: 1,
|
|
||||||
child: rowFields[i],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
final showTitle = title != null && title!.trim().isNotEmpty;
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
if (showTitle) ...[
|
|
||||||
Text(
|
|
||||||
title!.trim(),
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: compact ? 15 : 16,
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
color: Colors.black87,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
SizedBox(height: compact ? 8 : 12),
|
|
||||||
],
|
|
||||||
...rows,
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Décoration commune lecture seule / édition (modales validation, fiches admin).
|
|
||||||
class ValidationFieldDecoration {
|
|
||||||
ValidationFieldDecoration._();
|
|
||||||
|
|
||||||
static InputDecoration input({String? hint, bool compact = false}) {
|
|
||||||
return InputDecoration(
|
|
||||||
isDense: true,
|
|
||||||
filled: true,
|
|
||||||
fillColor: Colors.grey.shade50,
|
|
||||||
hintText: hint,
|
|
||||||
contentPadding: EdgeInsets.symmetric(
|
|
||||||
horizontal: compact ? 10 : 12,
|
|
||||||
vertical: compact ? 7 : 10,
|
|
||||||
),
|
|
||||||
border: OutlineInputBorder(
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
borderSide: BorderSide(color: Colors.grey.shade300),
|
|
||||||
),
|
|
||||||
enabledBorder: OutlineInputBorder(
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
borderSide: BorderSide(color: Colors.grey.shade300),
|
|
||||||
),
|
|
||||||
focusedBorder: OutlineInputBorder(
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
borderSide: BorderSide(color: Colors.grey.shade500),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
static InputDecoration readOnly({bool error = false, bool compact = false}) {
|
|
||||||
final borderColor = error ? Colors.red.shade400 : Colors.grey.shade300;
|
|
||||||
final fillColor = error ? Colors.red.shade50 : Colors.grey.shade50;
|
|
||||||
return input(compact: compact).copyWith(
|
|
||||||
filled: true,
|
|
||||||
fillColor: fillColor,
|
|
||||||
enabledBorder: OutlineInputBorder(
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
borderSide: BorderSide(color: borderColor),
|
|
||||||
),
|
|
||||||
focusedBorder: OutlineInputBorder(
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
borderSide: BorderSide(color: borderColor),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
static BoxDecoration container({bool error = false}) {
|
|
||||||
return BoxDecoration(
|
|
||||||
color: error ? Colors.red.shade50 : Colors.grey.shade50,
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
border: Border.all(
|
|
||||||
color: error ? Colors.red.shade400 : Colors.grey.shade300,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Libellé au-dessus d’un champ (même typo que [ValidationDetailSection]).
|
|
||||||
class ValidationLabeledField extends StatelessWidget {
|
|
||||||
final String label;
|
|
||||||
final Widget field;
|
|
||||||
|
|
||||||
const ValidationLabeledField({
|
|
||||||
super.key,
|
|
||||||
required this.label,
|
|
||||||
required this.field,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
label,
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
fontWeight: FontWeight.w500,
|
|
||||||
color: Colors.grey.shade700,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
field,
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Champ texte éditable, même rendu que [ValidationReadOnlyField].
|
|
||||||
class ValidationEditableField extends StatelessWidget {
|
|
||||||
final TextEditingController controller;
|
|
||||||
final TextInputType keyboardType;
|
|
||||||
final List<TextInputFormatter>? inputFormatters;
|
|
||||||
final String? hintText;
|
|
||||||
final int maxLines;
|
|
||||||
final bool compact;
|
|
||||||
|
|
||||||
const ValidationEditableField({
|
|
||||||
super.key,
|
|
||||||
required this.controller,
|
|
||||||
this.keyboardType = TextInputType.text,
|
|
||||||
this.inputFormatters,
|
|
||||||
this.hintText,
|
|
||||||
this.maxLines = 1,
|
|
||||||
this.compact = false,
|
|
||||||
});
|
|
||||||
|
|
||||||
static const double _compactFieldHeight = 34;
|
|
||||||
|
|
||||||
static BoxDecoration _compactDecoration({bool error = false}) {
|
|
||||||
return BoxDecoration(
|
|
||||||
color: error ? Colors.red.shade50 : Colors.grey.shade50,
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
border: Border.all(
|
|
||||||
color: error ? Colors.red.shade400 : Colors.grey.shade300,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
static InputDecoration _compactInputDecoration({String? hint}) {
|
|
||||||
return InputDecoration(
|
|
||||||
isDense: true,
|
|
||||||
filled: false,
|
|
||||||
hintText: hint,
|
|
||||||
border: InputBorder.none,
|
|
||||||
enabledBorder: InputBorder.none,
|
|
||||||
focusedBorder: InputBorder.none,
|
|
||||||
contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
if (maxLines > 1) {
|
|
||||||
return TextField(
|
|
||||||
controller: controller,
|
|
||||||
keyboardType: keyboardType,
|
|
||||||
inputFormatters: inputFormatters,
|
|
||||||
maxLines: maxLines,
|
|
||||||
style: const TextStyle(color: Colors.black87, fontSize: 14),
|
|
||||||
decoration: ValidationFieldDecoration.input(hint: hintText),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (!compact) {
|
|
||||||
return TextField(
|
|
||||||
controller: controller,
|
|
||||||
keyboardType: keyboardType,
|
|
||||||
inputFormatters: inputFormatters,
|
|
||||||
maxLines: 1,
|
|
||||||
style: const TextStyle(color: Colors.black87, fontSize: 14),
|
|
||||||
decoration: ValidationFieldDecoration.input(hint: hintText),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return SizedBox(
|
|
||||||
height: _compactFieldHeight,
|
|
||||||
child: DecoratedBox(
|
|
||||||
decoration: _compactDecoration(),
|
|
||||||
child: TextField(
|
|
||||||
controller: controller,
|
|
||||||
keyboardType: keyboardType,
|
|
||||||
inputFormatters: inputFormatters,
|
|
||||||
maxLines: 1,
|
|
||||||
textAlignVertical: TextAlignVertical.center,
|
|
||||||
style: const TextStyle(
|
|
||||||
color: Colors.black87,
|
|
||||||
fontSize: 13,
|
|
||||||
height: 1.0,
|
|
||||||
),
|
|
||||||
decoration: _compactInputDecoration(hint: hintText),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Grille label/champ éditable (délègue à [ValidationFormGrid]).
|
|
||||||
class ValidationEditableSection extends StatelessWidget {
|
|
||||||
final List<ValidationLabeledField> fields;
|
|
||||||
final List<int>? rowLayout;
|
|
||||||
final Map<int, List<int>>? rowFlex;
|
|
||||||
final bool compact;
|
|
||||||
|
|
||||||
const ValidationEditableSection({
|
|
||||||
super.key,
|
|
||||||
required this.fields,
|
|
||||||
this.rowLayout,
|
|
||||||
this.rowFlex,
|
|
||||||
this.compact = false,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return ValidationFormGrid(
|
|
||||||
rowLayout: rowLayout,
|
|
||||||
rowFlex: rowFlex,
|
|
||||||
compact: compact,
|
|
||||||
fields: fields,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Champ texte en lecture seule, même coque [TextField] que [ValidationEditableField].
|
|
||||||
class ValidationReadOnlyField extends StatefulWidget {
|
|
||||||
final String value;
|
|
||||||
final int? maxLines;
|
|
||||||
final bool compact;
|
|
||||||
final bool error;
|
|
||||||
|
|
||||||
const ValidationReadOnlyField({
|
|
||||||
super.key,
|
|
||||||
required this.value,
|
|
||||||
this.maxLines = 1,
|
|
||||||
this.compact = false,
|
|
||||||
this.error = false,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<ValidationReadOnlyField> createState() => _ValidationReadOnlyFieldState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _ValidationReadOnlyFieldState extends State<ValidationReadOnlyField> {
|
|
||||||
late final TextEditingController _controller;
|
|
||||||
|
|
||||||
static const double _compactFieldHeight = 34;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
_controller = TextEditingController(text: widget.value);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void didUpdateWidget(ValidationReadOnlyField oldWidget) {
|
|
||||||
super.didUpdateWidget(oldWidget);
|
|
||||||
if (oldWidget.value != widget.value) {
|
|
||||||
_controller.text = widget.value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
_controller.dispose();
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
if (!widget.compact && widget.maxLines == 1) {
|
|
||||||
return TextField(
|
|
||||||
controller: _controller,
|
|
||||||
readOnly: true,
|
|
||||||
enableInteractiveSelection: false,
|
|
||||||
style: TextStyle(
|
|
||||||
color: widget.error ? Colors.red.shade800 : Colors.black87,
|
|
||||||
fontSize: 14,
|
|
||||||
fontWeight: widget.error ? FontWeight.w600 : null,
|
|
||||||
),
|
|
||||||
decoration: ValidationFieldDecoration.readOnly(error: widget.error),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Container(
|
|
||||||
width: double.infinity,
|
|
||||||
height: widget.compact && widget.maxLines == 1 ? _compactFieldHeight : null,
|
|
||||||
alignment: widget.compact ? Alignment.centerLeft : null,
|
|
||||||
padding: EdgeInsets.symmetric(
|
|
||||||
horizontal: widget.compact ? 10 : 12,
|
|
||||||
vertical: widget.compact ? 7 : 10,
|
|
||||||
),
|
|
||||||
decoration: ValidationFieldDecoration.container(error: widget.error),
|
|
||||||
child: Text(
|
|
||||||
widget.value,
|
|
||||||
style: TextStyle(
|
|
||||||
color: widget.error ? Colors.red.shade800 : Colors.black87,
|
|
||||||
fontSize: widget.compact ? 13 : 14,
|
|
||||||
height: widget.compact ? 1.0 : null,
|
|
||||||
fontWeight: widget.error ? FontWeight.w600 : null,
|
|
||||||
),
|
|
||||||
maxLines: widget.maxLines,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:p_tits_pas/utils/enfant_status_utils.dart';
|
|
||||||
import 'package:p_tits_pas/models/enfant_admin_model.dart';
|
|
||||||
import 'package:p_tits_pas/services/user_service.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/admin/common/admin_child_detail_modal.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/admin/common/admin_enfant_user_card.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/admin/common/user_list.dart';
|
|
||||||
|
|
||||||
/// Onglet liste globale des enfants (doc 28 §6.2, ticket #137).
|
|
||||||
class EnfantManagementWidget extends StatefulWidget {
|
|
||||||
final String searchQuery;
|
|
||||||
final String? statusFilter;
|
|
||||||
|
|
||||||
const EnfantManagementWidget({
|
|
||||||
super.key,
|
|
||||||
required this.searchQuery,
|
|
||||||
this.statusFilter,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<EnfantManagementWidget> createState() => _EnfantManagementWidgetState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _EnfantManagementWidgetState extends State<EnfantManagementWidget> {
|
|
||||||
bool _isLoading = false;
|
|
||||||
String? _error;
|
|
||||||
List<EnfantAdminModel> _enfants = [];
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
_loadEnfants();
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _loadEnfants() async {
|
|
||||||
setState(() {
|
|
||||||
_isLoading = true;
|
|
||||||
_error = null;
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
final list = await UserService.getEnfants();
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
_enfants = list;
|
|
||||||
_isLoading = false;
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
_error = e.toString();
|
|
||||||
_isLoading = false;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _openEnfant(EnfantAdminModel enfant) async {
|
|
||||||
await showDialog<void>(
|
|
||||||
context: context,
|
|
||||||
builder: (ctx) => AdminChildDetailModal(
|
|
||||||
enfant: enfant,
|
|
||||||
onSaved: _loadEnfants,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final query = widget.searchQuery.toLowerCase();
|
|
||||||
final filtered = _enfants.where((e) {
|
|
||||||
final matchesName = e.fullName.toLowerCase().contains(query);
|
|
||||||
final matchesStatus = widget.statusFilter == null ||
|
|
||||||
normalizeEnfantStatus(e.status) ==
|
|
||||||
normalizeEnfantStatus(widget.statusFilter);
|
|
||||||
return matchesName && matchesStatus;
|
|
||||||
}).toList();
|
|
||||||
|
|
||||||
return UserList(
|
|
||||||
isLoading: _isLoading,
|
|
||||||
error: _error,
|
|
||||||
isEmpty: filtered.isEmpty,
|
|
||||||
emptyMessage: 'Aucun enfant trouvé.',
|
|
||||||
itemCount: filtered.length,
|
|
||||||
itemBuilder: (context, index) {
|
|
||||||
final enfant = filtered[index];
|
|
||||||
return AdminEnfantUserCard.fromEnfant(
|
|
||||||
enfant,
|
|
||||||
onCardTap: () => _openEnfant(enfant),
|
|
||||||
actions: [
|
|
||||||
IconButton(
|
|
||||||
icon: const Icon(Icons.visibility_outlined),
|
|
||||||
tooltip: 'Voir / modifier',
|
|
||||||
onPressed: () => _openEnfant(enfant),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,123 +0,0 @@
|
|||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:p_tits_pas/models/parent_model.dart';
|
|
||||||
import 'package:p_tits_pas/services/user_service.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/admin/common/admin_parent_edit_modal.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/admin/common/admin_user_card.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/admin/common/user_list.dart';
|
|
||||||
|
|
||||||
class ParentManagementWidget extends StatefulWidget {
|
|
||||||
final String searchQuery;
|
|
||||||
final String? statusFilter;
|
|
||||||
|
|
||||||
const ParentManagementWidget({
|
|
||||||
super.key,
|
|
||||||
required this.searchQuery,
|
|
||||||
this.statusFilter,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<ParentManagementWidget> createState() => _ParentManagementWidgetState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _ParentManagementWidgetState extends State<ParentManagementWidget> {
|
|
||||||
bool _isLoading = false;
|
|
||||||
String? _error;
|
|
||||||
List<ParentModel> _parents = [];
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
_loadParents();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() => super.dispose();
|
|
||||||
|
|
||||||
Future<void> _loadParents() async {
|
|
||||||
setState(() {
|
|
||||||
_isLoading = true;
|
|
||||||
_error = null;
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
final list = await UserService.getParents();
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
_parents = list;
|
|
||||||
_isLoading = false;
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
_error = e.toString();
|
|
||||||
_isLoading = false;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final query = widget.searchQuery.toLowerCase();
|
|
||||||
final filteredParents = _parents.where((p) {
|
|
||||||
final matchesName = p.user.fullName.toLowerCase().contains(query) ||
|
|
||||||
p.user.email.toLowerCase().contains(query);
|
|
||||||
final matchesStatus =
|
|
||||||
widget.statusFilter == null || p.user.statut == widget.statusFilter;
|
|
||||||
return matchesName && matchesStatus;
|
|
||||||
}).toList();
|
|
||||||
|
|
||||||
return UserList(
|
|
||||||
isLoading: _isLoading,
|
|
||||||
error: _error,
|
|
||||||
isEmpty: filteredParents.isEmpty,
|
|
||||||
emptyMessage: 'Aucun parent trouvé.',
|
|
||||||
itemCount: filteredParents.length,
|
|
||||||
itemBuilder: (context, index) {
|
|
||||||
final parent = filteredParents[index];
|
|
||||||
return AdminUserCard(
|
|
||||||
title: parent.user.fullName,
|
|
||||||
fallbackIcon: Icons.supervisor_account_outlined,
|
|
||||||
avatarUrl: parent.user.photoUrl,
|
|
||||||
onCardTap: () => _openParentDetails(parent),
|
|
||||||
subtitleLines: [
|
|
||||||
parent.user.email,
|
|
||||||
'Statut : ${_displayStatus(parent.user.statut)} | Enfants : ${parent.children.isNotEmpty ? parent.children.length : parent.childrenCount}',
|
|
||||||
],
|
|
||||||
actions: [
|
|
||||||
IconButton(
|
|
||||||
icon: const Icon(Icons.edit),
|
|
||||||
tooltip: 'Modifier',
|
|
||||||
onPressed: () {
|
|
||||||
_openParentDetails(parent);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
String _displayStatus(String? status) {
|
|
||||||
switch (status) {
|
|
||||||
case 'actif':
|
|
||||||
return 'Actif';
|
|
||||||
case 'en_attente':
|
|
||||||
return 'En attente';
|
|
||||||
case 'suspendu':
|
|
||||||
return 'Suspendu';
|
|
||||||
case 'refuse':
|
|
||||||
return 'Refusé';
|
|
||||||
default:
|
|
||||||
return 'Inconnu';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _openParentDetails(ParentModel parent) {
|
|
||||||
showDialog<void>(
|
|
||||||
context: context,
|
|
||||||
builder: (context) => AdminParentEditModal(
|
|
||||||
parent: parent,
|
|
||||||
onSaved: _loadParents,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,399 +0,0 @@
|
|||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:intl/intl.dart';
|
|
||||||
import 'package:p_tits_pas/models/user.dart';
|
|
||||||
import 'package:p_tits_pas/models/pending_family.dart';
|
|
||||||
import 'package:p_tits_pas/services/user_service.dart';
|
|
||||||
import 'package:p_tits_pas/utils/phone_utils.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/admin/validation_dossier_modal.dart';
|
|
||||||
|
|
||||||
/// Onglet « À valider » : deux listes (AM en attente, familles en attente). Ticket #107.
|
|
||||||
class PendingValidationWidget extends StatefulWidget {
|
|
||||||
final VoidCallback? onRefresh;
|
|
||||||
|
|
||||||
const PendingValidationWidget({super.key, this.onRefresh});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<PendingValidationWidget> createState() => _PendingValidationWidgetState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _PendingValidationWidgetState extends State<PendingValidationWidget> {
|
|
||||||
bool _isLoading = true;
|
|
||||||
String? _error;
|
|
||||||
List<AppUser> _pendingAM = [];
|
|
||||||
List<PendingFamily> _pendingFamilies = [];
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
_load();
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _load() async {
|
|
||||||
setState(() {
|
|
||||||
_isLoading = true;
|
|
||||||
_error = null;
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
final am = await UserService.getPendingUsers(role: 'assistante_maternelle');
|
|
||||||
final families = await UserService.getPendingFamilies();
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
_pendingAM = am;
|
|
||||||
_pendingFamilies = families;
|
|
||||||
_isLoading = false;
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
_error = e is Exception ? e.toString().replaceFirst('Exception: ', '') : 'Erreur inconnue';
|
|
||||||
_isLoading = false;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _onOpenValidation({String? type, String? id, String? numeroDossier}) {
|
|
||||||
final num = numeroDossier?.trim();
|
|
||||||
if (num == null || num.isEmpty) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(content: Text('Numéro de dossier manquant.')),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
showDialog<void>(
|
|
||||||
context: context,
|
|
||||||
builder: (context) => ValidationDossierModal(
|
|
||||||
numeroDossier: num,
|
|
||||||
onClose: () => Navigator.of(context).pop(),
|
|
||||||
onSuccess: () {
|
|
||||||
Navigator.of(context).pop();
|
|
||||||
_load();
|
|
||||||
widget.onRefresh?.call();
|
|
||||||
},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
if (_isLoading) {
|
|
||||||
return const Center(child: CircularProgressIndicator());
|
|
||||||
}
|
|
||||||
if (_error != null && _error!.isNotEmpty) {
|
|
||||||
return Center(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(24),
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
Text(_error!, style: const TextStyle(color: Colors.red)),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
ElevatedButton(
|
|
||||||
onPressed: _load,
|
|
||||||
child: const Text('Réessayer'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
final hasAM = _pendingAM.isNotEmpty;
|
|
||||||
final hasFamilies = _pendingFamilies.isNotEmpty;
|
|
||||||
if (!hasAM && !hasFamilies) {
|
|
||||||
return Center(
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
Icon(Icons.check_circle_outline, size: 64, color: Colors.grey.shade400),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Text(
|
|
||||||
'Aucun dossier en attente de validation',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
|
||||||
color: Colors.grey.shade600,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return RefreshIndicator(
|
|
||||||
onRefresh: () async {
|
|
||||||
await _load();
|
|
||||||
widget.onRefresh?.call();
|
|
||||||
},
|
|
||||||
child: SingleChildScrollView(
|
|
||||||
physics: const AlwaysScrollableScrollPhysics(),
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
if (hasAM) ...[
|
|
||||||
_sectionTitle('Assistantes maternelles en attente'),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
..._pendingAM.map((u) => _buildAMCard(u)),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
],
|
|
||||||
if (hasFamilies) ...[
|
|
||||||
_sectionTitle('Familles en attente'),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
..._pendingFamilies.map((f) => _buildFamilyCard(f)),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _sectionTitle(String title) {
|
|
||||||
return Text(
|
|
||||||
title,
|
|
||||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
color: Colors.black87,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// Sous-titre AM : `email - date • tél. • CP ville` (plan affichage lignes À valider).
|
|
||||||
String _amSubtitleLine(AppUser user) {
|
|
||||||
final email = user.email.trim();
|
|
||||||
final bits = <String>[];
|
|
||||||
bits.add(DateFormat('dd/MM/yyyy').format(user.createdAt.toLocal()));
|
|
||||||
final tel = user.telephone?.trim();
|
|
||||||
if (tel != null && tel.isNotEmpty) {
|
|
||||||
bits.add(formatPhoneForDisplay(tel));
|
|
||||||
}
|
|
||||||
final cp = user.codePostal?.trim();
|
|
||||||
final ville = user.ville?.trim();
|
|
||||||
final loc = [if (cp != null && cp.isNotEmpty) cp, if (ville != null && ville.isNotEmpty) ville]
|
|
||||||
.join(' ')
|
|
||||||
.trim();
|
|
||||||
if (loc.isNotEmpty) bits.add(loc);
|
|
||||||
final infos = bits.join(' • ');
|
|
||||||
if (email.isEmpty) return infos;
|
|
||||||
return '$email - $infos';
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildAMCard(AppUser user) {
|
|
||||||
final numDossier = user.numeroDossier ?? '–';
|
|
||||||
final nameBold =
|
|
||||||
user.fullName.isNotEmpty ? user.fullName : (user.email.isNotEmpty ? user.email : '–');
|
|
||||||
return _PendingValidationRow(
|
|
||||||
icon: Icons.person_outline,
|
|
||||||
title: Text.rich(
|
|
||||||
TextSpan(
|
|
||||||
style: const TextStyle(fontSize: 14, color: Colors.black87),
|
|
||||||
children: [
|
|
||||||
TextSpan(
|
|
||||||
text: nameBold,
|
|
||||||
style: const TextStyle(fontWeight: FontWeight.w700),
|
|
||||||
),
|
|
||||||
TextSpan(
|
|
||||||
text: ' - $numDossier',
|
|
||||||
style: const TextStyle(fontWeight: FontWeight.w400),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
subtitle: _amSubtitleLine(user),
|
|
||||||
subtitleStyle: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
fontStyle: FontStyle.italic,
|
|
||||||
color: Colors.grey.shade600,
|
|
||||||
),
|
|
||||||
onOpen: () => _onOpenValidation(
|
|
||||||
type: 'AM',
|
|
||||||
id: user.id,
|
|
||||||
numeroDossier: user.numeroDossier,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `email, tél., localisation` par parent, puis `date soumission`, puis `nb enfants`.
|
|
||||||
String _familyParentSegment(PendingParentLine p) {
|
|
||||||
final parts = <String>[];
|
|
||||||
final e = p.email?.trim();
|
|
||||||
if (e != null && e.isNotEmpty) parts.add(e);
|
|
||||||
final t = p.telephone?.trim();
|
|
||||||
if (t != null && t.isNotEmpty) parts.add(formatPhoneForDisplay(t));
|
|
||||||
final cp = p.codePostal?.trim();
|
|
||||||
final v = p.ville?.trim();
|
|
||||||
final loc = [if (cp != null && cp.isNotEmpty) cp, if (v != null && v.isNotEmpty) v]
|
|
||||||
.join(' ')
|
|
||||||
.trim();
|
|
||||||
if (loc.isNotEmpty) parts.add(loc);
|
|
||||||
return parts.join(', ');
|
|
||||||
}
|
|
||||||
|
|
||||||
String _familySubtitleLine(PendingFamily family) {
|
|
||||||
final blocks = family.parentLines
|
|
||||||
.map(_familyParentSegment)
|
|
||||||
.where((s) => s.isNotEmpty)
|
|
||||||
.join(' - ');
|
|
||||||
|
|
||||||
final tail = <String>[];
|
|
||||||
final date = family.dateSoumission;
|
|
||||||
if (date != null) {
|
|
||||||
tail.add(DateFormat('dd/MM/yyyy').format(date.toLocal()));
|
|
||||||
}
|
|
||||||
if (family.nombreEnfants > 0) {
|
|
||||||
tail.add(
|
|
||||||
family.nombreEnfants > 1
|
|
||||||
? '${family.nombreEnfants} enfants'
|
|
||||||
: '1 enfant',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
final right = tail.join(' - ');
|
|
||||||
|
|
||||||
if (blocks.isEmpty && right.isEmpty) return '';
|
|
||||||
if (blocks.isEmpty) return right;
|
|
||||||
if (right.isEmpty) return blocks;
|
|
||||||
return '$blocks - $right';
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildFamilyCard(PendingFamily family) {
|
|
||||||
final numDossier = family.numeroDossier ?? '–';
|
|
||||||
final nameBold = family.libelle.isNotEmpty ? family.libelle : 'Famille';
|
|
||||||
return _PendingValidationRow(
|
|
||||||
icon: Icons.family_restroom_outlined,
|
|
||||||
title: Text.rich(
|
|
||||||
TextSpan(
|
|
||||||
style: const TextStyle(fontSize: 14, color: Colors.black87),
|
|
||||||
children: [
|
|
||||||
TextSpan(
|
|
||||||
text: nameBold,
|
|
||||||
style: const TextStyle(fontWeight: FontWeight.w700),
|
|
||||||
),
|
|
||||||
TextSpan(
|
|
||||||
text: ' - $numDossier',
|
|
||||||
style: const TextStyle(fontWeight: FontWeight.w400),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
subtitle: _familySubtitleLine(family),
|
|
||||||
subtitleStyle: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
fontStyle: FontStyle.italic,
|
|
||||||
color: Colors.grey.shade600,
|
|
||||||
),
|
|
||||||
onOpen: () => _onOpenValidation(
|
|
||||||
type: 'famille',
|
|
||||||
id: family.parentIds.isNotEmpty ? family.parentIds.first : null,
|
|
||||||
numeroDossier: family.numeroDossier,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ligne « À valider » : survol comme [AdminUserCard], icône « Ouvrir » visible au hover uniquement.
|
|
||||||
class _PendingValidationRow extends StatefulWidget {
|
|
||||||
final IconData icon;
|
|
||||||
final Widget title;
|
|
||||||
final String? subtitle;
|
|
||||||
final TextStyle? subtitleStyle;
|
|
||||||
final VoidCallback onOpen;
|
|
||||||
|
|
||||||
const _PendingValidationRow({
|
|
||||||
required this.icon,
|
|
||||||
required this.title,
|
|
||||||
this.subtitle,
|
|
||||||
this.subtitleStyle,
|
|
||||||
required this.onOpen,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<_PendingValidationRow> createState() => _PendingValidationRowState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _PendingValidationRowState extends State<_PendingValidationRow> {
|
|
||||||
bool _isHovered = false;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final subStyle = widget.subtitleStyle ??
|
|
||||||
TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
color: Colors.grey.shade600,
|
|
||||||
);
|
|
||||||
return MouseRegion(
|
|
||||||
onEnter: (_) => setState(() => _isHovered = true),
|
|
||||||
onExit: (_) => setState(() => _isHovered = false),
|
|
||||||
cursor: SystemMouseCursors.click,
|
|
||||||
child: Material(
|
|
||||||
color: Colors.transparent,
|
|
||||||
borderRadius: BorderRadius.circular(10),
|
|
||||||
child: InkWell(
|
|
||||||
onTap: widget.onOpen,
|
|
||||||
borderRadius: BorderRadius.circular(10),
|
|
||||||
hoverColor: const Color(0x149CC5C0),
|
|
||||||
child: Card(
|
|
||||||
margin: const EdgeInsets.only(bottom: 12),
|
|
||||||
elevation: 0,
|
|
||||||
shape: RoundedRectangleBorder(
|
|
||||||
borderRadius: BorderRadius.circular(10),
|
|
||||||
side: BorderSide(color: Colors.grey.shade300),
|
|
||||||
),
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
|
||||||
child: Row(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.center,
|
|
||||||
children: [
|
|
||||||
Icon(widget.icon, color: Colors.grey.shade600, size: 28),
|
|
||||||
const SizedBox(width: 14),
|
|
||||||
Expanded(
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
widget.title,
|
|
||||||
if (widget.subtitle != null &&
|
|
||||||
widget.subtitle!.isNotEmpty) ...[
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text(
|
|
||||||
widget.subtitle!,
|
|
||||||
style: subStyle,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
SizedBox(
|
|
||||||
width: 52,
|
|
||||||
child: Center(
|
|
||||||
child: AnimatedOpacity(
|
|
||||||
duration: const Duration(milliseconds: 120),
|
|
||||||
opacity: _isHovered ? 1 : 0,
|
|
||||||
child: IgnorePointer(
|
|
||||||
ignoring: !_isHovered,
|
|
||||||
child: IconButtonTheme(
|
|
||||||
data: IconButtonThemeData(
|
|
||||||
style: IconButton.styleFrom(
|
|
||||||
padding: const EdgeInsets.all(0),
|
|
||||||
minimumSize: const Size(48, 48),
|
|
||||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: IconButton(
|
|
||||||
onPressed: widget.onOpen,
|
|
||||||
icon: const Icon(Icons.open_in_new),
|
|
||||||
iconSize: 34,
|
|
||||||
tooltip: 'Ouvrir',
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,507 +0,0 @@
|
|||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:p_tits_pas/models/dossier_unifie.dart';
|
|
||||||
import 'package:p_tits_pas/utils/date_display_utils.dart';
|
|
||||||
import 'package:p_tits_pas/utils/nir_utils.dart';
|
|
||||||
import 'package:p_tits_pas/models/user.dart';
|
|
||||||
import 'package:p_tits_pas/services/user_service.dart';
|
|
||||||
import 'package:p_tits_pas/services/api/api_config.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/admin/common/admin_detail_modal.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/admin/common/validation_detail_section.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/common/identity_block.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/common/auth_network_image.dart';
|
|
||||||
import 'validation_modal_theme.dart';
|
|
||||||
import 'validation_refus_form.dart';
|
|
||||||
import 'validation_valider_confirm_dialog.dart';
|
|
||||||
|
|
||||||
/// Wizard de validation dossier AM : étapes sobres (label/valeur), récap, Valider/Refuser/Annuler, page refus. Ticket #107.
|
|
||||||
class ValidationAmWizard extends StatefulWidget {
|
|
||||||
final DossierAM dossier;
|
|
||||||
final VoidCallback onClose;
|
|
||||||
final VoidCallback onSuccess;
|
|
||||||
final void Function(int step, int total)? onStepChanged;
|
|
||||||
|
|
||||||
const ValidationAmWizard({
|
|
||||||
super.key,
|
|
||||||
required this.dossier,
|
|
||||||
required this.onClose,
|
|
||||||
required this.onSuccess,
|
|
||||||
this.onStepChanged,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<ValidationAmWizard> createState() => _ValidationAmWizardState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _ValidationAmWizardState extends State<ValidationAmWizard> {
|
|
||||||
int _step = 0;
|
|
||||||
bool _showRefusForm = false;
|
|
||||||
bool _submitting = false;
|
|
||||||
|
|
||||||
static const int _stepCount = 3;
|
|
||||||
|
|
||||||
bool get _isEnAttente => widget.dossier.user.statut == 'en_attente';
|
|
||||||
|
|
||||||
static String _v(String? s) =>
|
|
||||||
(s != null && s.trim().isNotEmpty) ? s.trim() : '–';
|
|
||||||
|
|
||||||
/// Présentation lisible : `1 12 34 56 789 012 - 34` (15 caractères utiles requis).
|
|
||||||
static String _formatNirForDisplay(String? nir) {
|
|
||||||
final v = _v(nir);
|
|
||||||
if (v == '–') return v;
|
|
||||||
final raw = nirToRaw(v).toUpperCase();
|
|
||||||
return raw.length == 15 ? formatNir(raw) : v;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) => _emitStep());
|
|
||||||
}
|
|
||||||
|
|
||||||
void _emitStep() => widget.onStepChanged?.call(_step, _stepCount);
|
|
||||||
|
|
||||||
/// Panneau photo + grille droite : NIR|naissance, ville|pays, agrément|date, capa|places.
|
|
||||||
List<AdminDetailField> _photoProFields(DossierAM d) {
|
|
||||||
final u = d.user;
|
|
||||||
return [
|
|
||||||
AdminDetailField(label: 'NIR', value: _formatNirForDisplay(d.nir)),
|
|
||||||
AdminDetailField(
|
|
||||||
label: 'Date de naissance',
|
|
||||||
value: formatIsoDateFr(u.dateNaissance),
|
|
||||||
),
|
|
||||||
AdminDetailField(
|
|
||||||
label: 'Ville de naissance',
|
|
||||||
value: _v(u.lieuNaissanceVille),
|
|
||||||
),
|
|
||||||
AdminDetailField(
|
|
||||||
label: 'Pays de naissance',
|
|
||||||
value: _v(u.lieuNaissancePays),
|
|
||||||
),
|
|
||||||
AdminDetailField(label: 'N° Agrément', value: _v(d.numeroAgrement)),
|
|
||||||
AdminDetailField(
|
|
||||||
label: 'Date d’agrément',
|
|
||||||
value: formatIsoDateFr(d.dateAgrement),
|
|
||||||
),
|
|
||||||
AdminDetailField(
|
|
||||||
label: 'Capacité max (enfants)',
|
|
||||||
value: d.nbMaxEnfants != null ? d.nbMaxEnfants.toString() : '–',
|
|
||||||
),
|
|
||||||
AdminDetailField(
|
|
||||||
label: 'Places disponibles',
|
|
||||||
value: d.placesDisponibles != null
|
|
||||||
? d.placesDisponibles.toString()
|
|
||||||
: '–',
|
|
||||||
),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
static const List<int> _photoProRowLayout = [2, 2, 2, 2];
|
|
||||||
|
|
||||||
/// Proportion photo d’identité (35×45 mm).
|
|
||||||
static const double _idPhotoAspectRatio = 35 / 45;
|
|
||||||
|
|
||||||
static const double _photoProGap = 24;
|
|
||||||
/// Largeur mini réservée aux champs (évite une colonne photo trop gourmande).
|
|
||||||
static const double _proColumnMinWidth = 260;
|
|
||||||
static const double _photoColumnMinWidth = 160;
|
|
||||||
|
|
||||||
/// URL complète pour la photo : si relatif, préfixe [ApiConfig.baseUrl] (ex. `/api/v1/uploads/...`).
|
|
||||||
static String _fullPhotoUrl(String? url) => ApiConfig.absoluteMediaUrl(url);
|
|
||||||
|
|
||||||
Widget _buildPhotoSection(AppUser u) {
|
|
||||||
final photoUrl = _fullPhotoUrl(u.photoUrl);
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.only(right: 8),
|
|
||||||
child: LayoutBuilder(
|
|
||||||
builder: (context, c) {
|
|
||||||
// Cadre clair : une seule épaisseur partout (photo + padding identique haut/bas/gauche/droite).
|
|
||||||
const uniformFrame = 8.0;
|
|
||||||
final maxPhotoW =
|
|
||||||
(c.maxWidth - 2 * uniformFrame).clamp(0.0, double.infinity);
|
|
||||||
final maxPhotoH =
|
|
||||||
(c.maxHeight - 2 * uniformFrame).clamp(0.0, double.infinity);
|
|
||||||
const ar = _idPhotoAspectRatio;
|
|
||||||
double ph = maxPhotoH;
|
|
||||||
double pw = ph * ar;
|
|
||||||
if (pw > maxPhotoW) {
|
|
||||||
pw = maxPhotoW;
|
|
||||||
ph = pw / ar;
|
|
||||||
}
|
|
||||||
return Align(
|
|
||||||
alignment: Alignment.center,
|
|
||||||
child: Container(
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Colors.grey.shade100,
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
border: Border.all(color: Colors.grey.shade300),
|
|
||||||
),
|
|
||||||
clipBehavior: Clip.antiAlias,
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.all(uniformFrame),
|
|
||||||
child: ClipRRect(
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
child: SizedBox(
|
|
||||||
width: pw,
|
|
||||||
height: ph,
|
|
||||||
child: photoUrl.isEmpty
|
|
||||||
? ColoredBox(
|
|
||||||
color: Colors.grey.shade200,
|
|
||||||
child: Column(
|
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
|
||||||
children: [
|
|
||||||
Icon(Icons.person_off_outlined,
|
|
||||||
size: 40,
|
|
||||||
color: Colors.grey.shade400),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
'Aucune photo fournie',
|
|
||||||
style: TextStyle(
|
|
||||||
color: Colors.grey.shade600,
|
|
||||||
fontSize: 12),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: AuthNetworkImage(
|
|
||||||
url: photoUrl,
|
|
||||||
fit: BoxFit.cover,
|
|
||||||
width: pw,
|
|
||||||
height: ph,
|
|
||||||
loadingBuilder: (_, child, progress) {
|
|
||||||
if (progress == null) return child;
|
|
||||||
return ColoredBox(
|
|
||||||
color: Colors.grey.shade200,
|
|
||||||
child: Center(
|
|
||||||
child: CircularProgressIndicator(
|
|
||||||
value: progress.expectedTotalBytes !=
|
|
||||||
null
|
|
||||||
? progress.cumulativeBytesLoaded /
|
|
||||||
(progress.expectedTotalBytes!)
|
|
||||||
: null,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
errorBuilder: (_, __, ___) => ColoredBox(
|
|
||||||
color: Colors.grey.shade200,
|
|
||||||
child: Column(
|
|
||||||
mainAxisAlignment:
|
|
||||||
MainAxisAlignment.center,
|
|
||||||
children: [
|
|
||||||
Icon(Icons.broken_image_outlined,
|
|
||||||
size: 40,
|
|
||||||
color: Colors.grey.shade400),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Text(
|
|
||||||
'Impossible de charger la photo',
|
|
||||||
style: TextStyle(
|
|
||||||
color: Colors.grey.shade600,
|
|
||||||
fontSize: 12),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
if (_showRefusForm) {
|
|
||||||
return _buildRefusPage();
|
|
||||||
}
|
|
||||||
return Padding(
|
|
||||||
padding: const EdgeInsets.all(20),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Expanded(child: _buildStepContent()),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
_buildNavigation(),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildStepContent() {
|
|
||||||
final d = widget.dossier;
|
|
||||||
final u = d.user;
|
|
||||||
switch (_step) {
|
|
||||||
case 0:
|
|
||||||
return LayoutBuilder(
|
|
||||||
builder: (context, constraints) {
|
|
||||||
return SingleChildScrollView(
|
|
||||||
child: ConstrainedBox(
|
|
||||||
constraints: BoxConstraints(minWidth: constraints.maxWidth),
|
|
||||||
child: IdentityBlock.readOnlyFromUser(
|
|
||||||
u,
|
|
||||||
title: 'Identité et coordonnées',
|
|
||||||
emptyLabel: '–',
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
case 1:
|
|
||||||
// Pas de SingleChildScrollView sur la Row (hauteur non bornée). Défilement à droite.
|
|
||||||
// Largeur photo ≈ ratio × hauteur utile, plafonnée pour laisser au moins [_proColumnMinWidth] aux champs.
|
|
||||||
return LayoutBuilder(
|
|
||||||
builder: (context, c) {
|
|
||||||
final maxRowW = c.maxWidth;
|
|
||||||
final maxRowH = c.maxHeight;
|
|
||||||
const photoHeaderH = 0.0;
|
|
||||||
final bodyH = (maxRowH - photoHeaderH).clamp(0.0, double.infinity);
|
|
||||||
final idealPhotoW =
|
|
||||||
bodyH * _idPhotoAspectRatio + 16; // marge approx. cadre clair
|
|
||||||
final maxPhotoW = (maxRowW - _photoProGap - _proColumnMinWidth)
|
|
||||||
.clamp(0.0, double.infinity);
|
|
||||||
var photoW = idealPhotoW.clamp(_photoColumnMinWidth, 360.0);
|
|
||||||
if (photoW > maxPhotoW) photoW = maxPhotoW;
|
|
||||||
photoW = photoW.clamp(0.0, maxRowW - _photoProGap);
|
|
||||||
|
|
||||||
return Row(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
SizedBox(
|
|
||||||
width: photoW,
|
|
||||||
child: _buildPhotoSection(u),
|
|
||||||
),
|
|
||||||
const SizedBox(width: _photoProGap),
|
|
||||||
Expanded(
|
|
||||||
child: LayoutBuilder(
|
|
||||||
builder: (context, constraints) {
|
|
||||||
return SingleChildScrollView(
|
|
||||||
child: ConstrainedBox(
|
|
||||||
constraints: BoxConstraints(
|
|
||||||
minWidth: constraints.maxWidth),
|
|
||||||
child: ValidationDetailSection(
|
|
||||||
title: 'Dossier professionnel',
|
|
||||||
fields: _photoProFields(d),
|
|
||||||
rowLayout: _photoProRowLayout,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
case 2:
|
|
||||||
final presentation =
|
|
||||||
(d.presentation != null && d.presentation!.trim().isNotEmpty)
|
|
||||||
? d.presentation!
|
|
||||||
: '–';
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
const Text(
|
|
||||||
'Présentation',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 16,
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
color: Colors.black87,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Expanded(
|
|
||||||
child: LayoutBuilder(
|
|
||||||
builder: (context, constraints) {
|
|
||||||
return SingleChildScrollView(
|
|
||||||
child: ConstrainedBox(
|
|
||||||
constraints:
|
|
||||||
BoxConstraints(minHeight: constraints.maxHeight),
|
|
||||||
child: Container(
|
|
||||||
width: double.infinity,
|
|
||||||
padding: const EdgeInsets.symmetric(
|
|
||||||
horizontal: 12, vertical: 10),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Colors.grey.shade50,
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
border: Border.all(color: Colors.grey.shade300),
|
|
||||||
),
|
|
||||||
child: SelectableText(
|
|
||||||
presentation,
|
|
||||||
style: const TextStyle(
|
|
||||||
color: Colors.black87, fontSize: 14),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
default:
|
|
||||||
return const SizedBox();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildNavigation() {
|
|
||||||
if (_step == 2) {
|
|
||||||
return Row(
|
|
||||||
children: [
|
|
||||||
TextButton(onPressed: widget.onClose, child: const Text('Annuler')),
|
|
||||||
const Spacer(),
|
|
||||||
Row(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
TextButton(
|
|
||||||
onPressed: () {
|
|
||||||
setState(() => _step = 1);
|
|
||||||
_emitStep();
|
|
||||||
},
|
|
||||||
child: const Text('Précédent'),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
if (_isEnAttente) ...[
|
|
||||||
OutlinedButton(
|
|
||||||
onPressed: _submitting ? null : _refuser,
|
|
||||||
child: const Text('Refuser')),
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
ElevatedButton(
|
|
||||||
style: ValidationModalTheme.primaryElevatedStyle,
|
|
||||||
onPressed: _submitting ? null : _onValiderPressed,
|
|
||||||
child: Text(_submitting ? 'Envoi...' : 'Valider'),
|
|
||||||
),
|
|
||||||
] else
|
|
||||||
ElevatedButton(
|
|
||||||
style: ValidationModalTheme.primaryElevatedStyle,
|
|
||||||
onPressed: widget.onClose,
|
|
||||||
child: const Text('Fermer'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return Row(
|
|
||||||
children: [
|
|
||||||
TextButton(onPressed: widget.onClose, child: const Text('Annuler')),
|
|
||||||
const Spacer(),
|
|
||||||
if (_step > 0) ...[
|
|
||||||
TextButton(
|
|
||||||
onPressed: () {
|
|
||||||
setState(() => _step--);
|
|
||||||
_emitStep();
|
|
||||||
},
|
|
||||||
child: const Text('Précédent'),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
],
|
|
||||||
ElevatedButton(
|
|
||||||
style: ValidationModalTheme.primaryElevatedStyle,
|
|
||||||
onPressed: () {
|
|
||||||
setState(() => _step++);
|
|
||||||
_emitStep();
|
|
||||||
},
|
|
||||||
child: const Text('Suivant'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _onValiderPressed() async {
|
|
||||||
if (_submitting) return;
|
|
||||||
final ok = await showValidationValiderConfirmDialog(
|
|
||||||
context,
|
|
||||||
body:
|
|
||||||
'Voulez-vous valider le dossier de cette assistante maternelle ? Cette action confirme le compte.',
|
|
||||||
);
|
|
||||||
if (!mounted || !ok) return;
|
|
||||||
await _valider();
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _valider() async {
|
|
||||||
if (_submitting) return;
|
|
||||||
setState(() => _submitting = true);
|
|
||||||
try {
|
|
||||||
await UserService.validateUser(widget.dossier.user.id);
|
|
||||||
if (!mounted) return;
|
|
||||||
widget.onSuccess();
|
|
||||||
} catch (e) {
|
|
||||||
if (!mounted) return;
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text(e is Exception
|
|
||||||
? e.toString().replaceFirst('Exception: ', '')
|
|
||||||
: 'Erreur'),
|
|
||||||
backgroundColor: Colors.red.shade700,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
if (mounted) setState(() => _submitting = false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _refuser() => setState(() => _showRefusForm = true);
|
|
||||||
|
|
||||||
Widget _buildRefusPage() {
|
|
||||||
return Padding(
|
|
||||||
padding: const EdgeInsets.all(20),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: ValidationRefusForm(
|
|
||||||
isSubmitting: _submitting,
|
|
||||||
onCancel: widget.onClose,
|
|
||||||
onPrevious: () => setState(() => _showRefusForm = false),
|
|
||||||
onSubmit: (comment) {
|
|
||||||
if (comment == null || comment.trim().isEmpty) return;
|
|
||||||
_refuserEnvoyer(comment.trim());
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _refuserEnvoyer(String comment) async {
|
|
||||||
if (_submitting) return;
|
|
||||||
setState(() => _submitting = true);
|
|
||||||
try {
|
|
||||||
await UserService.refuseUser(widget.dossier.user.id, comment: comment);
|
|
||||||
if (!mounted) return;
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: const Text(
|
|
||||||
'Refus enregistré. Un e-mail avec le lien de reprise a été envoyé.',
|
|
||||||
),
|
|
||||||
duration: const Duration(seconds: 4),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
widget.onSuccess();
|
|
||||||
} catch (e) {
|
|
||||||
if (!mounted) return;
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text(e is Exception
|
|
||||||
? e.toString().replaceFirst('Exception: ', '')
|
|
||||||
: 'Erreur'),
|
|
||||||
backgroundColor: Colors.red.shade700,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
if (mounted) setState(() => _submitting = false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,724 +0,0 @@
|
|||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:flutter/gestures.dart';
|
|
||||||
import 'package:google_fonts/google_fonts.dart';
|
|
||||||
import 'package:p_tits_pas/models/dossier_unifie.dart';
|
|
||||||
import 'package:p_tits_pas/utils/date_display_utils.dart';
|
|
||||||
import 'package:p_tits_pas/utils/enfant_status_utils.dart';
|
|
||||||
import 'package:p_tits_pas/services/user_service.dart';
|
|
||||||
import 'package:p_tits_pas/services/api/api_config.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/admin/common/validation_detail_section.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/common/identity_block.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/common/auth_network_image.dart';
|
|
||||||
import 'validation_modal_theme.dart';
|
|
||||||
import 'validation_refus_form.dart';
|
|
||||||
import 'validation_valider_confirm_dialog.dart';
|
|
||||||
|
|
||||||
/// Wizard de validation dossier famille : étapes sobres (label/valeur), récap, Valider/Refuser/Annuler, page refus. Ticket #107.
|
|
||||||
class ValidationFamilyWizard extends StatefulWidget {
|
|
||||||
final DossierFamille dossier;
|
|
||||||
final VoidCallback onClose;
|
|
||||||
final VoidCallback onSuccess;
|
|
||||||
final void Function(int step, int total)? onStepChanged;
|
|
||||||
|
|
||||||
const ValidationFamilyWizard({
|
|
||||||
super.key,
|
|
||||||
required this.dossier,
|
|
||||||
required this.onClose,
|
|
||||||
required this.onSuccess,
|
|
||||||
this.onStepChanged,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<ValidationFamilyWizard> createState() => _ValidationFamilyWizardState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _ValidationFamilyWizardState extends State<ValidationFamilyWizard> {
|
|
||||||
int _step = 0;
|
|
||||||
bool _showRefusForm = false;
|
|
||||||
bool _submitting = false;
|
|
||||||
final ScrollController _enfantsScrollController = ScrollController();
|
|
||||||
|
|
||||||
/// Même logique que [ParentRegisterStep3Screen] : masque alpha sur les bords (ShaderMask dstIn).
|
|
||||||
bool _enfantsIsScrollable = false;
|
|
||||||
bool _enfantsFadeLeft = false;
|
|
||||||
bool _enfantsFadeRight = false;
|
|
||||||
|
|
||||||
/// Fraction de la largeur du viewport pour le fondu (identique inscription étape 3).
|
|
||||||
static const double _enfantsFadeExtent = 0.05;
|
|
||||||
|
|
||||||
int get _stepCount => 4;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
_enfantsScrollController.addListener(_syncEnfantsScrollFades);
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) => _emitStep());
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
_enfantsScrollController.removeListener(_syncEnfantsScrollFades);
|
|
||||||
_enfantsScrollController.dispose();
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
void _emitStep() => widget.onStepChanged?.call(_step, _stepCount);
|
|
||||||
|
|
||||||
void _syncEnfantsScrollFades() {
|
|
||||||
if (!mounted) return;
|
|
||||||
if (!_enfantsScrollController.hasClients) {
|
|
||||||
if (_enfantsFadeLeft || _enfantsFadeRight || _enfantsIsScrollable) {
|
|
||||||
setState(() {
|
|
||||||
_enfantsIsScrollable = false;
|
|
||||||
_enfantsFadeLeft = false;
|
|
||||||
_enfantsFadeRight = false;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final p = _enfantsScrollController.position;
|
|
||||||
final scrollable = p.maxScrollExtent > 0;
|
|
||||||
final left = scrollable &&
|
|
||||||
p.pixels > (p.viewportDimension * _enfantsFadeExtent / 2);
|
|
||||||
final right = scrollable &&
|
|
||||||
p.pixels <
|
|
||||||
(p.maxScrollExtent -
|
|
||||||
(p.viewportDimension * _enfantsFadeExtent / 2));
|
|
||||||
if (scrollable != _enfantsIsScrollable ||
|
|
||||||
left != _enfantsFadeLeft ||
|
|
||||||
right != _enfantsFadeRight) {
|
|
||||||
setState(() {
|
|
||||||
_enfantsIsScrollable = scrollable;
|
|
||||||
_enfantsFadeLeft = left;
|
|
||||||
_enfantsFadeRight = right;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool get _isEnAttente => widget.dossier.isEnAttente;
|
|
||||||
|
|
||||||
String? get _firstParentId => widget.dossier.parents.isNotEmpty
|
|
||||||
? widget.dossier.parents.first.id
|
|
||||||
: null;
|
|
||||||
|
|
||||||
static String _v(String? s) =>
|
|
||||||
(s != null && s.trim().isNotEmpty) ? s.trim() : 'Non défini';
|
|
||||||
|
|
||||||
/// Date de naissance en jour/mois/année (dd/MM/yyyy).
|
|
||||||
static String _formatBirthDate(String? s) =>
|
|
||||||
formatIsoDateFr(s, ifEmpty: 'Non défini');
|
|
||||||
|
|
||||||
static String _fullPhotoUrl(String? url) => ApiConfig.absoluteMediaUrl(url);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
if (_showRefusForm) {
|
|
||||||
return _buildRefusPage();
|
|
||||||
}
|
|
||||||
return Padding(
|
|
||||||
padding: const EdgeInsets.all(20),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Expanded(child: _buildStepContent()),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
_buildNavigation(),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildStepContent() {
|
|
||||||
final d = widget.dossier;
|
|
||||||
switch (_step) {
|
|
||||||
case 0:
|
|
||||||
return IdentityBlock.readOnlyFromParentDossier(
|
|
||||||
d.parents.first,
|
|
||||||
title: 'Parent principal',
|
|
||||||
);
|
|
||||||
case 1:
|
|
||||||
return _buildParent2Step();
|
|
||||||
case 2:
|
|
||||||
return _buildEnfantsStep();
|
|
||||||
case 3:
|
|
||||||
return _buildPresentationStep();
|
|
||||||
default:
|
|
||||||
return const SizedBox();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildParent2Step() {
|
|
||||||
if (widget.dossier.parents.length < 2) {
|
|
||||||
return const Padding(
|
|
||||||
padding: EdgeInsets.symmetric(vertical: 12),
|
|
||||||
child: Text('Un seul parent pour ce dossier.',
|
|
||||||
style: TextStyle(color: Colors.black87)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return IdentityBlock.readOnlyFromParentDossier(
|
|
||||||
widget.dossier.parents[1],
|
|
||||||
title: 'Deuxième parent',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
static const double _idPhotoAspectRatio = 35 / 45;
|
|
||||||
|
|
||||||
Widget _buildEnfantsStep() {
|
|
||||||
final enfants = widget.dossier.enfants;
|
|
||||||
if (enfants.isEmpty) {
|
|
||||||
return const Padding(
|
|
||||||
padding: EdgeInsets.symmetric(vertical: 12),
|
|
||||||
child: Text('Aucun enfant renseigné.',
|
|
||||||
style: TextStyle(color: Colors.black87)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
const Text(
|
|
||||||
'Enfants',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 16, fontWeight: FontWeight.w600, color: Colors.black87),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Expanded(
|
|
||||||
child: LayoutBuilder(
|
|
||||||
builder: (context, constraints) {
|
|
||||||
final cardHeight = constraints.maxHeight;
|
|
||||||
// Carte large : 1/3 photo + 2/3 champs (scroll horizontal si plusieurs enfants).
|
|
||||||
final cardWidth = (cardHeight * 1.72).clamp(500.0, 700.0);
|
|
||||||
return NotificationListener<ScrollMetricsNotification>(
|
|
||||||
onNotification: (_) {
|
|
||||||
_syncEnfantsScrollFades();
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
child: ShaderMask(
|
|
||||||
blendMode: BlendMode.dstIn,
|
|
||||||
shaderCallback: (Rect bounds) {
|
|
||||||
final stops = <double>[
|
|
||||||
0.0,
|
|
||||||
_enfantsFadeExtent,
|
|
||||||
1.0 - _enfantsFadeExtent,
|
|
||||||
1.0,
|
|
||||||
];
|
|
||||||
if (!_enfantsIsScrollable) {
|
|
||||||
return LinearGradient(
|
|
||||||
begin: Alignment.centerLeft,
|
|
||||||
end: Alignment.centerRight,
|
|
||||||
colors: const <Color>[
|
|
||||||
Colors.black,
|
|
||||||
Colors.black,
|
|
||||||
Colors.black,
|
|
||||||
Colors.black,
|
|
||||||
],
|
|
||||||
stops: stops,
|
|
||||||
).createShader(bounds);
|
|
||||||
}
|
|
||||||
final leftMask =
|
|
||||||
_enfantsFadeLeft ? Colors.transparent : Colors.black;
|
|
||||||
final rightMask =
|
|
||||||
_enfantsFadeRight ? Colors.transparent : Colors.black;
|
|
||||||
return LinearGradient(
|
|
||||||
begin: Alignment.centerLeft,
|
|
||||||
end: Alignment.centerRight,
|
|
||||||
colors: <Color>[
|
|
||||||
leftMask,
|
|
||||||
Colors.black,
|
|
||||||
Colors.black,
|
|
||||||
rightMask,
|
|
||||||
],
|
|
||||||
stops: stops,
|
|
||||||
).createShader(bounds);
|
|
||||||
},
|
|
||||||
child: Listener(
|
|
||||||
onPointerSignal: (event) {
|
|
||||||
if (event is PointerScrollEvent &&
|
|
||||||
_enfantsScrollController.hasClients) {
|
|
||||||
final offset = _enfantsScrollController.offset +
|
|
||||||
event.scrollDelta.dy;
|
|
||||||
_enfantsScrollController.jumpTo(offset.clamp(
|
|
||||||
_enfantsScrollController.position.minScrollExtent,
|
|
||||||
_enfantsScrollController.position.maxScrollExtent,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
child: ListView.builder(
|
|
||||||
controller: _enfantsScrollController,
|
|
||||||
scrollDirection: Axis.horizontal,
|
|
||||||
itemCount: enfants.length,
|
|
||||||
itemBuilder: (_, i) => Padding(
|
|
||||||
padding: EdgeInsets.only(
|
|
||||||
right: i < enfants.length - 1 ? 16 : 0),
|
|
||||||
child: SizedBox(
|
|
||||||
width: cardWidth,
|
|
||||||
height: cardHeight,
|
|
||||||
child: _buildEnfantCard(enfants[i]),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fond carte enfant : teintes très pastel ; bordure discrète ; accent léger (barre).
|
|
||||||
static const Color _enfantCardBoyBg = Color(0xFFF0F7FB);
|
|
||||||
static const Color _enfantCardBoyBorder = Color(0xFFE3EDF4);
|
|
||||||
static const Color _enfantCardGirlBg = Color(0xFFFCF5F8);
|
|
||||||
static const Color _enfantCardGirlBorder = Color(0xFFEAE3E7);
|
|
||||||
|
|
||||||
static const double _enfantCardRadius = 12;
|
|
||||||
|
|
||||||
static List<BoxShadow> _enfantCardShadows() => [
|
|
||||||
BoxShadow(
|
|
||||||
color: Colors.black.withOpacity(0.06),
|
|
||||||
blurRadius: 14,
|
|
||||||
offset: const Offset(0, 4),
|
|
||||||
),
|
|
||||||
];
|
|
||||||
|
|
||||||
static BoxDecoration _enfantCardDecoration(String? gender) {
|
|
||||||
final g = (gender ?? '').trim().toUpperCase();
|
|
||||||
if (g == 'H') {
|
|
||||||
return BoxDecoration(
|
|
||||||
color: _enfantCardBoyBg,
|
|
||||||
borderRadius: BorderRadius.circular(_enfantCardRadius),
|
|
||||||
border: Border.all(color: _enfantCardBoyBorder, width: 1),
|
|
||||||
boxShadow: _enfantCardShadows(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (g == 'F') {
|
|
||||||
return BoxDecoration(
|
|
||||||
color: _enfantCardGirlBg,
|
|
||||||
borderRadius: BorderRadius.circular(_enfantCardRadius),
|
|
||||||
border: Border.all(color: _enfantCardGirlBorder, width: 1),
|
|
||||||
boxShadow: _enfantCardShadows(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return BoxDecoration(
|
|
||||||
color: Colors.grey.shade50,
|
|
||||||
borderRadius: BorderRadius.circular(_enfantCardRadius),
|
|
||||||
border: Border.all(color: Colors.grey.shade300),
|
|
||||||
boxShadow: _enfantCardShadows(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Carte enfant : prénom pleine largeur, puis ligne photo 1/3 + colonne 2/3 (champs + statut hors TF si besoin).
|
|
||||||
Widget _buildEnfantCard(EnfantDossier e) {
|
|
||||||
final photoUrl = _fullPhotoUrl(e.photoUrl);
|
|
||||||
final columnStatusLabel = _enfantColumnStatusLabel(e);
|
|
||||||
return ClipRRect(
|
|
||||||
borderRadius: BorderRadius.circular(_enfantCardRadius),
|
|
||||||
child: Container(
|
|
||||||
decoration: _enfantCardDecoration(e.gender),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
Padding(
|
|
||||||
padding: const EdgeInsets.fromLTRB(12, 12, 12, 8),
|
|
||||||
child: _enfantLabeledField('Prénom', _v(e.firstName)),
|
|
||||||
),
|
|
||||||
Expanded(
|
|
||||||
child: Row(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
flex: 1,
|
|
||||||
child: LayoutBuilder(
|
|
||||||
builder: (context, c) {
|
|
||||||
// Même marge gauche que le bloc « Prénom » (12) ; droite / haut / bas 8.
|
|
||||||
const padL = 12.0;
|
|
||||||
const padR = 8.0;
|
|
||||||
const padV = 8.0;
|
|
||||||
final maxW =
|
|
||||||
(c.maxWidth - padL - padR).clamp(0.0, double.infinity);
|
|
||||||
final maxH =
|
|
||||||
(c.maxHeight - 2 * padV).clamp(0.0, double.infinity);
|
|
||||||
const ar = _idPhotoAspectRatio;
|
|
||||||
double ph = maxH;
|
|
||||||
double pw = ph * ar;
|
|
||||||
if (pw > maxW) {
|
|
||||||
pw = maxW;
|
|
||||||
ph = pw / ar;
|
|
||||||
}
|
|
||||||
return Padding(
|
|
||||||
padding: const EdgeInsets.fromLTRB(padL, padV, padR, padV),
|
|
||||||
child: Align(
|
|
||||||
alignment: Alignment.centerLeft,
|
|
||||||
child: _buildEnfantPhotoSlot(photoUrl, pw, ph),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Expanded(
|
|
||||||
flex: 2,
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.fromLTRB(4, 4, 14, 12),
|
|
||||||
child: columnStatusLabel == null
|
|
||||||
? SingleChildScrollView(
|
|
||||||
child: _buildEnfantInfoFields(e),
|
|
||||||
)
|
|
||||||
: CustomScrollView(
|
|
||||||
slivers: [
|
|
||||||
SliverToBoxAdapter(
|
|
||||||
child: _buildEnfantInfoFields(e),
|
|
||||||
),
|
|
||||||
SliverFillRemaining(
|
|
||||||
hasScrollBody: false,
|
|
||||||
child: Center(
|
|
||||||
child: Text(
|
|
||||||
columnStatusLabel,
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
style: GoogleFonts.merienda(
|
|
||||||
fontSize: 14,
|
|
||||||
fontStyle: FontStyle.italic,
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
color: Colors.grey.shade800,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Statut dans la colonne 2/3 (scolarisé·e, à naître, sans garde, en garde).
|
|
||||||
String? _enfantColumnStatusLabel(EnfantDossier e) {
|
|
||||||
return enfantColumnStatusLabel(status: e.status, gender: e.gender);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Nom ; date de naissance et genre sur une ligne (prénom au-dessus, pleine largeur).
|
|
||||||
Widget _buildEnfantInfoFields(EnfantDossier e) {
|
|
||||||
final isANaitre = (e.status ?? '').trim().toLowerCase() == 'a_naitre';
|
|
||||||
final dueDateRenseignee = e.dueDate != null && e.dueDate!.trim().isNotEmpty;
|
|
||||||
final dateValue = isANaitre
|
|
||||||
? (dueDateRenseignee ? '${_formatBirthDate(e.dueDate)} (P)' : '– (P)')
|
|
||||||
: _formatBirthDate(e.birthDate);
|
|
||||||
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
Padding(
|
|
||||||
padding: const EdgeInsets.only(bottom: 12),
|
|
||||||
child: _enfantLabeledField('Nom', _formatNom(e.lastName)),
|
|
||||||
),
|
|
||||||
Row(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
flex: 3,
|
|
||||||
child: _enfantLabeledField('Date de naissance', dateValue),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 16),
|
|
||||||
Expanded(
|
|
||||||
flex: 2,
|
|
||||||
child: _enfantLabeledField(
|
|
||||||
'Genre',
|
|
||||||
_genreEnfantLabel(e.gender, e.status),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _enfantLabeledField(String label, String value) {
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
label,
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 12,
|
|
||||||
fontWeight: FontWeight.w500,
|
|
||||||
color: Colors.grey.shade700,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
ValidationReadOnlyField(value: value),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildEnfantPhotoSlot(String photoUrl, double width, double height) {
|
|
||||||
const photoRadius = 8.0;
|
|
||||||
return Container(
|
|
||||||
width: width,
|
|
||||||
height: height,
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
borderRadius: BorderRadius.circular(photoRadius),
|
|
||||||
border: Border.all(color: Colors.black.withOpacity(0.08)),
|
|
||||||
boxShadow: [
|
|
||||||
BoxShadow(
|
|
||||||
color: Colors.black.withOpacity(0.05),
|
|
||||||
blurRadius: 6,
|
|
||||||
offset: const Offset(0, 2),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
clipBehavior: Clip.antiAlias,
|
|
||||||
child: photoUrl.isEmpty
|
|
||||||
? ColoredBox(
|
|
||||||
color: Colors.grey.shade100,
|
|
||||||
child: Center(
|
|
||||||
child: Icon(Icons.person_outline, size: 32, color: Colors.grey.shade400),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: AuthNetworkImage(
|
|
||||||
url: photoUrl,
|
|
||||||
fit: BoxFit.cover,
|
|
||||||
width: width,
|
|
||||||
height: height,
|
|
||||||
errorBuilder: (_, __, ___) => ColoredBox(
|
|
||||||
color: Colors.grey.shade100,
|
|
||||||
child: Center(
|
|
||||||
child: Icon(Icons.broken_image_outlined, size: 32, color: Colors.grey.shade400),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
static String _formatNom(String? lastName) {
|
|
||||||
final n = (lastName ?? '').trim().toUpperCase();
|
|
||||||
return n.isEmpty ? 'Non défini' : n;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Genre enfant : Garçon, Fille, ou "Non connu" (uniquement si l'enfant est à naître).
|
|
||||||
static String _genreEnfantLabel(String? gender, String? status) {
|
|
||||||
final g = (gender ?? '').trim().toUpperCase();
|
|
||||||
final isANaitre = (status ?? '').trim().toLowerCase() == 'a_naitre';
|
|
||||||
if (g == 'H') return 'Garçon';
|
|
||||||
if (g == 'F') return 'Fille';
|
|
||||||
if (isANaitre) return 'Non connu';
|
|
||||||
if (g.isEmpty) return 'Non défini';
|
|
||||||
return (gender ?? '').trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildPresentationStep() {
|
|
||||||
final p = widget.dossier.presentation ?? '';
|
|
||||||
final text = p.trim().isEmpty ? 'Non défini' : p;
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
const Text(
|
|
||||||
'Présentation',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 16, fontWeight: FontWeight.w600, color: Colors.black87),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Expanded(
|
|
||||||
child: LayoutBuilder(
|
|
||||||
builder: (context, constraints) {
|
|
||||||
return SingleChildScrollView(
|
|
||||||
child: ConstrainedBox(
|
|
||||||
constraints: BoxConstraints(minHeight: constraints.maxHeight),
|
|
||||||
child: Container(
|
|
||||||
width: double.infinity,
|
|
||||||
padding: const EdgeInsets.symmetric(
|
|
||||||
horizontal: 12, vertical: 10),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Colors.grey.shade50,
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
border: Border.all(color: Colors.grey.shade300),
|
|
||||||
),
|
|
||||||
child: SelectableText(
|
|
||||||
text,
|
|
||||||
style:
|
|
||||||
const TextStyle(color: Colors.black87, fontSize: 14),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildNavigation() {
|
|
||||||
if (_step == 3) {
|
|
||||||
return Row(
|
|
||||||
children: [
|
|
||||||
TextButton(onPressed: widget.onClose, child: const Text('Annuler')),
|
|
||||||
const Spacer(),
|
|
||||||
Row(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
TextButton(
|
|
||||||
onPressed: () {
|
|
||||||
setState(() => _step = 2);
|
|
||||||
_emitStep();
|
|
||||||
},
|
|
||||||
child: const Text('Précédent'),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
if (_isEnAttente && _firstParentId != null) ...[
|
|
||||||
OutlinedButton(
|
|
||||||
onPressed: _submitting ? null : _refuser,
|
|
||||||
child: const Text('Refuser')),
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
ElevatedButton(
|
|
||||||
style: ValidationModalTheme.primaryElevatedStyle,
|
|
||||||
onPressed: _submitting ? null : _onValiderPressed,
|
|
||||||
child: Text(_submitting ? 'Envoi...' : 'Valider'),
|
|
||||||
),
|
|
||||||
] else if (!_isEnAttente)
|
|
||||||
ElevatedButton(
|
|
||||||
style: ValidationModalTheme.primaryElevatedStyle,
|
|
||||||
onPressed: widget.onClose,
|
|
||||||
child: const Text('Fermer'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return Row(
|
|
||||||
children: [
|
|
||||||
TextButton(onPressed: widget.onClose, child: const Text('Annuler')),
|
|
||||||
const Spacer(),
|
|
||||||
if (_step > 0) ...[
|
|
||||||
TextButton(
|
|
||||||
onPressed: () {
|
|
||||||
setState(() => _step--);
|
|
||||||
_emitStep();
|
|
||||||
},
|
|
||||||
child: const Text('Précédent'),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
],
|
|
||||||
ElevatedButton(
|
|
||||||
style: ValidationModalTheme.primaryElevatedStyle,
|
|
||||||
onPressed: () {
|
|
||||||
setState(() => _step++);
|
|
||||||
_emitStep();
|
|
||||||
},
|
|
||||||
child: const Text('Suivant'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _onValiderPressed() async {
|
|
||||||
if (_submitting || _firstParentId == null) return;
|
|
||||||
final ok = await showValidationValiderConfirmDialog(
|
|
||||||
context,
|
|
||||||
body:
|
|
||||||
'Voulez-vous valider ce dossier famille ? Les comptes parents concernés seront confirmés.',
|
|
||||||
);
|
|
||||||
if (!mounted || !ok) return;
|
|
||||||
await _valider();
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _valider() async {
|
|
||||||
if (_submitting || _firstParentId == null) return;
|
|
||||||
setState(() => _submitting = true);
|
|
||||||
try {
|
|
||||||
await UserService.validerDossierFamille(_firstParentId!);
|
|
||||||
if (!mounted) return;
|
|
||||||
widget.onSuccess();
|
|
||||||
} catch (e) {
|
|
||||||
if (!mounted) return;
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text(e is Exception
|
|
||||||
? e.toString().replaceFirst('Exception: ', '')
|
|
||||||
: 'Erreur'),
|
|
||||||
backgroundColor: Colors.red.shade700,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
if (mounted) setState(() => _submitting = false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _refuser() => setState(() => _showRefusForm = true);
|
|
||||||
|
|
||||||
Widget _buildRefusPage() {
|
|
||||||
return Padding(
|
|
||||||
padding: const EdgeInsets.all(20),
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: ValidationRefusForm(
|
|
||||||
isSubmitting: _submitting,
|
|
||||||
onCancel: widget.onClose,
|
|
||||||
onPrevious: () => setState(() => _showRefusForm = false),
|
|
||||||
onSubmit: (comment) {
|
|
||||||
if (comment == null || comment.trim().isEmpty) return;
|
|
||||||
_refuserEnvoyer(comment.trim());
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Un seul appel : le back refuse tout le dossier famille (co-parents + mails). Ticket #110.
|
|
||||||
Future<void> _refuserEnvoyer(String comment) async {
|
|
||||||
if (_submitting) return;
|
|
||||||
final parentId = _firstParentId?.trim();
|
|
||||||
if (parentId == null || parentId.isEmpty || !_isEnAttente) {
|
|
||||||
if (!mounted) return;
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: const Text('Aucun compte en attente à refuser pour ce dossier.'),
|
|
||||||
backgroundColor: Colors.red.shade700,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setState(() => _submitting = true);
|
|
||||||
try {
|
|
||||||
await UserService.refuseUser(parentId, comment: comment);
|
|
||||||
if (!mounted) return;
|
|
||||||
final nbEnAttente = widget.dossier.parents
|
|
||||||
.where((p) => p.statut == 'en_attente')
|
|
||||||
.length;
|
|
||||||
final msg = nbEnAttente > 1
|
|
||||||
? 'Refus enregistré. Un e-mail de reprise a été envoyé à chaque parent du dossier.'
|
|
||||||
: 'Refus enregistré. Un e-mail avec le lien de reprise a été envoyé.';
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text(msg),
|
|
||||||
duration: const Duration(seconds: 4),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
widget.onSuccess();
|
|
||||||
} catch (e) {
|
|
||||||
if (!mounted) return;
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text(e is Exception
|
|
||||||
? e.toString().replaceFirst('Exception: ', '')
|
|
||||||
: 'Erreur'),
|
|
||||||
backgroundColor: Colors.red.shade700,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
if (mounted) setState(() => _submitting = false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:p_tits_pas/models/dossier_unifie.dart';
|
import 'package:p_tits_pas/models/dossier_unifie.dart';
|
||||||
import 'package:p_tits_pas/models/user.dart';
|
import 'package:p_tits_pas/models/user.dart';
|
||||||
|
import 'package:p_tits_pas/utils/name_format_utils.dart';
|
||||||
import 'package:p_tits_pas/utils/phone_utils.dart';
|
import 'package:p_tits_pas/utils/phone_utils.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/common/validation_detail_section.dart';
|
import 'package:p_tits_pas/widgets/dashboard/common/validation_detail_section.dart';
|
||||||
|
|
||||||
/// Valeurs affichées dans un [IdentityBlock] en lecture seule.
|
/// Valeurs affichées dans un [IdentityBlock] en lecture seule.
|
||||||
class IdentityValues {
|
class IdentityValues {
|
||||||
@@ -67,7 +68,9 @@ class IdentityValues {
|
|||||||
|
|
||||||
/// Bloc identité : Nom/Prénom, Tél/Email, Adresse, CP/Ville.
|
/// Bloc identité : Nom/Prénom, Tél/Email, Adresse, CP/Ville.
|
||||||
/// Grille partagée (création de compte, validation AM/famille, fiches admin, etc.).
|
/// Grille partagée (création de compte, validation AM/famille, fiches admin, etc.).
|
||||||
class IdentityBlock extends StatelessWidget { final String? title;
|
class IdentityBlock extends StatelessWidget {
|
||||||
|
final String? title;
|
||||||
|
final bool expandVertically;
|
||||||
|
|
||||||
final String? _nom;
|
final String? _nom;
|
||||||
final String? _prenom;
|
final String? _prenom;
|
||||||
@@ -91,6 +94,7 @@ class IdentityBlock extends StatelessWidget { final String? title;
|
|||||||
const IdentityBlock.readOnly({
|
const IdentityBlock.readOnly({
|
||||||
super.key,
|
super.key,
|
||||||
this.title,
|
this.title,
|
||||||
|
this.expandVertically = false,
|
||||||
required String nom,
|
required String nom,
|
||||||
required String prenom,
|
required String prenom,
|
||||||
required String telephone,
|
required String telephone,
|
||||||
@@ -116,6 +120,7 @@ class IdentityBlock extends StatelessWidget { final String? title;
|
|||||||
const IdentityBlock.editable({
|
const IdentityBlock.editable({
|
||||||
super.key,
|
super.key,
|
||||||
this.title,
|
this.title,
|
||||||
|
this.expandVertically = false,
|
||||||
required TextEditingController nomController,
|
required TextEditingController nomController,
|
||||||
required TextEditingController prenomController,
|
required TextEditingController prenomController,
|
||||||
required TextEditingController telephoneController,
|
required TextEditingController telephoneController,
|
||||||
@@ -142,11 +147,13 @@ class IdentityBlock extends StatelessWidget { final String? title;
|
|||||||
factory IdentityBlock.readOnlyValues({
|
factory IdentityBlock.readOnlyValues({
|
||||||
Key? key,
|
Key? key,
|
||||||
String? title,
|
String? title,
|
||||||
|
bool expandVertically = false,
|
||||||
required IdentityValues values,
|
required IdentityValues values,
|
||||||
}) {
|
}) {
|
||||||
return IdentityBlock.readOnly(
|
return IdentityBlock.readOnly(
|
||||||
key: key,
|
key: key,
|
||||||
title: title,
|
title: title,
|
||||||
|
expandVertically: expandVertically,
|
||||||
nom: values.nom,
|
nom: values.nom,
|
||||||
prenom: values.prenom,
|
prenom: values.prenom,
|
||||||
telephone: values.telephone,
|
telephone: values.telephone,
|
||||||
@@ -163,10 +170,12 @@ class IdentityBlock extends StatelessWidget { final String? title;
|
|||||||
Key? key,
|
Key? key,
|
||||||
String? title,
|
String? title,
|
||||||
String emptyLabel = 'Non défini',
|
String emptyLabel = 'Non défini',
|
||||||
|
bool expandVertically = false,
|
||||||
}) {
|
}) {
|
||||||
return IdentityBlock.readOnlyValues(
|
return IdentityBlock.readOnlyValues(
|
||||||
key: key,
|
key: key,
|
||||||
title: title,
|
title: title,
|
||||||
|
expandVertically: expandVertically,
|
||||||
values: IdentityValues.fromUser(user, emptyLabel: emptyLabel),
|
values: IdentityValues.fromUser(user, emptyLabel: emptyLabel),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -196,29 +205,29 @@ class IdentityBlock extends StatelessWidget { final String? title;
|
|||||||
title: title,
|
title: title,
|
||||||
rowLayout: rowLayout,
|
rowLayout: rowLayout,
|
||||||
rowFlex: rowFlex,
|
rowFlex: rowFlex,
|
||||||
|
expandVertically: expandVertically,
|
||||||
fields: [
|
fields: [
|
||||||
ValidationLabeledField(
|
ValidationLabeledField(
|
||||||
label: 'Nom',
|
label: 'Nom',
|
||||||
field: ValidationEditableField(controller: _nomCtrl!),
|
field: ValidationEditableField(
|
||||||
|
controller: _nomCtrl!,
|
||||||
|
inputFormatters: const [PersonNameInputFormatter()],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
ValidationLabeledField(
|
ValidationLabeledField(
|
||||||
label: 'Prénom',
|
label: 'Prénom',
|
||||||
field: ValidationEditableField(controller: _prenomCtrl!),
|
field: ValidationEditableField(
|
||||||
|
controller: _prenomCtrl!,
|
||||||
|
inputFormatters: const [PersonNameInputFormatter()],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
ValidationLabeledField(
|
ValidationLabeledField(
|
||||||
label: 'Téléphone',
|
label: 'Téléphone',
|
||||||
field: ValidationEditableField(
|
field: ValidationPhoneField(controller: _telCtrl!),
|
||||||
controller: _telCtrl!,
|
|
||||||
keyboardType: TextInputType.phone,
|
|
||||||
inputFormatters: frenchPhoneInputFormatters,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
ValidationLabeledField(
|
ValidationLabeledField(
|
||||||
label: 'Email',
|
label: 'Email',
|
||||||
field: ValidationEditableField(
|
field: ValidationEmailField(controller: _emailCtrl!),
|
||||||
controller: _emailCtrl!,
|
|
||||||
keyboardType: TextInputType.emailAddress,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
ValidationLabeledField(
|
ValidationLabeledField(
|
||||||
label: 'Adresse (N° et Rue)',
|
label: 'Adresse (N° et Rue)',
|
||||||
@@ -226,14 +235,14 @@ class IdentityBlock extends StatelessWidget { final String? title;
|
|||||||
),
|
),
|
||||||
ValidationLabeledField(
|
ValidationLabeledField(
|
||||||
label: 'Code postal',
|
label: 'Code postal',
|
||||||
field: ValidationEditableField(
|
field: ValidationPostalCodeField(controller: _cpCtrl!),
|
||||||
controller: _cpCtrl!,
|
|
||||||
keyboardType: TextInputType.number,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
ValidationLabeledField(
|
ValidationLabeledField(
|
||||||
label: 'Ville',
|
label: 'Ville',
|
||||||
field: ValidationEditableField(controller: _villeCtrl!),
|
field: ValidationEditableField(
|
||||||
|
controller: _villeCtrl!,
|
||||||
|
inputFormatters: const [PersonNameInputFormatter()],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
@@ -243,6 +252,7 @@ class IdentityBlock extends StatelessWidget { final String? title;
|
|||||||
title: title,
|
title: title,
|
||||||
rowLayout: rowLayout,
|
rowLayout: rowLayout,
|
||||||
rowFlex: rowFlex,
|
rowFlex: rowFlex,
|
||||||
|
expandVertically: expandVertically,
|
||||||
fields: [
|
fields: [
|
||||||
ValidationLabeledField(
|
ValidationLabeledField(
|
||||||
label: 'Nom',
|
label: 'Nom',
|
||||||
|
|||||||
+46
-9
@@ -5,7 +5,7 @@ import 'package:p_tits_pas/utils/date_display_utils.dart';
|
|||||||
import 'package:p_tits_pas/widgets/common/auth_network_image.dart';
|
import 'package:p_tits_pas/widgets/common/auth_network_image.dart';
|
||||||
|
|
||||||
/// Grille 2×2 des places d'accueil AM (max 4, limitée à [capacity]).
|
/// Grille 2×2 des places d'accueil AM (max 4, limitée à [capacity]).
|
||||||
class AdminAmChildrenCapacityGrid extends StatelessWidget {
|
class AmChildrenCapacityGrid extends StatelessWidget {
|
||||||
static const int _gridSlots = 4;
|
static const int _gridSlots = 4;
|
||||||
static const double _slotHeight = 44;
|
static const double _slotHeight = 44;
|
||||||
static const double _gridPadding = 10;
|
static const double _gridPadding = 10;
|
||||||
@@ -20,13 +20,16 @@ class AdminAmChildrenCapacityGrid extends StatelessWidget {
|
|||||||
final int capacity;
|
final int capacity;
|
||||||
final void Function(ParentChildSummary child) onOpen;
|
final void Function(ParentChildSummary child) onOpen;
|
||||||
final void Function(ParentChildSummary child) onDetach;
|
final void Function(ParentChildSummary child) onDetach;
|
||||||
|
/// Clic sur une case libre → même flux que « Rattacher un enfant » (#149).
|
||||||
|
final VoidCallback? onAttachEmpty;
|
||||||
|
|
||||||
const AdminAmChildrenCapacityGrid({
|
const AmChildrenCapacityGrid({
|
||||||
super.key,
|
super.key,
|
||||||
required this.children,
|
required this.children,
|
||||||
required this.capacity,
|
required this.capacity,
|
||||||
required this.onOpen,
|
required this.onOpen,
|
||||||
required this.onDetach,
|
required this.onDetach,
|
||||||
|
this.onAttachEmpty,
|
||||||
});
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -78,7 +81,7 @@ class AdminAmChildrenCapacityGrid extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (index < maxSlots) {
|
if (index < maxSlots) {
|
||||||
return const _EmptySlot();
|
return _EmptySlot(onTap: onAttachEmpty);
|
||||||
}
|
}
|
||||||
return const _UnavailableSlot();
|
return const _UnavailableSlot();
|
||||||
}
|
}
|
||||||
@@ -129,18 +132,52 @@ class _UnavailableSlot extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class _EmptySlot extends StatelessWidget {
|
class _EmptySlot extends StatefulWidget {
|
||||||
const _EmptySlot();
|
final VoidCallback? onTap;
|
||||||
|
|
||||||
|
const _EmptySlot({this.onTap});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_EmptySlot> createState() => _EmptySlotState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _EmptySlotState extends State<_EmptySlot> {
|
||||||
|
bool _hovered = false;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return _SlotShell(
|
final clickable = widget.onTap != null;
|
||||||
backgroundColor: Colors.grey.shade50,
|
return MouseRegion(
|
||||||
borderColor: Colors.grey.shade300,
|
onEnter: clickable ? (_) => setState(() => _hovered = true) : null,
|
||||||
|
onExit: clickable ? (_) => setState(() => _hovered = false) : null,
|
||||||
|
cursor: clickable ? SystemMouseCursors.click : MouseCursor.defer,
|
||||||
|
child: Material(
|
||||||
|
color: Colors.transparent,
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
child: InkWell(
|
||||||
|
onTap: widget.onTap,
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
hoverColor: const Color(0x149CC5C0),
|
||||||
|
child: _SlotShell(
|
||||||
|
backgroundColor: _hovered
|
||||||
|
? const Color(0xFFF3F0FA)
|
||||||
|
: Colors.grey.shade50,
|
||||||
|
borderColor: _hovered
|
||||||
|
? const Color(0xFFB8A4D4)
|
||||||
|
: Colors.grey.shade300,
|
||||||
child: Center(
|
child: Center(
|
||||||
child: Text(
|
child: Text(
|
||||||
'Place libre',
|
'Place libre',
|
||||||
style: TextStyle(fontSize: 12, color: Colors.grey.shade500),
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: _hovered
|
||||||
|
? const Color(0xFF6B3FA0)
|
||||||
|
: Colors.grey.shade500,
|
||||||
|
fontWeight: _hovered ? FontWeight.w600 : FontWeight.w400,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/dashboard/am_dossier_wizard.dart';
|
||||||
|
|
||||||
|
/// Modale de création dossier AM (#156) — même shell que [ValidationDossierModal].
|
||||||
|
class AmDossierCreateModal extends StatefulWidget {
|
||||||
|
final VoidCallback onClose;
|
||||||
|
final VoidCallback? onSuccess;
|
||||||
|
|
||||||
|
const AmDossierCreateModal({
|
||||||
|
super.key,
|
||||||
|
required this.onClose,
|
||||||
|
this.onSuccess,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<AmDossierCreateModal> createState() => _AmDossierCreateModalState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _AmDossierCreateModalState extends State<AmDossierCreateModal> {
|
||||||
|
int? _stepIndex;
|
||||||
|
int? _stepTotal;
|
||||||
|
|
||||||
|
void _onStepChanged(int step, int total) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_stepIndex = step;
|
||||||
|
_stepTotal = total;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onSuccess() {
|
||||||
|
widget.onSuccess?.call();
|
||||||
|
}
|
||||||
|
|
||||||
|
static const double _modalWidth = 930;
|
||||||
|
/// Hauteur calculée depuis 4 lignes de TF (voir [AmDossierWizard.shellBodyHeight]).
|
||||||
|
static double get _bodyHeight => AmDossierWizard.shellBodyHeight;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final maxH = MediaQuery.of(context).size.height * 0.85;
|
||||||
|
final showStep =
|
||||||
|
_stepIndex != null && _stepTotal != null && (_stepTotal ?? 0) > 0;
|
||||||
|
return Dialog(
|
||||||
|
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||||
|
child: ConstrainedBox(
|
||||||
|
constraints: BoxConstraints(maxWidth: _modalWidth, maxHeight: maxH),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.fromLTRB(18, 18, 0, 12),
|
||||||
|
child: Text(
|
||||||
|
'Nouvelle assistante maternelle',
|
||||||
|
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const Spacer(),
|
||||||
|
if (showStep) ...[
|
||||||
|
Text(
|
||||||
|
'Étape ${(_stepIndex ?? 0) + 1}/${_stepTotal ?? 1}',
|
||||||
|
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||||
|
color: Colors.black54,
|
||||||
|
fontStyle: FontStyle.italic,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
],
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.close),
|
||||||
|
onPressed: widget.onClose,
|
||||||
|
tooltip: 'Fermer',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const Divider(height: 1),
|
||||||
|
SizedBox(
|
||||||
|
height: _bodyHeight,
|
||||||
|
child: AmDossierWizard.create(
|
||||||
|
onClose: widget.onClose,
|
||||||
|
onSuccess: _onSuccess,
|
||||||
|
onStepChanged: _onStepChanged,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
+128
-91
@@ -1,37 +1,37 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:p_tits_pas/models/assistante_maternelle_model.dart';
|
import 'package:p_tits_pas/models/assistante_maternelle_model.dart';
|
||||||
import 'package:p_tits_pas/models/enfant_admin_model.dart';
|
|
||||||
import 'package:p_tits_pas/models/parent_child_summary.dart';
|
import 'package:p_tits_pas/models/parent_child_summary.dart';
|
||||||
import 'package:p_tits_pas/utils/am_vigilance.dart';
|
import 'package:p_tits_pas/utils/am_vigilance.dart';
|
||||||
import 'package:p_tits_pas/utils/date_display_utils.dart';
|
import 'package:p_tits_pas/utils/date_display_utils.dart';
|
||||||
import 'package:p_tits_pas/utils/nir_utils.dart';
|
import 'package:p_tits_pas/utils/nir_utils.dart';
|
||||||
import 'package:p_tits_pas/utils/phone_utils.dart';
|
import 'package:p_tits_pas/utils/phone_utils.dart';
|
||||||
import 'package:p_tits_pas/services/user_service.dart';
|
import 'package:p_tits_pas/services/user_service.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/common/admin_am_children_capacity_grid.dart';
|
import 'package:p_tits_pas/widgets/dashboard/am_children_capacity_grid.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/common/admin_am_photo_frame.dart';
|
import 'package:p_tits_pas/widgets/dashboard/am_photo_frame.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/common/admin_child_detail_modal.dart';
|
import 'package:p_tits_pas/widgets/dashboard/child_detail_modal.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/common/admin_status_capsule.dart';
|
import 'package:p_tits_pas/widgets/dashboard/select_enfant_modal.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/common/validation_detail_section.dart';
|
import 'package:p_tits_pas/widgets/dashboard/status_capsule.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/dashboard/common/validation_detail_section.dart';
|
||||||
import 'package:p_tits_pas/widgets/common/identity_block.dart';
|
import 'package:p_tits_pas/widgets/common/identity_block.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/validation_modal_theme.dart';
|
import 'package:p_tits_pas/widgets/dashboard/validation_modal_theme.dart';
|
||||||
|
|
||||||
/// Fiche AM éditable (ticket #131) — identité | fiche pro (photo) | enfants.
|
/// Fiche AM éditable (ticket #131) — identité | fiche pro (photo) | enfants.
|
||||||
class AdminAmEditModal extends StatefulWidget {
|
class AmEditModal extends StatefulWidget {
|
||||||
final AssistanteMaternelleModel assistante;
|
final AssistanteMaternelleModel assistante;
|
||||||
final VoidCallback? onSaved;
|
final VoidCallback? onSaved;
|
||||||
|
|
||||||
const AdminAmEditModal({
|
const AmEditModal({
|
||||||
super.key,
|
super.key,
|
||||||
required this.assistante,
|
required this.assistante,
|
||||||
this.onSaved,
|
this.onSaved,
|
||||||
});
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<AdminAmEditModal> createState() => _AdminAmEditModalState();
|
State<AmEditModal> createState() => _AmEditModalState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _AdminAmEditModalState extends State<AdminAmEditModal>
|
class _AmEditModalState extends State<AmEditModal>
|
||||||
with SingleTickerProviderStateMixin {
|
with SingleTickerProviderStateMixin {
|
||||||
late final TabController _tabCtrl;
|
late final TabController _tabCtrl;
|
||||||
late final TextEditingController _nomCtrl;
|
late final TextEditingController _nomCtrl;
|
||||||
@@ -55,6 +55,10 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
late List<ParentChildSummary> _children;
|
late List<ParentChildSummary> _children;
|
||||||
late Set<String> _baselineChildIds;
|
late Set<String> _baselineChildIds;
|
||||||
|
|
||||||
|
/// Enfants ajoutés localement qui étaient déjà chez une autre AM
|
||||||
|
/// (enfantId → amUserId d'origine). Au save : détacher puis rattacher.
|
||||||
|
final Map<String, String> _transferFromAmIds = {};
|
||||||
|
|
||||||
bool _saving = false;
|
bool _saving = false;
|
||||||
bool _dirty = false;
|
bool _dirty = false;
|
||||||
|
|
||||||
@@ -65,29 +69,6 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
static const double _proTabHeight = 300;
|
static const double _proTabHeight = 300;
|
||||||
static const List<int> _photoProRowLayout = [2, 2, 2];
|
static const List<int> _photoProRowLayout = [2, 2, 2];
|
||||||
|
|
||||||
/// Hauteur onglet enfants : champs + titre + grille 2×2 (+ alerte places si besoin).
|
|
||||||
double _childrenTabHeight() {
|
|
||||||
const capacityFields = 72.0;
|
|
||||||
const titleSection = 40.0;
|
|
||||||
const inconsistencyExtra = 46.0;
|
|
||||||
var h = capacityFields +
|
|
||||||
titleSection +
|
|
||||||
AdminAmChildrenCapacityGrid.fixedHeight;
|
|
||||||
if (_placesInconsistent()) h += inconsistencyExtra;
|
|
||||||
return h + 4;
|
|
||||||
}
|
|
||||||
|
|
||||||
double _tabViewHeight(int index) {
|
|
||||||
switch (index) {
|
|
||||||
case 1:
|
|
||||||
return _proTabHeight;
|
|
||||||
case 2:
|
|
||||||
return _childrenTabHeight();
|
|
||||||
default:
|
|
||||||
return 292;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
@@ -234,6 +215,13 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
|
|
||||||
int? _capaciteMax() => _parseIntField(_capaciteCtrl);
|
int? _capaciteMax() => _parseIntField(_capaciteCtrl);
|
||||||
|
|
||||||
|
/// True si plus aucune place d'accueil (enfants ≥ capacité max).
|
||||||
|
bool get _capacityFull {
|
||||||
|
final max = _capaciteMax();
|
||||||
|
if (max == null) return false;
|
||||||
|
return _children.length >= max;
|
||||||
|
}
|
||||||
|
|
||||||
int? _computedPlacesAvailable() => amExpectedPlacesAvailable(
|
int? _computedPlacesAvailable() => amExpectedPlacesAvailable(
|
||||||
maxChildren: _capaciteMax(),
|
maxChildren: _capaciteMax(),
|
||||||
childrenCount: _children.length,
|
childrenCount: _children.length,
|
||||||
@@ -311,6 +299,17 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
for (final id in currentIds.difference(_baselineChildIds)) {
|
for (final id in currentIds.difference(_baselineChildIds)) {
|
||||||
|
// Transfert : détacher l'ancienne AM sans recalculer ses places
|
||||||
|
// (le ! de vigilance apparaît côté liste AM).
|
||||||
|
final previousAmId = _transferFromAmIds[id] ??
|
||||||
|
(await UserService.findAmForEnfant(id))?.user.id;
|
||||||
|
if (previousAmId != null &&
|
||||||
|
previousAmId != widget.assistante.user.id) {
|
||||||
|
await UserService.detachEnfantFromAm(
|
||||||
|
amUserId: previousAmId,
|
||||||
|
enfantId: id,
|
||||||
|
);
|
||||||
|
}
|
||||||
await UserService.attachEnfantToAm(
|
await UserService.attachEnfantToAm(
|
||||||
amUserId: widget.assistante.user.id,
|
amUserId: widget.assistante.user.id,
|
||||||
enfantId: id,
|
enfantId: id,
|
||||||
@@ -346,6 +345,7 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
_dirty = false;
|
_dirty = false;
|
||||||
_saving = false;
|
_saving = false;
|
||||||
_baselineChildIds = currentIds;
|
_baselineChildIds = currentIds;
|
||||||
|
_transferFromAmIds.clear();
|
||||||
});
|
});
|
||||||
widget.onSaved?.call();
|
widget.onSaved?.call();
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
@@ -377,6 +377,7 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
setState(() {
|
setState(() {
|
||||||
_children = kids;
|
_children = kids;
|
||||||
_baselineChildIds = kids.map((c) => c.id).toSet();
|
_baselineChildIds = kids.map((c) => c.id).toSet();
|
||||||
|
_transferFromAmIds.clear();
|
||||||
});
|
});
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
}
|
}
|
||||||
@@ -403,7 +404,7 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
await showDialog<void>(
|
await showDialog<void>(
|
||||||
context: context,
|
context: context,
|
||||||
builder: (ctx) => AdminChildDetailModal(
|
builder: (ctx) => ChildDetailModal(
|
||||||
enfant: enfant,
|
enfant: enfant,
|
||||||
onSaved: _refreshChildrenDetails,
|
onSaved: _refreshChildrenDetails,
|
||||||
),
|
),
|
||||||
@@ -422,8 +423,7 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
builder: (ctx) => AlertDialog(
|
builder: (ctx) => AlertDialog(
|
||||||
title: const Text('Détacher l\'enfant'),
|
title: const Text('Détacher l\'enfant'),
|
||||||
content: Text(
|
content: Text(
|
||||||
'Retirer ${child.fullName} de la fiche de cette assistante ?\n'
|
'Retirer ${child.fullName} de la fiche de cette assistante ?',
|
||||||
'(L\'enfant ne sera pas supprimé.)',
|
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
TextButton(
|
||||||
@@ -442,55 +442,75 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
|
|
||||||
setState(() {
|
setState(() {
|
||||||
_children = _children.where((c) => c.id != child.id).toList();
|
_children = _children.where((c) => c.id != child.id).toList();
|
||||||
|
_transferFromAmIds.remove(child.id);
|
||||||
_syncPlacesAfterChildrenChange();
|
_syncPlacesAfterChildrenChange();
|
||||||
_dirty = true;
|
_dirty = true;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _attachChild() async {
|
Future<void> _attachChild() async {
|
||||||
List<EnfantAdminModel> all;
|
if (_capacityFull || !mounted) return;
|
||||||
try {
|
final selected = await SelectEnfantModal.show(
|
||||||
all = await UserService.getEnfants();
|
context,
|
||||||
} catch (e) {
|
excludeIds: _children.map((c) => c.id).toSet(),
|
||||||
if (!mounted) return;
|
title: 'Rattacher un enfant',
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
showSansGardeFilter: true,
|
||||||
SnackBar(content: Text(e.toString().replaceFirst('Exception: ', ''))),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
final linkedIds = _children.map((c) => c.id).toSet();
|
|
||||||
final candidates = all.where((e) => !linkedIds.contains(e.id)).toList();
|
|
||||||
if (candidates.isEmpty) {
|
|
||||||
if (!mounted) return;
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(content: Text('Aucun enfant disponible à rattacher')),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!mounted) return;
|
|
||||||
final selected = await showDialog<EnfantAdminModel>(
|
|
||||||
context: context,
|
|
||||||
builder: (ctx) => SimpleDialog(
|
|
||||||
title: const Text('Rattacher un enfant'),
|
|
||||||
children: candidates
|
|
||||||
.map(
|
|
||||||
(e) => SimpleDialogOption(
|
|
||||||
onPressed: () => Navigator.pop(ctx, e),
|
|
||||||
child: Text(e.fullName),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.toList(),
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
if (selected == null || !mounted) return;
|
if (selected == null || !mounted) return;
|
||||||
|
|
||||||
|
AssistanteMaternelleModel? previousAm;
|
||||||
|
try {
|
||||||
|
previousAm = await UserService.findAmForEnfant(selected.id);
|
||||||
|
} catch (_) {
|
||||||
|
previousAm = null;
|
||||||
|
}
|
||||||
|
if (!mounted) return;
|
||||||
|
|
||||||
|
final previousAmId = previousAm?.user.id;
|
||||||
|
final isTransfer = previousAmId != null &&
|
||||||
|
previousAmId != widget.assistante.user.id;
|
||||||
|
|
||||||
|
if (isTransfer) {
|
||||||
|
final amName = previousAm!.user.fullName.trim().isNotEmpty
|
||||||
|
? previousAm.user.fullName.trim()
|
||||||
|
: 'une autre assistante maternelle';
|
||||||
|
final gardeLabel =
|
||||||
|
(selected.gender ?? '').trim().toUpperCase() == 'F'
|
||||||
|
? 'déjà gardée'
|
||||||
|
: 'déjà gardé';
|
||||||
|
final confirmed = await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
builder: (ctx) => AlertDialog(
|
||||||
|
title: const Text('Changer d\'affectation'),
|
||||||
|
content: Text(
|
||||||
|
'${selected.fullName} est $gardeLabel par $amName.\n\n'
|
||||||
|
'Confirmer le transfert vers cette assistante ? '
|
||||||
|
'L\'enfant sera détaché de $amName.',
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(ctx, false),
|
||||||
|
child: const Text('Annuler'),
|
||||||
|
),
|
||||||
|
ElevatedButton(
|
||||||
|
onPressed: () => Navigator.pop(ctx, true),
|
||||||
|
style: ValidationModalTheme.primaryElevatedStyle,
|
||||||
|
child: const Text('Confirmer'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (confirmed != true || !mounted) return;
|
||||||
|
}
|
||||||
|
|
||||||
setState(() {
|
setState(() {
|
||||||
_children = [
|
_children = [
|
||||||
..._children,
|
..._children,
|
||||||
ParentChildSummary.fromEnfant(selected),
|
ParentChildSummary.fromEnfant(selected),
|
||||||
];
|
];
|
||||||
|
if (isTransfer) {
|
||||||
|
_transferFromAmIds[selected.id] = previousAmId!;
|
||||||
|
}
|
||||||
_syncPlacesAfterChildrenChange();
|
_syncPlacesAfterChildrenChange();
|
||||||
_dirty = true;
|
_dirty = true;
|
||||||
});
|
});
|
||||||
@@ -498,8 +518,7 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
|
|
||||||
|
|
||||||
Widget _identityTab() {
|
Widget _identityTab() {
|
||||||
return SingleChildScrollView(
|
return IdentityBlock.editable(
|
||||||
child: IdentityBlock.editable(
|
|
||||||
title: 'Identité et coordonnées',
|
title: 'Identité et coordonnées',
|
||||||
nomController: _nomCtrl,
|
nomController: _nomCtrl,
|
||||||
prenomController: _prenomCtrl,
|
prenomController: _prenomCtrl,
|
||||||
@@ -508,7 +527,6 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
adresseController: _adresseCtrl,
|
adresseController: _adresseCtrl,
|
||||||
codePostalController: _cpCtrl,
|
codePostalController: _cpCtrl,
|
||||||
villeController: _villeCtrl,
|
villeController: _villeCtrl,
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -567,9 +585,11 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
return LayoutBuilder(
|
return LayoutBuilder(
|
||||||
builder: (context, c) {
|
builder: (context, c) {
|
||||||
final maxRowW = c.maxWidth;
|
final maxRowW = c.maxWidth;
|
||||||
final maxRowH = c.maxHeight;
|
// Hauteur bornée : l’onglet pro a une hauteur fixe (photo ID).
|
||||||
|
final maxRowH =
|
||||||
|
c.maxHeight.isFinite ? c.maxHeight : _proTabHeight;
|
||||||
final bodyH = maxRowH;
|
final bodyH = maxRowH;
|
||||||
final idealPhotoW = bodyH * AdminAmPhotoFrame.idPhotoAspectRatio + 16;
|
final idealPhotoW = bodyH * AmPhotoFrame.idPhotoAspectRatio + 16;
|
||||||
final maxPhotoW = (maxRowW - _photoProGap - _proColumnMinWidth)
|
final maxPhotoW = (maxRowW - _photoProGap - _proColumnMinWidth)
|
||||||
.clamp(0.0, double.infinity);
|
.clamp(0.0, double.infinity);
|
||||||
var photoW = idealPhotoW.clamp(_photoColumnMinWidth, 220.0);
|
var photoW = idealPhotoW.clamp(_photoColumnMinWidth, 220.0);
|
||||||
@@ -580,7 +600,7 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
children: [
|
children: [
|
||||||
SizedBox(
|
SizedBox(
|
||||||
width: photoW,
|
width: photoW,
|
||||||
child: AdminAmPhotoFrame(
|
child: AmPhotoFrame(
|
||||||
photoUrl: widget.assistante.user.photoUrl,
|
photoUrl: widget.assistante.user.photoUrl,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -616,6 +636,18 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Corps de l’onglet actif — hauteur naturelle (pas de TabBarView).
|
||||||
|
Widget _buildActiveTabBody() {
|
||||||
|
switch (_tabCtrl.index) {
|
||||||
|
case 1:
|
||||||
|
return SizedBox(height: _proTabHeight, child: _proTab());
|
||||||
|
case 2:
|
||||||
|
return _childrenTab();
|
||||||
|
default:
|
||||||
|
return _identityTab();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Widget _childrenCapacityFields() {
|
Widget _childrenCapacityFields() {
|
||||||
final inconsistent = _placesInconsistent();
|
final inconsistent = _placesInconsistent();
|
||||||
return Column(
|
return Column(
|
||||||
@@ -696,11 +728,12 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
AdminAmChildrenCapacityGrid(
|
AmChildrenCapacityGrid(
|
||||||
children: _children,
|
children: _children,
|
||||||
capacity: capacity,
|
capacity: capacity,
|
||||||
onOpen: _openChild,
|
onOpen: _openChild,
|
||||||
onDetach: _detachChild,
|
onDetach: _detachChild,
|
||||||
|
onAttachEmpty: _capacityFull ? null : _attachChild,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
@@ -708,6 +741,7 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
|
|
||||||
Widget _buildFooter() {
|
Widget _buildFooter() {
|
||||||
final isChildrenTab = _tabCtrl.index == 2;
|
final isChildrenTab = _tabCtrl.index == 2;
|
||||||
|
final canAttachChild = !_saving && !_capacityFull;
|
||||||
return Row(
|
return Row(
|
||||||
children: [
|
children: [
|
||||||
TextButton(
|
TextButton(
|
||||||
@@ -716,11 +750,16 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
),
|
),
|
||||||
const Spacer(),
|
const Spacer(),
|
||||||
if (isChildrenTab)
|
if (isChildrenTab)
|
||||||
TextButton.icon(
|
Tooltip(
|
||||||
onPressed: _attachChild,
|
message: _capacityFull
|
||||||
|
? 'Capacité maximale atteinte'
|
||||||
|
: 'Rattacher un enfant',
|
||||||
|
child: TextButton.icon(
|
||||||
|
onPressed: canAttachChild ? _attachChild : null,
|
||||||
icon: const Icon(Icons.link, size: 18),
|
icon: const Icon(Icons.link, size: 18),
|
||||||
label: const Text('Rattacher un enfant'),
|
label: const Text('Rattacher un enfant'),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
if (isChildrenTab) const SizedBox(width: 12),
|
if (isChildrenTab) const SizedBox(width: 12),
|
||||||
ElevatedButton(
|
ElevatedButton(
|
||||||
style: ValidationModalTheme.primaryElevatedStyle,
|
style: ValidationModalTheme.primaryElevatedStyle,
|
||||||
@@ -781,7 +820,7 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
const SizedBox(width: 12),
|
const SizedBox(width: 12),
|
||||||
SizedBox(
|
SizedBox(
|
||||||
width: 160,
|
width: 160,
|
||||||
child: AdminStatusCapsule(
|
child: StatusCapsule(
|
||||||
statut: _statut,
|
statut: _statut,
|
||||||
onChanged: (v) => setState(() {
|
onChanged: (v) => setState(() {
|
||||||
_statut = v;
|
_statut = v;
|
||||||
@@ -817,15 +856,13 @@ class _AdminAmEditModalState extends State<AdminAmEditModal>
|
|||||||
const Divider(height: 1),
|
const Divider(height: 1),
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),
|
padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),
|
||||||
child: SizedBox(
|
child: AnimatedSize(
|
||||||
height: _tabViewHeight(_tabCtrl.index),
|
duration: const Duration(milliseconds: 180),
|
||||||
child: TabBarView(
|
curve: Curves.easeInOut,
|
||||||
controller: _tabCtrl,
|
alignment: Alignment.topCenter,
|
||||||
children: [
|
child: KeyedSubtree(
|
||||||
_identityTab(),
|
key: ValueKey<int>(_tabCtrl.index),
|
||||||
_proTab(),
|
child: _buildActiveTabBody(),
|
||||||
_childrenTab(),
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
+87
-8
@@ -1,14 +1,27 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:p_tits_pas/services/api/api_config.dart';
|
import 'package:p_tits_pas/services/api/api_config.dart';
|
||||||
import 'package:p_tits_pas/widgets/common/auth_network_image.dart';
|
import 'package:p_tits_pas/widgets/common/auth_network_image.dart';
|
||||||
|
|
||||||
/// Cadre photo identité AM (35×45 mm) — même logique que [ValidationAmWizard].
|
/// Cadre photo identité AM / enfant (35×45 mm) — même logique que [ValidationAmWizard].
|
||||||
class AdminAmPhotoFrame extends StatelessWidget {
|
class AmPhotoFrame extends StatelessWidget {
|
||||||
final String? photoUrl;
|
final String? photoUrl;
|
||||||
|
final Uint8List? imageBytes;
|
||||||
|
final VoidCallback? onTap;
|
||||||
|
final VoidCallback? onClear;
|
||||||
|
final String emptyLabel;
|
||||||
|
|
||||||
static const double idPhotoAspectRatio = 35 / 45;
|
static const double idPhotoAspectRatio = 35 / 45;
|
||||||
|
|
||||||
const AdminAmPhotoFrame({super.key, this.photoUrl});
|
const AmPhotoFrame({
|
||||||
|
super.key,
|
||||||
|
this.photoUrl,
|
||||||
|
this.imageBytes,
|
||||||
|
this.onTap,
|
||||||
|
this.onClear,
|
||||||
|
this.emptyLabel = 'Aucune photo',
|
||||||
|
});
|
||||||
|
|
||||||
/// Largeur colonne photo pour remplir [height] (cadre inclus).
|
/// Largeur colonne photo pour remplir [height] (cadre inclus).
|
||||||
static double columnWidthForHeight(double height) {
|
static double columnWidthForHeight(double height) {
|
||||||
@@ -36,9 +49,12 @@ class AdminAmPhotoFrame extends StatelessWidget {
|
|||||||
ph = pw / ar;
|
ph = pw / ar;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final hasLocal = imageBytes != null && imageBytes!.isNotEmpty;
|
||||||
|
final showClear = onClear != null && hasLocal;
|
||||||
|
|
||||||
// Cadre gris = taille photo + padding uniforme ; centré dans la colonne
|
// Cadre gris = taille photo + padding uniforme ; centré dans la colonne
|
||||||
// (évite le vide blanc en bas quand le conteneur parent est plus haut).
|
// (évite le vide blanc en bas quand le conteneur parent est plus haut).
|
||||||
return Align(
|
Widget frame = Align(
|
||||||
alignment: Alignment.topCenter,
|
alignment: Alignment.topCenter,
|
||||||
child: Container(
|
child: Container(
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
@@ -60,23 +76,82 @@ class AdminAmPhotoFrame extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (onTap != null) {
|
||||||
|
frame = MouseRegion(
|
||||||
|
cursor: SystemMouseCursors.click,
|
||||||
|
child: GestureDetector(
|
||||||
|
onTap: onTap,
|
||||||
|
behavior: HitTestBehavior.opaque,
|
||||||
|
child: frame,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!showClear) return frame;
|
||||||
|
|
||||||
|
return Stack(
|
||||||
|
clipBehavior: Clip.none,
|
||||||
|
children: [
|
||||||
|
frame,
|
||||||
|
Positioned(
|
||||||
|
top: 0,
|
||||||
|
right: 0,
|
||||||
|
child: Material(
|
||||||
|
color: Colors.transparent,
|
||||||
|
child: IconButton(
|
||||||
|
tooltip: 'Retirer la photo',
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
padding: EdgeInsets.zero,
|
||||||
|
constraints: const BoxConstraints(
|
||||||
|
minWidth: 32,
|
||||||
|
minHeight: 32,
|
||||||
|
),
|
||||||
|
icon: Icon(
|
||||||
|
Icons.cancel,
|
||||||
|
size: 22,
|
||||||
|
color: Colors.grey.shade700,
|
||||||
|
),
|
||||||
|
onPressed: onClear,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _photoContent(String fullUrl, double pw, double ph) {
|
Widget _photoContent(String fullUrl, double pw, double ph) {
|
||||||
|
if (imageBytes != null && imageBytes!.isNotEmpty) {
|
||||||
|
return Image.memory(
|
||||||
|
imageBytes!,
|
||||||
|
width: pw,
|
||||||
|
height: ph,
|
||||||
|
fit: BoxFit.cover,
|
||||||
|
alignment: Alignment.topCenter,
|
||||||
|
);
|
||||||
|
}
|
||||||
if (fullUrl.isEmpty) {
|
if (fullUrl.isEmpty) {
|
||||||
return ColoredBox(
|
return ColoredBox(
|
||||||
color: Colors.grey.shade200,
|
color: Colors.grey.shade200,
|
||||||
child: Column(
|
child: Column(
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
children: [
|
children: [
|
||||||
Icon(Icons.person_off_outlined, size: 36, color: Colors.grey.shade400),
|
Icon(
|
||||||
|
onTap != null ? Icons.add_a_photo_outlined : Icons.person_off_outlined,
|
||||||
|
size: 36,
|
||||||
|
color: Colors.grey.shade400,
|
||||||
|
),
|
||||||
const SizedBox(height: 6),
|
const SizedBox(height: 6),
|
||||||
Text(
|
Padding(
|
||||||
'Aucune photo',
|
padding: const EdgeInsets.symmetric(horizontal: 6),
|
||||||
|
child: Text(
|
||||||
|
emptyLabel,
|
||||||
|
textAlign: TextAlign.center,
|
||||||
style: TextStyle(color: Colors.grey.shade600, fontSize: 11),
|
style: TextStyle(color: Colors.grey.shade600, fontSize: 11),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -108,7 +183,11 @@ class AdminAmPhotoFrame extends StatelessWidget {
|
|||||||
},
|
},
|
||||||
errorBuilder: (_, __, ___) => ColoredBox(
|
errorBuilder: (_, __, ___) => ColoredBox(
|
||||||
color: Colors.grey.shade200,
|
color: Colors.grey.shade200,
|
||||||
child: Icon(Icons.broken_image_outlined, size: 36, color: Colors.grey.shade400),
|
child: Icon(
|
||||||
|
Icons.broken_image_outlined,
|
||||||
|
size: 36,
|
||||||
|
color: Colors.grey.shade400,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
+61
-5
@@ -1,10 +1,14 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:p_tits_pas/models/assistante_maternelle_model.dart';
|
import 'package:p_tits_pas/models/assistante_maternelle_model.dart';
|
||||||
|
import 'package:p_tits_pas/models/dossier_list_item.dart';
|
||||||
import 'package:p_tits_pas/utils/am_vigilance.dart';
|
import 'package:p_tits_pas/utils/am_vigilance.dart';
|
||||||
|
import 'package:p_tits_pas/services/auth_service.dart';
|
||||||
import 'package:p_tits_pas/services/user_service.dart';
|
import 'package:p_tits_pas/services/user_service.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/common/admin_am_edit_modal.dart';
|
import 'package:p_tits_pas/utils/staff_deletion_rights.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/common/admin_user_card.dart';
|
import 'package:p_tits_pas/widgets/dashboard/am_edit_modal.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/common/user_list.dart';
|
import 'package:p_tits_pas/widgets/dashboard/user_card.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/dashboard/common/suppression_confirm_dialog.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/dashboard/common/user_list.dart';
|
||||||
|
|
||||||
class AssistanteMaternelleManagementWidget extends StatefulWidget {
|
class AssistanteMaternelleManagementWidget extends StatefulWidget {
|
||||||
final String searchQuery;
|
final String searchQuery;
|
||||||
@@ -26,16 +30,24 @@ class _AssistanteMaternelleManagementWidgetState
|
|||||||
bool _isLoading = false;
|
bool _isLoading = false;
|
||||||
String? _error;
|
String? _error;
|
||||||
List<AssistanteMaternelleModel> _assistantes = [];
|
List<AssistanteMaternelleModel> _assistantes = [];
|
||||||
|
bool _canDelete = false;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
|
_loadRights();
|
||||||
_loadAssistantes();
|
_loadAssistantes();
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() => super.dispose();
|
void dispose() => super.dispose();
|
||||||
|
|
||||||
|
Future<void> _loadRights() async {
|
||||||
|
final user = await AuthService.getCurrentUser();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _canDelete = canDeleteMetier(user?.role));
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _loadAssistantes() async {
|
Future<void> _loadAssistantes() async {
|
||||||
setState(() {
|
setState(() {
|
||||||
_isLoading = true;
|
_isLoading = true;
|
||||||
@@ -57,6 +69,46 @@ class _AssistanteMaternelleManagementWidgetState
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _confirmDelete(AssistanteMaternelleModel am) async {
|
||||||
|
final num = (am.user.numeroDossier ?? '').trim();
|
||||||
|
final name = formatDossierPersonLabel(
|
||||||
|
nom: am.user.nom,
|
||||||
|
prenom: am.user.prenom,
|
||||||
|
email: am.user.email,
|
||||||
|
);
|
||||||
|
final confirmed = await showSuppressionConfirmDialog(
|
||||||
|
context,
|
||||||
|
title: 'Supprimer l\'assistante maternelle',
|
||||||
|
subtitle: num.isEmpty ? null : 'Dossier $num',
|
||||||
|
people: [SuppressionPersonLine.am(name)],
|
||||||
|
footnotes: const [
|
||||||
|
'Le compte et le dossier AM seront supprimés.',
|
||||||
|
'Les enfants accueillis ne seront pas supprimés '
|
||||||
|
'(placements clos).',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
if (!confirmed || !mounted) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
final result = await UserService.deleteUser(am.user.id);
|
||||||
|
if (!mounted) return;
|
||||||
|
final msg = (result['message'] ?? 'AM supprimée.').toString();
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(msg)));
|
||||||
|
await _loadAssistantes();
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(
|
||||||
|
e is Exception
|
||||||
|
? e.toString().replaceFirst('Exception: ', '')
|
||||||
|
: 'Erreur suppression',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final query = widget.searchQuery.toLowerCase();
|
final query = widget.searchQuery.toLowerCase();
|
||||||
@@ -78,7 +130,7 @@ class _AssistanteMaternelleManagementWidgetState
|
|||||||
itemBuilder: (context, index) {
|
itemBuilder: (context, index) {
|
||||||
final assistante = filteredAssistantes[index];
|
final assistante = filteredAssistantes[index];
|
||||||
final vigilance = amPlacesVigilanceMessage(assistante);
|
final vigilance = amPlacesVigilanceMessage(assistante);
|
||||||
return AdminUserCard(
|
return UserCard(
|
||||||
title: assistante.user.fullName,
|
title: assistante.user.fullName,
|
||||||
avatarUrl: assistante.user.photoUrl,
|
avatarUrl: assistante.user.photoUrl,
|
||||||
fallbackIcon: Icons.face,
|
fallbackIcon: Icons.face,
|
||||||
@@ -96,6 +148,10 @@ class _AssistanteMaternelleManagementWidgetState
|
|||||||
_openAssistanteDetails(assistante);
|
_openAssistanteDetails(assistante);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
if (_canDelete)
|
||||||
|
suppressionIconButton(
|
||||||
|
onPressed: () => _confirmDelete(assistante),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -105,7 +161,7 @@ class _AssistanteMaternelleManagementWidgetState
|
|||||||
void _openAssistanteDetails(AssistanteMaternelleModel assistante) {
|
void _openAssistanteDetails(AssistanteMaternelleModel assistante) {
|
||||||
showDialog<void>(
|
showDialog<void>(
|
||||||
context: context,
|
context: context,
|
||||||
builder: (context) => AdminAmEditModal(
|
builder: (context) => AmEditModal(
|
||||||
assistante: assistante,
|
assistante: assistante,
|
||||||
onSaved: _loadAssistantes,
|
onSaved: _loadAssistantes,
|
||||||
),
|
),
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user