Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38af471054 | ||
|
|
7f554e2ba3 | ||
|
|
d05a5e22b2 | ||
|
|
e6be1dffc4 | ||
|
|
cec1fc2ba7 | ||
|
|
1c0ff71f26 | ||
|
|
a5d1616a17 | ||
|
|
1e4e2d5198 | ||
|
|
8af579be53 | ||
|
|
a36e9ef176 | ||
|
|
5d36b0f4c1 | ||
|
|
ad48ab28cc | ||
|
|
342686f4e0 | ||
|
|
d42927297d | ||
|
|
1d3ec0b759 | ||
|
|
608e62d662 | ||
|
|
dc491470db | ||
|
|
5a73da898b | ||
|
|
0c736f5605 | ||
|
|
6c8ef32a11 | ||
|
|
f3b2da4b4d | ||
|
|
edab253296 | ||
|
|
d61e34a1e6 | ||
|
|
484fb9a3e5 |
@@ -5,6 +5,7 @@ import {
|
|||||||
JoinColumn,
|
JoinColumn,
|
||||||
ManyToOne,
|
ManyToOne,
|
||||||
PrimaryGeneratedColumn,
|
PrimaryGeneratedColumn,
|
||||||
|
RelationId,
|
||||||
} from 'typeorm';
|
} from 'typeorm';
|
||||||
import { CardInstance } from './card_instances.entity';
|
import { CardInstance } from './card_instances.entity';
|
||||||
import { Users } from './users.entity';
|
import { Users } from './users.entity';
|
||||||
@@ -20,20 +21,21 @@ export class CardResponse {
|
|||||||
@PrimaryGeneratedColumn('uuid')
|
@PrimaryGeneratedColumn('uuid')
|
||||||
id: string;
|
id: string;
|
||||||
|
|
||||||
@Column({ name: 'id_card', type: 'uuid' })
|
/** FK carte — une seule source de vérité via @JoinColumn (pas de @Column doublon). */
|
||||||
id_card: string;
|
|
||||||
|
|
||||||
@ManyToOne(() => CardInstance, (c) => c.responses, { onDelete: 'CASCADE' })
|
@ManyToOne(() => CardInstance, (c) => c.responses, { onDelete: 'CASCADE' })
|
||||||
@JoinColumn({ name: 'id_card', referencedColumnName: 'id' })
|
@JoinColumn({ name: 'id_card', referencedColumnName: 'id' })
|
||||||
card: CardInstance;
|
card: CardInstance;
|
||||||
|
|
||||||
@Column({ name: 'id_utilisateur', type: 'uuid' })
|
@RelationId((r: CardResponse) => r.card)
|
||||||
id_utilisateur: string;
|
id_card: string;
|
||||||
|
|
||||||
@ManyToOne(() => Users, { onDelete: 'CASCADE' })
|
@ManyToOne(() => Users, { onDelete: 'CASCADE' })
|
||||||
@JoinColumn({ name: 'id_utilisateur', referencedColumnName: 'id' })
|
@JoinColumn({ name: 'id_utilisateur', referencedColumnName: 'id' })
|
||||||
user: Users;
|
user: Users;
|
||||||
|
|
||||||
|
@RelationId((r: CardResponse) => r.user)
|
||||||
|
id_utilisateur: string;
|
||||||
|
|
||||||
@Column({
|
@Column({
|
||||||
type: 'enum',
|
type: 'enum',
|
||||||
enum: CardResponseActionType,
|
enum: CardResponseActionType,
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ export enum TypeEvenementAgendaType {
|
|||||||
ABSENCE_ENFANT = 'absence_enfant',
|
ABSENCE_ENFANT = 'absence_enfant',
|
||||||
CONGE_AM = 'conge_am',
|
CONGE_AM = 'conge_am',
|
||||||
ARRET_MALADIE_AM = 'arret_maladie_am',
|
ARRET_MALADIE_AM = 'arret_maladie_am',
|
||||||
|
SOIN_ENFANT = 'soin_enfant',
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum StatutEvenementAgendaType {
|
export enum StatutEvenementAgendaType {
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ describe('CardsService (#194)', () => {
|
|||||||
const cardsRepo = {
|
const cardsRepo = {
|
||||||
create: jest.fn((x) => x),
|
create: jest.fn((x) => x),
|
||||||
save: jest.fn(async (x) => ({ ...x, id: x.id ?? 'card-1', cree_le: new Date(), modifie_le: new Date() })),
|
save: jest.fn(async (x) => ({ ...x, id: x.id ?? 'card-1', cree_le: new Date(), modifie_le: new Date() })),
|
||||||
|
update: jest.fn(async () => ({ affected: 1 })),
|
||||||
findOne: jest.fn(),
|
findOne: jest.fn(),
|
||||||
delete: jest.fn(),
|
delete: jest.fn(),
|
||||||
createQueryBuilder: jest.fn(),
|
createQueryBuilder: jest.fn(),
|
||||||
@@ -37,7 +38,8 @@ describe('CardsService (#194)', () => {
|
|||||||
};
|
};
|
||||||
const responsesRepo = {
|
const responsesRepo = {
|
||||||
create: jest.fn((x) => x),
|
create: jest.fn((x) => x),
|
||||||
save: jest.fn(),
|
save: jest.fn(async (x) => x),
|
||||||
|
insert: jest.fn(),
|
||||||
};
|
};
|
||||||
const amChildrenRepo = { findOne: jest.fn() };
|
const amChildrenRepo = { findOne: jest.fn() };
|
||||||
const parentsChildrenRepo = { find: jest.fn(), findOne: jest.fn() };
|
const parentsChildrenRepo = { find: jest.fn(), findOne: jest.fn() };
|
||||||
@@ -110,7 +112,6 @@ describe('CardsService (#194)', () => {
|
|||||||
modifie_le: new Date(),
|
modifie_le: new Date(),
|
||||||
type: {
|
type: {
|
||||||
titre: 'Congé AM',
|
titre: 'Congé AM',
|
||||||
couleur: 'lavender',
|
|
||||||
response_mode: CardResponseModeType.ACCEPT_REFUSE,
|
response_mode: CardResponseModeType.ACCEPT_REFUSE,
|
||||||
retention_days: 14,
|
retention_days: 14,
|
||||||
},
|
},
|
||||||
@@ -156,4 +157,220 @@ describe('CardsService (#194)', () => {
|
|||||||
}),
|
}),
|
||||||
).rejects.toBeInstanceOf(ForbiddenException);
|
).rejects.toBeInstanceOf(ForbiddenException);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('parent crée absence_enfant → audience AM + co-parent', async () => {
|
||||||
|
typesRepo.findOne.mockResolvedValue({
|
||||||
|
code: 'absence_enfant',
|
||||||
|
system: true,
|
||||||
|
titre: 'Absence enfant',
|
||||||
|
emitter_roles: [RoleType.PARENT],
|
||||||
|
recipient_roles: [RoleType.ASSISTANTE_MATERNELLE],
|
||||||
|
audience_resolver: 'couple_am',
|
||||||
|
response_mode: CardResponseModeType.NONE,
|
||||||
|
retention_days: 7,
|
||||||
|
});
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
parentsChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
parentId: 'p-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
});
|
||||||
|
parentsChildrenRepo.find.mockResolvedValue([
|
||||||
|
{ parentId: 'p-1', enfantId: 'e-1' },
|
||||||
|
{ parentId: 'p-2', enfantId: 'e-1' },
|
||||||
|
]);
|
||||||
|
evenementsService.creer.mockResolvedValue({
|
||||||
|
id: 'abs-1',
|
||||||
|
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
|
||||||
|
statut: StatutEvenementAgendaType.ACCEPTE,
|
||||||
|
});
|
||||||
|
cardsRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'card-abs',
|
||||||
|
type_code: 'absence_enfant',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
id_evenement: 'abs-1',
|
||||||
|
cree_par: 'p-1',
|
||||||
|
operation: CardOperationType.CREATE,
|
||||||
|
statut: CardInstanceStatutType.OUVERTE,
|
||||||
|
payload: { date_debut: '2026-10-28', date_fin: '2026-10-29' },
|
||||||
|
purge_at: new Date(),
|
||||||
|
cree_le: new Date(),
|
||||||
|
modifie_le: new Date(),
|
||||||
|
type: {
|
||||||
|
titre: 'Absence enfant',
|
||||||
|
response_mode: CardResponseModeType.NONE,
|
||||||
|
retention_days: 7,
|
||||||
|
},
|
||||||
|
responses: [],
|
||||||
|
audience: [
|
||||||
|
{ id_utilisateur: 'p-1' },
|
||||||
|
{ id_utilisateur: 'am-1' },
|
||||||
|
{ id_utilisateur: 'p-2' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
await service.creer('p-1', RoleType.PARENT, {
|
||||||
|
type_code: 'absence_enfant',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
date_debut: '2026-10-28',
|
||||||
|
date_fin: '2026-10-29',
|
||||||
|
});
|
||||||
|
|
||||||
|
const saved = audienceRepo.save.mock.calls[0][0] as Array<{
|
||||||
|
id_utilisateur: string;
|
||||||
|
is_creator: boolean;
|
||||||
|
}>;
|
||||||
|
const ids = saved.map((m) => m.id_utilisateur).sort();
|
||||||
|
expect(ids).toEqual(['am-1', 'p-1', 'p-2']);
|
||||||
|
expect(saved.find((m) => m.id_utilisateur === 'p-2')?.is_creator).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parent accepte conge_am → response via relation + carte traitee', async () => {
|
||||||
|
cardsRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'card-1',
|
||||||
|
type_code: 'conge_am',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
id_evenement: 'ev-1',
|
||||||
|
cree_par: 'am-1',
|
||||||
|
operation: CardOperationType.CREATE,
|
||||||
|
statut: CardInstanceStatutType.OUVERTE,
|
||||||
|
payload: { date_debut: '2026-10-27', date_fin: '2026-10-31' },
|
||||||
|
purge_at: new Date(),
|
||||||
|
cree_le: new Date(),
|
||||||
|
modifie_le: new Date(),
|
||||||
|
type: {
|
||||||
|
titre: 'Congé AM',
|
||||||
|
response_mode: CardResponseModeType.ACCEPT_REFUSE,
|
||||||
|
retention_days: 14,
|
||||||
|
},
|
||||||
|
responses: [],
|
||||||
|
audience: [
|
||||||
|
{ id_utilisateur: 'am-1' },
|
||||||
|
{ id_utilisateur: 'p-1' },
|
||||||
|
{ id_utilisateur: 'p-2' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
audienceRepo.findOne.mockResolvedValue({ id_card: 'card-1', id_utilisateur: 'p-1' });
|
||||||
|
evenementsService.maj.mockResolvedValue({});
|
||||||
|
|
||||||
|
const res = await service.repondre('p-1', RoleType.PARENT, 'card-1', {
|
||||||
|
action: 'accept' as never,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(responsesRepo.create).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
card: { id: 'card-1' },
|
||||||
|
user: { id: 'p-1' },
|
||||||
|
action: 'accept',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(responsesRepo.save).toHaveBeenCalled();
|
||||||
|
expect(evenementsService.maj).toHaveBeenCalledWith(
|
||||||
|
'p-1',
|
||||||
|
RoleType.PARENT,
|
||||||
|
'ev-1',
|
||||||
|
expect.objectContaining({ statut: StatutEvenementAgendaType.ACCEPTE }),
|
||||||
|
);
|
||||||
|
expect(cardsRepo.update).toHaveBeenCalledWith(
|
||||||
|
{ id: 'card-1' },
|
||||||
|
expect.objectContaining({ statut: CardInstanceStatutType.TRAITEE }),
|
||||||
|
);
|
||||||
|
expect(res.statut).toBe(CardInstanceStatutType.TRAITEE);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('AM crée soin_enfant (fievre) → motif dérivé + payload structuré', async () => {
|
||||||
|
typesRepo.findOne.mockResolvedValue({
|
||||||
|
code: 'soin_enfant',
|
||||||
|
system: true,
|
||||||
|
emitter_roles: [RoleType.ASSISTANTE_MATERNELLE],
|
||||||
|
response_mode: CardResponseModeType.ACK,
|
||||||
|
retention_days: 7,
|
||||||
|
audience_resolver: 'couple_parents',
|
||||||
|
});
|
||||||
|
evenementsService.creer.mockResolvedValue({ id: 'ev-soin' });
|
||||||
|
cardsRepo.create.mockImplementation((c) => ({ ...c, id: 'card-soin' }));
|
||||||
|
cardsRepo.save.mockResolvedValue({ id: 'card-soin' });
|
||||||
|
cardsRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'card-soin',
|
||||||
|
type_code: 'soin_enfant',
|
||||||
|
statut: CardInstanceStatutType.OUVERTE,
|
||||||
|
payload: {
|
||||||
|
date_debut: '2026-10-28',
|
||||||
|
date_fin: '2026-10-28',
|
||||||
|
motif: '38,5 °C à 14:30 (Médicament : Doliprane)',
|
||||||
|
sous_type: 'fievre',
|
||||||
|
heure_releve: '14:30',
|
||||||
|
temperature_c: 38.5,
|
||||||
|
medicament_donne: 'Doliprane',
|
||||||
|
},
|
||||||
|
type: { response_mode: CardResponseModeType.ACK },
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await service.creer('am-1', RoleType.ASSISTANTE_MATERNELLE, {
|
||||||
|
type_code: 'soin_enfant',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
date_debut: '2026-10-28',
|
||||||
|
date_fin: '2026-10-28',
|
||||||
|
payload: {
|
||||||
|
sous_type: 'fievre',
|
||||||
|
heure_releve: '14:30',
|
||||||
|
temperature_c: 38.5,
|
||||||
|
medicament_donne: 'Doliprane',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(evenementsService.creer).toHaveBeenCalledWith(
|
||||||
|
'am-1',
|
||||||
|
RoleType.ASSISTANTE_MATERNELLE,
|
||||||
|
expect.objectContaining({
|
||||||
|
type: TypeEvenementAgendaType.SOIN_ENFANT,
|
||||||
|
motif: '38,5 °C à 14:30 (Médicament : Doliprane)',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(res.payload.motif).toBe('38,5 °C à 14:30 (Médicament : Doliprane)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('AM corrige soin_enfant dans les 24h → historique + re-ack', async () => {
|
||||||
|
const creeLe = new Date();
|
||||||
|
cardsRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'card-soin',
|
||||||
|
type_code: 'soin_enfant',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
id_evenement: 'ev-soin',
|
||||||
|
cree_par: 'am-1',
|
||||||
|
cree_le: creeLe,
|
||||||
|
statut: CardInstanceStatutType.TRAITEE, // déjà acquitté
|
||||||
|
payload: {
|
||||||
|
date_debut: '2026-10-28',
|
||||||
|
date_fin: '2026-10-28',
|
||||||
|
sous_type: 'fievre',
|
||||||
|
heure_releve: '14:30',
|
||||||
|
temperature_c: 38.5,
|
||||||
|
},
|
||||||
|
type: { retention_days: 7 },
|
||||||
|
});
|
||||||
|
evenementsService.maj.mockResolvedValue({});
|
||||||
|
|
||||||
|
await service.majEnAttente('am-1', RoleType.ASSISTANTE_MATERNELLE, 'card-soin', {
|
||||||
|
date_debut: '2026-10-28',
|
||||||
|
date_fin: '2026-10-28',
|
||||||
|
payload: {
|
||||||
|
sous_type: 'fievre',
|
||||||
|
heure_releve: '14:30',
|
||||||
|
temperature_c: 37.5, // correction
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(cardsRepo.manager.query).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('UPDATE card_instances'),
|
||||||
|
expect.arrayContaining([
|
||||||
|
CardInstanceStatutType.OUVERTE, // repasse ouverte
|
||||||
|
expect.stringContaining('37,5'), // nouveau payload stringifié
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -136,23 +136,76 @@ export class CardsService {
|
|||||||
let absenceId = dto.id_evenement;
|
let absenceId = dto.id_evenement;
|
||||||
const absenceType = this.mapAbsenceType(dto.type_code);
|
const absenceType = this.mapAbsenceType(dto.type_code);
|
||||||
|
|
||||||
|
let motif = dto.motif ?? null;
|
||||||
|
let finalPayload: Record<string, any> = {
|
||||||
|
date_debut: dto.date_debut,
|
||||||
|
date_fin: dto.date_fin,
|
||||||
|
motif,
|
||||||
|
...(dto.payload ?? {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (dto.type_code === 'soin_enfant') {
|
||||||
|
const p = dto.payload as Record<string, any>;
|
||||||
|
if (!p || !p?.sous_type || !p?.heure_releve) {
|
||||||
|
throw new BadRequestException('sous_type et heure_releve requis pour soin_enfant');
|
||||||
|
}
|
||||||
|
if (!/^([01]\d|2[0-3]):([0-5]\d)$/.test(p?.heure_releve)) {
|
||||||
|
throw new BadRequestException('Format heure_releve invalide (HH:mm)');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (p?.sous_type === 'fievre') {
|
||||||
|
if (typeof p?.temperature_c !== 'number' || p?.temperature_c < 34.0 || p?.temperature_c > 43.0) {
|
||||||
|
throw new BadRequestException('temperature_c invalide (34.0 - 43.0)');
|
||||||
|
}
|
||||||
|
motif = `${p?.temperature_c.toFixed(1).replace('.', ',')} °C à ${p?.heure_releve}`;
|
||||||
|
if (p?.medicament_donne && typeof p?.medicament_donne === 'string' && p?.medicament_donne.trim()) {
|
||||||
|
motif += ` (Médicament : ${p?.medicament_donne.trim()})`;
|
||||||
|
}
|
||||||
|
} else if (p?.sous_type === 'bobo') {
|
||||||
|
const natures = ['chute', 'coup', 'egratignure', 'piqure', 'brulure', 'autre'];
|
||||||
|
if (!natures.includes(p?.bobo_nature)) {
|
||||||
|
throw new BadRequestException('bobo_nature invalide');
|
||||||
|
}
|
||||||
|
motif = `Bobo (${p?.bobo_nature}) à ${p?.heure_releve}`;
|
||||||
|
if (p?.description && typeof p?.description === 'string' && p?.description.trim()) {
|
||||||
|
const desc = p?.description.trim();
|
||||||
|
if (desc.length > 120) throw new BadRequestException('description trop longue (max 120)');
|
||||||
|
motif += ` : ${desc.length > 30 ? desc.substring(0, 30) + '...' : desc}`;
|
||||||
|
}
|
||||||
|
} else if (p?.sous_type === 'medicament') {
|
||||||
|
if (!p?.medicament_nom || typeof p?.medicament_nom !== 'string' || !p?.medicament_nom.trim()) {
|
||||||
|
throw new BadRequestException('medicament_nom requis');
|
||||||
|
}
|
||||||
|
motif = `Médicament (${p?.medicament_nom.trim()}) à ${p?.heure_releve}`;
|
||||||
|
if (p?.contexte && typeof p?.contexte === 'string' && p?.contexte.trim()) {
|
||||||
|
if (p?.contexte.trim().length > 120) throw new BadRequestException('contexte trop long (max 120)');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new BadRequestException('sous_type invalide pour soin_enfant');
|
||||||
|
}
|
||||||
|
finalPayload.motif = motif;
|
||||||
|
}
|
||||||
|
|
||||||
if (operation === CardOperationType.CREATE) {
|
if (operation === CardOperationType.CREATE) {
|
||||||
const absence = await this.evenementsService.creer(userId, role, {
|
const absence = await this.evenementsService.creer(userId, role, {
|
||||||
id_placement: dto.id_placement,
|
id_placement: dto.id_placement,
|
||||||
type: absenceType,
|
type: absenceType,
|
||||||
date_debut: dto.date_debut,
|
date_debut: dto.date_debut,
|
||||||
date_fin: dto.date_fin,
|
date_fin: dto.date_fin,
|
||||||
motif: dto.motif,
|
motif: motif ? String(motif) : undefined,
|
||||||
});
|
});
|
||||||
absenceId = absence.id;
|
absenceId = absence.id;
|
||||||
} else {
|
} else {
|
||||||
|
if (dto.type_code === 'soin_enfant') {
|
||||||
|
throw new BadRequestException('operation=update interdite pour soin_enfant');
|
||||||
|
}
|
||||||
if (!absenceId) {
|
if (!absenceId) {
|
||||||
throw new BadRequestException('id_evenement requis pour operation=update');
|
throw new BadRequestException('id_evenement requis pour operation=update');
|
||||||
}
|
}
|
||||||
await this.evenementsService.maj(userId, role, absenceId, {
|
await this.evenementsService.maj(userId, role, absenceId, {
|
||||||
date_debut: dto.date_debut,
|
date_debut: dto.date_debut,
|
||||||
date_fin: dto.date_fin,
|
date_fin: dto.date_fin,
|
||||||
motif: dto.motif,
|
motif: motif ? String(motif) : undefined,
|
||||||
// Congé accepté modifié → repasse en attente via cartes respond flow;
|
// Congé accepté modifié → repasse en attente via cartes respond flow;
|
||||||
// pour absence enfant update immédiat déjà fait.
|
// pour absence enfant update immédiat déjà fait.
|
||||||
...(dto.type_code === 'conge_am'
|
...(dto.type_code === 'conge_am'
|
||||||
@@ -173,11 +226,7 @@ export class CardsService {
|
|||||||
cree_par: userId,
|
cree_par: userId,
|
||||||
operation,
|
operation,
|
||||||
statut: statutInitial,
|
statut: statutInitial,
|
||||||
payload: {
|
payload: finalPayload,
|
||||||
date_debut: dto.date_debut,
|
|
||||||
date_fin: dto.date_fin,
|
|
||||||
motif: dto.motif ?? null,
|
|
||||||
},
|
|
||||||
purge_at: this.purgeAt(type.retention_days, statutInitial),
|
purge_at: this.purgeAt(type.retention_days, statutInitial),
|
||||||
});
|
});
|
||||||
const saved = await this.cardsRepo.save(card);
|
const saved = await this.cardsRepo.save(card);
|
||||||
@@ -227,12 +276,14 @@ export class CardsService {
|
|||||||
throw new BadRequestException('Motivation obligatoire en cas de refus');
|
throw new BadRequestException('Motivation obligatoire en cas de refus');
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.responsesRepo.insert({
|
await this.responsesRepo.save(
|
||||||
id_card: card.id,
|
this.responsesRepo.create({
|
||||||
id_utilisateur: userId,
|
card: { id: card.id },
|
||||||
action: dto.action,
|
user: { id: userId },
|
||||||
comment: dto.comment?.trim() || undefined,
|
action: dto.action,
|
||||||
});
|
comment: dto.comment?.trim() || undefined,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
if (card.id_evenement) {
|
if (card.id_evenement) {
|
||||||
if (dto.action === CardResponseActionType.ACCEPT || dto.action === CardResponseActionType.ACK) {
|
if (dto.action === CardResponseActionType.ACCEPT || dto.action === CardResponseActionType.ACK) {
|
||||||
@@ -252,7 +303,12 @@ export class CardsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
card.purge_at = this.purgeAt(card.type.retention_days, card.statut);
|
card.purge_at = this.purgeAt(card.type.retention_days, card.statut);
|
||||||
await this.cardsRepo.save(card);
|
// Ne pas cardsRepo.save(card) avec relations chargées : TypeORM peut
|
||||||
|
// resynchroniser les FK enfants (UPDATE … SET id_card=null).
|
||||||
|
await this.cardsRepo.update(
|
||||||
|
{ id: card.id },
|
||||||
|
{ statut: card.statut, purge_at: card.purge_at },
|
||||||
|
);
|
||||||
const full = await this.loadCard(cardId);
|
const full = await this.loadCard(cardId);
|
||||||
const dtoOut = this.toDto(full, userId);
|
const dtoOut = this.toDto(full, userId);
|
||||||
this.emitAudience(full, 'response.added', {
|
this.emitAudience(full, 'response.added', {
|
||||||
@@ -273,11 +329,19 @@ export class CardsService {
|
|||||||
if (card.cree_par !== userId) {
|
if (card.cree_par !== userId) {
|
||||||
throw new ForbiddenException('Seul le créateur peut modifier cette carte');
|
throw new ForbiddenException('Seul le créateur peut modifier cette carte');
|
||||||
}
|
}
|
||||||
if (
|
|
||||||
card.statut !== CardInstanceStatutType.OUVERTE &&
|
if (card.type_code === 'soin_enfant') {
|
||||||
card.statut !== CardInstanceStatutType.REFUSEE
|
const msSinceCreation = Date.now() - new Date(card.cree_le).getTime();
|
||||||
) {
|
if (msSinceCreation > 24 * 60 * 60 * 1000) {
|
||||||
throw new BadRequestException('Carte non modifiable dans cet état');
|
throw new BadRequestException('Délai de correction de 24h dépassé');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (
|
||||||
|
card.statut !== CardInstanceStatutType.OUVERTE &&
|
||||||
|
card.statut !== CardInstanceStatutType.REFUSEE
|
||||||
|
) {
|
||||||
|
throw new BadRequestException('Carte non modifiable dans cet état');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const debut =
|
const debut =
|
||||||
@@ -287,24 +351,87 @@ export class CardsService {
|
|||||||
throw new BadRequestException('Dates invalides');
|
throw new BadRequestException('Dates invalides');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let motif = dto.motif ?? card.payload?.['motif'] ?? null;
|
||||||
|
let finalPayload: Record<string, any> = {
|
||||||
|
...card.payload,
|
||||||
|
date_debut: debut,
|
||||||
|
date_fin: fin,
|
||||||
|
...(dto.payload ?? {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (card.type_code === 'soin_enfant') {
|
||||||
|
const p = finalPayload;
|
||||||
|
if (!p || !p?.sous_type || !p?.heure_releve) {
|
||||||
|
throw new BadRequestException('sous_type et heure_releve requis pour soin_enfant');
|
||||||
|
}
|
||||||
|
if (!/^([01]\d|2[0-3]):([0-5]\d)$/.test(p?.heure_releve)) {
|
||||||
|
throw new BadRequestException('Format heure_releve invalide (HH:mm)');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (p?.sous_type === 'fievre') {
|
||||||
|
if (typeof p?.temperature_c !== 'number' || p?.temperature_c < 34.0 || p?.temperature_c > 43.0) {
|
||||||
|
throw new BadRequestException('temperature_c invalide (34.0 - 43.0)');
|
||||||
|
}
|
||||||
|
motif = `${p?.temperature_c.toFixed(1).replace('.', ',')} °C à ${p?.heure_releve}`;
|
||||||
|
if (p?.medicament_donne && typeof p?.medicament_donne === 'string' && p?.medicament_donne.trim()) {
|
||||||
|
motif += ` (Médicament : ${p?.medicament_donne.trim()})`;
|
||||||
|
}
|
||||||
|
} else if (p?.sous_type === 'bobo') {
|
||||||
|
const natures = ['chute', 'coup', 'egratignure', 'piqure', 'brulure', 'autre'];
|
||||||
|
if (!natures.includes(p?.bobo_nature)) {
|
||||||
|
throw new BadRequestException('bobo_nature invalide');
|
||||||
|
}
|
||||||
|
motif = `Bobo (${p?.bobo_nature}) à ${p?.heure_releve}`;
|
||||||
|
if (p?.description && typeof p?.description === 'string' && p?.description.trim()) {
|
||||||
|
const desc = p?.description.trim();
|
||||||
|
if (desc.length > 120) throw new BadRequestException('description trop longue (max 120)');
|
||||||
|
motif += ` : ${desc.length > 30 ? desc.substring(0, 30) + '...' : desc}`;
|
||||||
|
}
|
||||||
|
} else if (p?.sous_type === 'medicament') {
|
||||||
|
if (!p?.medicament_nom || typeof p?.medicament_nom !== 'string' || !p?.medicament_nom.trim()) {
|
||||||
|
throw new BadRequestException('medicament_nom requis');
|
||||||
|
}
|
||||||
|
motif = `Médicament (${p?.medicament_nom.trim()}) à ${p?.heure_releve}`;
|
||||||
|
if (p?.contexte && typeof p?.contexte === 'string' && p?.contexte.trim()) {
|
||||||
|
if (p?.contexte.trim().length > 120) throw new BadRequestException('contexte trop long (max 120)');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new BadRequestException('sous_type invalide pour soin_enfant');
|
||||||
|
}
|
||||||
|
finalPayload.motif = motif;
|
||||||
|
|
||||||
|
const hist = Array.isArray(card.payload?.['historique']) ? card.payload['historique'] : [];
|
||||||
|
const oldPayload = { ...card.payload };
|
||||||
|
delete oldPayload.historique;
|
||||||
|
hist.push({
|
||||||
|
...oldPayload,
|
||||||
|
corrige_le: new Date().toISOString(),
|
||||||
|
corrige_par: userId,
|
||||||
|
});
|
||||||
|
finalPayload.historique = hist;
|
||||||
|
finalPayload.corrige_le = new Date().toISOString();
|
||||||
|
} else {
|
||||||
|
finalPayload.motif = motif;
|
||||||
|
}
|
||||||
|
|
||||||
if (card.id_evenement) {
|
if (card.id_evenement) {
|
||||||
await this.evenementsService.maj(userId, role, card.id_evenement, {
|
await this.evenementsService.maj(userId, role, card.id_evenement, {
|
||||||
date_debut: debut,
|
date_debut: debut,
|
||||||
date_fin: fin,
|
date_fin: fin,
|
||||||
motif: dto.motif,
|
motif: motif ? String(motif) : undefined,
|
||||||
statut: StatutEvenementAgendaType.EN_ATTENTE,
|
...(card.type_code !== 'soin_enfant' ? { statut: StatutEvenementAgendaType.EN_ATTENTE } : {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
card.payload = {
|
card.payload = finalPayload;
|
||||||
...card.payload,
|
|
||||||
date_debut: debut,
|
|
||||||
date_fin: fin,
|
|
||||||
motif: dto.motif ?? card.payload?.['motif'] ?? null,
|
|
||||||
};
|
|
||||||
card.statut = CardInstanceStatutType.OUVERTE;
|
card.statut = CardInstanceStatutType.OUVERTE;
|
||||||
card.purge_at = this.purgeAt(card.type.retention_days, card.statut);
|
card.purge_at = this.purgeAt(card.type.retention_days, card.statut);
|
||||||
await this.cardsRepo.save(card);
|
await this.cardsRepo.manager.query(
|
||||||
|
`UPDATE card_instances
|
||||||
|
SET statut = $1, purge_at = $2, payload = $3::jsonb, modifie_le = now()
|
||||||
|
WHERE id = $4`,
|
||||||
|
[card.statut, card.purge_at, JSON.stringify(card.payload), card.id],
|
||||||
|
);
|
||||||
const full = await this.loadCard(cardId);
|
const full = await this.loadCard(cardId);
|
||||||
const dtoOut = this.toDto(full, userId);
|
const dtoOut = this.toDto(full, userId);
|
||||||
this.emitAudience(full, 'card.updated', dtoOut);
|
this.emitAudience(full, 'card.updated', dtoOut);
|
||||||
@@ -320,16 +447,25 @@ export class CardsService {
|
|||||||
if (card.cree_par !== userId) {
|
if (card.cree_par !== userId) {
|
||||||
throw new ForbiddenException('Seul le créateur peut supprimer cette carte');
|
throw new ForbiddenException('Seul le créateur peut supprimer cette carte');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (card.type_code === 'soin_enfant') {
|
||||||
|
const msSinceCreation = Date.now() - new Date(card.cree_le).getTime();
|
||||||
|
if (msSinceCreation > 24 * 60 * 60 * 1000) {
|
||||||
|
throw new BadRequestException('Délai de correction de 24h dépassé, suppression impossible');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const audienceIds = await this.audienceUserIds(card);
|
const audienceIds = await this.audienceUserIds(card);
|
||||||
if (card.id_evenement) {
|
if (card.id_evenement) {
|
||||||
const absStatut =
|
const absStatut =
|
||||||
card.statut === CardInstanceStatutType.TRAITEE
|
card.statut === CardInstanceStatutType.TRAITEE
|
||||||
? null
|
? null
|
||||||
: card.id_evenement;
|
: card.id_evenement;
|
||||||
// Supprime l’absence liée si pas encore acceptée définitivement
|
// Supprime l’absence liée si pas encore acceptée définitivement (ou si soin_enfant dans les 24h)
|
||||||
if (
|
if (
|
||||||
card.statut === CardInstanceStatutType.OUVERTE ||
|
card.statut === CardInstanceStatutType.OUVERTE ||
|
||||||
card.statut === CardInstanceStatutType.REFUSEE
|
card.statut === CardInstanceStatutType.REFUSEE ||
|
||||||
|
card.type_code === 'soin_enfant'
|
||||||
) {
|
) {
|
||||||
await this.evenementsService.supprimer(userId, role, card.id_evenement);
|
await this.evenementsService.supprimer(userId, role, card.id_evenement);
|
||||||
}
|
}
|
||||||
@@ -367,6 +503,9 @@ export class CardsService {
|
|||||||
if (typeCode === 'arret_maladie_am') {
|
if (typeCode === 'arret_maladie_am') {
|
||||||
return TypeEvenementAgendaType.ARRET_MALADIE_AM;
|
return TypeEvenementAgendaType.ARRET_MALADIE_AM;
|
||||||
}
|
}
|
||||||
|
if (typeCode === 'soin_enfant') {
|
||||||
|
return TypeEvenementAgendaType.SOIN_ENFANT;
|
||||||
|
}
|
||||||
throw new BadRequestException(`Type non mappé à une absence: ${typeCode}`);
|
throw new BadRequestException(`Type non mappé à une absence: ${typeCode}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -395,12 +534,25 @@ export class CardsService {
|
|||||||
];
|
];
|
||||||
|
|
||||||
if (type.audience_resolver === 'couple_am') {
|
if (type.audience_resolver === 'couple_am') {
|
||||||
|
// Destinataire métier = AM + miroir foyer : tous les co-parents de l’enfant
|
||||||
members.push({
|
members.push({
|
||||||
id_card: card.id,
|
id_card: card.id,
|
||||||
id_utilisateur: placement.amId,
|
id_utilisateur: placement.amId,
|
||||||
role_snapshot: RoleType.ASSISTANTE_MATERNELLE,
|
role_snapshot: RoleType.ASSISTANTE_MATERNELLE,
|
||||||
is_creator: false,
|
is_creator: false,
|
||||||
});
|
});
|
||||||
|
const liensAm = await this.parentsChildrenRepo.find({
|
||||||
|
where: { enfantId: placement.enfantId },
|
||||||
|
});
|
||||||
|
for (const l of liensAm) {
|
||||||
|
if (l.parentId === creatorId) continue;
|
||||||
|
members.push({
|
||||||
|
id_card: card.id,
|
||||||
|
id_utilisateur: l.parentId,
|
||||||
|
role_snapshot: RoleType.PARENT,
|
||||||
|
is_creator: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
} else if (type.audience_resolver === 'couple_parents') {
|
} else if (type.audience_resolver === 'couple_parents') {
|
||||||
const liens = await this.parentsChildrenRepo.find({
|
const liens = await this.parentsChildrenRepo.find({
|
||||||
where: { enfantId: placement.enfantId },
|
where: { enfantId: placement.enfantId },
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
IsDateString,
|
IsDateString,
|
||||||
IsEnum,
|
IsEnum,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
|
IsObject,
|
||||||
IsString,
|
IsString,
|
||||||
IsUUID,
|
IsUUID,
|
||||||
MaxLength,
|
MaxLength,
|
||||||
@@ -48,6 +49,11 @@ export class CreerCarteDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsEnum(CardOperationType)
|
@IsEnum(CardOperationType)
|
||||||
operation?: CardOperationType;
|
operation?: CardOperationType;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsObject()
|
||||||
|
payload?: Record<string, any>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class RepondreCarteDto {
|
export class RepondreCarteDto {
|
||||||
@@ -79,6 +85,11 @@ export class MajCarteDto {
|
|||||||
@IsString()
|
@IsString()
|
||||||
@MaxLength(2000)
|
@MaxLength(2000)
|
||||||
motif?: string;
|
motif?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsObject()
|
||||||
|
payload?: Record<string, any>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class CarteDto {
|
export class CarteDto {
|
||||||
|
|||||||
@@ -196,7 +196,7 @@ export class EvenementsAgendaService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private statutInitial(type: TypeEvenementAgendaType): StatutEvenementAgendaType {
|
private statutInitial(type: TypeEvenementAgendaType): StatutEvenementAgendaType {
|
||||||
if (type === TypeEvenementAgendaType.ABSENCE_ENFANT) {
|
if (type === TypeEvenementAgendaType.ABSENCE_ENFANT || type === TypeEvenementAgendaType.SOIN_ENFANT) {
|
||||||
return StatutEvenementAgendaType.ACCEPTE;
|
return StatutEvenementAgendaType.ACCEPTE;
|
||||||
}
|
}
|
||||||
return StatutEvenementAgendaType.EN_ATTENTE;
|
return StatutEvenementAgendaType.EN_ATTENTE;
|
||||||
@@ -233,10 +233,11 @@ export class EvenementsAgendaService {
|
|||||||
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
if (
|
if (
|
||||||
type !== TypeEvenementAgendaType.CONGE_AM &&
|
type !== TypeEvenementAgendaType.CONGE_AM &&
|
||||||
type !== TypeEvenementAgendaType.ARRET_MALADIE_AM
|
type !== TypeEvenementAgendaType.ARRET_MALADIE_AM &&
|
||||||
|
type !== TypeEvenementAgendaType.SOIN_ENFANT
|
||||||
) {
|
) {
|
||||||
throw new ForbiddenException(
|
throw new ForbiddenException(
|
||||||
'Une AM ne peut créer que congé ou arrêt maladie',
|
'Une AM ne peut créer que congé, arrêt maladie ou soin enfant',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ DO $$ BEGIN
|
|||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_evenement_agenda_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_evenement_agenda_type') THEN
|
||||||
CREATE TYPE type_evenement_agenda_type AS ENUM (
|
CREATE TYPE type_evenement_agenda_type AS ENUM (
|
||||||
'absence_enfant', 'conge_am', 'arret_maladie_am'
|
'absence_enfant', 'conge_am', 'arret_maladie_am', 'soin_enfant'
|
||||||
);
|
);
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_evenement_agenda_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_evenement_agenda_type') THEN
|
||||||
|
|||||||
@@ -108,6 +108,11 @@ INSERT INTO card_types (
|
|||||||
'arret_maladie_am', true, 'Arrêt maladie AM',
|
'arret_maladie_am', true, 'Arrêt maladie AM',
|
||||||
ARRAY['assistante_maternelle'], ARRAY['parent'],
|
ARRAY['assistante_maternelle'], ARRAY['parent'],
|
||||||
'couple_parents', 'ack', 14, 'pink'
|
'couple_parents', 'ack', 14, 'pink'
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'soin_enfant', true, 'Soins enfant',
|
||||||
|
ARRAY['assistante_maternelle'], ARRAY['parent'],
|
||||||
|
'couple_parents', 'ack', 7, 'pink'
|
||||||
)
|
)
|
||||||
ON CONFLICT (code) DO UPDATE SET
|
ON CONFLICT (code) DO UPDATE SET
|
||||||
titre = EXCLUDED.titre,
|
titre = EXCLUDED.titre,
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- Migration incrémentale : ajout du type soin_enfant à l'agenda
|
||||||
|
ALTER TYPE type_evenement_agenda_type ADD VALUE IF NOT EXISTS 'soin_enfant';
|
||||||
@@ -587,6 +587,12 @@ POST /repos/jmartin/petitspas/pulls/{index}/merge
|
|||||||
|
|
||||||
**Flux V1** : BDD agenda → API liste/CRUD → module Cartes SYSTEM → front bulles (séparé).
|
**Flux V1** : BDD agenda → API liste/CRUD → module Cartes SYSTEM → front bulles (séparé).
|
||||||
|
|
||||||
|
**V1 cartes (réponses)** :
|
||||||
|
- `absence_enfant` → info (`none`) — pas d’ack AM ; audience **AM + tous les parents du foyer** (co-parent inclus)
|
||||||
|
- `arret_maladie_am` → ack parent (« Bien reçu »)
|
||||||
|
- `conge_am` → accept / refuse (+ motivation refus)
|
||||||
|
- **Modifs d’absence** → via **agenda / calendrier**, pas via bulle `absence_enfant_modif` (reporté au ticket calendrier)
|
||||||
|
|
||||||
**Réf. détail** : `docs/32_MINI-SPEC-BULLES-CARTES.md`
|
**Réf. détail** : `docs/32_MINI-SPEC-BULLES-CARTES.md`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -41,9 +41,11 @@ Endpoint principal : `GET /api/v1/cards` (filtre couple / placement).
|
|||||||
| `payload.date_debut` / `date_fin` | Période (agenda) |
|
| `payload.date_debut` / `date_fin` | Période (agenda) |
|
||||||
| `payload.motif` | Texte libre / détail |
|
| `payload.motif` | Texte libre / détail |
|
||||||
| `last_refuse_comment` | Si `refusee` |
|
| `last_refuse_comment` | Si `refusee` |
|
||||||
| `id_absence` | Lien métier agenda (si applicable) |
|
| `id_evenement` | Lien métier agenda (`evenements_agenda`, si applicable) — ex-`id_absence` (#205) |
|
||||||
| `purge_at` | Péremption de la bulle dans la file |
|
| `purge_at` | Péremption de la bulle dans la file |
|
||||||
|
|
||||||
|
> **Front** : parser `id_evenement` (fallback éventuel `id_absence` uniquement pour anciennes fixtures / caches). Ne plus documenter ni dépendre de `id_absence` comme contrat.
|
||||||
|
|
||||||
**Pas de champ `couleur` dans l’API.**
|
**Pas de champ `couleur` dans l’API.**
|
||||||
La teinte pastel est **100 % front** : table de mapping `type_code` → asset (`card_*_h.png`). Le back ne gère pas la charte graphique.
|
La teinte pastel est **100 % front** : table de mapping `type_code` → asset (`card_*_h.png`). Le back ne gère pas la charte graphique.
|
||||||
|
|
||||||
@@ -61,7 +63,7 @@ La teinte pastel est **100 % front** : table de mapping `type_code` → asset (`
|
|||||||
- Libellés UI :
|
- Libellés UI :
|
||||||
- `conge_am` → « Demande de congés »
|
- `conge_am` → « Demande de congés »
|
||||||
- `arret_maladie_am` → « Arrêt maladie »
|
- `arret_maladie_am` → « Arrêt maladie »
|
||||||
- `absence_enfant` (+ `_modif`) → « Notification d’absence »
|
- `absence_enfant` → « Notification d’absence »
|
||||||
|
|
||||||
### 3.2 Carte **congés** (`conge_am`)
|
### 3.2 Carte **congés** (`conge_am`)
|
||||||
|
|
||||||
@@ -93,10 +95,13 @@ Clé = **choix front**, pas une valeur API.
|
|||||||
|------------|---------|--------|
|
|------------|---------|--------|
|
||||||
| **`aqua`** | Congés AM | `conge_am` |
|
| **`aqua`** | Congés AM | `conge_am` |
|
||||||
| **`blue`** | Arrêt maladie AM | `arret_maladie_am` |
|
| **`blue`** | Arrêt maladie AM | `arret_maladie_am` |
|
||||||
| **`peach`** | Absence enfant / info pratique | `absence_enfant`, `absence_enfant_modif` |
|
| **`peach`** | Absence enfant / info pratique | `absence_enfant` |
|
||||||
| **`pink`** | Soins / bobo / problème **enfant** (AM → parents) | `soin_enfant` *(nouveau — voir §5)* |
|
| **`pink`** | Soins / bobo / problème **enfant** (AM → parents) | `soin_enfant` *(nouveau — voir §5)* |
|
||||||
| **`lavender`** | Admin / divers | futurs types admin |
|
| **`lavender`** | Admin / divers | futurs types admin |
|
||||||
|
|
||||||
|
**Hors scope V1 cartes** : `absence_enfant_modif` (ack AM sur modif).
|
||||||
|
Les **modifications d’absence** se font via l’**agenda / calendrier**, pas via une bulle dédiée. On rebranchera une notif éventuelle quand le calendrier sera implémenté.
|
||||||
|
|
||||||
**Principes**
|
**Principes**
|
||||||
|
|
||||||
- Couleur = famille visuelle (lisible sans tout lire).
|
- Couleur = famille visuelle (lisible sans tout lire).
|
||||||
@@ -138,6 +143,7 @@ Pourquoi **pas seulement la messagerie** ?
|
|||||||
| Famille | Couleur UI | Exemples | `response_mode` |
|
| Famille | Couleur UI | Exemples | `response_mode` |
|
||||||
|---------|------------|----------|-----------------|
|
|---------|------------|----------|-----------------|
|
||||||
| Soins (détail) | `pink` | `soin_temperature`, `soin_medicament`, `soin_bobo` — ou sous-types dans payload | `ack` |
|
| Soins (détail) | `pink` | `soin_temperature`, `soin_medicament`, `soin_bobo` — ou sous-types dans payload | `ack` |
|
||||||
|
| Modif absence | `peach` | `absence_enfant_modif` — **via calendrier** d’abord ; bulle ack AM éventuelle ensuite | `ack` |
|
||||||
| Sortie | `peach` / `lavender` | `sortie_a_valider` | `accept_refuse` |
|
| Sortie | `peach` / `lavender` | `sortie_a_valider` | `accept_refuse` |
|
||||||
| Admin | `lavender` | `info_admin`, `document_a_fournir` | `ack` / `none` |
|
| Admin | `lavender` | `info_admin`, `document_a_fournir` | `ack` / `none` |
|
||||||
|
|
||||||
@@ -150,7 +156,9 @@ Variante soins : un seul fond rose ; l’icône / sous-type change.
|
|||||||
- Créateur : pas de boutons réponse ; éventuel « En attente de réponse ».
|
- Créateur : pas de boutons réponse ; éventuel « En attente de réponse ».
|
||||||
- Refus : afficher `last_refuse_comment`.
|
- Refus : afficher `last_refuse_comment`.
|
||||||
- Congé : `accept_refuse` côté destinataire.
|
- Congé : `accept_refuse` côté destinataire.
|
||||||
- Absence enfant : info / ack — pas de veto AM en V1.
|
- Absence enfant : **info seule** (`response_mode: none`) — pas de veto ni ack AM en V1.
|
||||||
|
- Absence enfant : audience = **AM + tous les parents du foyer** (créateur + co-parent), pas seulement le déclarant.
|
||||||
|
- Modif / édition d’absence : **agenda**, pas les cartes (V1).
|
||||||
- File courte : `purge_at` ; l’**agenda** conserve l’historique métier.
|
- File courte : `purge_at` ; l’**agenda** conserve l’historique métier.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -167,11 +175,14 @@ Variante soins : un seul fond rose ; l’icône / sous-type change.
|
|||||||
## 9. Recettes
|
## 9. Recettes
|
||||||
|
|
||||||
- [ ] API cartes **sans** champ `couleur` (ni feed ni `/types`).
|
- [ ] API cartes **sans** champ `couleur` (ni feed ni `/types`).
|
||||||
- [ ] Front mappe `conge_am` → aqua, `arret_maladie_am` → blue, `absence_*` → peach.
|
- [ ] Contrat lien agenda : champ API `id_evenement` (plus `id_absence`).
|
||||||
|
- [ ] Front mappe `conge_am` → aqua, `arret_maladie_am` → blue, `absence_enfant` → peach.
|
||||||
- [ ] Accept / refuse congé OK.
|
- [ ] Accept / refuse congé OK.
|
||||||
- [ ] Arrêt traité + période en cours → reste visible.
|
- [ ] Arrêt : ack parent « Bien reçu » ; traité + période en cours → reste visible.
|
||||||
|
- [ ] Absence enfant : pas de bouton (info).
|
||||||
- [ ] Filtre couple / placement.
|
- [ ] Filtre couple / placement.
|
||||||
- [ ] (Plus tard) `soin_enfant` rose AM → parents + ligne agenda.
|
- [ ] (Plus tard) `soin_enfant` rose AM → parents + ligne agenda.
|
||||||
|
- [ ] (Plus tard / calendrier) modifs d’absence + éventuel `absence_enfant_modif`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
|
After Width: | Height: | Size: 310 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 591 KiB |
|
Before Width: | Height: | Size: 683 KiB |
|
Before Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 202 KiB |
|
After Width: | Height: | Size: 158 KiB |
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 289 KiB |
|
After Width: | Height: | Size: 291 KiB |
|
After Width: | Height: | Size: 137 KiB |
@@ -13,6 +13,7 @@ enum CarteStatut {
|
|||||||
switch (raw) {
|
switch (raw) {
|
||||||
case 'refusee':
|
case 'refusee':
|
||||||
return CarteStatut.refusee;
|
return CarteStatut.refusee;
|
||||||
|
case 'fermee':
|
||||||
case 'traitee':
|
case 'traitee':
|
||||||
return CarteStatut.traitee;
|
return CarteStatut.traitee;
|
||||||
case 'ouverte':
|
case 'ouverte':
|
||||||
@@ -49,7 +50,6 @@ class CarteBulle {
|
|||||||
final String id;
|
final String id;
|
||||||
final String typeCode;
|
final String typeCode;
|
||||||
final String titre;
|
final String titre;
|
||||||
final String? couleur;
|
|
||||||
final String idPlacement;
|
final String idPlacement;
|
||||||
final String? idAbsence;
|
final String? idAbsence;
|
||||||
final String operation;
|
final String operation;
|
||||||
@@ -67,7 +67,6 @@ class CarteBulle {
|
|||||||
required this.id,
|
required this.id,
|
||||||
required this.typeCode,
|
required this.typeCode,
|
||||||
required this.titre,
|
required this.titre,
|
||||||
this.couleur,
|
|
||||||
required this.idPlacement,
|
required this.idPlacement,
|
||||||
this.idAbsence,
|
this.idAbsence,
|
||||||
this.operation = 'create',
|
this.operation = 'create',
|
||||||
@@ -82,10 +81,96 @@ class CarteBulle {
|
|||||||
this.modifieLe,
|
this.modifieLe,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
CarteBulle copyWith({
|
||||||
|
CarteStatut? statut,
|
||||||
|
bool? isCreator,
|
||||||
|
String? lastRefuseComment,
|
||||||
|
DateTime? modifieLe,
|
||||||
|
Map<String, dynamic>? payload,
|
||||||
|
}) {
|
||||||
|
return CarteBulle(
|
||||||
|
id: id,
|
||||||
|
typeCode: typeCode,
|
||||||
|
titre: titre,
|
||||||
|
idPlacement: idPlacement,
|
||||||
|
idAbsence: idAbsence,
|
||||||
|
operation: operation,
|
||||||
|
statut: statut ?? this.statut,
|
||||||
|
payload: payload ?? this.payload,
|
||||||
|
purgeAt: purgeAt,
|
||||||
|
creePar: creePar,
|
||||||
|
isCreator: isCreator ?? this.isCreator,
|
||||||
|
responseMode: responseMode,
|
||||||
|
lastRefuseComment: lastRefuseComment ?? this.lastRefuseComment,
|
||||||
|
creeLe: creeLe,
|
||||||
|
modifieLe: modifieLe ?? this.modifieLe,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
String? get dateDebut => payload['date_debut']?.toString();
|
String? get dateDebut => payload['date_debut']?.toString();
|
||||||
String? get dateFin => payload['date_fin']?.toString();
|
String? get dateFin => payload['date_fin']?.toString();
|
||||||
String? get motif => payload['motif']?.toString();
|
String? get motif => payload['motif']?.toString();
|
||||||
|
|
||||||
|
/// Heure de relevé (payload soins), format API `HH:mm`.
|
||||||
|
String? get heureReleve => payload['heure_releve']?.toString();
|
||||||
|
|
||||||
|
/// Heure affichable `18h19` (depuis `heure_releve`).
|
||||||
|
String? get heureReleveAffichee {
|
||||||
|
final h = heureReleve?.trim();
|
||||||
|
if (h == null || h.isEmpty) return null;
|
||||||
|
final parts = h.split(':');
|
||||||
|
if (parts.length < 2) return h;
|
||||||
|
return '${parts[0]}h${parts[1]}';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ligne détail soin (sans date/heure) — sous la ligne agenda.
|
||||||
|
String? get detailSoin {
|
||||||
|
if (!isSoinEnfant) return null;
|
||||||
|
final st = payload['sous_type']?.toString();
|
||||||
|
if (st == 'fievre') {
|
||||||
|
final t = payload['temperature_c'];
|
||||||
|
final med = payload['medicament_donne']?.toString().trim();
|
||||||
|
String? temp;
|
||||||
|
if (t is num) {
|
||||||
|
temp = t.toStringAsFixed(1).replaceAll('.', ',');
|
||||||
|
} else if (t != null) {
|
||||||
|
temp = t.toString().replaceAll('.', ',');
|
||||||
|
}
|
||||||
|
if (temp == null || temp.isEmpty) return motif;
|
||||||
|
var s = '$temp °C';
|
||||||
|
if (med != null && med.isNotEmpty) {
|
||||||
|
s += ' (Médicament : $med)';
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
if (st == 'bobo') {
|
||||||
|
final nature = payload['bobo_nature']?.toString() ?? 'bobo';
|
||||||
|
final desc = payload['description']?.toString().trim();
|
||||||
|
if (desc != null && desc.isNotEmpty) {
|
||||||
|
return 'Bobo ($nature) : $desc';
|
||||||
|
}
|
||||||
|
return 'Bobo ($nature)';
|
||||||
|
}
|
||||||
|
if (st == 'medicament') {
|
||||||
|
final nom = payload['medicament_nom']?.toString().trim();
|
||||||
|
final ctx = payload['contexte']?.toString().trim();
|
||||||
|
final label =
|
||||||
|
(nom != null && nom.isNotEmpty) ? 'Médicament ($nom)' : 'Médicament';
|
||||||
|
if (ctx != null && ctx.isNotEmpty) return '$label : $ctx';
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
return motif;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Motif de refus : réponse API, sinon motif payload (co-parent / reload).
|
||||||
|
String? get motifRefus {
|
||||||
|
final fromResponse = lastRefuseComment?.trim();
|
||||||
|
if (fromResponse != null && fromResponse.isNotEmpty) return fromResponse;
|
||||||
|
final fromPayload = motif?.trim();
|
||||||
|
if (fromPayload != null && fromPayload.isNotEmpty) return fromPayload;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
/// Libellé UI (sémantique produit) — pas le titre brut API.
|
/// Libellé UI (sémantique produit) — pas le titre brut API.
|
||||||
String get titreAffiche {
|
String get titreAffiche {
|
||||||
switch (typeCode) {
|
switch (typeCode) {
|
||||||
@@ -96,6 +181,8 @@ class CarteBulle {
|
|||||||
case 'absence_enfant':
|
case 'absence_enfant':
|
||||||
case 'absence_enfant_modif':
|
case 'absence_enfant_modif':
|
||||||
return 'Notification d’absence';
|
return 'Notification d’absence';
|
||||||
|
case 'soin_enfant':
|
||||||
|
return 'Soin / bobo';
|
||||||
default:
|
default:
|
||||||
return titre;
|
return titre;
|
||||||
}
|
}
|
||||||
@@ -103,6 +190,22 @@ class CarteBulle {
|
|||||||
|
|
||||||
bool get isArretMaladie => typeCode == 'arret_maladie_am';
|
bool get isArretMaladie => typeCode == 'arret_maladie_am';
|
||||||
bool get isCongeAm => typeCode == 'conge_am';
|
bool get isCongeAm => typeCode == 'conge_am';
|
||||||
|
bool get isSoinEnfant => typeCode == 'soin_enfant';
|
||||||
|
bool get isAbsenceEnfant =>
|
||||||
|
typeCode == 'absence_enfant' || typeCode == 'absence_enfant_modif';
|
||||||
|
|
||||||
|
/// Info seule (`response_mode: none`) : créée déjà `traitee`, mais reste
|
||||||
|
/// pertinente dans la file tant que la période n’est pas finie.
|
||||||
|
bool get restePleineDansFile {
|
||||||
|
if (statut == CarteStatut.ouverte) return true;
|
||||||
|
if (statut != CarteStatut.traitee) return false;
|
||||||
|
if (!periodeEncoreActive) return false;
|
||||||
|
// Arrêt maladie ack : opaque jusqu’à date_fin.
|
||||||
|
if (isArretMaladie) return true;
|
||||||
|
// Absence (et autres infos) : pas d’atténuation tant que période active.
|
||||||
|
if (responseMode == CarteResponseMode.none) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
/// Icône dessin (haut droite) selon le type de bulle.
|
/// Icône dessin (haut droite) selon le type de bulle.
|
||||||
String? get iconAsset {
|
String? get iconAsset {
|
||||||
@@ -110,10 +213,16 @@ class CarteBulle {
|
|||||||
case 'conge_am':
|
case 'conge_am':
|
||||||
return 'assets/images/valise.png';
|
return 'assets/images/valise.png';
|
||||||
case 'arret_maladie_am':
|
case 'arret_maladie_am':
|
||||||
return 'assets/images/cartes/icon_carte_maladie.png';
|
return 'assets/images/thermo_croix.png';
|
||||||
case 'absence_enfant':
|
case 'absence_enfant':
|
||||||
case 'absence_enfant_modif':
|
case 'absence_enfant_modif':
|
||||||
return 'assets/images/cartes/icon_carte_absence.png';
|
return 'assets/images/sac_lapin.png';
|
||||||
|
case 'soin_enfant':
|
||||||
|
final st = payload['sous_type']?.toString();
|
||||||
|
if (st == 'fievre') return 'assets/images/thermo_verre.png';
|
||||||
|
if (st == 'bobo') return 'assets/images/pansement.png';
|
||||||
|
if (st == 'medicament') return 'assets/images/flacon.png';
|
||||||
|
return null;
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -137,35 +246,27 @@ class CarteBulle {
|
|||||||
return !todayDay.isAfter(fin);
|
return !todayDay.isAfter(fin);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Asset horizontal pastel (palette `assets/cards/` uniquement).
|
/// Teinte pastel UI dérivée du `type_code` (pas de `couleur` API).
|
||||||
String get backgroundAsset {
|
/// Voir `docs/32_MINI-SPEC-BULLES-CARTES.md` §4.
|
||||||
// Congés : aqua (le lavande API ne convient pas au design).
|
CardColorHorizontal get colorFamily {
|
||||||
if (typeCode == 'conge_am') {
|
switch (typeCode) {
|
||||||
return CardColorHorizontal.aqua.path;
|
case 'conge_am':
|
||||||
}
|
return CardColorHorizontal.aqua;
|
||||||
final key = (couleur ?? '').trim().toLowerCase();
|
case 'arret_maladie_am':
|
||||||
switch (key) {
|
return CardColorHorizontal.blue;
|
||||||
case 'red':
|
case 'absence_enfant':
|
||||||
return CardColorHorizontal.red.path;
|
case 'absence_enfant_modif':
|
||||||
case 'pink':
|
return CardColorHorizontal.peach;
|
||||||
return CardColorHorizontal.pink.path;
|
case 'soin_enfant':
|
||||||
case 'peach':
|
return CardColorHorizontal.pink;
|
||||||
return CardColorHorizontal.peach.path;
|
|
||||||
case 'lime':
|
|
||||||
return CardColorHorizontal.lime.path;
|
|
||||||
case 'lavender':
|
|
||||||
return CardColorHorizontal.lavender.path;
|
|
||||||
case 'green':
|
|
||||||
return CardColorHorizontal.green.path;
|
|
||||||
case 'blue':
|
|
||||||
return CardColorHorizontal.blue.path;
|
|
||||||
case 'aqua':
|
|
||||||
return CardColorHorizontal.aqua.path;
|
|
||||||
default:
|
default:
|
||||||
return CardColorHorizontal.peach.path;
|
return CardColorHorizontal.lavender;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Asset horizontal pastel (palette `assets/cards/` uniquement).
|
||||||
|
String get backgroundAsset => colorFamily.path;
|
||||||
|
|
||||||
/// Le destinataire peut répondre (pas le créateur, carte ouverte).
|
/// Le destinataire peut répondre (pas le créateur, carte ouverte).
|
||||||
bool get peutRepondre =>
|
bool get peutRepondre =>
|
||||||
!isCreator &&
|
!isCreator &&
|
||||||
@@ -178,7 +279,6 @@ class CarteBulle {
|
|||||||
id: (json['id'] ?? '').toString(),
|
id: (json['id'] ?? '').toString(),
|
||||||
typeCode: (json['type_code'] ?? '').toString(),
|
typeCode: (json['type_code'] ?? '').toString(),
|
||||||
titre: (json['titre'] ?? json['type_code'] ?? 'Carte').toString(),
|
titre: (json['titre'] ?? json['type_code'] ?? 'Carte').toString(),
|
||||||
couleur: json['couleur']?.toString(),
|
|
||||||
idPlacement: (json['id_placement'] ?? '').toString(),
|
idPlacement: (json['id_placement'] ?? '').toString(),
|
||||||
idAbsence: json['id_absence']?.toString(),
|
idAbsence: json['id_absence']?.toString(),
|
||||||
operation: (json['operation'] ?? 'create').toString(),
|
operation: (json['operation'] ?? 'create').toString(),
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
/// Configuration UI d'un type de carte — catalogue front (#175).
|
||||||
|
/// Les types émissibles viennent de l'API ; ce fichier affine libellés / hints.
|
||||||
|
enum CartePeriodeMode {
|
||||||
|
/// Plage date_debut → date_fin.
|
||||||
|
range,
|
||||||
|
|
||||||
|
/// Une seule date (début = fin).
|
||||||
|
singleDay,
|
||||||
|
}
|
||||||
|
|
||||||
|
class CarteSousTypeUi {
|
||||||
|
final String code;
|
||||||
|
final String label;
|
||||||
|
|
||||||
|
const CarteSousTypeUi({required this.code, required this.label});
|
||||||
|
}
|
||||||
|
|
||||||
|
class CarteTypeUi {
|
||||||
|
final String typeCode;
|
||||||
|
final String label;
|
||||||
|
final String motifHint;
|
||||||
|
final bool motifRequired;
|
||||||
|
final CartePeriodeMode periodeMode;
|
||||||
|
final List<CarteSousTypeUi> sousTypes;
|
||||||
|
|
||||||
|
const CarteTypeUi({
|
||||||
|
required this.typeCode,
|
||||||
|
required this.label,
|
||||||
|
this.motifHint = 'Motif (optionnel)',
|
||||||
|
this.motifRequired = false,
|
||||||
|
this.periodeMode = CartePeriodeMode.range,
|
||||||
|
this.sousTypes = const [],
|
||||||
|
});
|
||||||
|
|
||||||
|
static const _catalog = <String, CarteTypeUi>{
|
||||||
|
'absence_enfant': CarteTypeUi(
|
||||||
|
typeCode: 'absence_enfant',
|
||||||
|
label: 'Notification d’absence',
|
||||||
|
motifHint: 'Motif de l’absence (optionnel)',
|
||||||
|
),
|
||||||
|
// absence_enfant_modif : hors scope cartes — via agenda uniquement.
|
||||||
|
'conge_am': CarteTypeUi(
|
||||||
|
typeCode: 'conge_am',
|
||||||
|
label: 'Demande de congés',
|
||||||
|
motifHint: 'Précisions (optionnel)',
|
||||||
|
),
|
||||||
|
'arret_maladie_am': CarteTypeUi(
|
||||||
|
typeCode: 'arret_maladie_am',
|
||||||
|
label: 'Arrêt maladie',
|
||||||
|
motifHint: 'Précisions (optionnel)',
|
||||||
|
),
|
||||||
|
'soin_enfant': CarteTypeUi(
|
||||||
|
typeCode: 'soin_enfant',
|
||||||
|
label: 'Soin / bobo',
|
||||||
|
periodeMode: CartePeriodeMode.singleDay,
|
||||||
|
sousTypes: [
|
||||||
|
CarteSousTypeUi(code: 'fievre', label: 'Fièvre'),
|
||||||
|
CarteSousTypeUi(code: 'bobo', label: 'Bobo'),
|
||||||
|
CarteSousTypeUi(code: 'medicament', label: 'Médicament'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Fusionne un type API avec le catalogue ; fallback générique sinon.
|
||||||
|
static CarteTypeUi resolve({
|
||||||
|
required String typeCode,
|
||||||
|
String? apiTitre,
|
||||||
|
}) {
|
||||||
|
final known = _catalog[typeCode];
|
||||||
|
if (known != null) return known;
|
||||||
|
final titre = (apiTitre ?? '').trim();
|
||||||
|
return CarteTypeUi(
|
||||||
|
typeCode: typeCode,
|
||||||
|
label: titre.isNotEmpty ? titre : typeCode,
|
||||||
|
motifHint: 'Motif (optionnel)',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Type SYSTEM émissible renvoyé par GET /cards/types.
|
||||||
|
class CarteTypeEmissible {
|
||||||
|
final String code;
|
||||||
|
final String titre;
|
||||||
|
final String? responseMode;
|
||||||
|
final CarteTypeUi ui;
|
||||||
|
|
||||||
|
const CarteTypeEmissible({
|
||||||
|
required this.code,
|
||||||
|
required this.titre,
|
||||||
|
this.responseMode,
|
||||||
|
required this.ui,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory CarteTypeEmissible.fromJson(Map<String, dynamic> json) {
|
||||||
|
final code = (json['code'] ?? '').toString();
|
||||||
|
final titre = (json['titre'] ?? code).toString();
|
||||||
|
return CarteTypeEmissible(
|
||||||
|
code: code,
|
||||||
|
titre: titre,
|
||||||
|
responseMode: json['response_mode']?.toString(),
|
||||||
|
ui: CarteTypeUi.resolve(typeCode: code, apiTitre: titre),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String get label => ui.label;
|
||||||
|
}
|
||||||
@@ -3,14 +3,15 @@ import 'package:p_tits_pas/models/couple_garde.dart';
|
|||||||
import 'package:p_tits_pas/models/user.dart';
|
import 'package:p_tits_pas/models/user.dart';
|
||||||
import 'package:p_tits_pas/services/auth_service.dart';
|
import 'package:p_tits_pas/services/auth_service.dart';
|
||||||
import 'package:p_tits_pas/services/couple_garde_service.dart';
|
import 'package:p_tits_pas/services/couple_garde_service.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/quotidien/cartes_feed.dart';
|
||||||
import 'package:p_tits_pas/widgets/quotidien/couple_selector_bandeau.dart';
|
import 'package:p_tits_pas/widgets/quotidien/couple_selector_bandeau.dart';
|
||||||
import 'package:p_tits_pas/widgets/quotidien/quotidien_shell.dart';
|
import 'package:p_tits_pas/widgets/quotidien/quotidien_shell.dart';
|
||||||
import 'package:p_tits_pas/widgets/quotidien/quotidien_theme.dart';
|
import 'package:p_tits_pas/widgets/quotidien/quotidien_theme.dart';
|
||||||
import 'package:p_tits_pas/screens/home/parent_screen/agenda_absences_stub.dart';
|
import 'package:p_tits_pas/screens/home/parent_screen/agenda_absences_stub.dart';
|
||||||
|
|
||||||
/// Dashboard assistante maternelle – coquille 3 colonnes quotidien (#169).
|
/// Dashboard assistante maternelle – coquille 3 colonnes quotidien (#169).
|
||||||
/// Colonne gauche : sélecteur de couple enfant–parent(s) (#170).
|
/// Contexte couple dans le bandeau (#211) ; colonne gauche = feed (#174).
|
||||||
/// Métier cartes / blog / messagerie : tickets C/D/E.
|
/// Création « Ajouter une carte » : modale générique (#175, réutilisée #176).
|
||||||
class AmDashboardScreen extends StatefulWidget {
|
class AmDashboardScreen extends StatefulWidget {
|
||||||
const AmDashboardScreen({super.key});
|
const AmDashboardScreen({super.key});
|
||||||
|
|
||||||
@@ -107,16 +108,17 @@ class _AmDashboardScreenState extends State<AmDashboardScreen> {
|
|||||||
userEmail: _user?.email,
|
userEmail: _user?.email,
|
||||||
onProfileTap: () => _soon('Profil'),
|
onProfileTap: () => _soon('Profil'),
|
||||||
onSettingsTap: () => _soon('Paramètres'),
|
onSettingsTap: () => _soon('Paramètres'),
|
||||||
// L'AM n'a pas de bouton "Recherche AM" dans le bandeau
|
|
||||||
onSearchAmTap: null,
|
onSearchAmTap: null,
|
||||||
leftColumn: _LeftColumn(
|
contextSelector: CoupleSelectorBandeau(
|
||||||
|
mode: CoupleBandeauMode.assistanteMaternelle,
|
||||||
couples: _couples,
|
couples: _couples,
|
||||||
selectedCoupleId: _selectedCoupleId,
|
selectedCoupleId: _selectedCoupleId,
|
||||||
loading: _couplesLoading,
|
loading: _couplesLoading,
|
||||||
error: _couplesError,
|
errorMessage: _couplesError,
|
||||||
onRetry: _loadCouples,
|
onRetry: _loadCouples,
|
||||||
onCoupleSelected: _selectCouple,
|
onCoupleSelected: _selectCouple,
|
||||||
),
|
),
|
||||||
|
leftColumn: _LeftColumn(selectedCoupleId: _selectedCoupleId),
|
||||||
centerColumn: const QuotidienColumnPlaceholder(
|
centerColumn: const QuotidienColumnPlaceholder(
|
||||||
title: 'Blog',
|
title: 'Blog',
|
||||||
subtitle:
|
subtitle:
|
||||||
@@ -138,51 +140,17 @@ class _AmDashboardScreenState extends State<AmDashboardScreen> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Colonne gauche : flux de cartes (#174 / #175). Couple = bandeau (#211).
|
||||||
class _LeftColumn extends StatelessWidget {
|
class _LeftColumn extends StatelessWidget {
|
||||||
final List<CoupleGarde> couples;
|
|
||||||
final String? selectedCoupleId;
|
final String? selectedCoupleId;
|
||||||
final bool loading;
|
|
||||||
final String? error;
|
|
||||||
final VoidCallback onRetry;
|
|
||||||
final ValueChanged<CoupleGarde> onCoupleSelected;
|
|
||||||
|
|
||||||
const _LeftColumn({
|
const _LeftColumn({required this.selectedCoupleId});
|
||||||
required this.couples,
|
|
||||||
required this.selectedCoupleId,
|
|
||||||
required this.loading,
|
|
||||||
required this.error,
|
|
||||||
required this.onRetry,
|
|
||||||
required this.onCoupleSelected,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.all(14),
|
padding: const EdgeInsets.all(14),
|
||||||
child: Column(
|
child: CartesFeed(placementId: selectedCoupleId),
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
CoupleSelectorBandeau(
|
|
||||||
mode: CoupleBandeauMode.assistanteMaternelle,
|
|
||||||
couples: couples,
|
|
||||||
selectedCoupleId: selectedCoupleId,
|
|
||||||
loading: loading,
|
|
||||||
errorMessage: error,
|
|
||||||
onRetry: onRetry,
|
|
||||||
onCoupleSelected: onCoupleSelected,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 14),
|
|
||||||
const Expanded(
|
|
||||||
child: QuotidienColumnPlaceholder(
|
|
||||||
title: 'Cartes',
|
|
||||||
subtitle:
|
|
||||||
'Absences, congés AM, sorties à valider\n(à brancher — ticket #174).',
|
|
||||||
icon: Icons.style_outlined,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import 'package:p_tits_pas/widgets/quotidien/quotidien_theme.dart';
|
|||||||
import 'package:p_tits_pas/screens/home/parent_screen/agenda_absences_stub.dart';
|
import 'package:p_tits_pas/screens/home/parent_screen/agenda_absences_stub.dart';
|
||||||
|
|
||||||
/// Tableau de bord parent — coquille 3 colonnes quotidien (#166).
|
/// Tableau de bord parent — coquille 3 colonnes quotidien (#166).
|
||||||
/// Colonne gauche : sélecteur de couple (#167) + feed bulles (#173).
|
/// Contexte couple dans le bandeau (#211) ; colonne gauche = feed (#173).
|
||||||
class ParentDashboardScreen extends StatefulWidget {
|
class ParentDashboardScreen extends StatefulWidget {
|
||||||
const ParentDashboardScreen({super.key});
|
const ParentDashboardScreen({super.key});
|
||||||
|
|
||||||
@@ -108,15 +108,15 @@ class _ParentDashboardScreenState extends State<ParentDashboardScreen> {
|
|||||||
onProfileTap: () => _soon('Profil'),
|
onProfileTap: () => _soon('Profil'),
|
||||||
onSearchAmTap: () => _soon('Recherche AM'),
|
onSearchAmTap: () => _soon('Recherche AM'),
|
||||||
onSettingsTap: () => _soon('Paramètres'),
|
onSettingsTap: () => _soon('Paramètres'),
|
||||||
leftColumn: _LeftColumn(
|
contextSelector: CoupleSelectorBandeau(
|
||||||
couples: _couples,
|
couples: _couples,
|
||||||
selectedCoupleId: _selectedCoupleId,
|
selectedCoupleId: _selectedCoupleId,
|
||||||
loading: _couplesLoading,
|
loading: _couplesLoading,
|
||||||
error: _couplesError,
|
errorMessage: _couplesError,
|
||||||
onRetry: _loadCouples,
|
onRetry: _loadCouples,
|
||||||
onCoupleSelected: _selectCouple,
|
onCoupleSelected: _selectCouple,
|
||||||
onAjouterBulle: () => _soon('Ajouter une bulle'),
|
|
||||||
),
|
),
|
||||||
|
leftColumn: _LeftColumn(selectedCoupleId: _selectedCoupleId),
|
||||||
centerColumn: const QuotidienColumnPlaceholder(
|
centerColumn: const QuotidienColumnPlaceholder(
|
||||||
title: 'Blog',
|
title: 'Blog',
|
||||||
subtitle:
|
subtitle:
|
||||||
@@ -138,50 +138,17 @@ class _ParentDashboardScreenState extends State<ParentDashboardScreen> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Colonne gauche : bandeau couple (#167) puis flux de cartes (#173).
|
/// Colonne gauche : flux de cartes (#173 / #175). Couple = bandeau (#211).
|
||||||
class _LeftColumn extends StatelessWidget {
|
class _LeftColumn extends StatelessWidget {
|
||||||
final List<CoupleGarde> couples;
|
|
||||||
final String? selectedCoupleId;
|
final String? selectedCoupleId;
|
||||||
final bool loading;
|
|
||||||
final String? error;
|
|
||||||
final VoidCallback onRetry;
|
|
||||||
final ValueChanged<CoupleGarde> onCoupleSelected;
|
|
||||||
final VoidCallback onAjouterBulle;
|
|
||||||
|
|
||||||
const _LeftColumn({
|
const _LeftColumn({required this.selectedCoupleId});
|
||||||
required this.couples,
|
|
||||||
required this.selectedCoupleId,
|
|
||||||
required this.loading,
|
|
||||||
required this.error,
|
|
||||||
required this.onRetry,
|
|
||||||
required this.onCoupleSelected,
|
|
||||||
required this.onAjouterBulle,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.all(14),
|
padding: const EdgeInsets.all(14),
|
||||||
child: Column(
|
child: CartesFeed(placementId: selectedCoupleId),
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
CoupleSelectorBandeau(
|
|
||||||
couples: couples,
|
|
||||||
selectedCoupleId: selectedCoupleId,
|
|
||||||
loading: loading,
|
|
||||||
errorMessage: error,
|
|
||||||
onRetry: onRetry,
|
|
||||||
onCoupleSelected: onCoupleSelected,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 14),
|
|
||||||
Expanded(
|
|
||||||
child: CartesFeed(
|
|
||||||
placementId: selectedCoupleId,
|
|
||||||
onAjouterBulle: onAjouterBulle,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,11 +2,14 @@ import 'dart:convert';
|
|||||||
|
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
import 'package:p_tits_pas/models/carte_bulle.dart';
|
import 'package:p_tits_pas/models/carte_bulle.dart';
|
||||||
|
import 'package:p_tits_pas/models/carte_type_ui.dart';
|
||||||
import 'package:p_tits_pas/services/api/api_config.dart';
|
import 'package:p_tits_pas/services/api/api_config.dart';
|
||||||
import 'package:p_tits_pas/services/api/tokenService.dart';
|
import 'package:p_tits_pas/services/api/tokenService.dart';
|
||||||
|
|
||||||
/// Accès API Cartes (file d'attention) — tickets #173 / #194.
|
/// Accès API Cartes (file d'attention) — tickets #173 / #175 / #194.
|
||||||
/// - GET /cards?placementId=
|
/// - GET /cards?placementId=
|
||||||
|
/// - GET /cards/types
|
||||||
|
/// - POST /cards
|
||||||
/// - POST /cards/:id/respond
|
/// - POST /cards/:id/respond
|
||||||
class CardsService {
|
class CardsService {
|
||||||
static Future<Map<String, String>> _headers() async {
|
static Future<Map<String, String>> _headers() async {
|
||||||
@@ -57,6 +60,105 @@ class CardsService {
|
|||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Types SYSTEM émissibles pour le rôle connecté.
|
||||||
|
static Future<List<CarteTypeEmissible>> listerTypes() async {
|
||||||
|
final response = await http.get(
|
||||||
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.cards}/types'),
|
||||||
|
headers: await _headers(),
|
||||||
|
);
|
||||||
|
if (response.statusCode != 200) {
|
||||||
|
throw Exception(
|
||||||
|
_extractError(response.body, 'Erreur chargement des types de cartes'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final decoded = jsonDecode(response.body);
|
||||||
|
final list = decoded is List
|
||||||
|
? decoded
|
||||||
|
: (decoded is Map ? decoded['items'] as List? : null) ?? const [];
|
||||||
|
return list
|
||||||
|
.whereType<Map>()
|
||||||
|
.map((e) => CarteTypeEmissible.fromJson(Map<String, dynamic>.from(e)))
|
||||||
|
.where((t) => t.code.isNotEmpty)
|
||||||
|
// Modif d’absence = agenda, pas la modale cartes (#175).
|
||||||
|
.where((t) => t.code != 'absence_enfant_modif')
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Créer une bulle (+ événement agenda côté back).
|
||||||
|
static Future<CarteBulle> creer({
|
||||||
|
required String typeCode,
|
||||||
|
required String idPlacement,
|
||||||
|
required String dateDebut,
|
||||||
|
required String dateFin,
|
||||||
|
String? motif,
|
||||||
|
Map<String, dynamic>? payload,
|
||||||
|
}) async {
|
||||||
|
final response = await http.post(
|
||||||
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.cards}'),
|
||||||
|
headers: await _headers(),
|
||||||
|
body: jsonEncode({
|
||||||
|
'type_code': typeCode,
|
||||||
|
'id_placement': idPlacement,
|
||||||
|
'date_debut': dateDebut,
|
||||||
|
'date_fin': dateFin,
|
||||||
|
if (motif != null && motif.trim().isNotEmpty) 'motif': motif.trim(),
|
||||||
|
if (payload != null) 'payload': payload,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode != 201 && response.statusCode != 200) {
|
||||||
|
throw Exception(
|
||||||
|
_extractError(response.body, 'Erreur lors de la création'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final decoded = jsonDecode(response.body);
|
||||||
|
return CarteBulle.fromJson(Map<String, dynamic>.from(decoded as Map));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Modifier une carte (corriger un soin, dates en attente...).
|
||||||
|
static Future<CarteBulle> maj({
|
||||||
|
required String cardId,
|
||||||
|
String? dateDebut,
|
||||||
|
String? dateFin,
|
||||||
|
String? motif,
|
||||||
|
Map<String, dynamic>? payload,
|
||||||
|
}) async {
|
||||||
|
final response = await http.patch(
|
||||||
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.cards}/$cardId'),
|
||||||
|
headers: await _headers(),
|
||||||
|
body: jsonEncode({
|
||||||
|
if (dateDebut != null) 'date_debut': dateDebut,
|
||||||
|
if (dateFin != null) 'date_fin': dateFin,
|
||||||
|
if (motif != null && motif.trim().isNotEmpty) 'motif': motif.trim(),
|
||||||
|
if (payload != null) 'payload': payload,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode != 200) {
|
||||||
|
throw Exception(
|
||||||
|
_extractError(response.body, 'Erreur lors de la mise à jour'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final decoded = jsonDecode(response.body);
|
||||||
|
return CarteBulle.fromJson(Map<String, dynamic>.from(decoded as Map));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Supprimer une bulle (AM 24h ou avant traitement).
|
||||||
|
static Future<void> supprimer(String cardId) async {
|
||||||
|
final response = await http.delete(
|
||||||
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.cards}/$cardId'),
|
||||||
|
headers: await _headers(),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode != 204 && response.statusCode != 200) {
|
||||||
|
throw Exception(
|
||||||
|
_extractError(response.body, 'Erreur lors de la suppression'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Répondre : accept | refuse | ack.
|
/// Répondre : accept | refuse | ack.
|
||||||
static Future<CarteBulle> repondre({
|
static Future<CarteBulle> repondre({
|
||||||
required String cardId,
|
required String cardId,
|
||||||
@@ -75,7 +177,7 @@ class CardsService {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (response.statusCode != 200) {
|
if (response.statusCode != 200 && response.statusCode != 201) {
|
||||||
throw Exception(
|
throw Exception(
|
||||||
_extractError(response.body, 'Erreur lors de la réponse'),
|
_extractError(response.body, 'Erreur lors de la réponse'),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:p_tits_pas/models/carte_bulle.dart';
|
||||||
|
import 'package:p_tits_pas/services/api/api_config.dart';
|
||||||
|
import 'package:p_tits_pas/services/api/tokenService.dart';
|
||||||
|
|
||||||
|
import 'cards_stream_connector_stub.dart'
|
||||||
|
if (dart.library.html) 'cards_stream_connector_web.dart'
|
||||||
|
if (dart.library.io) 'cards_stream_connector_io.dart';
|
||||||
|
|
||||||
|
/// Événement temps réel file d'attention — ticket #195.
|
||||||
|
class CardsStreamEvent {
|
||||||
|
final String type;
|
||||||
|
final String? cardId;
|
||||||
|
final CarteBulle? card;
|
||||||
|
|
||||||
|
const CardsStreamEvent({
|
||||||
|
required this.type,
|
||||||
|
this.cardId,
|
||||||
|
this.card,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Client SSE `GET /cards/stream` avec reconnexion.
|
||||||
|
class CardsStreamClient {
|
||||||
|
final void Function(CardsStreamEvent event) onEvent;
|
||||||
|
final VoidCallback? onReconnectSync;
|
||||||
|
|
||||||
|
CardsStreamClient({
|
||||||
|
required this.onEvent,
|
||||||
|
this.onReconnectSync,
|
||||||
|
});
|
||||||
|
|
||||||
|
final CardsStreamConnector _connector = CardsStreamConnector();
|
||||||
|
bool _started = false;
|
||||||
|
bool _stopRequested = false;
|
||||||
|
int _attempt = 0;
|
||||||
|
Timer? _retryTimer;
|
||||||
|
bool _hadConnection = false;
|
||||||
|
|
||||||
|
void start() {
|
||||||
|
if (_started) return;
|
||||||
|
_started = true;
|
||||||
|
_stopRequested = false;
|
||||||
|
_attempt = 0;
|
||||||
|
unawaited(_connect());
|
||||||
|
}
|
||||||
|
|
||||||
|
void stop() {
|
||||||
|
_stopRequested = true;
|
||||||
|
_started = false;
|
||||||
|
_retryTimer?.cancel();
|
||||||
|
_retryTimer = null;
|
||||||
|
_connector.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _connect() async {
|
||||||
|
if (_stopRequested) return;
|
||||||
|
|
||||||
|
final token = await TokenService.getToken();
|
||||||
|
if (token == null || token.isEmpty) {
|
||||||
|
_scheduleRetry();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final base =
|
||||||
|
'${ApiConfig.baseUrl}${ApiConfig.cardsStream}'.replaceAll(
|
||||||
|
RegExp(r'/+$'),
|
||||||
|
'',
|
||||||
|
);
|
||||||
|
|
||||||
|
// Web (EventSource) : token en query. IO : Bearer dans le connecteur.
|
||||||
|
final url = kIsWeb
|
||||||
|
? Uri.parse(base).replace(
|
||||||
|
queryParameters: {'access_token': token},
|
||||||
|
).toString()
|
||||||
|
: base;
|
||||||
|
|
||||||
|
await _connector.connect(
|
||||||
|
url: url,
|
||||||
|
bearerToken: kIsWeb ? null : token,
|
||||||
|
onEvent: _handleRaw,
|
||||||
|
onError: (_) {
|
||||||
|
if (_stopRequested) return;
|
||||||
|
_connector.close();
|
||||||
|
_scheduleRetry();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleRaw(String eventType, String data) {
|
||||||
|
if (_stopRequested) return;
|
||||||
|
|
||||||
|
// Premier événement (souvent heartbeat) = connexion OK.
|
||||||
|
if (!_hadConnection) {
|
||||||
|
_hadConnection = true;
|
||||||
|
_attempt = 0;
|
||||||
|
} else if (eventType == 'heartbeat') {
|
||||||
|
_attempt = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (eventType == 'heartbeat') return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(data);
|
||||||
|
if (decoded is! Map) return;
|
||||||
|
final map = Map<String, dynamic>.from(decoded);
|
||||||
|
final type = (map['event']?.toString().isNotEmpty == true)
|
||||||
|
? map['event'].toString()
|
||||||
|
: eventType;
|
||||||
|
final cardId = map['card_id']?.toString();
|
||||||
|
final payload = map['data'];
|
||||||
|
|
||||||
|
CarteBulle? card;
|
||||||
|
if (type == 'response.added' && payload is Map) {
|
||||||
|
final nested = payload['card'];
|
||||||
|
if (nested is Map) {
|
||||||
|
card = CarteBulle.fromJson(Map<String, dynamic>.from(nested));
|
||||||
|
}
|
||||||
|
} else if ((type == 'card.created' || type == 'card.updated') &&
|
||||||
|
payload is Map) {
|
||||||
|
card = CarteBulle.fromJson(Map<String, dynamic>.from(payload));
|
||||||
|
}
|
||||||
|
|
||||||
|
onEvent(
|
||||||
|
CardsStreamEvent(
|
||||||
|
type: type,
|
||||||
|
cardId: cardId ?? card?.id,
|
||||||
|
card: card,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} catch (_) {
|
||||||
|
// Événement mal formé : ignorer.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _scheduleRetry() {
|
||||||
|
if (_stopRequested) return;
|
||||||
|
_retryTimer?.cancel();
|
||||||
|
final delaySec = (1 << _attempt.clamp(0, 4)).clamp(1, 30);
|
||||||
|
_attempt++;
|
||||||
|
_retryTimer = Timer(Duration(seconds: delaySec), () {
|
||||||
|
if (_stopRequested) return;
|
||||||
|
if (_hadConnection) {
|
||||||
|
// Resync REST après coupure pour ne pas manquer d'événements.
|
||||||
|
onReconnectSync?.call();
|
||||||
|
}
|
||||||
|
unawaited(_connect());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
|
/// Connecteur SSE via HTTP stream (IO / mobile) — ticket #195.
|
||||||
|
class CardsStreamConnector {
|
||||||
|
http.Client? _client;
|
||||||
|
StreamSubscription<List<int>>? _sub;
|
||||||
|
bool _closed = false;
|
||||||
|
|
||||||
|
Future<void> connect({
|
||||||
|
required String url,
|
||||||
|
String? bearerToken,
|
||||||
|
required void Function(String eventType, String data) onEvent,
|
||||||
|
required void Function(Object error) onError,
|
||||||
|
}) async {
|
||||||
|
close();
|
||||||
|
_closed = false;
|
||||||
|
final client = http.Client();
|
||||||
|
_client = client;
|
||||||
|
|
||||||
|
try {
|
||||||
|
final request = http.Request('GET', Uri.parse(url));
|
||||||
|
request.headers['Accept'] = 'text/event-stream';
|
||||||
|
request.headers['Cache-Control'] = 'no-cache';
|
||||||
|
if (bearerToken != null && bearerToken.isNotEmpty) {
|
||||||
|
request.headers['Authorization'] = 'Bearer $bearerToken';
|
||||||
|
}
|
||||||
|
|
||||||
|
final response = await client.send(request);
|
||||||
|
if (response.statusCode != 200) {
|
||||||
|
onError(
|
||||||
|
StateError('SSE cards HTTP ${response.statusCode}'),
|
||||||
|
);
|
||||||
|
close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String? eventType;
|
||||||
|
final dataBuf = StringBuffer();
|
||||||
|
final lineBuf = StringBuffer();
|
||||||
|
|
||||||
|
void flushEvent() {
|
||||||
|
if (dataBuf.isEmpty) {
|
||||||
|
eventType = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onEvent(eventType ?? 'message', dataBuf.toString());
|
||||||
|
dataBuf.clear();
|
||||||
|
eventType = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
void handleLine(String line) {
|
||||||
|
if (line.isEmpty) {
|
||||||
|
flushEvent();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (line.startsWith(':')) return;
|
||||||
|
if (line.startsWith('event:')) {
|
||||||
|
eventType = line.substring(6).trim();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (line.startsWith('data:')) {
|
||||||
|
final payload = line.length > 5 ? line.substring(5) : '';
|
||||||
|
final trimmed = payload.startsWith(' ')
|
||||||
|
? payload.substring(1)
|
||||||
|
: payload;
|
||||||
|
if (dataBuf.isNotEmpty) dataBuf.write('\n');
|
||||||
|
dataBuf.write(trimmed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_sub = response.stream.listen(
|
||||||
|
(chunk) {
|
||||||
|
if (_closed) return;
|
||||||
|
lineBuf.write(utf8.decode(chunk, allowMalformed: true));
|
||||||
|
var content = lineBuf.toString();
|
||||||
|
var idx = content.indexOf('\n');
|
||||||
|
while (idx >= 0) {
|
||||||
|
var line = content.substring(0, idx);
|
||||||
|
if (line.endsWith('\r')) {
|
||||||
|
line = line.substring(0, line.length - 1);
|
||||||
|
}
|
||||||
|
handleLine(line);
|
||||||
|
content = content.substring(idx + 1);
|
||||||
|
idx = content.indexOf('\n');
|
||||||
|
}
|
||||||
|
lineBuf
|
||||||
|
..clear()
|
||||||
|
..write(content);
|
||||||
|
},
|
||||||
|
onError: (Object e) {
|
||||||
|
if (!_closed) onError(e);
|
||||||
|
},
|
||||||
|
onDone: () {
|
||||||
|
if (!_closed) onError(StateError('SSE cards fermé'));
|
||||||
|
},
|
||||||
|
cancelOnError: true,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
if (!_closed) onError(e);
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void close() {
|
||||||
|
_closed = true;
|
||||||
|
_sub?.cancel();
|
||||||
|
_sub = null;
|
||||||
|
_client?.close();
|
||||||
|
_client = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
/// Connecteur SSE — stub (tests / plateformes sans impl).
|
||||||
|
class CardsStreamConnector {
|
||||||
|
Future<void> connect({
|
||||||
|
required String url,
|
||||||
|
String? bearerToken,
|
||||||
|
required void Function(String eventType, String data) onEvent,
|
||||||
|
required void Function(Object error) onError,
|
||||||
|
}) async {}
|
||||||
|
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
// Connecteur web uniquement (import conditionnel).
|
||||||
|
// ignore_for_file: avoid_web_libraries_in_flutter, deprecated_member_use
|
||||||
|
|
||||||
|
import 'dart:html' as html;
|
||||||
|
|
||||||
|
/// Connecteur SSE navigateur (EventSource) — ticket #195.
|
||||||
|
/// Auth via `?access_token=` (EventSource ne permet pas Authorization).
|
||||||
|
class CardsStreamConnector {
|
||||||
|
html.EventSource? _source;
|
||||||
|
final Map<String, html.EventListener> _listeners = {};
|
||||||
|
|
||||||
|
Future<void> connect({
|
||||||
|
required String url,
|
||||||
|
String? bearerToken,
|
||||||
|
required void Function(String eventType, String data) onEvent,
|
||||||
|
required void Function(Object error) onError,
|
||||||
|
}) async {
|
||||||
|
close();
|
||||||
|
final source = html.EventSource(url);
|
||||||
|
_source = source;
|
||||||
|
|
||||||
|
const names = [
|
||||||
|
'card.created',
|
||||||
|
'card.updated',
|
||||||
|
'card.deleted',
|
||||||
|
'response.added',
|
||||||
|
'heartbeat',
|
||||||
|
];
|
||||||
|
for (final name in names) {
|
||||||
|
void listener(html.Event raw) {
|
||||||
|
final msg = raw as html.MessageEvent;
|
||||||
|
final data = msg.data?.toString() ?? '';
|
||||||
|
if (data.isEmpty) return;
|
||||||
|
onEvent(name, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
_listeners[name] = listener;
|
||||||
|
source.addEventListener(name, listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
void onErr(html.Event _) {
|
||||||
|
onError(StateError('SSE cards déconnecté'));
|
||||||
|
}
|
||||||
|
|
||||||
|
_listeners['error'] = onErr;
|
||||||
|
source.addEventListener('error', onErr);
|
||||||
|
}
|
||||||
|
|
||||||
|
void close() {
|
||||||
|
final source = _source;
|
||||||
|
if (source != null) {
|
||||||
|
_listeners.forEach((name, listener) {
|
||||||
|
source.removeEventListener(name, listener);
|
||||||
|
});
|
||||||
|
source.close();
|
||||||
|
}
|
||||||
|
_listeners.clear();
|
||||||
|
_source = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,704 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:google_fonts/google_fonts.dart';
|
||||||
|
import 'package:p_tits_pas/models/carte_bulle.dart';
|
||||||
|
import 'package:p_tits_pas/models/carte_type_ui.dart';
|
||||||
|
import 'package:p_tits_pas/services/api/cards_service.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/quotidien/quotidien_theme.dart';
|
||||||
|
|
||||||
|
/// Ouvre la modale Material générique « Ajouter une carte » (#175).
|
||||||
|
/// Retourne la bulle créée, ou `null` si annulé.
|
||||||
|
Future<CarteBulle?> showAjouterCarteModal(
|
||||||
|
BuildContext context, {
|
||||||
|
required String placementId,
|
||||||
|
CarteBulle? carteToEdit,
|
||||||
|
}) {
|
||||||
|
return showDialog<CarteBulle>(
|
||||||
|
context: context,
|
||||||
|
barrierDismissible: false,
|
||||||
|
builder: (ctx) => AjouterCarteModal(
|
||||||
|
placementId: placementId,
|
||||||
|
carteToEdit: carteToEdit,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Modale générique : types API + catalogue UI, période, soins
|
||||||
|
class AjouterCarteModal extends StatefulWidget {
|
||||||
|
final String placementId;
|
||||||
|
final CarteBulle? carteToEdit;
|
||||||
|
|
||||||
|
const AjouterCarteModal({
|
||||||
|
super.key,
|
||||||
|
required this.placementId,
|
||||||
|
this.carteToEdit,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<AjouterCarteModal> createState() => _AjouterCarteModalState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _AjouterCarteModalState extends State<AjouterCarteModal> {
|
||||||
|
List<CarteTypeEmissible> _types = const [];
|
||||||
|
CarteTypeEmissible? _selected;
|
||||||
|
String? _sousTypeCode;
|
||||||
|
DateTime _dateDebut = DateTime.now();
|
||||||
|
DateTime _dateFin = DateTime.now();
|
||||||
|
bool _loadingTypes = true;
|
||||||
|
bool _submitting = false;
|
||||||
|
String? _error;
|
||||||
|
|
||||||
|
TimeOfDay _heureReleve = TimeOfDay.now();
|
||||||
|
|
||||||
|
// --- Controllers Soins ---
|
||||||
|
final _motifController = TextEditingController();
|
||||||
|
final _temperatureController = TextEditingController();
|
||||||
|
final _medicamentDonneController = TextEditingController();
|
||||||
|
String? _boboNature;
|
||||||
|
final _boboDescriptionController = TextEditingController();
|
||||||
|
final _medicamentNomController = TextEditingController();
|
||||||
|
final _medicamentContexteController = TextEditingController();
|
||||||
|
|
||||||
|
CarteTypeUi get _ui =>
|
||||||
|
_selected?.ui ??
|
||||||
|
CarteTypeUi.resolve(typeCode: _selected?.code ?? 'inconnu');
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
final now = DateTime.now();
|
||||||
|
_dateDebut = DateTime(now.year, now.month, now.day);
|
||||||
|
_dateFin = _dateDebut;
|
||||||
|
_loadTypes();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _prefillIfEdit(List<CarteTypeEmissible> types) {
|
||||||
|
if (widget.carteToEdit == null) return;
|
||||||
|
final card = widget.carteToEdit!;
|
||||||
|
final type = types.where((t) => t.code == card.typeCode).firstOrNull;
|
||||||
|
if (type != null) {
|
||||||
|
_selected = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (card.dateDebut != null) {
|
||||||
|
_dateDebut = DateTime.tryParse(card.dateDebut!) ?? _dateDebut;
|
||||||
|
}
|
||||||
|
if (card.dateFin != null) {
|
||||||
|
_dateFin = DateTime.tryParse(card.dateFin!) ?? _dateFin;
|
||||||
|
}
|
||||||
|
|
||||||
|
_motifController.text = card.motif ?? '';
|
||||||
|
|
||||||
|
if (card.typeCode == 'soin_enfant') {
|
||||||
|
final p = card.payload;
|
||||||
|
_sousTypeCode = p['sous_type']?.toString();
|
||||||
|
final h = p['heure_releve']?.toString();
|
||||||
|
if (h != null && h.contains(':')) {
|
||||||
|
final parts = h.split(':');
|
||||||
|
_heureReleve = TimeOfDay(
|
||||||
|
hour: int.tryParse(parts[0]) ?? 0,
|
||||||
|
minute: int.tryParse(parts[1]) ?? 0,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_sousTypeCode == 'fievre') {
|
||||||
|
_temperatureController.text = p['temperature_c']?.toString() ?? '';
|
||||||
|
_medicamentDonneController.text = p['medicament_donne']?.toString() ?? '';
|
||||||
|
} else if (_sousTypeCode == 'bobo') {
|
||||||
|
final nature = p['bobo_nature']?.toString() ?? '';
|
||||||
|
final naturesValides = ['Chute', 'Coup', 'Égratignure', 'Piqûre', 'Brûlure', 'Autre'];
|
||||||
|
if (naturesValides.map((n) => n.toLowerCase().replaceAll('é', 'e').replaceAll('û', 'u')).contains(nature.toLowerCase())) {
|
||||||
|
_boboNature = naturesValides.firstWhere(
|
||||||
|
(n) => n.toLowerCase().replaceAll('é', 'e').replaceAll('û', 'u') == nature.toLowerCase().replaceAll('é', 'e').replaceAll('û', 'u'),
|
||||||
|
orElse: () => 'Autre'
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
_boboNature = 'Autre';
|
||||||
|
}
|
||||||
|
_boboDescriptionController.text = p['description']?.toString() ?? '';
|
||||||
|
} else if (_sousTypeCode == 'medicament') {
|
||||||
|
_medicamentNomController.text = p['medicament_nom']?.toString() ?? '';
|
||||||
|
_medicamentContexteController.text = p['contexte']?.toString() ?? '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_temperatureController.dispose();
|
||||||
|
_medicamentDonneController.dispose();
|
||||||
|
_boboDescriptionController.dispose();
|
||||||
|
_medicamentNomController.dispose();
|
||||||
|
_medicamentContexteController.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _loadTypes() async {
|
||||||
|
setState(() {
|
||||||
|
_loadingTypes = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final types = await CardsService.listerTypes();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_types = types;
|
||||||
|
_selected = types.isNotEmpty ? types.first : null;
|
||||||
|
_sousTypeCode = null;
|
||||||
|
_loadingTypes = false;
|
||||||
|
if (types.isEmpty) {
|
||||||
|
_error = 'Aucun type de carte disponible pour votre rôle.';
|
||||||
|
} else {
|
||||||
|
_prefillIfEdit(types);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_loadingTypes = false;
|
||||||
|
_error = e.toString().replaceFirst('Exception: ', '');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _fmtIso(DateTime d) {
|
||||||
|
final y = d.year.toString().padLeft(4, '0');
|
||||||
|
final m = d.month.toString().padLeft(2, '0');
|
||||||
|
final day = d.day.toString().padLeft(2, '0');
|
||||||
|
return '$y-$m-$day';
|
||||||
|
}
|
||||||
|
|
||||||
|
String _fmtUi(DateTime d) {
|
||||||
|
final day = d.day.toString().padLeft(2, '0');
|
||||||
|
final m = d.month.toString().padLeft(2, '0');
|
||||||
|
return '$day/$m/${d.year}';
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickTime() async {
|
||||||
|
final picked = await showTimePicker(
|
||||||
|
context: context,
|
||||||
|
initialTime: _heureReleve,
|
||||||
|
builder: (context, child) {
|
||||||
|
return MediaQuery(
|
||||||
|
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
|
||||||
|
child: child ?? const SizedBox(),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (picked != null && mounted) {
|
||||||
|
setState(() => _heureReleve = picked);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickSingleDay() async {
|
||||||
|
final picked = await showDatePicker(
|
||||||
|
context: context,
|
||||||
|
useRootNavigator: true,
|
||||||
|
initialDate: _dateDebut,
|
||||||
|
firstDate: DateTime(2020),
|
||||||
|
lastDate: DateTime(2040),
|
||||||
|
helpText: 'Date',
|
||||||
|
cancelText: 'Annuler',
|
||||||
|
confirmText: 'Valider',
|
||||||
|
);
|
||||||
|
if (picked == null || !mounted) return;
|
||||||
|
final day = DateTime(picked.year, picked.month, picked.day);
|
||||||
|
setState(() {
|
||||||
|
_dateDebut = day;
|
||||||
|
_dateFin = day;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Plage Material (jours surlignés), en boîte compacte — pas plein écran.
|
||||||
|
/// Astuce : le mode calendrier de [DateRangePickerDialog] prend
|
||||||
|
/// `MediaQuery.size` comme taille de dialog ; on la bride.
|
||||||
|
Future<void> _pickDateRange() async {
|
||||||
|
final initialEnd =
|
||||||
|
_dateFin.isBefore(_dateDebut) ? _dateDebut : _dateFin;
|
||||||
|
final picked = await showDialog<DateTimeRange>(
|
||||||
|
context: context,
|
||||||
|
useRootNavigator: true,
|
||||||
|
barrierDismissible: true,
|
||||||
|
builder: (dialogContext) {
|
||||||
|
final base = MediaQuery.of(dialogContext);
|
||||||
|
final theme = Theme.of(dialogContext);
|
||||||
|
return MediaQuery(
|
||||||
|
data: base.copyWith(size: const Size(420, 560)),
|
||||||
|
child: Theme(
|
||||||
|
data: theme.copyWith(
|
||||||
|
datePickerTheme: theme.datePickerTheme.copyWith(
|
||||||
|
rangePickerShape: RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.circular(20),
|
||||||
|
),
|
||||||
|
shape: RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.circular(20),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
dialogTheme: theme.dialogTheme.copyWith(
|
||||||
|
shape: RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.circular(20),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: DateRangePickerDialog(
|
||||||
|
initialDateRange: DateTimeRange(
|
||||||
|
start: _dateDebut,
|
||||||
|
end: initialEnd,
|
||||||
|
),
|
||||||
|
firstDate: DateTime(2020),
|
||||||
|
lastDate: DateTime(2040),
|
||||||
|
currentDate: DateTime.now(),
|
||||||
|
helpText: 'Début, puis fin (même jour : 2×)',
|
||||||
|
saveText: 'Valider',
|
||||||
|
cancelText: 'Annuler',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (picked == null || !mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_dateDebut = DateTime(
|
||||||
|
picked.start.year,
|
||||||
|
picked.start.month,
|
||||||
|
picked.start.day,
|
||||||
|
);
|
||||||
|
_dateFin = DateTime(
|
||||||
|
picked.end.year,
|
||||||
|
picked.end.month,
|
||||||
|
picked.end.day,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _sousTypeLabel() {
|
||||||
|
final sous = _sousTypeCode;
|
||||||
|
if (sous == null) return null;
|
||||||
|
for (final s in _ui.sousTypes) {
|
||||||
|
if (s.code == sous) return s.label;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// V1 : pas de texte libre pour le motif si la logique change.
|
||||||
|
/// (On retire `motifOptionnel` car le backend va dériver du payload).
|
||||||
|
Map<String, dynamic>? _buildPayload() {
|
||||||
|
if (_selected?.code != 'soin_enfant') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final base = <String, dynamic>{
|
||||||
|
'sous_type': _sousTypeCode,
|
||||||
|
'heure_releve':
|
||||||
|
'${_heureReleve.hour.toString().padLeft(2, '0')}:${_heureReleve.minute.toString().padLeft(2, '0')}',
|
||||||
|
};
|
||||||
|
|
||||||
|
if (_sousTypeCode == 'fievre') {
|
||||||
|
final t = _temperatureController.text.trim().replaceAll(',', '.');
|
||||||
|
if (t.isNotEmpty) {
|
||||||
|
base['temperature_c'] = double.tryParse(t);
|
||||||
|
}
|
||||||
|
base['medicament_donne'] = _medicamentDonneController.text.trim();
|
||||||
|
} else if (_sousTypeCode == 'bobo') {
|
||||||
|
// Normaliser l'enregistrement pour le back :
|
||||||
|
final nature = _boboNature?.toLowerCase().replaceAll('é', 'e').replaceAll('û', 'u') ?? 'autre';
|
||||||
|
base['bobo_nature'] = nature;
|
||||||
|
base['description'] = _boboDescriptionController.text.trim();
|
||||||
|
} else if (_sousTypeCode == 'medicament') {
|
||||||
|
base['medicament_nom'] = _medicamentNomController.text.trim();
|
||||||
|
base['contexte'] = _medicamentContexteController.text.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _submit() async {
|
||||||
|
if (_selected == null) return;
|
||||||
|
|
||||||
|
// Validations locales spécifiques soins
|
||||||
|
if (_selected?.code == 'soin_enfant') {
|
||||||
|
if (_sousTypeCode == null) {
|
||||||
|
setState(() => _error = 'Veuillez choisir un sous-type.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (_sousTypeCode == 'fievre') {
|
||||||
|
final t = _temperatureController.text.trim().replaceAll(',', '.');
|
||||||
|
if (t.isNotEmpty && double.tryParse(t) == null) {
|
||||||
|
setState(() => _error = 'La température est invalide.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else if (_sousTypeCode == 'bobo' && _boboNature == null) {
|
||||||
|
setState(() => _error = 'Veuillez indiquer la nature du bobo.');
|
||||||
|
return;
|
||||||
|
} else if (_sousTypeCode == 'medicament' &&
|
||||||
|
_medicamentNomController.text.trim().isEmpty) {
|
||||||
|
setState(() => _error = 'Le nom du médicament est obligatoire.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_dateFin.isBefore(_dateDebut)) {
|
||||||
|
setState(() => _error = 'La date de fin doit être après la date de début.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setState(() {
|
||||||
|
_submitting = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final payload = _buildPayload();
|
||||||
|
|
||||||
|
final dynamic created;
|
||||||
|
if (widget.carteToEdit != null) {
|
||||||
|
created = await CardsService.maj(
|
||||||
|
cardId: widget.carteToEdit!.id,
|
||||||
|
dateDebut: _fmtIso(_dateDebut),
|
||||||
|
dateFin: _fmtIso(
|
||||||
|
_ui.periodeMode == CartePeriodeMode.singleDay
|
||||||
|
? _dateDebut
|
||||||
|
: _dateFin,
|
||||||
|
),
|
||||||
|
motif: _selected?.code == 'soin_enfant' ? null : _motifController.text.trim(),
|
||||||
|
payload: payload,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
created = await CardsService.creer(
|
||||||
|
typeCode: _selected!.code,
|
||||||
|
idPlacement: widget.placementId,
|
||||||
|
dateDebut: _fmtIso(_dateDebut),
|
||||||
|
dateFin: _fmtIso(
|
||||||
|
_ui.periodeMode == CartePeriodeMode.singleDay
|
||||||
|
? _dateDebut
|
||||||
|
: _dateFin,
|
||||||
|
),
|
||||||
|
motif: _selected?.code == 'soin_enfant' ? null : _motifController.text.trim(),
|
||||||
|
payload: payload,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mounted) return;
|
||||||
|
Navigator.of(context).pop(created);
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_submitting = false;
|
||||||
|
_error = e.toString().replaceFirst('Exception: ', '');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return AlertDialog(
|
||||||
|
title: Text(
|
||||||
|
'Ajouter une carte',
|
||||||
|
style: GoogleFonts.merienda(fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
content: SizedBox(
|
||||||
|
width: 420,
|
||||||
|
child: _loadingTypes
|
||||||
|
? const Padding(
|
||||||
|
padding: EdgeInsets.symmetric(vertical: 24),
|
||||||
|
child: Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 28,
|
||||||
|
height: 28,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: SingleChildScrollView(
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
if (_error != null) ...[
|
||||||
|
Text(
|
||||||
|
_error!,
|
||||||
|
style: GoogleFonts.merriweather(
|
||||||
|
fontSize: 13,
|
||||||
|
color: Theme.of(context).colorScheme.error,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
],
|
||||||
|
_buildTypeSelector(),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
if (_ui.periodeMode == CartePeriodeMode.singleDay)
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: _DateField(
|
||||||
|
label: 'Date',
|
||||||
|
value: _fmtUi(_dateDebut),
|
||||||
|
onTap: _submitting ? null : _pickSingleDay,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (_selected?.code == 'soin_enfant') ...[
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: _DateField(
|
||||||
|
label: 'Heure',
|
||||||
|
value: _heureReleve.format(context),
|
||||||
|
icon: Icons.access_time,
|
||||||
|
onTap: _submitting ? null : _pickTime,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
else
|
||||||
|
_DateField(
|
||||||
|
label: 'Période',
|
||||||
|
value: _dateDebut == _dateFin
|
||||||
|
? _fmtUi(_dateDebut)
|
||||||
|
: '${_fmtUi(_dateDebut)} → ${_fmtUi(_dateFin)}',
|
||||||
|
onTap: _submitting ? null : _pickDateRange,
|
||||||
|
),
|
||||||
|
if (_ui.sousTypes.isNotEmpty) ...[
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
Text(
|
||||||
|
'Sous-type',
|
||||||
|
style: GoogleFonts.merriweather(
|
||||||
|
fontSize: 13,
|
||||||
|
color: QuotidienTheme.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 8,
|
||||||
|
children: [
|
||||||
|
for (final s in _ui.sousTypes)
|
||||||
|
ChoiceChip(
|
||||||
|
label: Text(s.label),
|
||||||
|
selected: _sousTypeCode == s.code,
|
||||||
|
onSelected: _submitting
|
||||||
|
? null
|
||||||
|
: (sel) {
|
||||||
|
setState(() {
|
||||||
|
_sousTypeCode = sel ? s.code : null;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
if (_selected?.code == 'soin_enfant') _buildSoinForm(),
|
||||||
|
if (_selected?.code != 'soin_enfant') ...[
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
TextFormField(
|
||||||
|
controller: _motifController,
|
||||||
|
enabled: !_submitting,
|
||||||
|
maxLines: 3,
|
||||||
|
decoration: InputDecoration(
|
||||||
|
labelText: _ui.motifRequired ? 'Motif *' : 'Motif',
|
||||||
|
hintText: _ui.motifHint,
|
||||||
|
border: const OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
validator: (v) {
|
||||||
|
if (!_ui.motifRequired) return null;
|
||||||
|
final text = v?.trim() ?? '';
|
||||||
|
if (text.isEmpty) return 'Motif obligatoire';
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: _submitting ? null : () => Navigator.pop(context),
|
||||||
|
child: const Text('Annuler'),
|
||||||
|
),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: (_submitting ||
|
||||||
|
_loadingTypes ||
|
||||||
|
_selected == null ||
|
||||||
|
_types.isEmpty)
|
||||||
|
? null
|
||||||
|
: _submit,
|
||||||
|
child: _submitting
|
||||||
|
? const SizedBox(
|
||||||
|
width: 18,
|
||||||
|
height: 18,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
)
|
||||||
|
: const Text('Envoyer'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildTypeSelector() {
|
||||||
|
if (_types.isEmpty) {
|
||||||
|
return Text(
|
||||||
|
'Aucun type disponible.',
|
||||||
|
style: GoogleFonts.merriweather(fontSize: 13),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (_types.length == 1) {
|
||||||
|
return Text(
|
||||||
|
_types.first.label,
|
||||||
|
style: GoogleFonts.merienda(
|
||||||
|
fontSize: 16,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: QuotidienTheme.ink,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return DropdownButtonFormField<String>(
|
||||||
|
value: _selected?.code,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Type de carte',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
items: [
|
||||||
|
for (final t in _types)
|
||||||
|
DropdownMenuItem(value: t.code, child: Text(t.label)),
|
||||||
|
],
|
||||||
|
onChanged: _submitting
|
||||||
|
? null
|
||||||
|
: (code) {
|
||||||
|
if (code == null) return;
|
||||||
|
CarteTypeEmissible? next;
|
||||||
|
for (final t in _types) {
|
||||||
|
if (t.code == code) {
|
||||||
|
next = t;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (next == null) return;
|
||||||
|
setState(() {
|
||||||
|
_selected = next;
|
||||||
|
_sousTypeCode = null;
|
||||||
|
if (next!.ui.periodeMode == CartePeriodeMode.singleDay) {
|
||||||
|
_dateFin = _dateDebut;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Widget _buildSoinForm() {
|
||||||
|
if (_sousTypeCode == null) return const SizedBox.shrink();
|
||||||
|
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
if (_sousTypeCode == 'fievre') ...[
|
||||||
|
TextFormField(
|
||||||
|
controller: _temperatureController,
|
||||||
|
enabled: !_submitting,
|
||||||
|
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Température (°C) *',
|
||||||
|
hintText: 'ex: 38.5',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
TextFormField(
|
||||||
|
controller: _medicamentDonneController,
|
||||||
|
enabled: !_submitting,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Médicament donné (optionnel)',
|
||||||
|
hintText: 'ex: Doliprane 2.4kg',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
] else if (_sousTypeCode == 'bobo') ...[
|
||||||
|
DropdownButtonFormField<String>(
|
||||||
|
value: _boboNature,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Nature du bobo *',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
items: const [
|
||||||
|
DropdownMenuItem(value: 'Chute', child: Text('Chute')),
|
||||||
|
DropdownMenuItem(value: 'Égratignure', child: Text('Égratignure')),
|
||||||
|
DropdownMenuItem(value: 'Coup', child: Text('Coup')),
|
||||||
|
DropdownMenuItem(value: 'Piqûre', child: Text('Piqûre')),
|
||||||
|
DropdownMenuItem(value: 'Brûlure', child: Text('Brûlure')),
|
||||||
|
DropdownMenuItem(value: 'Autre', child: Text('Autre')),
|
||||||
|
],
|
||||||
|
onChanged: _submitting
|
||||||
|
? null
|
||||||
|
: (val) {
|
||||||
|
setState(() {
|
||||||
|
_boboNature = val;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
TextFormField(
|
||||||
|
controller: _boboDescriptionController,
|
||||||
|
enabled: !_submitting,
|
||||||
|
maxLines: 2,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Description / Zone touchée *',
|
||||||
|
hintText: 'ex: Égratignure sur le genou droit',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
] else if (_sousTypeCode == 'medicament') ...[
|
||||||
|
TextFormField(
|
||||||
|
controller: _medicamentNomController,
|
||||||
|
enabled: !_submitting,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Nom du médicament *',
|
||||||
|
hintText: 'ex: Ventoline',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
TextFormField(
|
||||||
|
controller: _medicamentContexteController,
|
||||||
|
enabled: !_submitting,
|
||||||
|
maxLines: 2,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'Contexte / Posologie (optionnel)',
|
||||||
|
hintText: 'ex: 2 bouffées suite à une quinte de toux',
|
||||||
|
border: OutlineInputBorder(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DateField extends StatelessWidget {
|
||||||
|
final String label;
|
||||||
|
final String value;
|
||||||
|
final VoidCallback? onTap;
|
||||||
|
final IconData icon;
|
||||||
|
|
||||||
|
const _DateField({
|
||||||
|
required this.label,
|
||||||
|
required this.value,
|
||||||
|
required this.onTap,
|
||||||
|
this.icon = Icons.calendar_today_outlined,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return InkWell(
|
||||||
|
onTap: onTap,
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
child: InputDecorator(
|
||||||
|
decoration: InputDecoration(
|
||||||
|
labelText: label,
|
||||||
|
border: const OutlineInputBorder(),
|
||||||
|
suffixIcon: Icon(icon, size: 18),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
value,
|
||||||
|
style: GoogleFonts.merriweather(fontSize: 14),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,12 +8,12 @@ import 'package:p_tits_pas/widgets/quotidien/quotidien_theme.dart';
|
|||||||
|
|
||||||
/// Rôle qui consulte le bandeau : côté parent (enfant | nounou) ou côté AM
|
/// Rôle qui consulte le bandeau : côté parent (enfant | nounou) ou côté AM
|
||||||
/// (enfant | parent(s)). Le composant est le même, seule la lecture change.
|
/// (enfant | parent(s)). Le composant est le même, seule la lecture change.
|
||||||
/// Ticket #167 (parent) ; #170 réutilise en mode AM.
|
/// Ticket #167 (parent) ; #170 (AM) ; #211 (compact dans le bandeau haut).
|
||||||
enum CoupleBandeauMode { parent, assistanteMaternelle }
|
enum CoupleBandeauMode { parent, assistanteMaternelle }
|
||||||
|
|
||||||
/// Bandeau « couple de garde » en haut de la colonne gauche du TdB.
|
/// Sélecteur « couple de garde » compact dans le bandeau haut (#211).
|
||||||
///
|
///
|
||||||
/// - Plusieurs couples → contrôle unique avec chevron (dropdown de bascule).
|
/// - Plusieurs couples → contrôle unique avec chevron (menu de bascule).
|
||||||
/// - Un seul couple → affichage informatif (pas de chevron, pas de menu).
|
/// - Un seul couple → affichage informatif (pas de chevron, pas de menu).
|
||||||
/// - Aucun couple → état vide discret.
|
/// - Aucun couple → état vide discret.
|
||||||
class CoupleSelectorBandeau extends StatelessWidget {
|
class CoupleSelectorBandeau extends StatelessWidget {
|
||||||
@@ -25,6 +25,9 @@ class CoupleSelectorBandeau extends StatelessWidget {
|
|||||||
final String? errorMessage;
|
final String? errorMessage;
|
||||||
final VoidCallback? onRetry;
|
final VoidCallback? onRetry;
|
||||||
|
|
||||||
|
static const double height = 40;
|
||||||
|
static const double avatarSize = 28;
|
||||||
|
|
||||||
const CoupleSelectorBandeau({
|
const CoupleSelectorBandeau({
|
||||||
super.key,
|
super.key,
|
||||||
this.mode = CoupleBandeauMode.parent,
|
this.mode = CoupleBandeauMode.parent,
|
||||||
@@ -38,7 +41,7 @@ class CoupleSelectorBandeau extends StatelessWidget {
|
|||||||
|
|
||||||
CoupleGarde? get _selected {
|
CoupleGarde? get _selected {
|
||||||
if (couples.isEmpty) return null;
|
if (couples.isEmpty) return null;
|
||||||
if (selectedCoupleId != null) {
|
if (selectedCoupleId != null) {
|
||||||
for (final c in couples) {
|
for (final c in couples) {
|
||||||
if (c.id == selectedCoupleId) return c;
|
if (c.id == selectedCoupleId) return c;
|
||||||
}
|
}
|
||||||
@@ -79,11 +82,12 @@ class CoupleSelectorBandeau extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
child: PopupMenuButton<String>(
|
child: PopupMenuButton<String>(
|
||||||
tooltip: 'Changer de garde',
|
tooltip: 'Changer de garde',
|
||||||
// L'offset doit être suffisant pour descendre sous la carte (qui fait 90px).
|
offset: const Offset(0, height + 6),
|
||||||
offset: const Offset(0, 95),
|
color: Colors.transparent,
|
||||||
color: Colors.transparent, // Le fond devient invisible
|
elevation: 0,
|
||||||
elevation: 0, // Pas d'ombre carrée
|
constraints: BoxConstraints.tightFor(
|
||||||
constraints: BoxConstraints.tightFor(width: constraints.maxWidth),
|
width: constraints.maxWidth.clamp(180, 320),
|
||||||
|
),
|
||||||
padding: EdgeInsets.zero,
|
padding: EdgeInsets.zero,
|
||||||
onSelected: (id) {
|
onSelected: (id) {
|
||||||
final chosen = couples.firstWhere((c) => c.id == id);
|
final chosen = couples.firstWhere((c) => c.id == id);
|
||||||
@@ -95,15 +99,14 @@ class CoupleSelectorBandeau extends StatelessWidget {
|
|||||||
PopupMenuItem<String>(
|
PopupMenuItem<String>(
|
||||||
value: c.id,
|
value: c.id,
|
||||||
padding: EdgeInsets.zero,
|
padding: EdgeInsets.zero,
|
||||||
height: 100, // Hauteur de la carte (90) + un peu de marge (10)
|
height: height + 8,
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.only(bottom: 10),
|
padding: const EdgeInsets.only(bottom: 6),
|
||||||
child: _CoupleCard(
|
child: _CoupleCard(
|
||||||
mode: mode,
|
mode: mode,
|
||||||
couple: c,
|
couple: c,
|
||||||
showChevron: false,
|
showChevron: false,
|
||||||
selected: false,
|
selected: false,
|
||||||
isMenuItem: true,
|
|
||||||
colorIndex: couples.indexOf(c),
|
colorIndex: couples.indexOf(c),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -116,13 +119,12 @@ class CoupleSelectorBandeau extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Carte principale : enfant à gauche, séparateur, AM/parents à droite.
|
/// Carte compacte : enfant | AM/parents (+ chevron si multi).
|
||||||
class _CoupleCard extends StatelessWidget {
|
class _CoupleCard extends StatelessWidget {
|
||||||
final CoupleBandeauMode mode;
|
final CoupleBandeauMode mode;
|
||||||
final CoupleGarde couple;
|
final CoupleGarde couple;
|
||||||
final bool showChevron;
|
final bool showChevron;
|
||||||
final bool selected;
|
final bool selected;
|
||||||
final bool isMenuItem;
|
|
||||||
final int colorIndex;
|
final int colorIndex;
|
||||||
|
|
||||||
const _CoupleCard({
|
const _CoupleCard({
|
||||||
@@ -130,11 +132,9 @@ class _CoupleCard extends StatelessWidget {
|
|||||||
required this.couple,
|
required this.couple,
|
||||||
required this.showChevron,
|
required this.showChevron,
|
||||||
this.selected = true,
|
this.selected = true,
|
||||||
this.isMenuItem = false,
|
|
||||||
required this.colorIndex,
|
required this.colorIndex,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Libellé parents côté AM : « Sophie » ou « Thomas et Claire ».
|
|
||||||
static String _parentsLabel(List<CoupleMembre> parents) {
|
static String _parentsLabel(List<CoupleMembre> parents) {
|
||||||
if (parents.isEmpty) return 'Parents';
|
if (parents.isEmpty) return 'Parents';
|
||||||
String prenomOf(CoupleMembre p) {
|
String prenomOf(CoupleMembre p) {
|
||||||
@@ -142,20 +142,18 @@ class _CoupleCard extends StatelessWidget {
|
|||||||
if (prenom.isNotEmpty) return prenom;
|
if (prenom.isNotEmpty) return prenom;
|
||||||
return p.displayName(fallback: 'Parent');
|
return p.displayName(fallback: 'Parent');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (parents.length == 1) return prenomOf(parents.first);
|
if (parents.length == 1) return prenomOf(parents.first);
|
||||||
return '${prenomOf(parents[0])} et ${prenomOf(parents[1])}';
|
return '${prenomOf(parents[0])} et ${prenomOf(parents[1])}';
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
// Parent mode: enfant | AM (photo + prénom)
|
|
||||||
// AM mode: enfant | parent(s) — texte seul, pas de vignette parent
|
|
||||||
final isParentMode = mode == CoupleBandeauMode.parent;
|
final isParentMode = mode == CoupleBandeauMode.parent;
|
||||||
|
|
||||||
Widget amOrParentsWidget;
|
final Widget right;
|
||||||
|
|
||||||
if (isParentMode) {
|
if (isParentMode) {
|
||||||
amOrParentsWidget = _MembreTile(
|
right = _MembreTile(
|
||||||
photoUrl: couple.am?.photoUrl,
|
photoUrl: couple.am?.photoUrl,
|
||||||
name: (couple.am?.prenom != null && couple.am!.prenom!.isNotEmpty)
|
name: (couple.am?.prenom != null && couple.am!.prenom!.isNotEmpty)
|
||||||
? couple.am!.prenom!
|
? couple.am!.prenom!
|
||||||
@@ -163,28 +161,28 @@ class _CoupleCard extends StatelessWidget {
|
|||||||
fallbackIcon: Icons.volunteer_activism,
|
fallbackIcon: Icons.volunteer_activism,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
amOrParentsWidget = Text(
|
right = Text(
|
||||||
_parentsLabel(couple.parents),
|
_parentsLabel(couple.parents),
|
||||||
maxLines: 1,
|
maxLines: 1,
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
style: GoogleFonts.merienda(
|
style: GoogleFonts.merienda(
|
||||||
fontSize: 22,
|
fontSize: 13,
|
||||||
fontWeight: FontWeight.bold,
|
fontWeight: FontWeight.w600,
|
||||||
color: QuotidienTheme.ink,
|
color: QuotidienTheme.ink,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Carte.bandeau(
|
return Opacity(
|
||||||
assetPath: QuotidienTheme
|
opacity: selected ? 1 : 0.92,
|
||||||
.bandeauColors[colorIndex % QuotidienTheme.bandeauColors.length],
|
child: Carte.bandeau(
|
||||||
height: 90,
|
assetPath: QuotidienTheme
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
.bandeauColors[colorIndex % QuotidienTheme.bandeauColors.length],
|
||||||
child: Row(
|
height: CoupleSelectorBandeau.height,
|
||||||
children: [
|
padding: const EdgeInsets.symmetric(horizontal: 10),
|
||||||
Expanded(
|
child: Row(
|
||||||
child: Padding(
|
children: [
|
||||||
padding: const EdgeInsets.only(right: 12),
|
Expanded(
|
||||||
child: _MembreTile(
|
child: _MembreTile(
|
||||||
photoUrl: couple.enfant.photoUrl,
|
photoUrl: couple.enfant.photoUrl,
|
||||||
name: (couple.enfant.prenom != null &&
|
name: (couple.enfant.prenom != null &&
|
||||||
@@ -194,39 +192,34 @@ class _CoupleCard extends StatelessWidget {
|
|||||||
fallbackIcon: Icons.child_care,
|
fallbackIcon: Icons.child_care,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
Container(
|
||||||
Container(
|
width: 5,
|
||||||
width: 8,
|
height: 22,
|
||||||
height: 44,
|
margin: const EdgeInsets.symmetric(horizontal: 4),
|
||||||
decoration: const BoxDecoration(
|
decoration: const BoxDecoration(
|
||||||
image: DecorationImage(
|
image: DecorationImage(
|
||||||
image: AssetImage(QuotidienTheme.pencilLineVerticalAsset),
|
image: AssetImage(QuotidienTheme.pencilLineVerticalAsset),
|
||||||
fit: BoxFit.contain,
|
fit: BoxFit.contain,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
Expanded(child: right),
|
||||||
Expanded(
|
if (showChevron)
|
||||||
child: Padding(
|
const Icon(
|
||||||
padding: const EdgeInsets.only(left: 12),
|
Icons.keyboard_arrow_down,
|
||||||
child: amOrParentsWidget,
|
size: 18,
|
||||||
),
|
color: QuotidienTheme.ink,
|
||||||
),
|
)
|
||||||
SizedBox(
|
else
|
||||||
width: 28,
|
const SizedBox(width: 4),
|
||||||
child: showChevron
|
],
|
||||||
? const Icon(
|
),
|
||||||
Icons.keyboard_arrow_down,
|
|
||||||
color: QuotidienTheme.ink,
|
|
||||||
)
|
|
||||||
: null,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Photo ronde + nom (une moitié du couple).
|
/// Photo ronde + prénom (une moitié du couple).
|
||||||
class _MembreTile extends StatelessWidget {
|
class _MembreTile extends StatelessWidget {
|
||||||
final String? photoUrl;
|
final String? photoUrl;
|
||||||
final String name;
|
final String name;
|
||||||
@@ -242,16 +235,20 @@ class _MembreTile extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Row(
|
return Row(
|
||||||
children: [
|
children: [
|
||||||
_Avatar(photoUrl: photoUrl, fallbackIcon: fallbackIcon, size: 64),
|
_Avatar(
|
||||||
const SizedBox(width: 12),
|
photoUrl: photoUrl,
|
||||||
|
fallbackIcon: fallbackIcon,
|
||||||
|
size: CoupleSelectorBandeau.avatarSize,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 6),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Text(
|
child: Text(
|
||||||
name,
|
name,
|
||||||
maxLines: 1,
|
maxLines: 1,
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
style: GoogleFonts.merienda(
|
style: GoogleFonts.merienda(
|
||||||
fontSize: 22,
|
fontSize: 13,
|
||||||
fontWeight: FontWeight.bold,
|
fontWeight: FontWeight.w600,
|
||||||
color: QuotidienTheme.ink,
|
color: QuotidienTheme.ink,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -279,7 +276,7 @@ class _Avatar extends StatelessWidget {
|
|||||||
width: size,
|
width: size,
|
||||||
height: size,
|
height: size,
|
||||||
color: QuotidienTheme.lavender.withValues(alpha: 0.35),
|
color: QuotidienTheme.lavender.withValues(alpha: 0.35),
|
||||||
child: Icon(fallbackIcon, size: size * 0.5, color: QuotidienTheme.ink),
|
child: Icon(fallbackIcon, size: size * 0.55, color: QuotidienTheme.ink),
|
||||||
);
|
);
|
||||||
return ClipOval(
|
return ClipOval(
|
||||||
child: SizedBox(
|
child: SizedBox(
|
||||||
@@ -311,11 +308,11 @@ class _CoupleBandeauSkeleton extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
child: Carte.bandeau(
|
child: Carte.bandeau(
|
||||||
assetPath: QuotidienTheme.bandeauLime,
|
assetPath: QuotidienTheme.bandeauLime,
|
||||||
height: 90,
|
height: CoupleSelectorBandeau.height,
|
||||||
child: const Center(
|
child: const Center(
|
||||||
child: SizedBox(
|
child: SizedBox(
|
||||||
width: 26,
|
width: 18,
|
||||||
height: 26,
|
height: 18,
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -331,17 +328,19 @@ class _CoupleBandeauEmpty extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Carte.bandeau(
|
return Carte.bandeau(
|
||||||
assetPath: QuotidienTheme.bandeauLime,
|
assetPath: QuotidienTheme.bandeauLime,
|
||||||
height: 90,
|
height: CoupleSelectorBandeau.height,
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
padding: const EdgeInsets.symmetric(horizontal: 10),
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
const Icon(Icons.info_outline, color: QuotidienTheme.muted),
|
const Icon(Icons.info_outline, size: 18, color: QuotidienTheme.muted),
|
||||||
const SizedBox(width: 12),
|
const SizedBox(width: 8),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Text(
|
child: Text(
|
||||||
'Aucune garde active pour le moment.',
|
'Aucune garde active',
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
style: GoogleFonts.merriweather(
|
style: GoogleFonts.merriweather(
|
||||||
fontSize: 14,
|
fontSize: 12,
|
||||||
color: QuotidienTheme.muted,
|
color: QuotidienTheme.muted,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -367,25 +366,30 @@ class _CoupleBandeauError extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
child: Carte.bandeau(
|
child: Carte.bandeau(
|
||||||
assetPath: QuotidienTheme.bandeauLime,
|
assetPath: QuotidienTheme.bandeauLime,
|
||||||
height: 90,
|
height: CoupleSelectorBandeau.height,
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
const Icon(Icons.error_outline, color: QuotidienTheme.ink),
|
const Icon(Icons.error_outline, size: 18, color: QuotidienTheme.ink),
|
||||||
const SizedBox(width: 12),
|
const SizedBox(width: 6),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Text(
|
child: Text(
|
||||||
message,
|
message,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
style: GoogleFonts.merriweather(
|
style: GoogleFonts.merriweather(
|
||||||
fontSize: 13,
|
fontSize: 11,
|
||||||
color: QuotidienTheme.ink,
|
color: QuotidienTheme.ink,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (onRetry != null)
|
if (onRetry != null)
|
||||||
TextButton(
|
IconButton(
|
||||||
onPressed: onRetry,
|
onPressed: onRetry,
|
||||||
child: const Text('Réessayer'),
|
icon: const Icon(Icons.refresh, size: 18),
|
||||||
|
tooltip: 'Réessayer',
|
||||||
|
padding: EdgeInsets.zero,
|
||||||
|
constraints: const BoxConstraints(minWidth: 28, minHeight: 28),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -5,25 +5,31 @@ import 'package:p_tits_pas/services/auth_service.dart';
|
|||||||
import 'package:p_tits_pas/widgets/image_button.dart';
|
import 'package:p_tits_pas/widgets/image_button.dart';
|
||||||
import 'package:p_tits_pas/widgets/quotidien/quotidien_theme.dart';
|
import 'package:p_tits_pas/widgets/quotidien/quotidien_theme.dart';
|
||||||
|
|
||||||
/// Bandeau quotidien pastel : logo · pastilles Cahier de liaison / Agenda /
|
/// Bandeau quotidien pastel : logo · [contexte couple] · pastilles · menu user.
|
||||||
/// Contrat · menu user.
|
/// Réutilisable parent (#166) et AM (#169) ; couple compact (#211).
|
||||||
/// Réutilisable parent (#166) et AM (#169).
|
|
||||||
class QuotidienBandeau extends StatelessWidget {
|
class QuotidienBandeau extends StatelessWidget {
|
||||||
final QuotidienNavSection selectedSection;
|
final QuotidienNavSection selectedSection;
|
||||||
final ValueChanged<QuotidienNavSection> onSectionSelected;
|
final ValueChanged<QuotidienNavSection> onSectionSelected;
|
||||||
final String userDisplayName;
|
final String userDisplayName;
|
||||||
final String? userEmail;
|
final String? userEmail;
|
||||||
|
|
||||||
|
/// Sélecteur de couple compact, juste après le logo (~280 px).
|
||||||
|
final Widget? contextSelector;
|
||||||
|
|
||||||
final VoidCallback? onProfileTap;
|
final VoidCallback? onProfileTap;
|
||||||
final VoidCallback? onSearchAmTap;
|
final VoidCallback? onSearchAmTap;
|
||||||
final VoidCallback? onSettingsTap;
|
final VoidCallback? onSettingsTap;
|
||||||
final VoidCallback? onLogout;
|
final VoidCallback? onLogout;
|
||||||
|
|
||||||
|
static const double contextSelectorMaxWidth = 280;
|
||||||
|
|
||||||
const QuotidienBandeau({
|
const QuotidienBandeau({
|
||||||
super.key,
|
super.key,
|
||||||
required this.selectedSection,
|
required this.selectedSection,
|
||||||
required this.onSectionSelected,
|
required this.onSectionSelected,
|
||||||
required this.userDisplayName,
|
required this.userDisplayName,
|
||||||
this.userEmail,
|
this.userEmail,
|
||||||
|
this.contextSelector,
|
||||||
this.onProfileTap,
|
this.onProfileTap,
|
||||||
this.onSearchAmTap,
|
this.onSearchAmTap,
|
||||||
this.onSettingsTap,
|
this.onSettingsTap,
|
||||||
@@ -32,28 +38,61 @@ class QuotidienBandeau extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
// 3 zones : gauche (logo + couple vers le centre) · pastilles · menu.
|
||||||
|
// Les Expanded gauche/droite équilibrent le centrage des pastilles.
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
|
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
Image.asset(
|
Expanded(
|
||||||
QuotidienTheme.logoAsset,
|
child: Row(
|
||||||
height: 44,
|
children: [
|
||||||
fit: BoxFit.contain,
|
Image.asset(
|
||||||
|
QuotidienTheme.logoAsset,
|
||||||
|
height: 44,
|
||||||
|
fit: BoxFit.contain,
|
||||||
|
),
|
||||||
|
if (contextSelector != null) ...[
|
||||||
|
const SizedBox(width: 16),
|
||||||
|
Flexible(
|
||||||
|
child: Align(
|
||||||
|
// Pousse le couple vers le centre du bandeau.
|
||||||
|
alignment: Alignment.centerRight,
|
||||||
|
child: ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(
|
||||||
|
maxWidth: contextSelectorMaxWidth,
|
||||||
|
),
|
||||||
|
child: contextSelector!,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const Spacer(),
|
const SizedBox(width: 8),
|
||||||
_NavPills(
|
Flexible(
|
||||||
selected: selectedSection,
|
flex: 2,
|
||||||
onSelected: onSectionSelected,
|
child: Center(
|
||||||
|
child: _NavPills(
|
||||||
|
selected: selectedSection,
|
||||||
|
onSelected: onSectionSelected,
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const Spacer(),
|
const SizedBox(width: 8),
|
||||||
_UserMenu(
|
Expanded(
|
||||||
displayName: userDisplayName,
|
child: Align(
|
||||||
email: userEmail,
|
alignment: Alignment.centerRight,
|
||||||
onProfileTap: onProfileTap,
|
child: _UserMenu(
|
||||||
onSearchAmTap: onSearchAmTap,
|
displayName: userDisplayName,
|
||||||
onSettingsTap: onSettingsTap,
|
email: userEmail,
|
||||||
onLogout: onLogout,
|
onProfileTap: onProfileTap,
|
||||||
|
onSearchAmTap: onSearchAmTap,
|
||||||
|
onSettingsTap: onSettingsTap,
|
||||||
|
onLogout: onLogout,
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -70,51 +109,78 @@ class _NavPills extends StatelessWidget {
|
|||||||
required this.onSelected,
|
required this.onSelected,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
static const double _pillHeight = 46;
|
||||||
|
static const double _gap = 10;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Row(
|
return LayoutBuilder(
|
||||||
mainAxisSize: MainAxisSize.min,
|
builder: (context, constraints) {
|
||||||
children: [
|
final naturalW = _pillHeight * QuotidienTheme.pillAspectRatio;
|
||||||
_pill(
|
final naturalTotal = 3 * naturalW + 2 * _gap;
|
||||||
label: 'Cahier de liaison',
|
final maxW = constraints.maxWidth;
|
||||||
section: QuotidienNavSection.liaison,
|
// Réduit proportionnellement si la fenêtre est trop étroite
|
||||||
),
|
// (évite l’overflow jaune/noir sur les pastilles).
|
||||||
const SizedBox(width: 10),
|
final scale = maxW.isFinite && maxW > 0 && maxW < naturalTotal
|
||||||
_pill(
|
? (maxW / naturalTotal).clamp(0.55, 1.0)
|
||||||
label: 'Agenda',
|
: 1.0;
|
||||||
section: QuotidienNavSection.agenda,
|
final h = _pillHeight * scale;
|
||||||
),
|
final w = naturalW * scale;
|
||||||
const SizedBox(width: 10),
|
final g = _gap * scale;
|
||||||
_pill(
|
final fontSize = (14 * scale).clamp(10.0, 14.0);
|
||||||
label: 'Contrat',
|
|
||||||
section: QuotidienNavSection.contrat,
|
return Row(
|
||||||
),
|
mainAxisSize: MainAxisSize.min,
|
||||||
],
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
children: [
|
||||||
|
_pill(
|
||||||
|
label: 'Cahier de liaison',
|
||||||
|
section: QuotidienNavSection.liaison,
|
||||||
|
width: w,
|
||||||
|
height: h,
|
||||||
|
fontSize: fontSize,
|
||||||
|
),
|
||||||
|
SizedBox(width: g),
|
||||||
|
_pill(
|
||||||
|
label: 'Agenda',
|
||||||
|
section: QuotidienNavSection.agenda,
|
||||||
|
width: w,
|
||||||
|
height: h,
|
||||||
|
fontSize: fontSize,
|
||||||
|
),
|
||||||
|
SizedBox(width: g),
|
||||||
|
_pill(
|
||||||
|
label: 'Contrat',
|
||||||
|
section: QuotidienNavSection.contrat,
|
||||||
|
width: w,
|
||||||
|
height: h,
|
||||||
|
fontSize: fontSize,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _pill({
|
Widget _pill({
|
||||||
required String label,
|
required String label,
|
||||||
required QuotidienNavSection section,
|
required QuotidienNavSection section,
|
||||||
|
required double width,
|
||||||
|
required double height,
|
||||||
|
required double fontSize,
|
||||||
}) {
|
}) {
|
||||||
final active = selected == section;
|
final active = selected == section;
|
||||||
// Même famille que l’inscription : fonds « dessinés » (pas Material).
|
|
||||||
// Les deux pastilles ont la même silhouette (ratio ~4:1) : la largeur
|
|
||||||
// est dérivée de la hauteur pour ne jamais déformer le PNG.
|
|
||||||
// Chaque section garde sa couleur ; l'inactive est juste plus claire.
|
|
||||||
return ImageButton(
|
return ImageButton(
|
||||||
bg: QuotidienTheme.pillAssetFor(section),
|
bg: QuotidienTheme.pillAssetFor(section),
|
||||||
bgOpacity: active ? 1.0 : QuotidienTheme.pillInactiveOpacity,
|
bgOpacity: active ? 1.0 : QuotidienTheme.pillInactiveOpacity,
|
||||||
width: _pillHeight * QuotidienTheme.pillAspectRatio,
|
width: width,
|
||||||
height: _pillHeight,
|
height: height,
|
||||||
text: label,
|
text: label,
|
||||||
textColor: QuotidienTheme.ink,
|
textColor: QuotidienTheme.ink,
|
||||||
fontSize: 14,
|
fontSize: fontSize,
|
||||||
onPressed: () => onSelected(section),
|
onPressed: () => onSelected(section),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
static const double _pillHeight = 46;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class _UserMenu extends StatelessWidget {
|
class _UserMenu extends StatelessWidget {
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ class QuotidienShell extends StatelessWidget {
|
|||||||
final VoidCallback? onSettingsTap;
|
final VoidCallback? onSettingsTap;
|
||||||
final VoidCallback? onLogout;
|
final VoidCallback? onLogout;
|
||||||
|
|
||||||
/// Colonne gauche (couple + cartes + actions).
|
/// Colonne gauche (cartes + actions).
|
||||||
final Widget leftColumn;
|
final Widget leftColumn;
|
||||||
|
|
||||||
/// Colonne milieu (blog).
|
/// Colonne milieu (blog).
|
||||||
@@ -25,6 +25,9 @@ class QuotidienShell extends StatelessWidget {
|
|||||||
/// Colonne droite (messagerie).
|
/// Colonne droite (messagerie).
|
||||||
final Widget rightColumn;
|
final Widget rightColumn;
|
||||||
|
|
||||||
|
/// Sélecteur de couple compact dans le bandeau haut (#211).
|
||||||
|
final Widget? contextSelector;
|
||||||
|
|
||||||
/// Corps affiché hors Cahier de liaison (Agenda / Contrat stubs).
|
/// Corps affiché hors Cahier de liaison (Agenda / Contrat stubs).
|
||||||
final Widget? agendaBody;
|
final Widget? agendaBody;
|
||||||
final Widget? contratBody;
|
final Widget? contratBody;
|
||||||
@@ -37,6 +40,7 @@ class QuotidienShell extends StatelessWidget {
|
|||||||
required this.leftColumn,
|
required this.leftColumn,
|
||||||
required this.centerColumn,
|
required this.centerColumn,
|
||||||
required this.rightColumn,
|
required this.rightColumn,
|
||||||
|
this.contextSelector,
|
||||||
this.userEmail,
|
this.userEmail,
|
||||||
this.onProfileTap,
|
this.onProfileTap,
|
||||||
this.onSearchAmTap,
|
this.onSearchAmTap,
|
||||||
@@ -59,6 +63,7 @@ class QuotidienShell extends StatelessWidget {
|
|||||||
onSectionSelected: onSectionSelected,
|
onSectionSelected: onSectionSelected,
|
||||||
userDisplayName: userDisplayName,
|
userDisplayName: userDisplayName,
|
||||||
userEmail: userEmail,
|
userEmail: userEmail,
|
||||||
|
contextSelector: contextSelector,
|
||||||
onProfileTap: onProfileTap,
|
onProfileTap: onProfileTap,
|
||||||
onSearchAmTap: onSearchAmTap,
|
onSearchAmTap: onSearchAmTap,
|
||||||
onSettingsTap: onSettingsTap,
|
onSettingsTap: onSettingsTap,
|
||||||
|
|||||||