Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8c9cfbc4d | ||
|
|
530e896b66 | ||
|
|
0029c5ab86 | ||
|
|
2ce9e9215f | ||
|
|
3fdd913367 | ||
|
|
6708f73b06 | ||
|
|
f596f062a6 |
@@ -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 {
|
||||||
@@ -718,6 +719,167 @@ export class AuthService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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).
|
* Cœur partagé création dossier AM (#156).
|
||||||
* - public : statut en_attente + mail pending
|
* - public : statut en_attente + mail pending
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { DossiersController } from './dossiers.controller';
|
||||||
|
import { DossiersService } from './dossiers.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(),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
controllers: [DossiersController],
|
||||||
|
providers: [{ provide: DossiersService, useValue: dossiersServiceMock }],
|
||||||
|
})
|
||||||
|
.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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,18 +1,46 @@
|
|||||||
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
|
import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
|
||||||
import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
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 } 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 { DossiersService } from './dossiers.service';
|
import { DossiersService } from './dossiers.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) {}
|
||||||
|
|
||||||
|
@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.',
|
||||||
|
})
|
||||||
|
@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)
|
||||||
@ApiOperation({ summary: 'Dossier complet par numéro (AM ou famille) – Ticket #119' })
|
@ApiOperation({ summary: 'Dossier complet par numéro (AM ou famille) – Ticket #119' })
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
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 { 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(),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
DossiersService,
|
||||||
|
{ provide: getRepositoryToken(Parents), useValue: parentsRepo },
|
||||||
|
{ provide: getRepositoryToken(AssistanteMaternelle), useValue: amRepo },
|
||||||
|
{ provide: ParentsService, useValue: parentsService },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get(DossiersService);
|
||||||
|
jest.clearAllMocks();
|
||||||
|
parentsRepo.createQueryBuilder.mockReturnValue(parentsQb);
|
||||||
|
amRepo.createQueryBuilder.mockReturnValue(amQb);
|
||||||
|
});
|
||||||
|
|
||||||
|
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,14 @@ 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 { 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).
|
||||||
*/
|
*/
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class DossiersService {
|
export class DossiersService {
|
||||||
@@ -20,6 +22,159 @@ export class DossiersService {
|
|||||||
private readonly parentsService: ParentsService,
|
private readonly parentsService: ParentsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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');
|
||||||
|
});
|
||||||
|
|
||||||
|
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,52 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
@@ -141,12 +141,20 @@ 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)
|
||||||
|
|||||||
@@ -195,7 +195,12 @@ export class EnfantsService {
|
|||||||
|
|
||||||
|
|
||||||
// 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');
|
||||||
|
|
||||||
@@ -205,6 +210,13 @@ export class EnfantsService {
|
|||||||
patch.consent_photo = dto.consent_photo;
|
patch.consent_photo = dto.consent_photo;
|
||||||
patch.consent_photo_at = dto.consent_photo ? new Date() : null!;
|
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);
|
await this.childrenRepository.update(id, patch);
|
||||||
return this.findOne(id, currentUser);
|
return this.findOne(id, currentUser);
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ describe('ParentsController', () => {
|
|||||||
let controller: ParentsController;
|
let controller: ParentsController;
|
||||||
const authServiceMock = {
|
const authServiceMock = {
|
||||||
createParentDossierStaff: jest.fn(),
|
createParentDossierStaff: jest.fn(),
|
||||||
|
addCoParentStaff: jest.fn(),
|
||||||
};
|
};
|
||||||
const parentsServiceMock = {};
|
const parentsServiceMock = {};
|
||||||
const userServiceMock = {};
|
const userServiceMock = {};
|
||||||
@@ -77,4 +78,27 @@ describe('ParentsController', () => {
|
|||||||
expect(res.enfant_ids).toEqual(['e1']);
|
expect(res.enfant_ids).toEqual(['e1']);
|
||||||
expect(res.statut).toBe(StatutUtilisateurType.ACTIF);
|
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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ 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 { StaffCreateParentDossierDto } from './dto/staff-create-parent-dossier.dto';
|
||||||
import { StaffCreateParentDossierResponseDto } from './dto/staff-create-parent-dossier-response.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 { 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';
|
||||||
@@ -176,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' })
|
||||||
|
|||||||
@@ -251,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,
|
||||||
@@ -267,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
|
||||||
@@ -317,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,
|
||||||
|
|||||||
@@ -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,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,196 @@
|
|||||||
|
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;
|
||||||
|
|
||||||
|
const DossierListItem({
|
||||||
|
required this.type,
|
||||||
|
required this.numeroDossier,
|
||||||
|
required this.libelle,
|
||||||
|
this.emails = const [],
|
||||||
|
this.statut,
|
||||||
|
this.photoUrl,
|
||||||
|
});
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
items.add(
|
||||||
|
DossierListItem(
|
||||||
|
type: DossierListType.famille,
|
||||||
|
numeroDossier: entry.key,
|
||||||
|
libelle: names.isNotEmpty ? names.join(' - ') : 'Famille',
|
||||||
|
emails: emails,
|
||||||
|
statut: _preferStatut(statuts),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
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';
|
||||||
|
}
|
||||||
@@ -215,8 +215,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(),
|
||||||
|
|||||||
@@ -525,17 +525,58 @@ class UserService {
|
|||||||
return enfant.copyWith(parentLinks: enriched);
|
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) {
|
||||||
headers: await _headers(),
|
throw Exception('Identifiant enfant manquant.');
|
||||||
body: jsonEncode(body),
|
}
|
||||||
);
|
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(),
|
||||||
|
body: jsonEncode(body),
|
||||||
|
);
|
||||||
|
}
|
||||||
if (response.statusCode != 200) {
|
if (response.statusCode != 200) {
|
||||||
throw Exception(_extractErrorMessage(response.body, 'Erreur mise à jour enfant'));
|
throw Exception(
|
||||||
|
_extractErrorMessage(response.body, 'Erreur mise à jour enfant'),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
final enfant = EnfantAdminModel.fromJson(
|
final enfant = EnfantAdminModel.fromJson(
|
||||||
jsonDecode(response.body) as Map<String, dynamic>,
|
jsonDecode(response.body) as Map<String, dynamic>,
|
||||||
@@ -645,6 +686,57 @@ 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).
|
/// Création dossier famille actif côté staff (#129).
|
||||||
/// `POST /parents/dossier` — body aligné sur register parent complet.
|
/// `POST /parents/dossier` — body aligné sur register parent complet.
|
||||||
/// Succès 201 : dossier actif + `numero_dossier` (mail MDP côté serveur, par parent créé).
|
/// Succès 201 : dossier actif + `numero_dossier` (mail MDP côté serveur, par parent créé).
|
||||||
|
|||||||
@@ -23,9 +23,9 @@ import 'package:p_tits_pas/widgets/admin/validation_valider_confirm_dialog.dart'
|
|||||||
import 'package:p_tits_pas/widgets/common/auth_network_image.dart';
|
import 'package:p_tits_pas/widgets/common/auth_network_image.dart';
|
||||||
import 'package:p_tits_pas/widgets/common/identity_block.dart';
|
import 'package:p_tits_pas/widgets/common/identity_block.dart';
|
||||||
|
|
||||||
enum AmDossierWizardMode { review, create }
|
enum AmDossierWizardMode { review, create, edit }
|
||||||
|
|
||||||
/// Wizard dossier AM — modes [review] (validation pending) et [create] (staff #156).
|
/// Wizard dossier AM — [review] (#107), [create] (#156), [edit] (#135).
|
||||||
class AmDossierWizard extends StatefulWidget {
|
class AmDossierWizard extends StatefulWidget {
|
||||||
final AmDossierWizardMode mode;
|
final AmDossierWizardMode mode;
|
||||||
final DossierAM? dossier;
|
final DossierAM? dossier;
|
||||||
@@ -74,7 +74,25 @@ class AmDossierWizard extends StatefulWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
factory AmDossierWizard.edit({
|
||||||
|
Key? key,
|
||||||
|
required DossierAM dossier,
|
||||||
|
required VoidCallback onClose,
|
||||||
|
required VoidCallback onSuccess,
|
||||||
|
void Function(int step, int total)? onStepChanged,
|
||||||
|
}) {
|
||||||
|
return AmDossierWizard._(
|
||||||
|
key: key,
|
||||||
|
mode: AmDossierWizardMode.edit,
|
||||||
|
dossier: dossier,
|
||||||
|
onClose: onClose,
|
||||||
|
onSuccess: onSuccess,
|
||||||
|
onStepChanged: onStepChanged,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
bool get isCreate => mode == AmDossierWizardMode.create;
|
bool get isCreate => mode == AmDossierWizardMode.create;
|
||||||
|
bool get isEdit => mode == AmDossierWizardMode.edit;
|
||||||
|
|
||||||
/// Hauteur corps modale AM — dérivée de [ValidationFormMetrics] (4 lignes).
|
/// Hauteur corps modale AM — dérivée de [ValidationFormMetrics] (4 lignes).
|
||||||
static double get shellBodyHeight =>
|
static double get shellBodyHeight =>
|
||||||
@@ -118,9 +136,11 @@ class _AmDossierWizardState extends State<AmDossierWizard> {
|
|||||||
String? _photoFilename;
|
String? _photoFilename;
|
||||||
|
|
||||||
bool get _isCreate => widget.isCreate;
|
bool get _isCreate => widget.isCreate;
|
||||||
|
bool get _isEdit => widget.isEdit;
|
||||||
|
bool get _isEditable => _isCreate || _isEdit;
|
||||||
DossierAM get _dossier => widget.dossier!;
|
DossierAM get _dossier => widget.dossier!;
|
||||||
bool get _isEnAttente =>
|
bool get _isEnAttente =>
|
||||||
!_isCreate && _dossier.user.statut == 'en_attente';
|
!_isCreate && !_isEdit && _dossier.user.statut == 'en_attente';
|
||||||
|
|
||||||
static String _v(String? s) =>
|
static String _v(String? s) =>
|
||||||
(s != null && s.trim().isNotEmpty) ? s.trim() : '–';
|
(s != null && s.trim().isNotEmpty) ? s.trim() : '–';
|
||||||
@@ -151,9 +171,33 @@ class _AmDossierWizardState extends State<AmDossierWizard> {
|
|||||||
_capaciteCtrl = TextEditingController(text: '1');
|
_capaciteCtrl = TextEditingController(text: '1');
|
||||||
_placesCtrl = TextEditingController(text: '1');
|
_placesCtrl = TextEditingController(text: '1');
|
||||||
_presentationCtrl = TextEditingController();
|
_presentationCtrl = TextEditingController();
|
||||||
|
if (_isEdit) {
|
||||||
|
_prefillFromDossier();
|
||||||
|
}
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) => _emitStep());
|
WidgetsBinding.instance.addPostFrameCallback((_) => _emitStep());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _prefillFromDossier() {
|
||||||
|
final u = _dossier.user;
|
||||||
|
_nomCtrl.text = (u.nom ?? '').trim();
|
||||||
|
_prenomCtrl.text = (u.prenom ?? '').trim();
|
||||||
|
_telCtrl.text = (u.telephone ?? '').trim();
|
||||||
|
_emailCtrl.text = u.email.trim();
|
||||||
|
_adresseCtrl.text = (u.adresse ?? '').trim();
|
||||||
|
_cpCtrl.text = (u.codePostal ?? '').trim();
|
||||||
|
_villeCtrl.text = (u.ville ?? '').trim();
|
||||||
|
_nirCtrl.text = (_dossier.nir ?? '').trim();
|
||||||
|
_dateNaissanceCtrl.text = formatIsoDateFrInput(u.dateNaissance);
|
||||||
|
_lieuNaissanceVilleCtrl.text = (u.lieuNaissanceVille ?? '').trim();
|
||||||
|
final pays = (u.lieuNaissancePays ?? '').trim();
|
||||||
|
_lieuNaissancePaysCtrl.text = pays.isEmpty ? 'France' : pays;
|
||||||
|
_agrementCtrl.text = (_dossier.numeroAgrement ?? '').trim();
|
||||||
|
_dateAgrementCtrl.text = formatIsoDateFrInput(_dossier.dateAgrement);
|
||||||
|
_capaciteCtrl.text = '${_dossier.nbMaxEnfants ?? 1}';
|
||||||
|
_placesCtrl.text = '${_dossier.placesDisponibles ?? 0}';
|
||||||
|
_presentationCtrl.text = (_dossier.presentation ?? '').trim();
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_nomCtrl.dispose();
|
_nomCtrl.dispose();
|
||||||
@@ -373,8 +417,8 @@ class _AmDossierWizardState extends State<AmDossierWizard> {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
String? _validateStep1() {
|
String? _validateStep1({required bool requirePhoto}) {
|
||||||
if (_photoBytes == null || _photoBytes!.isEmpty) {
|
if (requirePhoto && (_photoBytes == null || _photoBytes!.isEmpty)) {
|
||||||
return 'Une photo de profil est requise.';
|
return 'Une photo de profil est requise.';
|
||||||
}
|
}
|
||||||
final birthIso = parseFrDateToIso(_dateNaissanceCtrl.text);
|
final birthIso = parseFrDateToIso(_dateNaissanceCtrl.text);
|
||||||
@@ -407,12 +451,12 @@ class _AmDossierWizardState extends State<AmDossierWizard> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
String? _validateCurrentStep() {
|
String? _validateCurrentStep() {
|
||||||
if (!_isCreate) return null;
|
if (!_isEditable) return null;
|
||||||
switch (_step) {
|
switch (_step) {
|
||||||
case 0:
|
case 0:
|
||||||
return _validateStep0();
|
return _validateStep0();
|
||||||
case 1:
|
case 1:
|
||||||
return _validateStep1();
|
return _validateStep1(requirePhoto: _isCreate);
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -511,7 +555,7 @@ class _AmDossierWizardState extends State<AmDossierWizard> {
|
|||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final err1 = _validateStep1();
|
final err1 = _validateStep1(requirePhoto: true);
|
||||||
if (err1 != null) {
|
if (err1 != null) {
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
SnackBar(content: Text(err1), backgroundColor: Colors.red.shade700),
|
SnackBar(content: Text(err1), backgroundColor: Colors.red.shade700),
|
||||||
@@ -554,6 +598,94 @@ class _AmDossierWizardState extends State<AmDossierWizard> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _saveEdit() async {
|
||||||
|
if (_submitting || !_isEdit) return;
|
||||||
|
final err0 = _validateStep0();
|
||||||
|
if (err0 != null) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text(err0), backgroundColor: Colors.red.shade700),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final err1 = _validateStep1(requirePhoto: false);
|
||||||
|
if (err1 != null) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text(err1), backgroundColor: Colors.red.shade700),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final amId = _dossier.user.id.trim();
|
||||||
|
if (amId.isEmpty) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: const Text('Identifiant AM manquant.'),
|
||||||
|
backgroundColor: Colors.red.shade700,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final ok = await showValidationValiderConfirmDialog(
|
||||||
|
context,
|
||||||
|
body: 'Enregistrer les modifications de la fiche assistante maternelle ?',
|
||||||
|
);
|
||||||
|
if (!mounted || !ok) return;
|
||||||
|
|
||||||
|
final birthIso = parseFrDateToIso(_dateNaissanceCtrl.text);
|
||||||
|
final agrementIso = parseFrDateToIso(_dateAgrementCtrl.text);
|
||||||
|
final capa = int.tryParse(_capaciteCtrl.text.trim());
|
||||||
|
final places = int.tryParse(_placesCtrl.text.trim());
|
||||||
|
final biography = _presentationCtrl.text.trim();
|
||||||
|
|
||||||
|
setState(() => _submitting = true);
|
||||||
|
try {
|
||||||
|
await UserService.updateAmFiche(
|
||||||
|
amUserId: amId,
|
||||||
|
body: {
|
||||||
|
'nom': formatPersonNameCase(_nomCtrl.text),
|
||||||
|
'prenom': formatPersonNameCase(_prenomCtrl.text),
|
||||||
|
'email': normalizeEmailText(_emailCtrl.text),
|
||||||
|
'telephone': normalizePhone(_telCtrl.text),
|
||||||
|
'adresse': _adresseCtrl.text.trim(),
|
||||||
|
'ville': formatPersonNameCase(_villeCtrl.text),
|
||||||
|
'code_postal': _cpCtrl.text.trim(),
|
||||||
|
'approval_number': _agrementCtrl.text.trim(),
|
||||||
|
'nir': nirToRaw(_nirCtrl.text),
|
||||||
|
if (birthIso != null) 'date_naissance': birthIso,
|
||||||
|
'lieu_naissance_ville':
|
||||||
|
formatPersonNameCase(_lieuNaissanceVilleCtrl.text),
|
||||||
|
'lieu_naissance_pays':
|
||||||
|
formatPersonNameCase(_lieuNaissancePaysCtrl.text),
|
||||||
|
if (agrementIso != null) 'agreement_date': agrementIso,
|
||||||
|
if (capa != null) 'max_children': capa,
|
||||||
|
if (places != null) 'places_available': places,
|
||||||
|
'biography': biography,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(
|
||||||
|
content: Text('Fiche AM enregistrée.'),
|
||||||
|
duration: 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
if (_showRefusForm) {
|
if (_showRefusForm) {
|
||||||
@@ -587,7 +719,7 @@ class _AmDossierWizardState extends State<AmDossierWizard> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildStep0() {
|
Widget _buildStep0() {
|
||||||
if (_isCreate) {
|
if (_isEditable) {
|
||||||
return IdentityBlock.editable(
|
return IdentityBlock.editable(
|
||||||
title: 'Identité et coordonnées',
|
title: 'Identité et coordonnées',
|
||||||
nomController: _nomCtrl,
|
nomController: _nomCtrl,
|
||||||
@@ -620,7 +752,7 @@ class _AmDossierWizardState extends State<AmDossierWizard> {
|
|||||||
.clamp(_photoColumnMinWidth, 360.0);
|
.clamp(_photoColumnMinWidth, 360.0);
|
||||||
if (photoW > maxPhotoW) photoW = maxPhotoW;
|
if (photoW > maxPhotoW) photoW = maxPhotoW;
|
||||||
|
|
||||||
final form = _isCreate
|
final form = _isEditable
|
||||||
? _buildCreateProFields()
|
? _buildCreateProFields()
|
||||||
: ValidationDetailSection(
|
: ValidationDetailSection(
|
||||||
title: 'Dossier professionnel',
|
title: 'Dossier professionnel',
|
||||||
@@ -628,20 +760,25 @@ class _AmDossierWizardState extends State<AmDossierWizard> {
|
|||||||
rowLayout: _photoProRowLayout,
|
rowLayout: _photoProRowLayout,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
final Widget photo;
|
||||||
|
if (_isCreate) {
|
||||||
|
photo = AdminAmPhotoFrame(
|
||||||
|
imageBytes: _photoBytes,
|
||||||
|
onTap: _pickPhoto,
|
||||||
|
onClear: _photoBytes != null ? _clearPhoto : null,
|
||||||
|
emptyLabel: 'Ajouter une photo',
|
||||||
|
);
|
||||||
|
} else if (_isEdit) {
|
||||||
|
// Édition : photo existante en lecture ; remplacement hors scope PATCH fiche.
|
||||||
|
photo = _buildPhotoSectionReview(_dossier.user);
|
||||||
|
} else {
|
||||||
|
photo = _buildPhotoSectionReview(_dossier.user);
|
||||||
|
}
|
||||||
|
|
||||||
return Row(
|
return Row(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
SizedBox(
|
SizedBox(width: photoW, child: photo),
|
||||||
width: photoW,
|
|
||||||
child: _isCreate
|
|
||||||
? AdminAmPhotoFrame(
|
|
||||||
imageBytes: _photoBytes,
|
|
||||||
onTap: _pickPhoto,
|
|
||||||
onClear: _photoBytes != null ? _clearPhoto : null,
|
|
||||||
emptyLabel: 'Ajouter une photo',
|
|
||||||
)
|
|
||||||
: _buildPhotoSectionReview(_dossier.user),
|
|
||||||
),
|
|
||||||
const SizedBox(width: _photoProGap),
|
const SizedBox(width: _photoProGap),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Align(
|
child: Align(
|
||||||
@@ -721,7 +858,7 @@ class _AmDossierWizardState extends State<AmDossierWizard> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildStep2() {
|
Widget _buildStep2() {
|
||||||
if (_isCreate) {
|
if (_isEditable) {
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
@@ -832,6 +969,12 @@ class _AmDossierWizardState extends State<AmDossierWizard> {
|
|||||||
onPressed: _submitting ? null : _createAndValidate,
|
onPressed: _submitting ? null : _createAndValidate,
|
||||||
child: Text(_submitting ? 'Envoi...' : 'Créer et valider'),
|
child: Text(_submitting ? 'Envoi...' : 'Créer et valider'),
|
||||||
),
|
),
|
||||||
|
] else if (_isEdit) ...[
|
||||||
|
ElevatedButton(
|
||||||
|
style: ValidationModalTheme.primaryElevatedStyle,
|
||||||
|
onPressed: _submitting ? null : _saveEdit,
|
||||||
|
child: Text(_submitting ? 'Envoi...' : 'Enregistrer'),
|
||||||
|
),
|
||||||
] else if (_isEnAttente) ...[
|
] else if (_isEnAttente) ...[
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
onPressed: _submitting ? null : _refuser,
|
onPressed: _submitting ? null : _refuser,
|
||||||
|
|||||||
@@ -12,6 +12,10 @@ class AdminUserCard extends StatefulWidget {
|
|||||||
final Color? backgroundColor;
|
final Color? backgroundColor;
|
||||||
final Color? titleColor;
|
final Color? titleColor;
|
||||||
final Color? infoColor;
|
final Color? infoColor;
|
||||||
|
/// Fond du cercle avatar / icône (défaut lavande admin).
|
||||||
|
final Color? avatarBackgroundColor;
|
||||||
|
/// Couleur de l’icône fallback (défaut violet admin).
|
||||||
|
final Color? avatarIconColor;
|
||||||
final String? vigilanceTooltip;
|
final String? vigilanceTooltip;
|
||||||
final VoidCallback? onCardTap;
|
final VoidCallback? onCardTap;
|
||||||
final EdgeInsetsGeometry? margin;
|
final EdgeInsetsGeometry? margin;
|
||||||
@@ -28,6 +32,8 @@ class AdminUserCard extends StatefulWidget {
|
|||||||
this.backgroundColor,
|
this.backgroundColor,
|
||||||
this.titleColor,
|
this.titleColor,
|
||||||
this.infoColor,
|
this.infoColor,
|
||||||
|
this.avatarBackgroundColor,
|
||||||
|
this.avatarIconColor,
|
||||||
this.vigilanceTooltip,
|
this.vigilanceTooltip,
|
||||||
this.onCardTap,
|
this.onCardTap,
|
||||||
this.margin,
|
this.margin,
|
||||||
@@ -159,8 +165,8 @@ class _AdminUserCardState extends State<AdminUserCard> {
|
|||||||
|
|
||||||
Widget _buildAvatar(String url) {
|
Widget _buildAvatar(String url) {
|
||||||
const size = 28.0;
|
const size = 28.0;
|
||||||
const bg = Color(0xFFEDE5FA);
|
final bg = widget.avatarBackgroundColor ?? const Color(0xFFEDE5FA);
|
||||||
const iconColor = Color(0xFF6B3FA0);
|
final iconColor = widget.avatarIconColor ?? const Color(0xFF6B3FA0);
|
||||||
|
|
||||||
if (url.isEmpty) {
|
if (url.isEmpty) {
|
||||||
return CircleAvatar(
|
return CircleAvatar(
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ class DashboardUserManagementSubBar extends StatelessWidget {
|
|||||||
final ValueChanged<int> onSubTabChange;
|
final ValueChanged<int> onSubTabChange;
|
||||||
final TextEditingController searchController;
|
final TextEditingController searchController;
|
||||||
final String searchHint;
|
final String searchHint;
|
||||||
|
/// Infobulle au survol de la barre de recherche (ex. critères de recherche).
|
||||||
|
final String? searchTooltip;
|
||||||
final Widget? filterControl;
|
final Widget? filterControl;
|
||||||
final VoidCallback? onAddPressed;
|
final VoidCallback? onAddPressed;
|
||||||
final String addLabel;
|
final String addLabel;
|
||||||
@@ -22,12 +24,16 @@ class DashboardUserManagementSubBar extends StatelessWidget {
|
|||||||
'Administrateurs',
|
'Administrateurs',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/// Aligné sur la taille des libellés d’onglets.
|
||||||
|
static const double _searchFontSize = 13;
|
||||||
|
|
||||||
const DashboardUserManagementSubBar({
|
const DashboardUserManagementSubBar({
|
||||||
Key? key,
|
Key? key,
|
||||||
required this.selectedSubIndex,
|
required this.selectedSubIndex,
|
||||||
required this.onSubTabChange,
|
required this.onSubTabChange,
|
||||||
required this.searchController,
|
required this.searchController,
|
||||||
required this.searchHint,
|
required this.searchHint,
|
||||||
|
this.searchTooltip,
|
||||||
this.filterControl,
|
this.filterControl,
|
||||||
this.onAddPressed,
|
this.onAddPressed,
|
||||||
this.addLabel = '+ Ajouter',
|
this.addLabel = '+ Ajouter',
|
||||||
@@ -54,22 +60,7 @@ class DashboardUserManagementSubBar extends StatelessWidget {
|
|||||||
_buildSubNavItem(context, labels[i], i),
|
_buildSubNavItem(context, labels[i], i),
|
||||||
],
|
],
|
||||||
const SizedBox(width: 36),
|
const SizedBox(width: 36),
|
||||||
_pillField(
|
_buildSearchField(),
|
||||||
width: 320,
|
|
||||||
child: TextField(
|
|
||||||
controller: searchController,
|
|
||||||
decoration: InputDecoration(
|
|
||||||
hintText: searchHint,
|
|
||||||
prefixIcon: const Icon(Icons.search, size: 18),
|
|
||||||
border: InputBorder.none,
|
|
||||||
isDense: true,
|
|
||||||
contentPadding: const EdgeInsets.symmetric(
|
|
||||||
horizontal: 10,
|
|
||||||
vertical: 8,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (filterControl != null) ...[
|
if (filterControl != null) ...[
|
||||||
const SizedBox(width: 12),
|
const SizedBox(width: 12),
|
||||||
_pillField(width: 150, child: filterControl!),
|
_pillField(width: 150, child: filterControl!),
|
||||||
@@ -81,6 +72,40 @@ class DashboardUserManagementSubBar extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Widget _buildSearchField() {
|
||||||
|
final field = _pillField(
|
||||||
|
width: 320,
|
||||||
|
child: TextField(
|
||||||
|
controller: searchController,
|
||||||
|
style: const TextStyle(fontSize: _searchFontSize),
|
||||||
|
decoration: InputDecoration(
|
||||||
|
hintText: searchHint,
|
||||||
|
hintStyle: TextStyle(
|
||||||
|
fontSize: _searchFontSize,
|
||||||
|
fontStyle: FontStyle.normal,
|
||||||
|
fontWeight: FontWeight.normal,
|
||||||
|
color: Colors.black45,
|
||||||
|
),
|
||||||
|
prefixIcon: const Icon(Icons.search, size: 18),
|
||||||
|
border: InputBorder.none,
|
||||||
|
isDense: true,
|
||||||
|
contentPadding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: 10,
|
||||||
|
vertical: 8,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
final tip = (searchTooltip ?? '').trim();
|
||||||
|
if (tip.isEmpty) return field;
|
||||||
|
return Tooltip(
|
||||||
|
message: tip,
|
||||||
|
preferBelow: false,
|
||||||
|
waitDuration: const Duration(milliseconds: 400),
|
||||||
|
child: field,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Widget _pillField({required double width, required Widget child}) {
|
Widget _pillField({required double width, required Widget child}) {
|
||||||
return Container(
|
return Container(
|
||||||
width: width,
|
width: width,
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/admin/common/admin_user_card.dart';
|
||||||
|
|
||||||
|
/// Carte dossier unifiée (#153) — fond neutre, accent couleur sur l’icône.
|
||||||
|
class DossierListCard extends StatelessWidget {
|
||||||
|
final String numeroDossier;
|
||||||
|
final String namesLine;
|
||||||
|
final bool isFamille;
|
||||||
|
final VoidCallback onOpen;
|
||||||
|
/// Photo AM (si absente → icône fallback).
|
||||||
|
final String? photoUrl;
|
||||||
|
|
||||||
|
/// Lavande — Famille / Parents.
|
||||||
|
static const Color familleAccent = Color(0xFFB289C9);
|
||||||
|
|
||||||
|
/// Menthe logo — AM.
|
||||||
|
static const Color amAccent = Color(0xFF5A9D94);
|
||||||
|
|
||||||
|
const DossierListCard({
|
||||||
|
super.key,
|
||||||
|
required this.numeroDossier,
|
||||||
|
required this.namesLine,
|
||||||
|
required this.isFamille,
|
||||||
|
required this.onOpen,
|
||||||
|
this.photoUrl,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final accent = isFamille ? familleAccent : amAccent;
|
||||||
|
final num = numeroDossier.trim().isEmpty ? '–' : numeroDossier.trim();
|
||||||
|
final names = namesLine.trim();
|
||||||
|
final avatar = (photoUrl ?? '').trim();
|
||||||
|
|
||||||
|
return AdminUserCard(
|
||||||
|
title: num,
|
||||||
|
subtitleLines: names.isEmpty ? const [] : [names],
|
||||||
|
avatarUrl: !isFamille && avatar.isNotEmpty ? avatar : null,
|
||||||
|
fallbackIcon:
|
||||||
|
isFamille ? Icons.family_restroom_outlined : Icons.face,
|
||||||
|
// N° = titre neutre (comme Parents / AM) ; accent = icône seule.
|
||||||
|
avatarIconColor: accent,
|
||||||
|
infoColor: Colors.black87,
|
||||||
|
onCardTap: onOpen,
|
||||||
|
actions: [
|
||||||
|
IconButton(
|
||||||
|
tooltip: 'Ouvrir',
|
||||||
|
icon: Icon(Icons.open_in_new, size: 20, color: accent),
|
||||||
|
onPressed: onOpen,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:p_tits_pas/models/dossier_list_item.dart';
|
||||||
|
import 'package:p_tits_pas/services/user_service.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/admin/dossier_list_card.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/admin/pending_validation_widget.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/admin/validation_dossier_modal.dart';
|
||||||
|
|
||||||
|
/// Onglet permanent « Dossiers » (#153) : pending en haut + liste unifiée en bas.
|
||||||
|
class DossiersManagementWidget extends StatefulWidget {
|
||||||
|
final String searchQuery;
|
||||||
|
final VoidCallback? onRefresh;
|
||||||
|
|
||||||
|
const DossiersManagementWidget({
|
||||||
|
super.key,
|
||||||
|
this.searchQuery = '',
|
||||||
|
this.onRefresh,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<DossiersManagementWidget> createState() =>
|
||||||
|
_DossiersManagementWidgetState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DossiersManagementWidgetState extends State<DossiersManagementWidget> {
|
||||||
|
bool _loading = true;
|
||||||
|
String? _error;
|
||||||
|
List<DossierListItem> _all = [];
|
||||||
|
Set<String> _pendingNumeros = {};
|
||||||
|
int _pendingRefreshTick = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_loadAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _loadAll() async {
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final parents = await UserService.getParents();
|
||||||
|
final ams = await UserService.getAssistantesMaternelles();
|
||||||
|
if (!mounted) return;
|
||||||
|
final items = <DossierListItem>[
|
||||||
|
...DossierListItem.fromParents(parents),
|
||||||
|
...DossierListItem.fromAssistantes(ams),
|
||||||
|
];
|
||||||
|
items.sort((a, b) {
|
||||||
|
final byNum = a.numeroDossier.compareTo(b.numeroDossier);
|
||||||
|
if (byNum != 0) return byNum;
|
||||||
|
return a.typeLabel.compareTo(b.typeLabel);
|
||||||
|
});
|
||||||
|
setState(() {
|
||||||
|
_all = items;
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_error = e is Exception
|
||||||
|
? e.toString().replaceFirst('Exception: ', '')
|
||||||
|
: 'Erreur inconnue';
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _refreshEverything() async {
|
||||||
|
setState(() => _pendingRefreshTick++);
|
||||||
|
await _loadAll();
|
||||||
|
widget.onRefresh?.call();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _openDossier(String numeroDossier) {
|
||||||
|
final num = numeroDossier.trim();
|
||||||
|
if (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,
|
||||||
|
openAsEdit: true,
|
||||||
|
onClose: () => Navigator.of(context).pop(),
|
||||||
|
onSuccess: () {
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
_refreshEverything();
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final query = widget.searchQuery;
|
||||||
|
// Pending uniquement en haut — exclus de « Tous les dossiers ».
|
||||||
|
final filtered = _all
|
||||||
|
.where((d) => !_pendingNumeros.contains(d.numeroDossier))
|
||||||
|
.where((d) => (d.statut ?? '').toLowerCase() != 'en_attente')
|
||||||
|
.where((d) => d.matchesQuery(query))
|
||||||
|
.toList(growable: false);
|
||||||
|
|
||||||
|
return RefreshIndicator(
|
||||||
|
onRefresh: _refreshEverything,
|
||||||
|
child: CustomScrollView(
|
||||||
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
|
slivers: [
|
||||||
|
SliverToBoxAdapter(
|
||||||
|
child: PendingValidationWidget(
|
||||||
|
key: ValueKey('pending-$_pendingRefreshTick'),
|
||||||
|
searchQuery: query,
|
||||||
|
compactWhenEmpty: true,
|
||||||
|
onPendingNumerosChanged: (nums) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _pendingNumeros = nums);
|
||||||
|
},
|
||||||
|
onRefresh: () {
|
||||||
|
_loadAll();
|
||||||
|
widget.onRefresh?.call();
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SliverToBoxAdapter(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
|
||||||
|
child: Text(
|
||||||
|
'Tous les dossiers',
|
||||||
|
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: Colors.black87,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (_loading)
|
||||||
|
const SliverFillRemaining(
|
||||||
|
hasScrollBody: false,
|
||||||
|
child: Center(child: CircularProgressIndicator()),
|
||||||
|
)
|
||||||
|
else if (_error != null && _error!.isNotEmpty)
|
||||||
|
SliverFillRemaining(
|
||||||
|
hasScrollBody: false,
|
||||||
|
child: 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: _loadAll,
|
||||||
|
child: const Text('Réessayer'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (filtered.isEmpty)
|
||||||
|
SliverToBoxAdapter(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(24, 12, 24, 32),
|
||||||
|
child: Text(
|
||||||
|
query.trim().isEmpty
|
||||||
|
? 'Aucun dossier pour le moment.\n'
|
||||||
|
'Pour créer un dossier → onglet Parents (+ Parents) '
|
||||||
|
'ou Assistantes maternelles (+ Asmat).'
|
||||||
|
: 'Aucun dossier ne correspond à la recherche.',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(color: Colors.grey.shade600, height: 1.4),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
SliverPadding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),
|
||||||
|
sliver: SliverList(
|
||||||
|
delegate: SliverChildBuilderDelegate(
|
||||||
|
(context, index) {
|
||||||
|
final item = filtered[index];
|
||||||
|
return DossierListCard(
|
||||||
|
numeroDossier: item.numeroDossier,
|
||||||
|
namesLine: item.namesLine,
|
||||||
|
isFamille: item.isFamille,
|
||||||
|
photoUrl: item.photoUrl,
|
||||||
|
onOpen: () => _openDossier(item.numeroDossier),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
childCount: filtered.length,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,10 +22,15 @@ import 'package:p_tits_pas/widgets/admin/validation_valider_confirm_dialog.dart'
|
|||||||
import 'package:p_tits_pas/widgets/common/auth_network_image.dart';
|
import 'package:p_tits_pas/widgets/common/auth_network_image.dart';
|
||||||
import 'package:p_tits_pas/widgets/common/identity_block.dart';
|
import 'package:p_tits_pas/widgets/common/identity_block.dart';
|
||||||
|
|
||||||
enum ParentDossierWizardMode { review, create }
|
enum ParentDossierWizardMode { review, create, edit }
|
||||||
|
|
||||||
/// Enfant en cours de saisie (mode création). Contrôleurs propres, à disposer.
|
/// Enfant en cours de saisie (création / édition). Contrôleurs propres, à disposer.
|
||||||
class _CreateChild {
|
class _CreateChild {
|
||||||
|
/// Id existant en base (mode edit) — null = nouvel enfant → POST.
|
||||||
|
String? existingChildId;
|
||||||
|
String? existingPhotoUrl;
|
||||||
|
/// Statut d’origine (hors à naître) pour ne pas écraser garde/scolarise.
|
||||||
|
String? existingStatus;
|
||||||
final TextEditingController prenomCtrl = TextEditingController();
|
final TextEditingController prenomCtrl = TextEditingController();
|
||||||
final TextEditingController nomCtrl = TextEditingController();
|
final TextEditingController nomCtrl = TextEditingController();
|
||||||
final TextEditingController dateCtrl = TextEditingController();
|
final TextEditingController dateCtrl = TextEditingController();
|
||||||
@@ -34,6 +39,8 @@ class _CreateChild {
|
|||||||
Uint8List? photoBytes;
|
Uint8List? photoBytes;
|
||||||
String? photoFilename;
|
String? photoFilename;
|
||||||
|
|
||||||
|
bool get hasExistingId => (existingChildId ?? '').trim().isNotEmpty;
|
||||||
|
|
||||||
void dispose() {
|
void dispose() {
|
||||||
prenomCtrl.dispose();
|
prenomCtrl.dispose();
|
||||||
nomCtrl.dispose();
|
nomCtrl.dispose();
|
||||||
@@ -41,8 +48,7 @@ class _CreateChild {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Wizard dossier famille — modes [review] (validation dossier en attente, ticket #107)
|
/// Wizard dossier famille — [review] (#107), [create] (#129), [edit] (#135).
|
||||||
/// et [create] (création dossier famille actif par le staff, ticket #129).
|
|
||||||
class ParentDossierWizard extends StatefulWidget {
|
class ParentDossierWizard extends StatefulWidget {
|
||||||
final ParentDossierWizardMode mode;
|
final ParentDossierWizardMode mode;
|
||||||
final DossierFamille? dossier;
|
final DossierFamille? dossier;
|
||||||
@@ -91,7 +97,25 @@ class ParentDossierWizard extends StatefulWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
factory ParentDossierWizard.edit({
|
||||||
|
Key? key,
|
||||||
|
required DossierFamille dossier,
|
||||||
|
required VoidCallback onClose,
|
||||||
|
required VoidCallback onSuccess,
|
||||||
|
void Function(int step, int total)? onStepChanged,
|
||||||
|
}) {
|
||||||
|
return ParentDossierWizard._(
|
||||||
|
key: key,
|
||||||
|
mode: ParentDossierWizardMode.edit,
|
||||||
|
dossier: dossier,
|
||||||
|
onClose: onClose,
|
||||||
|
onSuccess: onSuccess,
|
||||||
|
onStepChanged: onStepChanged,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
bool get isCreate => mode == ParentDossierWizardMode.create;
|
bool get isCreate => mode == ParentDossierWizardMode.create;
|
||||||
|
bool get isEdit => mode == ParentDossierWizardMode.edit;
|
||||||
|
|
||||||
/// Hauteur corps modale famille — 4 lignes TF + marge pour le bandeau switch.
|
/// Hauteur corps modale famille — 4 lignes TF + marge pour le bandeau switch.
|
||||||
static double get shellBodyHeight =>
|
static double get shellBodyHeight =>
|
||||||
@@ -141,16 +165,27 @@ class _ParentDossierWizardState extends State<ParentDossierWizard> {
|
|||||||
final List<_CreateChild> _children = [];
|
final List<_CreateChild> _children = [];
|
||||||
late final TextEditingController _presentationCtrl;
|
late final TextEditingController _presentationCtrl;
|
||||||
|
|
||||||
|
/// Nb de parents déjà en base au moment de l’ouverture (mode edit).
|
||||||
|
int _initialParentCount = 0;
|
||||||
|
|
||||||
|
/// Enfants existants retirés en edit → DELETE au save.
|
||||||
|
final List<String> _removedEnfantIds = [];
|
||||||
|
|
||||||
bool get _isCreate => widget.isCreate;
|
bool get _isCreate => widget.isCreate;
|
||||||
|
bool get _isEdit => widget.isEdit;
|
||||||
|
bool get _isEditable => _isCreate || _isEdit;
|
||||||
DossierFamille get _dossier => widget.dossier!;
|
DossierFamille get _dossier => widget.dossier!;
|
||||||
|
|
||||||
bool get _isEnAttente => !_isCreate && _dossier.isEnAttente;
|
bool get _isEnAttente => !_isCreate && !_isEdit && _dossier.isEnAttente;
|
||||||
|
|
||||||
String? get _firstParentId {
|
String? get _firstParentId {
|
||||||
if (_isCreate) return null;
|
if (_isCreate) return null;
|
||||||
return _dossier.parents.isNotEmpty ? _dossier.parents.first.id : null;
|
return _dossier.parents.isNotEmpty ? _dossier.parents.first.id : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Co-parent déjà présent au chargement (edit) — pas un ajout via POST.
|
||||||
|
bool get _hadExistingCoParent => _isEdit && _initialParentCount >= 2;
|
||||||
|
|
||||||
static String _v(String? s) =>
|
static String _v(String? s) =>
|
||||||
(s != null && s.trim().isNotEmpty) ? s.trim() : 'Non défini';
|
(s != null && s.trim().isNotEmpty) ? s.trim() : 'Non défini';
|
||||||
|
|
||||||
@@ -184,11 +219,81 @@ class _ParentDossierWizardState extends State<ParentDossierWizard> {
|
|||||||
_presentationCtrl = TextEditingController();
|
_presentationCtrl = TextEditingController();
|
||||||
if (_isCreate) {
|
if (_isCreate) {
|
||||||
_children.add(_CreateChild());
|
_children.add(_CreateChild());
|
||||||
|
} else if (_isEdit) {
|
||||||
|
_prefillFromDossier();
|
||||||
}
|
}
|
||||||
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) => _emitStep());
|
WidgetsBinding.instance.addPostFrameCallback((_) => _emitStep());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _prefillFromDossier() {
|
||||||
|
final parents = _dossier.parents;
|
||||||
|
_initialParentCount = parents.length;
|
||||||
|
|
||||||
|
if (parents.isNotEmpty) {
|
||||||
|
final p1 = parents.first;
|
||||||
|
_p1NomCtrl.text = (p1.nom ?? '').trim();
|
||||||
|
_p1PrenomCtrl.text = (p1.prenom ?? '').trim();
|
||||||
|
_p1TelCtrl.text = (p1.telephone ?? '').trim();
|
||||||
|
_p1EmailCtrl.text = (p1.email).trim();
|
||||||
|
_p1AdresseCtrl.text = (p1.adresse ?? '').trim();
|
||||||
|
_p1CpCtrl.text = (p1.codePostal ?? '').trim();
|
||||||
|
_p1VilleCtrl.text = (p1.ville ?? '').trim();
|
||||||
|
|
||||||
|
if (parents.length >= 2) {
|
||||||
|
_hasCoParent = true;
|
||||||
|
final p2 = parents[1];
|
||||||
|
_p2NomCtrl.text = (p2.nom ?? '').trim();
|
||||||
|
_p2PrenomCtrl.text = (p2.prenom ?? '').trim();
|
||||||
|
_p2TelCtrl.text = (p2.telephone ?? '').trim();
|
||||||
|
_p2EmailCtrl.text = (p2.email).trim();
|
||||||
|
_p2AdresseCtrl.text = (p2.adresse ?? '').trim();
|
||||||
|
_p2CpCtrl.text = (p2.codePostal ?? '').trim();
|
||||||
|
_p2VilleCtrl.text = (p2.ville ?? '').trim();
|
||||||
|
} else {
|
||||||
|
_hasCoParent = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_prefillChildrenFromDossier();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _prefillChildrenFromDossier() {
|
||||||
|
for (final c in _children) {
|
||||||
|
c.dispose();
|
||||||
|
}
|
||||||
|
_children.clear();
|
||||||
|
_removedEnfantIds.clear();
|
||||||
|
|
||||||
|
final enfants = _dossier.enfants;
|
||||||
|
if (enfants.isEmpty) {
|
||||||
|
_children.add(_CreateChild());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (final e in enfants) {
|
||||||
|
final status = (e.status ?? '').trim().toLowerCase();
|
||||||
|
final id = e.id.trim();
|
||||||
|
final child = _CreateChild()
|
||||||
|
..existingChildId = id.isEmpty ? null : id
|
||||||
|
..existingPhotoUrl = e.photoUrl
|
||||||
|
..existingStatus = status.isEmpty ? null : status
|
||||||
|
..isUnborn = status == 'a_naitre';
|
||||||
|
child.prenomCtrl.text = (e.firstName ?? '').trim();
|
||||||
|
child.nomCtrl.text = (e.lastName ?? '').trim();
|
||||||
|
final g = (e.gender ?? '').trim();
|
||||||
|
final gUp = g.toUpperCase();
|
||||||
|
if (gUp == 'H' || gUp == 'F') {
|
||||||
|
child.genre = gUp;
|
||||||
|
} else if (g == 'Autre' || child.isUnborn) {
|
||||||
|
child.genre = child.isUnborn ? 'Autre' : g;
|
||||||
|
}
|
||||||
|
final dateSrc = child.isUnborn ? e.dueDate : e.birthDate;
|
||||||
|
child.dateCtrl.text = formatIsoDateFrInput(dateSrc);
|
||||||
|
_children.add(child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_enfantsScrollController.removeListener(_syncEnfantsScrollFades);
|
_enfantsScrollController.removeListener(_syncEnfantsScrollFades);
|
||||||
@@ -291,7 +396,7 @@ class _ParentDossierWizardState extends State<ParentDossierWizard> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildStep0() {
|
Widget _buildStep0() {
|
||||||
if (_isCreate) {
|
if (_isEditable) {
|
||||||
return IdentityBlock.editable(
|
return IdentityBlock.editable(
|
||||||
title: 'Parent principal',
|
title: 'Parent principal',
|
||||||
nomController: _p1NomCtrl,
|
nomController: _p1NomCtrl,
|
||||||
@@ -310,13 +415,15 @@ class _ParentDossierWizardState extends State<ParentDossierWizard> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildStep1() {
|
Widget _buildStep1() {
|
||||||
if (_isCreate) {
|
if (_isEditable) {
|
||||||
return _buildCoParentStepCreate();
|
return _buildCoParentStepEditable(
|
||||||
|
allowToggle: !_hadExistingCoParent,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return _buildParent2Step();
|
return _buildParent2Step();
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildCoParentStepCreate() {
|
Widget _buildCoParentStepEditable({required bool allowToggle}) {
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
@@ -330,19 +437,21 @@ class _ParentDossierWizardState extends State<ParentDossierWizard> {
|
|||||||
color: Colors.black87,
|
color: Colors.black87,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const Spacer(),
|
if (allowToggle) ...[
|
||||||
const Text(
|
const Spacer(),
|
||||||
'Ajouter un co-parent',
|
const Text(
|
||||||
style: TextStyle(fontSize: 14, color: Colors.black87),
|
'Ajouter un co-parent',
|
||||||
),
|
style: TextStyle(fontSize: 14, color: Colors.black87),
|
||||||
Transform.scale(
|
|
||||||
scale: 0.75,
|
|
||||||
child: Switch(
|
|
||||||
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
|
||||||
value: _hasCoParent,
|
|
||||||
onChanged: (v) => setState(() => _hasCoParent = v),
|
|
||||||
),
|
),
|
||||||
),
|
Transform.scale(
|
||||||
|
scale: 0.75,
|
||||||
|
child: Switch(
|
||||||
|
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||||
|
value: _hasCoParent,
|
||||||
|
onChanged: (v) => setState(() => _hasCoParent = v),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
@@ -539,7 +648,7 @@ class _ParentDossierWizardState extends State<ParentDossierWizard> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildEnfantsStep() {
|
Widget _buildEnfantsStep() {
|
||||||
if (_isCreate) {
|
if (_isCreate || _isEdit) {
|
||||||
return _buildEnfantsStepCreate();
|
return _buildEnfantsStepCreate();
|
||||||
}
|
}
|
||||||
final enfants = _dossier.enfants;
|
final enfants = _dossier.enfants;
|
||||||
@@ -618,6 +727,10 @@ class _ParentDossierWizardState extends State<ParentDossierWizard> {
|
|||||||
if (_children.length <= 1) return;
|
if (_children.length <= 1) return;
|
||||||
setState(() {
|
setState(() {
|
||||||
final removed = _children.removeAt(index);
|
final removed = _children.removeAt(index);
|
||||||
|
final existingId = (removed.existingChildId ?? '').trim();
|
||||||
|
if (existingId.isNotEmpty) {
|
||||||
|
_removedEnfantIds.add(existingId);
|
||||||
|
}
|
||||||
removed.dispose();
|
removed.dispose();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -706,7 +819,8 @@ class _ParentDossierWizardState extends State<ParentDossierWizard> {
|
|||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.fromLTRB(12, 12, 14, 8),
|
// Réserve l’angle haut-droit pour la croix de suppression.
|
||||||
|
padding: EdgeInsets.fromLTRB(12, 12, canRemove ? 36 : 14, 8),
|
||||||
child: ValidationLabeledField(
|
child: ValidationLabeledField(
|
||||||
label: 'Prénom',
|
label: 'Prénom',
|
||||||
field: ValidationEditableField(
|
field: ValidationEditableField(
|
||||||
@@ -747,6 +861,9 @@ class _ParentDossierWizardState extends State<ParentDossierWizard> {
|
|||||||
width: pw,
|
width: pw,
|
||||||
height: ph,
|
height: ph,
|
||||||
child: AdminAmPhotoFrame(
|
child: AdminAmPhotoFrame(
|
||||||
|
photoUrl: child.photoBytes == null
|
||||||
|
? child.existingPhotoUrl
|
||||||
|
: null,
|
||||||
imageBytes: child.photoBytes,
|
imageBytes: child.photoBytes,
|
||||||
onTap: () => _pickChildPhoto(index),
|
onTap: () => _pickChildPhoto(index),
|
||||||
onClear: child.photoBytes != null
|
onClear: child.photoBytes != null
|
||||||
@@ -833,19 +950,28 @@ class _ParentDossierWizardState extends State<ParentDossierWizard> {
|
|||||||
),
|
),
|
||||||
if (canRemove)
|
if (canRemove)
|
||||||
Positioned(
|
Positioned(
|
||||||
top: 4,
|
top: 6,
|
||||||
right: 4,
|
right: 6,
|
||||||
child: Material(
|
child: Material(
|
||||||
color: Colors.transparent,
|
color: Colors.white,
|
||||||
child: IconButton(
|
elevation: 1,
|
||||||
tooltip: 'Retirer cet enfant',
|
shape: const CircleBorder(),
|
||||||
visualDensity: VisualDensity.compact,
|
clipBehavior: Clip.antiAlias,
|
||||||
padding: EdgeInsets.zero,
|
child: InkWell(
|
||||||
constraints:
|
customBorder: const CircleBorder(),
|
||||||
const BoxConstraints(minWidth: 32, minHeight: 32),
|
onTap: () => _removeChild(index),
|
||||||
icon: Icon(Icons.close,
|
child: Tooltip(
|
||||||
size: 18, color: Colors.grey.shade700),
|
message: 'Retirer cet enfant',
|
||||||
onPressed: () => _removeChild(index),
|
child: SizedBox(
|
||||||
|
width: 22,
|
||||||
|
height: 22,
|
||||||
|
child: Icon(
|
||||||
|
Icons.close,
|
||||||
|
size: 14,
|
||||||
|
color: Colors.grey.shade800,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -1264,6 +1390,18 @@ class _ParentDossierWizardState extends State<ParentDossierWizard> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
String? _validateCurrentStep() {
|
String? _validateCurrentStep() {
|
||||||
|
if (_isEdit) {
|
||||||
|
switch (_step) {
|
||||||
|
case 0:
|
||||||
|
return _validateP1();
|
||||||
|
case 1:
|
||||||
|
return _validateP2();
|
||||||
|
case 2:
|
||||||
|
return _validateEnfants();
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
if (!_isCreate) return null;
|
if (!_isCreate) return null;
|
||||||
switch (_step) {
|
switch (_step) {
|
||||||
case 0:
|
case 0:
|
||||||
@@ -1440,6 +1578,299 @@ class _ParentDossierWizardState extends State<ParentDossierWizard> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> _parentFicheBody({
|
||||||
|
required TextEditingController nom,
|
||||||
|
required TextEditingController prenom,
|
||||||
|
required TextEditingController email,
|
||||||
|
required TextEditingController tel,
|
||||||
|
required TextEditingController adresse,
|
||||||
|
required TextEditingController cp,
|
||||||
|
required TextEditingController ville,
|
||||||
|
}) {
|
||||||
|
return {
|
||||||
|
'nom': formatPersonNameCase(nom.text),
|
||||||
|
'prenom': formatPersonNameCase(prenom.text),
|
||||||
|
'email': normalizeEmailText(email.text),
|
||||||
|
'telephone': normalizePhone(tel.text),
|
||||||
|
'adresse': adresse.text.trim(),
|
||||||
|
'ville': formatPersonNameCase(ville.text),
|
||||||
|
'code_postal': cp.text.trim(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _saveEdit() async {
|
||||||
|
if (_submitting || !_isEdit) return;
|
||||||
|
final err0 = _validateP1();
|
||||||
|
if (err0 != null) {
|
||||||
|
_showError(err0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final err1 = _validateP2();
|
||||||
|
if (err1 != null) {
|
||||||
|
_showError(err1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final err2 = _validateEnfants();
|
||||||
|
if (err2 != null) {
|
||||||
|
_showError(err2);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final pivotId = (_firstParentId ?? '').trim();
|
||||||
|
if (pivotId.isEmpty) {
|
||||||
|
_showError('Identifiant du parent principal manquant.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final addingCoParent = _hasCoParent && !_hadExistingCoParent;
|
||||||
|
final ok = await showValidationValiderConfirmDialog(
|
||||||
|
context,
|
||||||
|
body: addingCoParent
|
||||||
|
? 'Enregistrer le dossier et ajouter le co-parent ? Un e-mail de création de mot de passe lui sera envoyé.'
|
||||||
|
: 'Enregistrer les modifications du dossier famille ?',
|
||||||
|
);
|
||||||
|
if (!mounted || !ok) return;
|
||||||
|
|
||||||
|
setState(() => _submitting = true);
|
||||||
|
try {
|
||||||
|
await UserService.updateParentFiche(
|
||||||
|
parentUserId: pivotId,
|
||||||
|
body: _parentFicheBody(
|
||||||
|
nom: _p1NomCtrl,
|
||||||
|
prenom: _p1PrenomCtrl,
|
||||||
|
email: _p1EmailCtrl,
|
||||||
|
tel: _p1TelCtrl,
|
||||||
|
adresse: _p1AdresseCtrl,
|
||||||
|
cp: _p1CpCtrl,
|
||||||
|
ville: _p1VilleCtrl,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (_hadExistingCoParent) {
|
||||||
|
final coId = _dossier.parents[1].id.trim();
|
||||||
|
if (coId.isEmpty) {
|
||||||
|
throw Exception('Identifiant du co-parent manquant.');
|
||||||
|
}
|
||||||
|
await UserService.updateParentFiche(
|
||||||
|
parentUserId: coId,
|
||||||
|
body: _parentFicheBody(
|
||||||
|
nom: _p2NomCtrl,
|
||||||
|
prenom: _p2PrenomCtrl,
|
||||||
|
email: _p2EmailCtrl,
|
||||||
|
tel: _p2TelCtrl,
|
||||||
|
adresse: _p2AdresseCtrl,
|
||||||
|
cp: _p2CpCtrl,
|
||||||
|
ville: _p2VilleCtrl,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else if (addingCoParent) {
|
||||||
|
if (_sameAddress) _copyP1AddressToP2();
|
||||||
|
final body = <String, dynamic>{
|
||||||
|
'email': normalizeEmailText(_p2EmailCtrl.text),
|
||||||
|
'prenom': formatPersonNameCase(_p2PrenomCtrl.text),
|
||||||
|
'nom': formatPersonNameCase(_p2NomCtrl.text),
|
||||||
|
'telephone': normalizePhone(_p2TelCtrl.text),
|
||||||
|
'meme_adresse': _sameAddress,
|
||||||
|
};
|
||||||
|
if (!_sameAddress) {
|
||||||
|
body['adresse'] = _p2AdresseCtrl.text.trim();
|
||||||
|
body['code_postal'] = _p2CpCtrl.text.trim();
|
||||||
|
body['ville'] = formatPersonNameCase(_p2VilleCtrl.text);
|
||||||
|
}
|
||||||
|
await UserService.addCoParent(pivotId, body: body);
|
||||||
|
}
|
||||||
|
|
||||||
|
await _saveEnfantsEdit(pivotId);
|
||||||
|
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(
|
||||||
|
addingCoParent
|
||||||
|
? 'Dossier enregistré. Co-parent ajouté.'
|
||||||
|
: 'Dossier enregistré.',
|
||||||
|
),
|
||||||
|
duration: const Duration(seconds: 4),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
widget.onSuccess();
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
_showError(
|
||||||
|
e is Exception ? e.toString().replaceFirst('Exception: ', '') : 'Erreur',
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
if (mounted) setState(() => _submitting = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> _enfantStaffBody(_CreateChild c) {
|
||||||
|
final prenom = formatPersonNameCase(c.prenomCtrl.text);
|
||||||
|
final nomRaw = c.nomCtrl.text.trim();
|
||||||
|
final nom = nomRaw.isNotEmpty
|
||||||
|
? formatPersonNameCase(nomRaw)
|
||||||
|
: formatPersonNameCase(_p1NomCtrl.text);
|
||||||
|
final dateIso = parseFrDateToIso(c.dateCtrl.text);
|
||||||
|
final existingStatus = (c.existingStatus ?? '').trim().toLowerCase();
|
||||||
|
final status = c.isUnborn
|
||||||
|
? 'a_naitre'
|
||||||
|
: (existingStatus.isNotEmpty && existingStatus != 'a_naitre'
|
||||||
|
? existingStatus
|
||||||
|
: 'sans_garde');
|
||||||
|
final gender = c.genre ?? 'H';
|
||||||
|
|
||||||
|
final map = <String, dynamic>{
|
||||||
|
'status': status,
|
||||||
|
'gender': gender,
|
||||||
|
'consent_photo': true,
|
||||||
|
'is_multiple': false,
|
||||||
|
};
|
||||||
|
if (prenom.length >= 2) map['first_name'] = prenom;
|
||||||
|
if (nom.length >= 2) map['last_name'] = nom;
|
||||||
|
if (c.isUnborn) {
|
||||||
|
if (dateIso != null) map['due_date'] = dateIso;
|
||||||
|
} else if (dateIso != null) {
|
||||||
|
map['birth_date'] = dateIso;
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Empreinte identité pour rattacher un brouillon sans id à un enfant du GET.
|
||||||
|
String _enfantIdentityKey({
|
||||||
|
required String prenom,
|
||||||
|
required String nom,
|
||||||
|
required String? dateIso,
|
||||||
|
required bool isUnborn,
|
||||||
|
}) {
|
||||||
|
final pn = formatPersonNameCase(prenom).toLowerCase().trim();
|
||||||
|
final nm = formatPersonNameCase(nom).toLowerCase().trim();
|
||||||
|
final d = _normalizeDateKey(dateIso);
|
||||||
|
final kind = isUnborn ? 'due' : 'birth';
|
||||||
|
return '$pn|$nm|$kind|$d';
|
||||||
|
}
|
||||||
|
|
||||||
|
String _normalizeDateKey(String? raw) {
|
||||||
|
final s = (raw ?? '').trim();
|
||||||
|
if (s.isEmpty) return '';
|
||||||
|
final fromFr = parseFrDateToIso(s);
|
||||||
|
if (fromFr != null) return fromFr;
|
||||||
|
try {
|
||||||
|
final dt = DateTime.parse(s);
|
||||||
|
final y = dt.year.toString().padLeft(4, '0');
|
||||||
|
final m = dt.month.toString().padLeft(2, '0');
|
||||||
|
final d = dt.day.toString().padLeft(2, '0');
|
||||||
|
return '$y-$m-$d';
|
||||||
|
} catch (_) {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _enfantKeyFromCreate(_CreateChild c) {
|
||||||
|
final prenom = formatPersonNameCase(c.prenomCtrl.text);
|
||||||
|
final nomRaw = c.nomCtrl.text.trim();
|
||||||
|
final nom = nomRaw.isNotEmpty
|
||||||
|
? formatPersonNameCase(nomRaw)
|
||||||
|
: formatPersonNameCase(_p1NomCtrl.text);
|
||||||
|
return _enfantIdentityKey(
|
||||||
|
prenom: prenom,
|
||||||
|
nom: nom,
|
||||||
|
dateIso: parseFrDateToIso(c.dateCtrl.text),
|
||||||
|
isUnborn: c.isUnborn,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _enfantKeyFromDossier(EnfantDossier e) {
|
||||||
|
final isUnborn = (e.status ?? '').trim().toLowerCase() == 'a_naitre';
|
||||||
|
final nomRaw = (e.lastName ?? '').trim();
|
||||||
|
final nom = nomRaw.isNotEmpty ? nomRaw : (_p1NomCtrl.text.trim());
|
||||||
|
return _enfantIdentityKey(
|
||||||
|
prenom: e.firstName ?? '',
|
||||||
|
nom: nom,
|
||||||
|
dateIso: isUnborn ? e.dueDate : e.birthDate,
|
||||||
|
isUnborn: isUnborn,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _isBlankChildDraft(_CreateChild c) {
|
||||||
|
if (c.hasExistingId) return false;
|
||||||
|
final prenom = c.prenomCtrl.text.trim();
|
||||||
|
final nom = c.nomCtrl.text.trim();
|
||||||
|
final date = c.dateCtrl.text.trim();
|
||||||
|
return prenom.isEmpty && nom.isEmpty && date.isEmpty && c.genre == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Résout l’id enfant : tracker edit, sinon match sur le GET dossier.
|
||||||
|
String? _resolveExistingChildId(
|
||||||
|
_CreateChild c,
|
||||||
|
Map<String, String> dossierIdByIdentity,
|
||||||
|
Set<String> alreadyUsedIds,
|
||||||
|
) {
|
||||||
|
final tracked = (c.existingChildId ?? '').trim();
|
||||||
|
if (tracked.isNotEmpty && !alreadyUsedIds.contains(tracked)) {
|
||||||
|
return tracked;
|
||||||
|
}
|
||||||
|
final key = _enfantKeyFromCreate(c);
|
||||||
|
final matched = (dossierIdByIdentity[key] ?? '').trim();
|
||||||
|
if (matched.isNotEmpty && !alreadyUsedIds.contains(matched)) {
|
||||||
|
return matched;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _saveEnfantsEdit(String pivotUserId) async {
|
||||||
|
// Index id connus du GET (ne jamais POST pour ceux-là).
|
||||||
|
final dossierIdByIdentity = <String, String>{};
|
||||||
|
for (final e in _dossier.enfants) {
|
||||||
|
final id = e.id.trim();
|
||||||
|
if (id.isEmpty) continue;
|
||||||
|
dossierIdByIdentity[_enfantKeyFromDossier(e)] = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (final id in _removedEnfantIds) {
|
||||||
|
await UserService.deleteEnfant(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
final usedIds = <String>{..._removedEnfantIds};
|
||||||
|
for (final c in _children) {
|
||||||
|
if (_isBlankChildDraft(c)) continue;
|
||||||
|
|
||||||
|
final existingId = _resolveExistingChildId(
|
||||||
|
c,
|
||||||
|
dossierIdByIdentity,
|
||||||
|
usedIds,
|
||||||
|
);
|
||||||
|
final body = _enfantStaffBody(c);
|
||||||
|
|
||||||
|
if (existingId != null && existingId.isNotEmpty) {
|
||||||
|
// Ré-attache l’id au modèle (si match identité a récupéré un id perdu).
|
||||||
|
c.existingChildId = existingId;
|
||||||
|
final bytes = c.photoBytes;
|
||||||
|
await UserService.updateEnfant(
|
||||||
|
enfantId: existingId,
|
||||||
|
body: body,
|
||||||
|
photoBytes: (bytes != null && bytes.isNotEmpty) ? bytes : null,
|
||||||
|
photoFilename: c.photoFilename,
|
||||||
|
);
|
||||||
|
usedIds.add(existingId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Uniquement les vrais nouveaux enfants (pas d’id dossier).
|
||||||
|
final bytes = c.photoBytes;
|
||||||
|
final created = await UserService.createEnfant(
|
||||||
|
parentUserId: pivotUserId,
|
||||||
|
body: body,
|
||||||
|
photoBytes: (bytes != null && bytes.isNotEmpty) ? bytes : null,
|
||||||
|
photoFilename: c.photoFilename,
|
||||||
|
);
|
||||||
|
final newId = created.id.trim();
|
||||||
|
if (newId.isNotEmpty) {
|
||||||
|
c.existingChildId = newId;
|
||||||
|
usedIds.add(newId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Widget _buildNavigation() {
|
Widget _buildNavigation() {
|
||||||
if (_step == 3) {
|
if (_step == 3) {
|
||||||
return Row(
|
return Row(
|
||||||
@@ -1463,6 +1894,12 @@ class _ParentDossierWizardState extends State<ParentDossierWizard> {
|
|||||||
onPressed: _submitting ? null : _createAndValidate,
|
onPressed: _submitting ? null : _createAndValidate,
|
||||||
child: Text(_submitting ? 'Envoi...' : 'Créer et valider'),
|
child: Text(_submitting ? 'Envoi...' : 'Créer et valider'),
|
||||||
),
|
),
|
||||||
|
] else if (_isEdit) ...[
|
||||||
|
ElevatedButton(
|
||||||
|
style: ValidationModalTheme.primaryElevatedStyle,
|
||||||
|
onPressed: _submitting ? null : _saveEdit,
|
||||||
|
child: Text(_submitting ? 'Envoi...' : 'Enregistrer'),
|
||||||
|
),
|
||||||
] else if (_isEnAttente && _firstParentId != null) ...[
|
] else if (_isEnAttente && _firstParentId != null) ...[
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
onPressed: _submitting ? null : _refuser,
|
onPressed: _submitting ? null : _refuser,
|
||||||
|
|||||||
@@ -1,19 +1,32 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:intl/intl.dart';
|
import 'package:p_tits_pas/models/dossier_list_item.dart';
|
||||||
import 'package:p_tits_pas/models/user.dart';
|
import 'package:p_tits_pas/models/user.dart';
|
||||||
import 'package:p_tits_pas/models/pending_family.dart';
|
import 'package:p_tits_pas/models/pending_family.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/phone_utils.dart';
|
import 'package:p_tits_pas/widgets/admin/dossier_list_card.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/validation_dossier_modal.dart';
|
import 'package:p_tits_pas/widgets/admin/validation_dossier_modal.dart';
|
||||||
|
|
||||||
/// Onglet « À valider » : deux listes (AM en attente, familles en attente). Ticket #107.
|
/// Section « dossiers à valider » (liste unifiée AM + familles). Ticket #107 / #153.
|
||||||
class PendingValidationWidget extends StatefulWidget {
|
class PendingValidationWidget extends StatefulWidget {
|
||||||
final VoidCallback? onRefresh;
|
final VoidCallback? onRefresh;
|
||||||
|
/// Filtre client (n°, nom, email) — onglet Dossiers (#153).
|
||||||
|
final String searchQuery;
|
||||||
|
/// Si true et liste vide : message court (pas de grand vide centré).
|
||||||
|
final bool compactWhenEmpty;
|
||||||
|
/// Numéros des dossiers pending (pour exclure de « Tous les dossiers »).
|
||||||
|
final ValueChanged<Set<String>>? onPendingNumerosChanged;
|
||||||
|
|
||||||
const PendingValidationWidget({super.key, this.onRefresh});
|
const PendingValidationWidget({
|
||||||
|
super.key,
|
||||||
|
this.onRefresh,
|
||||||
|
this.searchQuery = '',
|
||||||
|
this.compactWhenEmpty = false,
|
||||||
|
this.onPendingNumerosChanged,
|
||||||
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<PendingValidationWidget> createState() => _PendingValidationWidgetState();
|
State<PendingValidationWidget> createState() =>
|
||||||
|
_PendingValidationWidgetState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _PendingValidationWidgetState extends State<PendingValidationWidget> {
|
class _PendingValidationWidgetState extends State<PendingValidationWidget> {
|
||||||
@@ -21,6 +34,8 @@ class _PendingValidationWidgetState extends State<PendingValidationWidget> {
|
|||||||
String? _error;
|
String? _error;
|
||||||
List<AppUser> _pendingAM = [];
|
List<AppUser> _pendingAM = [];
|
||||||
List<PendingFamily> _pendingFamilies = [];
|
List<PendingFamily> _pendingFamilies = [];
|
||||||
|
/// Noms enrichis via GET /dossiers/:numero (libelle API = noms seuls).
|
||||||
|
final Map<String, String> _familyNamesByNumero = {};
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@@ -34,24 +49,77 @@ class _PendingValidationWidgetState extends State<PendingValidationWidget> {
|
|||||||
_error = null;
|
_error = null;
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
final am = await UserService.getPendingUsers(role: 'assistante_maternelle');
|
final am =
|
||||||
|
await UserService.getPendingUsers(role: 'assistante_maternelle');
|
||||||
final families = await UserService.getPendingFamilies();
|
final families = await UserService.getPendingFamilies();
|
||||||
|
final namesByNumero = await _enrichFamilyNames(families);
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() {
|
setState(() {
|
||||||
_pendingAM = am;
|
_pendingAM = am;
|
||||||
_pendingFamilies = families;
|
_pendingFamilies = families;
|
||||||
|
_familyNamesByNumero
|
||||||
|
..clear()
|
||||||
|
..addAll(namesByNumero);
|
||||||
_isLoading = false;
|
_isLoading = false;
|
||||||
});
|
});
|
||||||
|
_emitPendingNumeros();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() {
|
setState(() {
|
||||||
_error = e is Exception ? e.toString().replaceFirst('Exception: ', '') : 'Erreur inconnue';
|
_error = e is Exception
|
||||||
|
? e.toString().replaceFirst('Exception: ', '')
|
||||||
|
: 'Erreur inconnue';
|
||||||
_isLoading = false;
|
_isLoading = false;
|
||||||
});
|
});
|
||||||
|
widget.onPendingNumerosChanged?.call(const {});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _onOpenValidation({String? type, String? id, String? numeroDossier}) {
|
/// Complète `NOM Prénom` via le détail dossier (sans changer le back).
|
||||||
|
Future<Map<String, String>> _enrichFamilyNames(
|
||||||
|
List<PendingFamily> families,
|
||||||
|
) async {
|
||||||
|
final out = <String, String>{};
|
||||||
|
await Future.wait(families.map((f) async {
|
||||||
|
final num = (f.numeroDossier ?? '').trim();
|
||||||
|
if (num.isEmpty) return;
|
||||||
|
try {
|
||||||
|
final dossier = await UserService.getDossier(num);
|
||||||
|
if (!dossier.isFamily) return;
|
||||||
|
final labels = <String>[];
|
||||||
|
final seen = <String>{};
|
||||||
|
for (final p in dossier.asFamily.parents) {
|
||||||
|
final id = p.id.trim();
|
||||||
|
if (id.isNotEmpty && !seen.add(id)) continue;
|
||||||
|
final label = formatDossierPersonLabel(
|
||||||
|
nom: p.nom,
|
||||||
|
prenom: p.prenom,
|
||||||
|
email: p.email,
|
||||||
|
);
|
||||||
|
if (label.isNotEmpty) labels.add(label);
|
||||||
|
}
|
||||||
|
if (labels.isNotEmpty) out[num] = labels.join(' - ');
|
||||||
|
} catch (_) {
|
||||||
|
// Repli libellé API ci-dessous.
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _emitPendingNumeros() {
|
||||||
|
final nums = <String>{};
|
||||||
|
for (final u in _pendingAM) {
|
||||||
|
final n = (u.numeroDossier ?? '').trim();
|
||||||
|
if (n.isNotEmpty) nums.add(n);
|
||||||
|
}
|
||||||
|
for (final f in _pendingFamilies) {
|
||||||
|
final n = (f.numeroDossier ?? '').trim();
|
||||||
|
if (n.isNotEmpty) nums.add(n);
|
||||||
|
}
|
||||||
|
widget.onPendingNumerosChanged?.call(nums);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onOpenValidation({String? numeroDossier}) {
|
||||||
final num = numeroDossier?.trim();
|
final num = numeroDossier?.trim();
|
||||||
if (num == null || num.isEmpty) {
|
if (num == null || num.isEmpty) {
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
@@ -73,9 +141,48 @@ class _PendingValidationWidgetState extends State<PendingValidationWidget> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool _matchesQuery(String haystack) {
|
||||||
|
final q = widget.searchQuery.trim().toLowerCase();
|
||||||
|
if (q.isEmpty) return true;
|
||||||
|
return haystack.toLowerCase().contains(q);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<AppUser> get _filteredAM {
|
||||||
|
return _pendingAM.where((u) {
|
||||||
|
final bits = [
|
||||||
|
u.numeroDossier ?? '',
|
||||||
|
u.fullName,
|
||||||
|
u.email,
|
||||||
|
u.nom ?? '',
|
||||||
|
u.prenom ?? '',
|
||||||
|
].join(' ');
|
||||||
|
return _matchesQuery(bits);
|
||||||
|
}).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<PendingFamily> get _filteredFamilies {
|
||||||
|
return _pendingFamilies.where((f) {
|
||||||
|
final num = (f.numeroDossier ?? '').trim();
|
||||||
|
final enriched = _familyNamesByNumero[num] ?? '';
|
||||||
|
final bits = [
|
||||||
|
f.numeroDossier ?? '',
|
||||||
|
f.libelle,
|
||||||
|
enriched,
|
||||||
|
f.emails.join(' '),
|
||||||
|
].join(' ');
|
||||||
|
return _matchesQuery(bits);
|
||||||
|
}).toList();
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
if (_isLoading) {
|
if (_isLoading) {
|
||||||
|
if (widget.compactWhenEmpty) {
|
||||||
|
return const Padding(
|
||||||
|
padding: EdgeInsets.all(24),
|
||||||
|
child: Center(child: CircularProgressIndicator()),
|
||||||
|
);
|
||||||
|
}
|
||||||
return const Center(child: CircularProgressIndicator());
|
return const Center(child: CircularProgressIndicator());
|
||||||
}
|
}
|
||||||
if (_error != null && _error!.isNotEmpty) {
|
if (_error != null && _error!.isNotEmpty) {
|
||||||
@@ -97,14 +204,32 @@ class _PendingValidationWidgetState extends State<PendingValidationWidget> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
final hasAM = _pendingAM.isNotEmpty;
|
final pendingAM = _filteredAM;
|
||||||
final hasFamilies = _pendingFamilies.isNotEmpty;
|
final pendingFamilies = _filteredFamilies;
|
||||||
if (!hasAM && !hasFamilies) {
|
final cards = <Widget>[
|
||||||
|
...pendingAM.map(_buildAMCard),
|
||||||
|
...pendingFamilies.map(_buildFamilyCard),
|
||||||
|
];
|
||||||
|
|
||||||
|
if (cards.isEmpty) {
|
||||||
|
if (widget.compactWhenEmpty) {
|
||||||
|
final searching = widget.searchQuery.trim().isNotEmpty;
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
|
||||||
|
child: Text(
|
||||||
|
searching
|
||||||
|
? 'Aucun dossier en attente ne correspond à la recherche.'
|
||||||
|
: 'Aucun dossier en attente.',
|
||||||
|
style: TextStyle(color: Colors.grey.shade600, fontSize: 13),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
return Center(
|
return Center(
|
||||||
child: Column(
|
child: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
Icon(Icons.check_circle_outline, size: 64, color: Colors.grey.shade400),
|
Icon(Icons.check_circle_outline,
|
||||||
|
size: 64, color: Colors.grey.shade400),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(
|
Text(
|
||||||
'Aucun dossier en attente de validation',
|
'Aucun dossier en attente de validation',
|
||||||
@@ -117,6 +242,28 @@ class _PendingValidationWidgetState extends State<PendingValidationWidget> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final list = Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
'Dossiers à valider',
|
||||||
|
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: Colors.black87,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
...cards,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (widget.compactWhenEmpty) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
||||||
|
child: list,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return RefreshIndicator(
|
return RefreshIndicator(
|
||||||
onRefresh: () async {
|
onRefresh: () async {
|
||||||
await _load();
|
await _load();
|
||||||
@@ -125,275 +272,40 @@ class _PendingValidationWidgetState extends State<PendingValidationWidget> {
|
|||||||
child: SingleChildScrollView(
|
child: SingleChildScrollView(
|
||||||
physics: const AlwaysScrollableScrollPhysics(),
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
child: Column(
|
child: list,
|
||||||
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) {
|
String _amNamesLine(AppUser user) {
|
||||||
return Text(
|
return formatDossierPersonLabel(
|
||||||
title,
|
nom: user.nom,
|
||||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
prenom: user.prenom,
|
||||||
fontWeight: FontWeight.w600,
|
email: user.email,
|
||||||
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) {
|
Widget _buildAMCard(AppUser user) {
|
||||||
final numDossier = user.numeroDossier ?? '–';
|
return DossierListCard(
|
||||||
final nameBold =
|
numeroDossier: user.numeroDossier ?? '',
|
||||||
user.fullName.isNotEmpty ? user.fullName : (user.email.isNotEmpty ? user.email : '–');
|
namesLine: _amNamesLine(user),
|
||||||
return _PendingValidationRow(
|
isFamille: false,
|
||||||
icon: Icons.person_outline,
|
photoUrl: user.photoUrl,
|
||||||
title: Text.rich(
|
onOpen: () => _onOpenValidation(numeroDossier: user.numeroDossier),
|
||||||
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) {
|
Widget _buildFamilyCard(PendingFamily family) {
|
||||||
final numDossier = family.numeroDossier ?? '–';
|
final num = (family.numeroDossier ?? '').trim();
|
||||||
final nameBold = family.libelle.isNotEmpty ? family.libelle : 'Famille';
|
final enriched = num.isNotEmpty ? _familyNamesByNumero[num] : null;
|
||||||
return _PendingValidationRow(
|
final names = (enriched != null && enriched.isNotEmpty)
|
||||||
icon: Icons.family_restroom_outlined,
|
? enriched
|
||||||
title: Text.rich(
|
: formatDossierFamilyNamesLine(family.libelle);
|
||||||
TextSpan(
|
return DossierListCard(
|
||||||
style: const TextStyle(fontSize: 14, color: Colors.black87),
|
numeroDossier: family.numeroDossier ?? '',
|
||||||
children: [
|
namesLine: names,
|
||||||
TextSpan(
|
isFamille: true,
|
||||||
text: nameBold,
|
onOpen: () => _onOpenValidation(numeroDossier: family.numeroDossier),
|
||||||
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,19 +1,18 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.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/user_service.dart';
|
|
||||||
import 'package:p_tits_pas/widgets/admin/admin_management_widget.dart';
|
import 'package:p_tits_pas/widgets/admin/admin_management_widget.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/am_dossier_create_modal.dart';
|
import 'package:p_tits_pas/widgets/admin/am_dossier_create_modal.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/assistante_maternelle_management_widget.dart';
|
import 'package:p_tits_pas/widgets/admin/assistante_maternelle_management_widget.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/common/admin_child_detail_modal.dart';
|
import 'package:p_tits_pas/widgets/admin/common/admin_child_detail_modal.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/dashboard_admin.dart';
|
import 'package:p_tits_pas/widgets/admin/dashboard_admin.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/admin/dossiers_management_widget.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/enfant_management_widget.dart';
|
import 'package:p_tits_pas/widgets/admin/enfant_management_widget.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/gestionnaire_management_widget.dart';
|
import 'package:p_tits_pas/widgets/admin/gestionnaire_management_widget.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/parent_dossier_create_modal.dart';
|
import 'package:p_tits_pas/widgets/admin/parent_dossier_create_modal.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/parent_managmant_widget.dart';
|
import 'package:p_tits_pas/widgets/admin/parent_managmant_widget.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/pending_validation_widget.dart';
|
|
||||||
|
|
||||||
class UserManagementPanel extends StatefulWidget {
|
class UserManagementPanel extends StatefulWidget {
|
||||||
/// Afficher l'onglet Administrateurs (sinon 3 onglets : Gestionnaires, Parents, AM).
|
/// Afficher l'onglet Administrateurs (sinon sans Administrateurs).
|
||||||
final bool showAdministrateursTab;
|
final bool showAdministrateursTab;
|
||||||
|
|
||||||
const UserManagementPanel({
|
const UserManagementPanel({
|
||||||
@@ -32,45 +31,17 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
int _adminRefreshTick = 0;
|
int _adminRefreshTick = 0;
|
||||||
int _enfantRefreshTick = 0;
|
int _enfantRefreshTick = 0;
|
||||||
int _amRefreshTick = 0;
|
int _amRefreshTick = 0;
|
||||||
|
int _dossiersRefreshTick = 0;
|
||||||
final TextEditingController _searchController = TextEditingController();
|
final TextEditingController _searchController = TextEditingController();
|
||||||
final TextEditingController _amCapacityController = TextEditingController();
|
final TextEditingController _amCapacityController = TextEditingController();
|
||||||
String? _parentStatus;
|
String? _parentStatus;
|
||||||
String? _enfantStatus;
|
String? _enfantStatus;
|
||||||
bool _hasPending = false;
|
|
||||||
bool _pendingLoading = true;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_searchController.addListener(_onFilterChanged);
|
_searchController.addListener(_onFilterChanged);
|
||||||
_amCapacityController.addListener(_onFilterChanged);
|
_amCapacityController.addListener(_onFilterChanged);
|
||||||
_loadPending();
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _loadPending() async {
|
|
||||||
try {
|
|
||||||
final am = await UserService.getPendingUsers(role: 'assistante_maternelle');
|
|
||||||
final families = await UserService.getPendingFamilies();
|
|
||||||
if (!mounted) return;
|
|
||||||
final hasPending = am.isNotEmpty || families.isNotEmpty;
|
|
||||||
setState(() {
|
|
||||||
final hadPending = _hasPending;
|
|
||||||
_hasPending = hasPending;
|
|
||||||
_pendingLoading = false;
|
|
||||||
// Si on passe à "plus de dossiers", recaler l'index (onglet À valider disparaît).
|
|
||||||
if (hadPending && !hasPending) {
|
|
||||||
_subIndex = (_subIndex > 0 ? _subIndex - 1 : 0).clamp(0, _tabLabels.length - 1);
|
|
||||||
} else if (!hadPending && hasPending) {
|
|
||||||
_subIndex = 0; // Afficher l'onglet À valider
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (_) {
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
_hasPending = false;
|
|
||||||
_pendingLoading = false;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -87,13 +58,19 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
setState(() {});
|
setState(() {});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ordre #153 : Dossiers | Parents | Enfants | AM | Gestionnaires | (Admin).
|
||||||
List<String> get _tabLabels {
|
List<String> get _tabLabels {
|
||||||
const base = ['Parents', 'Enfants', 'Assistantes maternelles', 'Gestionnaires'];
|
const base = [
|
||||||
final withAdmin = [...base, 'Administrateurs'];
|
'Dossiers',
|
||||||
final list = widget.showAdministrateursTab ? withAdmin : base;
|
'Parents',
|
||||||
// Onglet « À valider » visible seulement s'il y a des dossiers en attente (ticket #107).
|
'Enfants',
|
||||||
if (!_pendingLoading && _hasPending) return ['À valider', ...list];
|
'Assistantes maternelles',
|
||||||
return list;
|
'Gestionnaires',
|
||||||
|
];
|
||||||
|
if (widget.showAdministrateursTab) {
|
||||||
|
return [...base, 'Administrateurs'];
|
||||||
|
}
|
||||||
|
return base;
|
||||||
}
|
}
|
||||||
|
|
||||||
void _onSubTabChange(int index) {
|
void _onSubTabChange(int index) {
|
||||||
@@ -107,31 +84,35 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Index du contenu : -1 = À valider, 0 = Parents, 1 = Enfants, 2 = AM, 3 = Gestionnaires, 4 = Admin.
|
bool get _isDossiersTab => _subIndex == 0;
|
||||||
int get _contentIndexOffset => (_hasPending && !_pendingLoading) ? 1 : 0;
|
|
||||||
|
|
||||||
String _searchHintForTab() {
|
String _searchHintForTab() {
|
||||||
final contentIndex = _subIndex - _contentIndexOffset;
|
switch (_subIndex) {
|
||||||
switch (contentIndex) {
|
|
||||||
case -1:
|
|
||||||
return 'À valider (pas de recherche)';
|
|
||||||
case 0:
|
case 0:
|
||||||
return 'Rechercher un parent...';
|
return 'Rechercher un dossier';
|
||||||
case 1:
|
case 1:
|
||||||
return 'Rechercher un enfant...';
|
return 'Rechercher un parent...';
|
||||||
case 2:
|
case 2:
|
||||||
return 'Rechercher une assistante...';
|
return 'Rechercher un enfant...';
|
||||||
case 3:
|
case 3:
|
||||||
return 'Rechercher un gestionnaire...';
|
return 'Rechercher une assistante...';
|
||||||
case 4:
|
case 4:
|
||||||
|
return 'Rechercher un gestionnaire...';
|
||||||
|
case 5:
|
||||||
return 'Rechercher un administrateur...';
|
return 'Rechercher un administrateur...';
|
||||||
default:
|
default:
|
||||||
return 'Rechercher...';
|
return 'Rechercher...';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String? _searchTooltipForTab() {
|
||||||
|
if (_subIndex != 0) return null;
|
||||||
|
return 'Recherche possible : n° de dossier, nom, prénom ou e-mail.';
|
||||||
|
}
|
||||||
|
|
||||||
Widget? _subBarFilterControl() {
|
Widget? _subBarFilterControl() {
|
||||||
if (_subIndex == _contentIndexOffset + 0) {
|
// Parents
|
||||||
|
if (_subIndex == 1) {
|
||||||
return DropdownButtonHideUnderline(
|
return DropdownButtonHideUnderline(
|
||||||
child: DropdownButton<String?>(
|
child: DropdownButton<String?>(
|
||||||
value: _parentStatus,
|
value: _parentStatus,
|
||||||
@@ -186,7 +167,8 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_subIndex == _contentIndexOffset + 1) {
|
// Enfants
|
||||||
|
if (_subIndex == 2) {
|
||||||
return DropdownButtonHideUnderline(
|
return DropdownButtonHideUnderline(
|
||||||
child: DropdownButton<String?>(
|
child: DropdownButton<String?>(
|
||||||
value: _enfantStatus,
|
value: _enfantStatus,
|
||||||
@@ -241,7 +223,8 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_subIndex == _contentIndexOffset + 2) {
|
// AM
|
||||||
|
if (_subIndex == 3) {
|
||||||
return TextField(
|
return TextField(
|
||||||
controller: _amCapacityController,
|
controller: _amCapacityController,
|
||||||
decoration: const InputDecoration(
|
decoration: const InputDecoration(
|
||||||
@@ -258,35 +241,36 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildBody() {
|
Widget _buildBody() {
|
||||||
final contentIndex = _subIndex - _contentIndexOffset;
|
switch (_subIndex) {
|
||||||
if (_hasPending && !_pendingLoading && contentIndex == -1) {
|
|
||||||
return PendingValidationWidget(onRefresh: _loadPending);
|
|
||||||
}
|
|
||||||
switch (contentIndex) {
|
|
||||||
case 0:
|
case 0:
|
||||||
|
return DossiersManagementWidget(
|
||||||
|
key: ValueKey('dossiers-$_dossiersRefreshTick'),
|
||||||
|
searchQuery: _searchController.text,
|
||||||
|
);
|
||||||
|
case 1:
|
||||||
return ParentManagementWidget(
|
return ParentManagementWidget(
|
||||||
key: ValueKey('parents-$_parentRefreshTick'),
|
key: ValueKey('parents-$_parentRefreshTick'),
|
||||||
searchQuery: _searchController.text,
|
searchQuery: _searchController.text,
|
||||||
statusFilter: _parentStatus,
|
statusFilter: _parentStatus,
|
||||||
);
|
);
|
||||||
case 1:
|
case 2:
|
||||||
return EnfantManagementWidget(
|
return EnfantManagementWidget(
|
||||||
key: ValueKey('enfants-$_enfantRefreshTick'),
|
key: ValueKey('enfants-$_enfantRefreshTick'),
|
||||||
searchQuery: _searchController.text,
|
searchQuery: _searchController.text,
|
||||||
statusFilter: _enfantStatus,
|
statusFilter: _enfantStatus,
|
||||||
);
|
);
|
||||||
case 2:
|
case 3:
|
||||||
return AssistanteMaternelleManagementWidget(
|
return AssistanteMaternelleManagementWidget(
|
||||||
key: ValueKey('ams-$_amRefreshTick'),
|
key: ValueKey('ams-$_amRefreshTick'),
|
||||||
searchQuery: _searchController.text,
|
searchQuery: _searchController.text,
|
||||||
capacityMin: int.tryParse(_amCapacityController.text),
|
capacityMin: int.tryParse(_amCapacityController.text),
|
||||||
);
|
);
|
||||||
case 3:
|
case 4:
|
||||||
return GestionnaireManagementWidget(
|
return GestionnaireManagementWidget(
|
||||||
key: ValueKey('gestionnaires-$_gestionnaireRefreshTick'),
|
key: ValueKey('gestionnaires-$_gestionnaireRefreshTick'),
|
||||||
searchQuery: _searchController.text,
|
searchQuery: _searchController.text,
|
||||||
);
|
);
|
||||||
case 4:
|
case 5:
|
||||||
return AdminManagementWidget(
|
return AdminManagementWidget(
|
||||||
key: ValueKey('admins-$_adminRefreshTick'),
|
key: ValueKey('admins-$_adminRefreshTick'),
|
||||||
searchQuery: _searchController.text,
|
searchQuery: _searchController.text,
|
||||||
@@ -299,7 +283,6 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final labels = _tabLabels;
|
final labels = _tabLabels;
|
||||||
final isAValiderTab = _hasPending && !_pendingLoading && _subIndex == 0;
|
|
||||||
return Column(
|
return Column(
|
||||||
children: [
|
children: [
|
||||||
DashboardUserManagementSubBar(
|
DashboardUserManagementSubBar(
|
||||||
@@ -307,8 +290,10 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
onSubTabChange: _onSubTabChange,
|
onSubTabChange: _onSubTabChange,
|
||||||
searchController: _searchController,
|
searchController: _searchController,
|
||||||
searchHint: _searchHintForTab(),
|
searchHint: _searchHintForTab(),
|
||||||
|
searchTooltip: _searchTooltipForTab(),
|
||||||
filterControl: _subBarFilterControl(),
|
filterControl: _subBarFilterControl(),
|
||||||
onAddPressed: isAValiderTab ? null : _handleAddPressed,
|
// Pas de « Créer » sur l’onglet Dossiers (#153).
|
||||||
|
onAddPressed: _isDossiersTab ? null : _handleAddPressed,
|
||||||
addLabel: 'Ajouter',
|
addLabel: 'Ajouter',
|
||||||
subTabCount: labels.length,
|
subTabCount: labels.length,
|
||||||
tabLabels: labels,
|
tabLabels: labels,
|
||||||
@@ -319,9 +304,8 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _handleAddPressed() async {
|
Future<void> _handleAddPressed() async {
|
||||||
final contentIndex = _subIndex - _contentIndexOffset;
|
// 1 Parents, 2 Enfants, 3 AM, 4 Gestionnaires, 5 Admin
|
||||||
|
if (_subIndex == 1) {
|
||||||
if (contentIndex == 0) {
|
|
||||||
await showDialog<void>(
|
await showDialog<void>(
|
||||||
context: context,
|
context: context,
|
||||||
barrierDismissible: false,
|
barrierDismissible: false,
|
||||||
@@ -331,7 +315,10 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
onSuccess: () {
|
onSuccess: () {
|
||||||
Navigator.of(dialogContext).pop();
|
Navigator.of(dialogContext).pop();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _parentRefreshTick++);
|
setState(() {
|
||||||
|
_parentRefreshTick++;
|
||||||
|
_dossiersRefreshTick++;
|
||||||
|
});
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -339,7 +326,7 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (contentIndex == 1) {
|
if (_subIndex == 2) {
|
||||||
await showDialog<void>(
|
await showDialog<void>(
|
||||||
context: context,
|
context: context,
|
||||||
barrierDismissible: false,
|
barrierDismissible: false,
|
||||||
@@ -355,7 +342,7 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (contentIndex == 2) {
|
if (_subIndex == 3) {
|
||||||
await showDialog<void>(
|
await showDialog<void>(
|
||||||
context: context,
|
context: context,
|
||||||
barrierDismissible: false,
|
barrierDismissible: false,
|
||||||
@@ -365,7 +352,10 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
onSuccess: () {
|
onSuccess: () {
|
||||||
Navigator.of(dialogContext).pop();
|
Navigator.of(dialogContext).pop();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _amRefreshTick++);
|
setState(() {
|
||||||
|
_amRefreshTick++;
|
||||||
|
_dossiersRefreshTick++;
|
||||||
|
});
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -373,7 +363,7 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (contentIndex == 3) {
|
if (_subIndex == 4) {
|
||||||
final created = await showDialog<bool>(
|
final created = await showDialog<bool>(
|
||||||
context: context,
|
context: context,
|
||||||
barrierDismissible: false,
|
barrierDismissible: false,
|
||||||
@@ -391,7 +381,7 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (contentIndex == 4) {
|
if (_subIndex == 5) {
|
||||||
final created = await showDialog<bool>(
|
final created = await showDialog<bool>(
|
||||||
context: context,
|
context: context,
|
||||||
barrierDismissible: false,
|
barrierDismissible: false,
|
||||||
@@ -409,16 +399,6 @@ class _UserManagementPanelState extends State<UserManagementPanel> {
|
|||||||
_adminRefreshTick++;
|
_adminRefreshTick++;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!mounted) return;
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
const SnackBar(
|
|
||||||
content: Text(
|
|
||||||
'La création parent sera disponible avec le ticket #129.',
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,20 +2,25 @@ 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/services/user_service.dart';
|
import 'package:p_tits_pas/services/user_service.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/am_dossier_wizard.dart';
|
import 'package:p_tits_pas/widgets/admin/am_dossier_wizard.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/admin/parent_dossier_wizard.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/validation_am_wizard.dart';
|
import 'package:p_tits_pas/widgets/admin/validation_am_wizard.dart';
|
||||||
import 'package:p_tits_pas/widgets/admin/validation_family_wizard.dart';
|
import 'package:p_tits_pas/widgets/admin/validation_family_wizard.dart';
|
||||||
|
|
||||||
/// Modale (dialog) : charge le dossier par numéro puis affiche le wizard AM ou Famille. Ticket #107, #119.
|
/// Modale (dialog) : charge le dossier par numéro puis affiche le wizard AM ou Famille.
|
||||||
|
/// Ticket #107 / #119 (review), #135 (`openAsEdit`).
|
||||||
class ValidationDossierModal extends StatefulWidget {
|
class ValidationDossierModal extends StatefulWidget {
|
||||||
final String numeroDossier;
|
final String numeroDossier;
|
||||||
final VoidCallback onClose;
|
final VoidCallback onClose;
|
||||||
final VoidCallback? onSuccess;
|
final VoidCallback? onSuccess;
|
||||||
|
/// Liste Dossiers actifs → mode edit (#135). Pending reste en review (défaut).
|
||||||
|
final bool openAsEdit;
|
||||||
|
|
||||||
const ValidationDossierModal({
|
const ValidationDossierModal({
|
||||||
super.key,
|
super.key,
|
||||||
required this.numeroDossier,
|
required this.numeroDossier,
|
||||||
required this.onClose,
|
required this.onClose,
|
||||||
this.onSuccess,
|
this.onSuccess,
|
||||||
|
this.openAsEdit = false,
|
||||||
});
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -77,12 +82,12 @@ class _ValidationDossierModalState extends State<ValidationDossierModal> {
|
|||||||
|
|
||||||
/// Largeur modale = 1,5 × 620.
|
/// Largeur modale = 1,5 × 620.
|
||||||
static const double _modalWidth = 930; // 620 * 1.5
|
static const double _modalWidth = 930; // 620 * 1.5
|
||||||
static const double _familyBodyHeight = 435;
|
|
||||||
|
|
||||||
double get _bodyHeight {
|
double get _bodyHeight {
|
||||||
final d = _dossier;
|
final d = _dossier;
|
||||||
if (d != null && d.isAm) return AmDossierWizard.shellBodyHeight;
|
if (d != null && d.isAm) return AmDossierWizard.shellBodyHeight;
|
||||||
return _familyBodyHeight;
|
// Aligné create (#129) / edit (#135) — évite overflow IdentityBlock (8px).
|
||||||
|
return ParentDossierWizard.shellBodyHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -162,6 +167,14 @@ class _ValidationDossierModalState extends State<ValidationDossierModal> {
|
|||||||
}
|
}
|
||||||
final d = _dossier!;
|
final d = _dossier!;
|
||||||
if (d.isAm) {
|
if (d.isAm) {
|
||||||
|
if (widget.openAsEdit) {
|
||||||
|
return AmDossierWizard.edit(
|
||||||
|
dossier: d.asAm,
|
||||||
|
onClose: widget.onClose,
|
||||||
|
onSuccess: _onSuccess,
|
||||||
|
onStepChanged: _onStepChanged,
|
||||||
|
);
|
||||||
|
}
|
||||||
return ValidationAmWizard(
|
return ValidationAmWizard(
|
||||||
dossier: d.asAm,
|
dossier: d.asAm,
|
||||||
onClose: widget.onClose,
|
onClose: widget.onClose,
|
||||||
@@ -169,6 +182,14 @@ class _ValidationDossierModalState extends State<ValidationDossierModal> {
|
|||||||
onStepChanged: _onStepChanged,
|
onStepChanged: _onStepChanged,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if (widget.openAsEdit) {
|
||||||
|
return ParentDossierWizard.edit(
|
||||||
|
dossier: d.asFamily,
|
||||||
|
onClose: widget.onClose,
|
||||||
|
onSuccess: _onSuccess,
|
||||||
|
onStepChanged: _onStepChanged,
|
||||||
|
);
|
||||||
|
}
|
||||||
return ValidationFamilyWizard(
|
return ValidationFamilyWizard(
|
||||||
dossier: d.asFamily,
|
dossier: d.asFamily,
|
||||||
onClose: widget.onClose,
|
onClose: widget.onClose,
|
||||||
|
|||||||
Reference in New Issue
Block a user