Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ea251c305 | ||
|
|
df130aedd9 | ||
|
|
0ac8526053 | ||
|
|
6419f4e8d3 | ||
|
|
af7d1b4da4 | ||
|
|
25d030601d | ||
|
|
8629b5dcbf | ||
|
|
90a2bc9ba6 | ||
|
|
a972285787 | ||
|
|
d84cc7e13e | ||
|
|
7f43dc1778 | ||
|
|
e9924ddef8 | ||
|
|
b2c0e12066 | ||
|
|
38af471054 | ||
|
|
7f554e2ba3 | ||
|
|
d05a5e22b2 | ||
|
|
f7ae13a909 | ||
|
|
e6be1dffc4 | ||
|
|
cec1fc2ba7 | ||
|
|
1c0ff71f26 | ||
|
|
a5d1616a17 | ||
|
|
1e4e2d5198 | ||
|
|
8af579be53 | ||
|
|
a36e9ef176 | ||
|
|
9a74c8eefe | ||
|
|
14c24a51a4 | ||
|
|
35496741ce | ||
|
|
5d36b0f4c1 | ||
|
|
ad48ab28cc | ||
|
|
3c6f90d508 | ||
|
|
da024d997a | ||
|
|
342686f4e0 | ||
|
|
d42927297d | ||
|
|
1d3ec0b759 | ||
|
|
608e62d662 | ||
|
|
dc491470db | ||
|
|
5a73da898b | ||
|
|
0c736f5605 | ||
|
|
6c8ef32a11 | ||
|
|
f3b2da4b4d | ||
|
|
edab253296 | ||
|
|
d61e34a1e6 | ||
|
|
484fb9a3e5 | ||
|
|
72982f792b | ||
|
|
32f6eeeeed | ||
|
|
8b1c4555ad | ||
|
|
f978e65dfd | ||
|
|
6683139429 | ||
|
|
da12418aa0 | ||
|
|
8c778d1a6d | ||
|
|
1d68f86b3e | ||
|
|
2a24c0a061 | ||
|
|
07d3160bff | ||
|
|
bace0edd96 | ||
|
|
e267cdf8bc | ||
|
|
9c021c56b3 | ||
|
|
c922421919 | ||
|
|
e91468616b | ||
|
|
1f985f5b37 | ||
|
|
7705a14bb5 | ||
|
|
535af3b146 | ||
|
|
2832499d3e | ||
|
|
676e22665a | ||
|
|
5eb0f13e75 | ||
|
|
2c461abc82 | ||
|
|
42163826fe | ||
|
|
7ff169d4c9 | ||
|
|
ebf77b1ebb | ||
|
|
d53682110d | ||
|
|
290d442123 | ||
|
|
2114748d44 | ||
|
|
0842f66df8 | ||
|
|
c3fd098464 | ||
|
|
ed3546d196 | ||
|
|
da6836cda3 | ||
|
|
91f2c3e1ef | ||
|
|
4007d7010e | ||
|
|
4261667198 | ||
|
|
15e2d8d850 | ||
|
|
34a516d509 | ||
|
|
ba6078feab | ||
|
|
9240d35d9e | ||
|
|
7a3ba178ec | ||
|
|
77832d53c4 | ||
|
|
d127ab4ecb | ||
|
|
f4fce0a1ef | ||
|
|
2daf6c9cda | ||
|
|
aeda636983 | ||
|
|
a7c0864279 | ||
|
|
aae2beeac8 | ||
|
|
f745079f0a | ||
|
|
5b83102a59 | ||
|
|
eb5e4aa915 | ||
|
|
d6d8b299dd | ||
|
|
ea0e97d930 | ||
|
|
84e46162fd | ||
|
|
14580c34e0 | ||
|
|
ae610733cc | ||
|
|
846afed86c | ||
|
|
99a6c17c23 | ||
|
|
04f49cb62f | ||
|
|
3c7f4f6e16 | ||
|
|
dcd407a3da | ||
|
|
fde63f8e72 | ||
|
|
1f8f1b9507 |
@@ -15,6 +15,7 @@
|
|||||||
"@nestjs/jwt": "^11.0.0",
|
"@nestjs/jwt": "^11.0.0",
|
||||||
"@nestjs/mapped-types": "^2.1.0",
|
"@nestjs/mapped-types": "^2.1.0",
|
||||||
"@nestjs/platform-express": "^11.0.1",
|
"@nestjs/platform-express": "^11.0.1",
|
||||||
|
"@nestjs/schedule": "^12.0.2",
|
||||||
"@nestjs/swagger": "^11.2.0",
|
"@nestjs/swagger": "^11.2.0",
|
||||||
"@nestjs/typeorm": "^11.0.0",
|
"@nestjs/typeorm": "^11.0.0",
|
||||||
"@sentry/nestjs": "^10.10.0",
|
"@sentry/nestjs": "^10.10.0",
|
||||||
@@ -2544,6 +2545,22 @@
|
|||||||
"node": ">= 0.6"
|
"node": ">= 0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@nestjs/schedule": {
|
||||||
|
"version": "12.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@nestjs/schedule/-/schedule-12.0.2.tgz",
|
||||||
|
"integrity": "sha512-5iAvJEtk0njbfTrG4JQr+SXw8ZrqgDM1wJH9nUs6tVLCX5pWGd1LJ0a8b089UT1FDeDWaThRRfSLixFz9zztcA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"cron": "4.4.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.19.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@nestjs/common": "^11.0.0 || ^12.0.0",
|
||||||
|
"@nestjs/core": "^11.0.0 || ^12.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@nestjs/schematics": {
|
"node_modules/@nestjs/schematics": {
|
||||||
"version": "11.0.7",
|
"version": "11.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-11.0.7.tgz",
|
"resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-11.0.7.tgz",
|
||||||
@@ -3767,6 +3784,12 @@
|
|||||||
"@types/node": "*"
|
"@types/node": "*"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/luxon": {
|
||||||
|
"version": "3.7.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.7.6.tgz",
|
||||||
|
"integrity": "sha512-6KSjliQAXK8ZLgFQO4B7iE4Rpf/B3rItzCFuXezBY/XIAGxOdLd7vRNK9/StRPwiS/yJsVbB7HKpW46B8tcEuQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@types/methods": {
|
"node_modules/@types/methods": {
|
||||||
"version": "1.1.4",
|
"version": "1.1.4",
|
||||||
"resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",
|
||||||
@@ -5856,6 +5879,23 @@
|
|||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/cron": {
|
||||||
|
"version": "4.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/cron/-/cron-4.4.0.tgz",
|
||||||
|
"integrity": "sha512-fkdfq+b+AHI4cKdhZlppHveI/mgz2qpiYxcm+t5E5TsxX7QrLS1VE0+7GENEk9z0EeGPcpSciGv6ez24duWhwQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/luxon": "~3.7.0",
|
||||||
|
"luxon": "~3.7.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.x"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "ko-fi",
|
||||||
|
"url": "https://ko-fi.com/intcreator"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/cross-spawn": {
|
"node_modules/cross-spawn": {
|
||||||
"version": "7.0.6",
|
"version": "7.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||||
@@ -8786,6 +8826,15 @@
|
|||||||
"yallist": "^3.0.2"
|
"yallist": "^3.0.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/luxon": {
|
||||||
|
"version": "3.7.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz",
|
||||||
|
"integrity": "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/magic-string": {
|
"node_modules/magic-string": {
|
||||||
"version": "0.30.17",
|
"version": "0.30.17",
|
||||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz",
|
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz",
|
||||||
|
|||||||
@@ -29,6 +29,7 @@
|
|||||||
"@nestjs/jwt": "^11.0.0",
|
"@nestjs/jwt": "^11.0.0",
|
||||||
"@nestjs/mapped-types": "^2.1.0",
|
"@nestjs/mapped-types": "^2.1.0",
|
||||||
"@nestjs/platform-express": "^11.0.1",
|
"@nestjs/platform-express": "^11.0.1",
|
||||||
|
"@nestjs/schedule": "^12.0.2",
|
||||||
"@nestjs/swagger": "^11.2.0",
|
"@nestjs/swagger": "^11.2.0",
|
||||||
"@nestjs/typeorm": "^11.0.0",
|
"@nestjs/typeorm": "^11.0.0",
|
||||||
"@sentry/nestjs": "^10.10.0",
|
"@sentry/nestjs": "^10.10.0",
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { ScheduleModule } from '@nestjs/schedule';
|
||||||
import { AppController } from './app.controller';
|
import { AppController } from './app.controller';
|
||||||
import { AppService } from './app.service';
|
import { AppService } from './app.service';
|
||||||
import appConfig from './config/app.config';
|
import appConfig from './config/app.config';
|
||||||
@@ -16,7 +17,7 @@ import { AllExceptionsFilter } from './common/filters/all_exceptions.filters';
|
|||||||
import { EnfantsModule } from './routes/enfants/enfants.module';
|
import { EnfantsModule } from './routes/enfants/enfants.module';
|
||||||
import { AppConfigModule } from './modules/config/config.module';
|
import { AppConfigModule } from './modules/config/config.module';
|
||||||
import { DocumentsLegauxModule } from './modules/documents-legaux';
|
import { DocumentsLegauxModule } from './modules/documents-legaux';
|
||||||
import { AbsencesGardeModule } from './modules/absences-garde';
|
import { EvenementsAgendaModule } from './modules/evenements-agenda';
|
||||||
import { CardsModule } from './modules/cards';
|
import { CardsModule } from './modules/cards';
|
||||||
import { RelaisModule } from './routes/relais/relais.module';
|
import { RelaisModule } from './routes/relais/relais.module';
|
||||||
import { DossiersModule } from './routes/dossiers/dossiers.module';
|
import { DossiersModule } from './routes/dossiers/dossiers.module';
|
||||||
@@ -58,7 +59,8 @@ import { SuppressionsModule } from './routes/suppressions/suppressions.module';
|
|||||||
AuthModule,
|
AuthModule,
|
||||||
AppConfigModule,
|
AppConfigModule,
|
||||||
DocumentsLegauxModule,
|
DocumentsLegauxModule,
|
||||||
AbsencesGardeModule,
|
ScheduleModule.forRoot(),
|
||||||
|
EvenementsAgendaModule,
|
||||||
CardsModule,
|
CardsModule,
|
||||||
RelaisModule,
|
RelaisModule,
|
||||||
DossiersModule,
|
DossiersModule,
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
/** Dates calendaires Europe/Paris — comparaison lexicographique YYYY-MM-DD = calendaire (DST-safe). */
|
||||||
|
|
||||||
|
const PARIS_YMD = new Intl.DateTimeFormat('en-CA', {
|
||||||
|
timeZone: 'Europe/Paris',
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Aujourd’hui civil à Paris (YYYY-MM-DD). */
|
||||||
|
export function todayParis(): string {
|
||||||
|
return PARIS_YMD.format(new Date());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Décale une date calendaire YYYY-MM-DD de `deltaDays` (UTC, sans glissement DST). */
|
||||||
|
export function shiftYmd(ymd: string, deltaDays: number): string {
|
||||||
|
const [y, m, d] = ymd.split('-').map(Number);
|
||||||
|
const dt = new Date(Date.UTC(y, m - 1, d + deltaDays));
|
||||||
|
const yy = dt.getUTCFullYear();
|
||||||
|
const mm = String(dt.getUTCMonth() + 1).padStart(2, '0');
|
||||||
|
const dd = String(dt.getUTCDate()).padStart(2, '0');
|
||||||
|
return `${yy}-${mm}-${dd}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function yesterdayParis(): string {
|
||||||
|
return shiftYmd(todayParis(), -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fenêtre temporelle exacte en ms (ex. 7×24 h = 168 h). */
|
||||||
|
export const MS_24H = 24 * 60 * 60 * 1000;
|
||||||
|
export const MS_7X24H = 7 * MS_24H;
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
import {
|
|
||||||
Column,
|
|
||||||
CreateDateColumn,
|
|
||||||
Entity,
|
|
||||||
JoinColumn,
|
|
||||||
ManyToOne,
|
|
||||||
PrimaryGeneratedColumn,
|
|
||||||
UpdateDateColumn,
|
|
||||||
} from 'typeorm';
|
|
||||||
import { AmChildren } from './am_children.entity';
|
|
||||||
import { Users } from './users.entity';
|
|
||||||
|
|
||||||
export enum TypeAbsenceGardeType {
|
|
||||||
ABSENCE_ENFANT = 'absence_enfant',
|
|
||||||
CONGE_AM = 'conge_am',
|
|
||||||
ARRET_MALADIE_AM = 'arret_maladie_am',
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum StatutAbsenceGardeType {
|
|
||||||
EN_ATTENTE = 'en_attente',
|
|
||||||
ACCEPTE = 'accepte',
|
|
||||||
REFUSE = 'refuse',
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Vérité métier des absences / congés / arrêts par couple AM↔enfant.
|
|
||||||
* Les cartes (module ultérieur) collectent ; cette table stocke.
|
|
||||||
* Ticket #193.
|
|
||||||
*/
|
|
||||||
@Entity('absences_garde', { schema: 'public' })
|
|
||||||
export class AbsencesGarde {
|
|
||||||
@PrimaryGeneratedColumn('uuid')
|
|
||||||
id: string;
|
|
||||||
|
|
||||||
@Column({ name: 'id_placement', type: 'uuid' })
|
|
||||||
id_placement: string;
|
|
||||||
|
|
||||||
@ManyToOne(() => AmChildren, { onDelete: 'CASCADE' })
|
|
||||||
@JoinColumn({ name: 'id_placement', referencedColumnName: 'id' })
|
|
||||||
placement: AmChildren;
|
|
||||||
|
|
||||||
@Column({
|
|
||||||
type: 'enum',
|
|
||||||
enum: TypeAbsenceGardeType,
|
|
||||||
enumName: 'type_absence_garde_type',
|
|
||||||
name: 'type',
|
|
||||||
})
|
|
||||||
type: TypeAbsenceGardeType;
|
|
||||||
|
|
||||||
@Column({ name: 'date_debut', type: 'date' })
|
|
||||||
date_debut: string;
|
|
||||||
|
|
||||||
@Column({ name: 'date_fin', type: 'date' })
|
|
||||||
date_fin: string;
|
|
||||||
|
|
||||||
@Column({
|
|
||||||
type: 'enum',
|
|
||||||
enum: StatutAbsenceGardeType,
|
|
||||||
enumName: 'statut_absence_garde_type',
|
|
||||||
name: 'statut',
|
|
||||||
default: StatutAbsenceGardeType.EN_ATTENTE,
|
|
||||||
})
|
|
||||||
statut: StatutAbsenceGardeType;
|
|
||||||
|
|
||||||
/** Purge auto pour en_attente/refuse ; accepte → infinity. */
|
|
||||||
@Column({ name: 'expire_at', type: 'timestamptz' })
|
|
||||||
expire_at: Date;
|
|
||||||
|
|
||||||
@Column({ name: 'cree_par', type: 'uuid', nullable: true })
|
|
||||||
cree_par?: string;
|
|
||||||
|
|
||||||
@ManyToOne(() => Users, { nullable: true, onDelete: 'SET NULL' })
|
|
||||||
@JoinColumn({ name: 'cree_par', referencedColumnName: 'id' })
|
|
||||||
createdBy?: Users;
|
|
||||||
|
|
||||||
/** Réf. carte de collecte (FK quand module Cartes existera). */
|
|
||||||
@Column({ name: 'id_card_instance', type: 'uuid', nullable: true })
|
|
||||||
id_card_instance?: string;
|
|
||||||
|
|
||||||
@Column({ name: 'motif', type: 'text', nullable: true })
|
|
||||||
motif?: string;
|
|
||||||
|
|
||||||
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
|
||||||
cree_le: Date;
|
|
||||||
|
|
||||||
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
|
|
||||||
modifie_le: Date;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
ManyToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { Users } from './users.entity';
|
||||||
|
|
||||||
|
/** Aligné sur type_evenement_agenda_type (évite import circulaire avec EvenementsAgenda). */
|
||||||
|
export enum AgendaLotTypeType {
|
||||||
|
ABSENCE_ENFANT = 'absence_enfant',
|
||||||
|
CONGE_AM = 'conge_am',
|
||||||
|
ARRET_MALADIE_AM = 'arret_maladie_am',
|
||||||
|
SOIN_ENFANT = 'soin_enfant',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum AgendaLotStatutType {
|
||||||
|
EN_ATTENTE = 'en_attente',
|
||||||
|
ACCEPTE = 'accepte',
|
||||||
|
REFUSE = 'refuse',
|
||||||
|
ANNULE = 'annule',
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lot collectif Agenda (congé / arrêt / absence groupés) — cycle versionné.
|
||||||
|
* Ticket #214 (B0).
|
||||||
|
*/
|
||||||
|
@Entity('agenda_lots', { schema: 'public' })
|
||||||
|
export class AgendaLots {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'enum',
|
||||||
|
enum: AgendaLotTypeType,
|
||||||
|
enumName: 'type_evenement_agenda_type',
|
||||||
|
name: 'type',
|
||||||
|
})
|
||||||
|
type: AgendaLotTypeType;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'enum',
|
||||||
|
enum: AgendaLotStatutType,
|
||||||
|
enumName: 'agenda_lot_statut_type',
|
||||||
|
name: 'statut',
|
||||||
|
default: AgendaLotStatutType.EN_ATTENTE,
|
||||||
|
})
|
||||||
|
statut: AgendaLotStatutType;
|
||||||
|
|
||||||
|
@Column({ name: 'revision', type: 'int', default: 1 })
|
||||||
|
revision: number;
|
||||||
|
|
||||||
|
@Column({ name: 'soumis_le', type: 'timestamptz', default: () => 'now()' })
|
||||||
|
soumis_le: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'verrouille_le', type: 'timestamptz', nullable: true })
|
||||||
|
verrouille_le?: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'refuse_le', type: 'timestamptz', nullable: true })
|
||||||
|
refuse_le?: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'annule_le', type: 'timestamptz', nullable: true })
|
||||||
|
annule_le?: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'annule_par', type: 'uuid', nullable: true })
|
||||||
|
annule_par?: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => Users, { nullable: true, onDelete: 'SET NULL' })
|
||||||
|
@JoinColumn({ name: 'annule_par', referencedColumnName: 'id' })
|
||||||
|
annulePar?: Users;
|
||||||
|
|
||||||
|
@Column({ name: 'cree_par', type: 'uuid', nullable: true })
|
||||||
|
cree_par?: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => Users, { nullable: true, onDelete: 'SET NULL' })
|
||||||
|
@JoinColumn({ name: 'cree_par', referencedColumnName: 'id' })
|
||||||
|
createdBy?: Users;
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||||
|
cree_le: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
|
||||||
|
modifie_le: Date;
|
||||||
|
}
|
||||||
@@ -9,21 +9,24 @@ import {
|
|||||||
UpdateDateColumn,
|
UpdateDateColumn,
|
||||||
} from 'typeorm';
|
} from 'typeorm';
|
||||||
import { AmChildren } from './am_children.entity';
|
import { AmChildren } from './am_children.entity';
|
||||||
import { AbsencesGarde } from './absences_garde.entity';
|
import { EvenementsAgenda } from './evenements_agenda.entity';
|
||||||
import { Users } from './users.entity';
|
import { Users } from './users.entity';
|
||||||
import { CardType } from './card_types.entity';
|
import { CardType } from './card_types.entity';
|
||||||
import { CardAudienceMember } from './card_audience_members.entity';
|
import { CardAudienceMember } from './card_audience_members.entity';
|
||||||
import { CardResponse } from './card_responses.entity';
|
import { CardResponse } from './card_responses.entity';
|
||||||
|
import { AgendaLots } from './agenda_lots.entity';
|
||||||
|
|
||||||
export enum CardInstanceStatutType {
|
export enum CardInstanceStatutType {
|
||||||
OUVERTE = 'ouverte',
|
OUVERTE = 'ouverte',
|
||||||
REFUSEE = 'refusee',
|
REFUSEE = 'refusee',
|
||||||
TRAITEE = 'traitee',
|
TRAITEE = 'traitee',
|
||||||
|
ANNULEE = 'annulee',
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum CardOperationType {
|
export enum CardOperationType {
|
||||||
CREATE = 'create',
|
CREATE = 'create',
|
||||||
UPDATE = 'update',
|
UPDATE = 'update',
|
||||||
|
CANCEL = 'cancel',
|
||||||
}
|
}
|
||||||
|
|
||||||
@Entity('card_instances', { schema: 'public' })
|
@Entity('card_instances', { schema: 'public' })
|
||||||
@@ -45,12 +48,12 @@ export class CardInstance {
|
|||||||
@JoinColumn({ name: 'id_placement', referencedColumnName: 'id' })
|
@JoinColumn({ name: 'id_placement', referencedColumnName: 'id' })
|
||||||
placement: AmChildren;
|
placement: AmChildren;
|
||||||
|
|
||||||
@Column({ name: 'id_absence', type: 'uuid', nullable: true })
|
@Column({ name: 'id_evenement', type: 'uuid', nullable: true })
|
||||||
id_absence?: string;
|
id_evenement?: string;
|
||||||
|
|
||||||
@ManyToOne(() => AbsencesGarde, { nullable: true, onDelete: 'SET NULL' })
|
@ManyToOne(() => EvenementsAgenda, { nullable: true, onDelete: 'SET NULL' })
|
||||||
@JoinColumn({ name: 'id_absence', referencedColumnName: 'id' })
|
@JoinColumn({ name: 'id_evenement', referencedColumnName: 'id' })
|
||||||
absence?: AbsencesGarde;
|
evenement?: EvenementsAgenda;
|
||||||
|
|
||||||
@Column({ name: 'cree_par', type: 'uuid', nullable: true })
|
@Column({ name: 'cree_par', type: 'uuid', nullable: true })
|
||||||
cree_par?: string;
|
cree_par?: string;
|
||||||
@@ -83,6 +86,27 @@ export class CardInstance {
|
|||||||
@Column({ name: 'purge_at', type: 'timestamptz' })
|
@Column({ name: 'purge_at', type: 'timestamptz' })
|
||||||
purge_at: Date;
|
purge_at: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'id_lot', type: 'uuid', nullable: true })
|
||||||
|
id_lot?: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => AgendaLots, { nullable: true, onDelete: 'SET NULL' })
|
||||||
|
@JoinColumn({ name: 'id_lot', referencedColumnName: 'id' })
|
||||||
|
lot?: AgendaLots;
|
||||||
|
|
||||||
|
@Column({ name: 'annule_le', type: 'timestamptz', nullable: true })
|
||||||
|
annule_le?: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'annule_par', type: 'uuid', nullable: true })
|
||||||
|
annule_par?: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => Users, { nullable: true, onDelete: 'SET NULL' })
|
||||||
|
@JoinColumn({ name: 'annule_par', referencedColumnName: 'id' })
|
||||||
|
annulePar?: Users;
|
||||||
|
|
||||||
|
/** Réanimation dans le fil (tri COALESCE(remonte_le, cree_le)). */
|
||||||
|
@Column({ name: 'remonte_le', type: 'timestamptz', nullable: true })
|
||||||
|
remonte_le?: Date;
|
||||||
|
|
||||||
@OneToMany(() => CardAudienceMember, (m) => m.card)
|
@OneToMany(() => CardAudienceMember, (m) => m.card)
|
||||||
audience: CardAudienceMember[];
|
audience: CardAudienceMember[];
|
||||||
|
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -45,6 +47,10 @@ export class CardResponse {
|
|||||||
@Column({ name: 'comment', type: 'text', nullable: true })
|
@Column({ name: 'comment', type: 'text', nullable: true })
|
||||||
comment?: string;
|
comment?: string;
|
||||||
|
|
||||||
|
/** Doit matcher agenda_lots.revision pour compter dans l'unanimité (#214). */
|
||||||
|
@Column({ name: 'revision_lot', type: 'int', default: 1 })
|
||||||
|
revision_lot: number;
|
||||||
|
|
||||||
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||||
cree_le: Date;
|
cree_le: Date;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
ManyToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { AmChildren } from './am_children.entity';
|
||||||
|
import { Users } from './users.entity';
|
||||||
|
import { AgendaLots } from './agenda_lots.entity';
|
||||||
|
|
||||||
|
export enum TypeEvenementAgendaType {
|
||||||
|
ABSENCE_ENFANT = 'absence_enfant',
|
||||||
|
CONGE_AM = 'conge_am',
|
||||||
|
ARRET_MALADIE_AM = 'arret_maladie_am',
|
||||||
|
SOIN_ENFANT = 'soin_enfant',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum StatutEvenementAgendaType {
|
||||||
|
EN_ATTENTE = 'en_attente',
|
||||||
|
ACCEPTE = 'accepte',
|
||||||
|
REFUSE = 'refuse',
|
||||||
|
ANNULE = 'annule',
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vérité métier agenda par couple AM↔enfant (placement).
|
||||||
|
* Types V1 : absences / congés / arrêts ; extensible (soins, école, mairie…).
|
||||||
|
* Les cartes collectent ; cette table historise. Tickets #205 / #214.
|
||||||
|
*/
|
||||||
|
@Entity('evenements_agenda', { schema: 'public' })
|
||||||
|
export class EvenementsAgenda {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ name: 'id_placement', type: 'uuid' })
|
||||||
|
id_placement: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => AmChildren, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'id_placement', referencedColumnName: 'id' })
|
||||||
|
placement: AmChildren;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'enum',
|
||||||
|
enum: TypeEvenementAgendaType,
|
||||||
|
enumName: 'type_evenement_agenda_type',
|
||||||
|
name: 'type',
|
||||||
|
})
|
||||||
|
type: TypeEvenementAgendaType;
|
||||||
|
|
||||||
|
@Column({ name: 'date_debut', type: 'date' })
|
||||||
|
date_debut: string;
|
||||||
|
|
||||||
|
@Column({ name: 'date_fin', type: 'date' })
|
||||||
|
date_fin: string;
|
||||||
|
|
||||||
|
@Column({
|
||||||
|
type: 'enum',
|
||||||
|
enum: StatutEvenementAgendaType,
|
||||||
|
enumName: 'statut_evenement_agenda_type',
|
||||||
|
name: 'statut',
|
||||||
|
default: StatutEvenementAgendaType.EN_ATTENTE,
|
||||||
|
})
|
||||||
|
statut: StatutEvenementAgendaType;
|
||||||
|
|
||||||
|
/** Purge auto pour en_attente/refuse ; accepte → infinity. */
|
||||||
|
@Column({ name: 'expire_at', type: 'timestamptz' })
|
||||||
|
expire_at: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'cree_par', type: 'uuid', nullable: true })
|
||||||
|
cree_par?: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => Users, { nullable: true, onDelete: 'SET NULL' })
|
||||||
|
@JoinColumn({ name: 'cree_par', referencedColumnName: 'id' })
|
||||||
|
createdBy?: Users;
|
||||||
|
|
||||||
|
/** Réf. carte de collecte (module Cartes). */
|
||||||
|
@Column({ name: 'id_card_instance', type: 'uuid', nullable: true })
|
||||||
|
id_card_instance?: string;
|
||||||
|
|
||||||
|
@Column({ name: 'motif', type: 'text', nullable: true })
|
||||||
|
motif?: string;
|
||||||
|
|
||||||
|
/** Heure métier (soin) — durable hors payload carte. */
|
||||||
|
@Column({ name: 'heure', type: 'time', nullable: true })
|
||||||
|
heure?: string;
|
||||||
|
|
||||||
|
@Column({ name: 'id_lot', type: 'uuid', nullable: true })
|
||||||
|
id_lot?: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => AgendaLots, { nullable: true, onDelete: 'SET NULL' })
|
||||||
|
@JoinColumn({ name: 'id_lot', referencedColumnName: 'id' })
|
||||||
|
lot?: AgendaLots;
|
||||||
|
|
||||||
|
@Column({ name: 'verrouille_le', type: 'timestamptz', nullable: true })
|
||||||
|
verrouille_le?: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'refuse_le', type: 'timestamptz', nullable: true })
|
||||||
|
refuse_le?: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'annule_le', type: 'timestamptz', nullable: true })
|
||||||
|
annule_le?: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'annule_par', type: 'uuid', nullable: true })
|
||||||
|
annule_par?: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => Users, { nullable: true, onDelete: 'SET NULL' })
|
||||||
|
@JoinColumn({ name: 'annule_par', referencedColumnName: 'id' })
|
||||||
|
annulePar?: Users;
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||||
|
cree_le: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
|
||||||
|
modifie_le: Date;
|
||||||
|
}
|
||||||
@@ -177,6 +177,10 @@ export class Users {
|
|||||||
@Column({ nullable: true, name: 'numero_dossier', length: 20 })
|
@Column({ nullable: true, name: 'numero_dossier', length: 20 })
|
||||||
numero_dossier?: string;
|
numero_dossier?: string;
|
||||||
|
|
||||||
|
/** Préférences UI (ex. jours_affiches_semaine) — #214 */
|
||||||
|
@Column({ name: 'preferences', type: 'jsonb', default: {} })
|
||||||
|
preferences: Record<string, unknown>;
|
||||||
|
|
||||||
@ManyToOne(() => Relais, relais => relais.gestionnaires, { nullable: true })
|
@ManyToOne(() => Relais, relais => relais.gestionnaires, { nullable: true })
|
||||||
@JoinColumn({ name: 'relais_id' })
|
@JoinColumn({ name: 'relais_id' })
|
||||||
relais?: Relais;
|
relais?: Relais;
|
||||||
|
|||||||
@@ -1,124 +0,0 @@
|
|||||||
import {
|
|
||||||
Body,
|
|
||||||
Controller,
|
|
||||||
Delete,
|
|
||||||
Get,
|
|
||||||
HttpCode,
|
|
||||||
HttpStatus,
|
|
||||||
Param,
|
|
||||||
ParseUUIDPipe,
|
|
||||||
Patch,
|
|
||||||
Post,
|
|
||||||
Query,
|
|
||||||
UseGuards,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import {
|
|
||||||
ApiBearerAuth,
|
|
||||||
ApiBody,
|
|
||||||
ApiOperation,
|
|
||||||
ApiQuery,
|
|
||||||
ApiResponse,
|
|
||||||
ApiTags,
|
|
||||||
} from '@nestjs/swagger';
|
|
||||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
|
||||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
|
||||||
import { Roles } from 'src/common/decorators/roles.decorator';
|
|
||||||
import { User } from 'src/common/decorators/user.decorator';
|
|
||||||
import {
|
|
||||||
StatutAbsenceGardeType,
|
|
||||||
TypeAbsenceGardeType,
|
|
||||||
} from 'src/entities/absences_garde.entity';
|
|
||||||
import { RoleType } from 'src/entities/users.entity';
|
|
||||||
import { AbsencesGardeService } from './absences-garde.service';
|
|
||||||
import {
|
|
||||||
AbsenceGardeDto,
|
|
||||||
CreerAbsenceGardeDto,
|
|
||||||
ListeAbsencesGardeDto,
|
|
||||||
MajAbsenceGardeDto,
|
|
||||||
} from './dto/absences-garde.dto';
|
|
||||||
|
|
||||||
@ApiTags('Absences garde')
|
|
||||||
@ApiBearerAuth('access-token')
|
|
||||||
@Controller('absences-garde')
|
|
||||||
@UseGuards(AuthGuard, RolesGuard)
|
|
||||||
export class AbsencesGardeController {
|
|
||||||
constructor(private readonly absencesGardeService: AbsencesGardeService) {}
|
|
||||||
|
|
||||||
@Get()
|
|
||||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
|
||||||
@ApiOperation({
|
|
||||||
summary: 'Lister les absences / congés / arrêts — ticket #172',
|
|
||||||
description:
|
|
||||||
'Sans placementId : tous les placements du user (parent = famille multi-AM ; AM = tous accueils). ' +
|
|
||||||
'Avec placementId : un couple enfant–AM.',
|
|
||||||
})
|
|
||||||
@ApiQuery({ name: 'placementId', required: false })
|
|
||||||
@ApiQuery({ name: 'type', required: false, enum: TypeAbsenceGardeType })
|
|
||||||
@ApiQuery({ name: 'statut', required: false, enum: StatutAbsenceGardeType })
|
|
||||||
@ApiQuery({ name: 'from', required: false, description: 'YYYY-MM-DD' })
|
|
||||||
@ApiQuery({ name: 'to', required: false, description: 'YYYY-MM-DD' })
|
|
||||||
@ApiResponse({ status: 200, type: ListeAbsencesGardeDto })
|
|
||||||
lister(
|
|
||||||
@User('id') userId: string,
|
|
||||||
@User('role') role: RoleType,
|
|
||||||
@Query('placementId') placementId?: string,
|
|
||||||
@Query('type') type?: TypeAbsenceGardeType,
|
|
||||||
@Query('statut') statut?: StatutAbsenceGardeType,
|
|
||||||
@Query('from') from?: string,
|
|
||||||
@Query('to') to?: string,
|
|
||||||
): Promise<ListeAbsencesGardeDto> {
|
|
||||||
return this.absencesGardeService.lister(userId, role, {
|
|
||||||
placementId,
|
|
||||||
type,
|
|
||||||
statut,
|
|
||||||
from,
|
|
||||||
to,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post()
|
|
||||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
|
||||||
@ApiOperation({ summary: 'Créer une période d’absence / congé / arrêt — #172' })
|
|
||||||
@ApiBody({ type: CreerAbsenceGardeDto })
|
|
||||||
@ApiResponse({ status: 201, type: AbsenceGardeDto })
|
|
||||||
@HttpCode(HttpStatus.CREATED)
|
|
||||||
creer(
|
|
||||||
@User('id') userId: string,
|
|
||||||
@User('role') role: RoleType,
|
|
||||||
@Body() dto: CreerAbsenceGardeDto,
|
|
||||||
): Promise<AbsenceGardeDto> {
|
|
||||||
return this.absencesGardeService.creer(userId, role, dto);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Patch(':id')
|
|
||||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
|
||||||
@ApiOperation({
|
|
||||||
summary: 'Mettre à jour dates / statut / motif — #172',
|
|
||||||
description:
|
|
||||||
'Parent : accept/refuse congé (motivation si refus), ack arrêt. ' +
|
|
||||||
'AM : modifier dates (en attente / refuse / accepté), republication après refus.',
|
|
||||||
})
|
|
||||||
@ApiBody({ type: MajAbsenceGardeDto })
|
|
||||||
@ApiResponse({ status: 200, type: AbsenceGardeDto })
|
|
||||||
maj(
|
|
||||||
@User('id') userId: string,
|
|
||||||
@User('role') role: RoleType,
|
|
||||||
@Param('id', ParseUUIDPipe) id: string,
|
|
||||||
@Body() dto: MajAbsenceGardeDto,
|
|
||||||
): Promise<AbsenceGardeDto> {
|
|
||||||
return this.absencesGardeService.maj(userId, role, id, dto);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Delete(':id')
|
|
||||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
|
||||||
@HttpCode(HttpStatus.NO_CONTENT)
|
|
||||||
@ApiOperation({ summary: 'Supprimer une absence (hard delete) — #172' })
|
|
||||||
@ApiResponse({ status: 204 })
|
|
||||||
async supprimer(
|
|
||||||
@User('id') userId: string,
|
|
||||||
@User('role') role: RoleType,
|
|
||||||
@Param('id', ParseUUIDPipe) id: string,
|
|
||||||
): Promise<void> {
|
|
||||||
await this.absencesGardeService.supprimer(userId, role, id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
import { Module } from '@nestjs/common';
|
|
||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
|
||||||
import { JwtModule } from '@nestjs/jwt';
|
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
||||||
import { AbsencesGarde } from 'src/entities/absences_garde.entity';
|
|
||||||
import { AmChildren } from 'src/entities/am_children.entity';
|
|
||||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
|
||||||
import { AbsencesGardeController } from './absences-garde.controller';
|
|
||||||
import { AbsencesGardeService } from './absences-garde.service';
|
|
||||||
|
|
||||||
@Module({
|
|
||||||
imports: [
|
|
||||||
TypeOrmModule.forFeature([AbsencesGarde, AmChildren, ParentsChildren]),
|
|
||||||
JwtModule.registerAsync({
|
|
||||||
imports: [ConfigModule],
|
|
||||||
useFactory: (config: ConfigService) => ({
|
|
||||||
secret: config.get('jwt.accessSecret'),
|
|
||||||
signOptions: { expiresIn: config.get('jwt.accessExpiresIn') },
|
|
||||||
}),
|
|
||||||
inject: [ConfigService],
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
controllers: [AbsencesGardeController],
|
|
||||||
providers: [AbsencesGardeService],
|
|
||||||
exports: [AbsencesGardeService],
|
|
||||||
})
|
|
||||||
export class AbsencesGardeModule {}
|
|
||||||
@@ -1,168 +0,0 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
|
||||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
|
||||||
import { ForbiddenException, BadRequestException } from '@nestjs/common';
|
|
||||||
import { AbsencesGardeService } from './absences-garde.service';
|
|
||||||
import {
|
|
||||||
AbsencesGarde,
|
|
||||||
StatutAbsenceGardeType,
|
|
||||||
TypeAbsenceGardeType,
|
|
||||||
} from 'src/entities/absences_garde.entity';
|
|
||||||
import { AmChildren } from 'src/entities/am_children.entity';
|
|
||||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
|
||||||
import { RoleType } from 'src/entities/users.entity';
|
|
||||||
|
|
||||||
describe('AbsencesGardeService (#172)', () => {
|
|
||||||
let service: AbsencesGardeService;
|
|
||||||
const absencesRepo = {
|
|
||||||
create: jest.fn((x) => x),
|
|
||||||
save: jest.fn(async (x) => ({
|
|
||||||
...x,
|
|
||||||
id: x.id ?? 'abs-1',
|
|
||||||
cree_le: new Date(),
|
|
||||||
modifie_le: new Date(),
|
|
||||||
})),
|
|
||||||
findOne: jest.fn(),
|
|
||||||
delete: jest.fn(),
|
|
||||||
createQueryBuilder: jest.fn(),
|
|
||||||
};
|
|
||||||
const amChildrenRepo = {
|
|
||||||
find: jest.fn(),
|
|
||||||
findOne: jest.fn(),
|
|
||||||
};
|
|
||||||
const parentsChildrenRepo = {
|
|
||||||
find: jest.fn(),
|
|
||||||
findOne: jest.fn(),
|
|
||||||
};
|
|
||||||
|
|
||||||
beforeEach(async () => {
|
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
|
||||||
providers: [
|
|
||||||
AbsencesGardeService,
|
|
||||||
{ provide: getRepositoryToken(AbsencesGarde), useValue: absencesRepo },
|
|
||||||
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo },
|
|
||||||
{
|
|
||||||
provide: getRepositoryToken(ParentsChildren),
|
|
||||||
useValue: parentsChildrenRepo,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}).compile();
|
|
||||||
service = module.get(AbsencesGardeService);
|
|
||||||
jest.clearAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should be defined', () => {
|
|
||||||
expect(service).toBeDefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('parent crée absence_enfant → statut accepte', async () => {
|
|
||||||
amChildrenRepo.findOne.mockResolvedValue({
|
|
||||||
id: 'pl-1',
|
|
||||||
amId: 'am-1',
|
|
||||||
enfantId: 'e-1',
|
|
||||||
date_fin: null,
|
|
||||||
});
|
|
||||||
parentsChildrenRepo.findOne.mockResolvedValue({
|
|
||||||
parentId: 'p-1',
|
|
||||||
enfantId: 'e-1',
|
|
||||||
});
|
|
||||||
absencesRepo.findOne.mockResolvedValue({
|
|
||||||
id: 'abs-1',
|
|
||||||
id_placement: 'pl-1',
|
|
||||||
type: TypeAbsenceGardeType.ABSENCE_ENFANT,
|
|
||||||
date_debut: '2026-10-01',
|
|
||||||
date_fin: '2026-10-02',
|
|
||||||
statut: StatutAbsenceGardeType.ACCEPTE,
|
|
||||||
expire_at: new Date('9999-12-31'),
|
|
||||||
cree_le: new Date(),
|
|
||||||
modifie_le: new Date(),
|
|
||||||
placement: {
|
|
||||||
enfantId: 'e-1',
|
|
||||||
amId: 'am-1',
|
|
||||||
child: { id: 'e-1', first_name: 'Léo' },
|
|
||||||
am: { user: { prenom: 'Marie', nom: 'AM' } },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const res = await service.creer('p-1', RoleType.PARENT, {
|
|
||||||
id_placement: 'pl-1',
|
|
||||||
type: TypeAbsenceGardeType.ABSENCE_ENFANT,
|
|
||||||
date_debut: '2026-10-01',
|
|
||||||
date_fin: '2026-10-02',
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(absencesRepo.save).toHaveBeenCalled();
|
|
||||||
const savedArg = absencesRepo.save.mock.calls[0][0];
|
|
||||||
expect(savedArg.statut).toBe(StatutAbsenceGardeType.ACCEPTE);
|
|
||||||
expect(res.type).toBe(TypeAbsenceGardeType.ABSENCE_ENFANT);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('parent ne peut pas créer un congé AM', async () => {
|
|
||||||
amChildrenRepo.findOne.mockResolvedValue({
|
|
||||||
id: 'pl-1',
|
|
||||||
amId: 'am-1',
|
|
||||||
enfantId: 'e-1',
|
|
||||||
date_fin: null,
|
|
||||||
});
|
|
||||||
parentsChildrenRepo.findOne.mockResolvedValue({
|
|
||||||
parentId: 'p-1',
|
|
||||||
enfantId: 'e-1',
|
|
||||||
});
|
|
||||||
await expect(
|
|
||||||
service.creer('p-1', RoleType.PARENT, {
|
|
||||||
id_placement: 'pl-1',
|
|
||||||
type: TypeAbsenceGardeType.CONGE_AM,
|
|
||||||
date_debut: '2026-10-01',
|
|
||||||
date_fin: '2026-10-05',
|
|
||||||
}),
|
|
||||||
).rejects.toBeInstanceOf(ForbiddenException);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('refus congé sans motif → BadRequest', async () => {
|
|
||||||
absencesRepo.findOne.mockResolvedValue({
|
|
||||||
id: 'abs-1',
|
|
||||||
id_placement: 'pl-1',
|
|
||||||
type: TypeAbsenceGardeType.CONGE_AM,
|
|
||||||
date_debut: '2026-10-01',
|
|
||||||
date_fin: '2026-10-05',
|
|
||||||
statut: StatutAbsenceGardeType.EN_ATTENTE,
|
|
||||||
expire_at: new Date(),
|
|
||||||
});
|
|
||||||
amChildrenRepo.findOne.mockResolvedValue({
|
|
||||||
id: 'pl-1',
|
|
||||||
amId: 'am-1',
|
|
||||||
enfantId: 'e-1',
|
|
||||||
date_fin: null,
|
|
||||||
});
|
|
||||||
parentsChildrenRepo.findOne.mockResolvedValue({
|
|
||||||
parentId: 'p-1',
|
|
||||||
enfantId: 'e-1',
|
|
||||||
});
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
service.maj('p-1', RoleType.PARENT, 'abs-1', {
|
|
||||||
statut: StatutAbsenceGardeType.REFUSE,
|
|
||||||
}),
|
|
||||||
).rejects.toBeInstanceOf(BadRequestException);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('dates invalides → BadRequest', async () => {
|
|
||||||
amChildrenRepo.findOne.mockResolvedValue({
|
|
||||||
id: 'pl-1',
|
|
||||||
amId: 'am-1',
|
|
||||||
enfantId: 'e-1',
|
|
||||||
date_fin: null,
|
|
||||||
});
|
|
||||||
parentsChildrenRepo.findOne.mockResolvedValue({
|
|
||||||
parentId: 'p-1',
|
|
||||||
enfantId: 'e-1',
|
|
||||||
});
|
|
||||||
await expect(
|
|
||||||
service.creer('p-1', RoleType.PARENT, {
|
|
||||||
id_placement: 'pl-1',
|
|
||||||
type: TypeAbsenceGardeType.ABSENCE_ENFANT,
|
|
||||||
date_debut: '2026-10-10',
|
|
||||||
date_fin: '2026-10-01',
|
|
||||||
}),
|
|
||||||
).rejects.toBeInstanceOf(BadRequestException);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,421 +0,0 @@
|
|||||||
import {
|
|
||||||
BadRequestException,
|
|
||||||
ForbiddenException,
|
|
||||||
Injectable,
|
|
||||||
NotFoundException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
|
||||||
import { In, IsNull, Repository } from 'typeorm';
|
|
||||||
import {
|
|
||||||
AbsencesGarde,
|
|
||||||
StatutAbsenceGardeType,
|
|
||||||
TypeAbsenceGardeType,
|
|
||||||
} from 'src/entities/absences_garde.entity';
|
|
||||||
import { AmChildren } from 'src/entities/am_children.entity';
|
|
||||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
|
||||||
import { RoleType } from 'src/entities/users.entity';
|
|
||||||
import {
|
|
||||||
AbsenceGardeDto,
|
|
||||||
CreerAbsenceGardeDto,
|
|
||||||
ListeAbsencesGardeDto,
|
|
||||||
MajAbsenceGardeDto,
|
|
||||||
} from './dto/absences-garde.dto';
|
|
||||||
|
|
||||||
const TTL_EN_ATTENTE_MS = 15 * 24 * 60 * 60 * 1000;
|
|
||||||
const TTL_REFUSE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
||||||
/** Sentinel « pas de purge » pour les périodes acceptées */
|
|
||||||
const EXPIRE_ACCEPTE = new Date('9999-12-31T23:59:59.999Z');
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class AbsencesGardeService {
|
|
||||||
constructor(
|
|
||||||
@InjectRepository(AbsencesGarde)
|
|
||||||
private readonly absencesRepo: Repository<AbsencesGarde>,
|
|
||||||
@InjectRepository(AmChildren)
|
|
||||||
private readonly amChildrenRepo: Repository<AmChildren>,
|
|
||||||
@InjectRepository(ParentsChildren)
|
|
||||||
private readonly parentsChildrenRepo: Repository<ParentsChildren>,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
async lister(
|
|
||||||
userId: string,
|
|
||||||
role: RoleType,
|
|
||||||
opts: {
|
|
||||||
placementId?: string;
|
|
||||||
type?: TypeAbsenceGardeType;
|
|
||||||
statut?: StatutAbsenceGardeType;
|
|
||||||
from?: string;
|
|
||||||
to?: string;
|
|
||||||
},
|
|
||||||
): Promise<ListeAbsencesGardeDto> {
|
|
||||||
const placementIds = await this.resolvePlacementIds(
|
|
||||||
userId,
|
|
||||||
role,
|
|
||||||
opts.placementId,
|
|
||||||
);
|
|
||||||
if (placementIds.length === 0) {
|
|
||||||
return { items: [] };
|
|
||||||
}
|
|
||||||
|
|
||||||
const qb = this.absencesRepo
|
|
||||||
.createQueryBuilder('ag')
|
|
||||||
.leftJoinAndSelect('ag.placement', 'placement')
|
|
||||||
.leftJoinAndSelect('placement.child', 'child')
|
|
||||||
.leftJoinAndSelect('placement.am', 'am')
|
|
||||||
.leftJoinAndSelect('am.user', 'amUser')
|
|
||||||
.where('ag.id_placement IN (:...placementIds)', { placementIds })
|
|
||||||
.orderBy('ag.date_debut', 'DESC');
|
|
||||||
|
|
||||||
if (opts.type) {
|
|
||||||
qb.andWhere('ag.type = :type', { type: opts.type });
|
|
||||||
}
|
|
||||||
if (opts.statut) {
|
|
||||||
qb.andWhere('ag.statut = :statut', { statut: opts.statut });
|
|
||||||
}
|
|
||||||
if (opts.from) {
|
|
||||||
qb.andWhere('ag.date_fin >= :from', { from: opts.from });
|
|
||||||
}
|
|
||||||
if (opts.to) {
|
|
||||||
qb.andWhere('ag.date_debut <= :to', { to: opts.to });
|
|
||||||
}
|
|
||||||
|
|
||||||
const rows = await qb.getMany();
|
|
||||||
return { items: rows.map((r) => this.toDto(r)) };
|
|
||||||
}
|
|
||||||
|
|
||||||
async creer(
|
|
||||||
userId: string,
|
|
||||||
role: RoleType,
|
|
||||||
dto: CreerAbsenceGardeDto,
|
|
||||||
): Promise<AbsenceGardeDto> {
|
|
||||||
this.assertDates(dto.date_debut, dto.date_fin);
|
|
||||||
await this.assertCanAccessPlacement(userId, role, dto.id_placement);
|
|
||||||
this.assertCanCreateType(role, dto.type);
|
|
||||||
|
|
||||||
const statut = this.statutInitial(dto.type);
|
|
||||||
const entity = this.absencesRepo.create({
|
|
||||||
id_placement: dto.id_placement,
|
|
||||||
type: dto.type,
|
|
||||||
date_debut: dto.date_debut,
|
|
||||||
date_fin: dto.date_fin,
|
|
||||||
statut,
|
|
||||||
expire_at: this.expireAtFor(statut),
|
|
||||||
cree_par: userId,
|
|
||||||
motif: dto.motif?.trim() || undefined,
|
|
||||||
});
|
|
||||||
const saved = await this.absencesRepo.save(entity);
|
|
||||||
return this.getByIdForUser(saved.id, userId, role);
|
|
||||||
}
|
|
||||||
|
|
||||||
async maj(
|
|
||||||
userId: string,
|
|
||||||
role: RoleType,
|
|
||||||
id: string,
|
|
||||||
dto: MajAbsenceGardeDto,
|
|
||||||
): Promise<AbsenceGardeDto> {
|
|
||||||
const row = await this.absencesRepo.findOne({ where: { id } });
|
|
||||||
if (!row) {
|
|
||||||
throw new NotFoundException('Absence introuvable');
|
|
||||||
}
|
|
||||||
await this.assertCanAccessPlacement(userId, role, row.id_placement);
|
|
||||||
|
|
||||||
if (dto.date_debut !== undefined || dto.date_fin !== undefined) {
|
|
||||||
const debut = dto.date_debut ?? row.date_debut;
|
|
||||||
const fin = dto.date_fin ?? row.date_fin;
|
|
||||||
this.assertDates(debut, fin);
|
|
||||||
// Parent : peut modifier ses absences enfant
|
|
||||||
// AM : peut modifier congé/arrêt en_attente (avant accept) ou dates si créateur
|
|
||||||
this.assertCanEditDates(role, row);
|
|
||||||
row.date_debut = debut;
|
|
||||||
row.date_fin = fin;
|
|
||||||
if (row.statut === StatutAbsenceGardeType.EN_ATTENTE) {
|
|
||||||
row.expire_at = this.expireAtFor(StatutAbsenceGardeType.EN_ATTENTE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dto.statut !== undefined && dto.statut !== row.statut) {
|
|
||||||
this.assertCanChangeStatut(role, row, dto.statut, dto.motif);
|
|
||||||
if (
|
|
||||||
dto.statut === StatutAbsenceGardeType.REFUSE &&
|
|
||||||
(!dto.motif || !dto.motif.trim())
|
|
||||||
) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
'Une motivation est obligatoire en cas de refus',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
row.statut = dto.statut;
|
|
||||||
row.expire_at = this.expireAtFor(dto.statut);
|
|
||||||
if (dto.motif?.trim()) {
|
|
||||||
row.motif = dto.motif.trim();
|
|
||||||
}
|
|
||||||
} else if (dto.motif !== undefined) {
|
|
||||||
row.motif = dto.motif.trim() || undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.absencesRepo.save(row);
|
|
||||||
return this.getByIdForUser(id, userId, role);
|
|
||||||
}
|
|
||||||
|
|
||||||
async supprimer(
|
|
||||||
userId: string,
|
|
||||||
role: RoleType,
|
|
||||||
id: string,
|
|
||||||
): Promise<void> {
|
|
||||||
const row = await this.absencesRepo.findOne({ where: { id } });
|
|
||||||
if (!row) {
|
|
||||||
throw new NotFoundException('Absence introuvable');
|
|
||||||
}
|
|
||||||
await this.assertCanAccessPlacement(userId, role, row.id_placement);
|
|
||||||
|
|
||||||
if (
|
|
||||||
role === RoleType.PARENT &&
|
|
||||||
row.type !== TypeAbsenceGardeType.ABSENCE_ENFANT
|
|
||||||
) {
|
|
||||||
throw new ForbiddenException(
|
|
||||||
'Un parent ne peut supprimer que les absences enfant',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.absencesRepo.delete({ id });
|
|
||||||
}
|
|
||||||
|
|
||||||
private async getByIdForUser(
|
|
||||||
id: string,
|
|
||||||
userId: string,
|
|
||||||
role: RoleType,
|
|
||||||
): Promise<AbsenceGardeDto> {
|
|
||||||
const row = await this.absencesRepo.findOne({
|
|
||||||
where: { id },
|
|
||||||
relations: ['placement', 'placement.child', 'placement.am', 'placement.am.user'],
|
|
||||||
});
|
|
||||||
if (!row) {
|
|
||||||
throw new NotFoundException('Absence introuvable');
|
|
||||||
}
|
|
||||||
await this.assertCanAccessPlacement(userId, role, row.id_placement);
|
|
||||||
return this.toDto(row);
|
|
||||||
}
|
|
||||||
|
|
||||||
private statutInitial(type: TypeAbsenceGardeType): StatutAbsenceGardeType {
|
|
||||||
if (type === TypeAbsenceGardeType.ABSENCE_ENFANT) {
|
|
||||||
return StatutAbsenceGardeType.ACCEPTE;
|
|
||||||
}
|
|
||||||
return StatutAbsenceGardeType.EN_ATTENTE;
|
|
||||||
}
|
|
||||||
|
|
||||||
private expireAtFor(statut: StatutAbsenceGardeType): Date {
|
|
||||||
const now = Date.now();
|
|
||||||
if (statut === StatutAbsenceGardeType.ACCEPTE) {
|
|
||||||
return EXPIRE_ACCEPTE;
|
|
||||||
}
|
|
||||||
if (statut === StatutAbsenceGardeType.REFUSE) {
|
|
||||||
return new Date(now + TTL_REFUSE_MS);
|
|
||||||
}
|
|
||||||
return new Date(now + TTL_EN_ATTENTE_MS);
|
|
||||||
}
|
|
||||||
|
|
||||||
private assertDates(debut: string, fin: string): void {
|
|
||||||
if (fin < debut) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
'date_fin doit être supérieure ou égale à date_debut',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private assertCanCreateType(role: RoleType, type: TypeAbsenceGardeType): void {
|
|
||||||
if (role === RoleType.PARENT) {
|
|
||||||
if (type !== TypeAbsenceGardeType.ABSENCE_ENFANT) {
|
|
||||||
throw new ForbiddenException(
|
|
||||||
'Un parent ne peut créer que des absences enfant',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
|
||||||
if (
|
|
||||||
type !== TypeAbsenceGardeType.CONGE_AM &&
|
|
||||||
type !== TypeAbsenceGardeType.ARRET_MALADIE_AM
|
|
||||||
) {
|
|
||||||
throw new ForbiddenException(
|
|
||||||
'Une AM ne peut créer que congé ou arrêt maladie',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
throw new ForbiddenException('Rôle non autorisé à créer une absence');
|
|
||||||
}
|
|
||||||
|
|
||||||
private assertCanEditDates(
|
|
||||||
role: RoleType,
|
|
||||||
row: AbsencesGarde,
|
|
||||||
): void {
|
|
||||||
if (role === RoleType.PARENT) {
|
|
||||||
if (row.type !== TypeAbsenceGardeType.ABSENCE_ENFANT) {
|
|
||||||
throw new ForbiddenException(
|
|
||||||
'Un parent ne peut modifier que les absences enfant',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
|
||||||
if (
|
|
||||||
row.type === TypeAbsenceGardeType.CONGE_AM ||
|
|
||||||
row.type === TypeAbsenceGardeType.ARRET_MALADIE_AM
|
|
||||||
) {
|
|
||||||
if (
|
|
||||||
row.statut !== StatutAbsenceGardeType.EN_ATTENTE &&
|
|
||||||
row.statut !== StatutAbsenceGardeType.REFUSE &&
|
|
||||||
row.statut !== StatutAbsenceGardeType.ACCEPTE
|
|
||||||
) {
|
|
||||||
throw new ForbiddenException('Statut incompatible avec une modification');
|
|
||||||
}
|
|
||||||
// Accepté : autorisé (S2b — re-validation via cartes plus tard ; API permet update dates)
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
throw new ForbiddenException('Type non modifiable par l’AM');
|
|
||||||
}
|
|
||||||
throw new ForbiddenException('Modification non autorisée');
|
|
||||||
}
|
|
||||||
|
|
||||||
private assertCanChangeStatut(
|
|
||||||
role: RoleType,
|
|
||||||
row: AbsencesGarde,
|
|
||||||
next: StatutAbsenceGardeType,
|
|
||||||
_motif?: string,
|
|
||||||
): void {
|
|
||||||
if (role === RoleType.PARENT) {
|
|
||||||
// Accept / refuse congé ; ack arrêt (accepte)
|
|
||||||
if (
|
|
||||||
row.type === TypeAbsenceGardeType.CONGE_AM ||
|
|
||||||
row.type === TypeAbsenceGardeType.ARRET_MALADIE_AM
|
|
||||||
) {
|
|
||||||
if (
|
|
||||||
next !== StatutAbsenceGardeType.ACCEPTE &&
|
|
||||||
next !== StatutAbsenceGardeType.REFUSE
|
|
||||||
) {
|
|
||||||
throw new BadRequestException('Transition de statut invalide');
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
row.type === TypeAbsenceGardeType.ARRET_MALADIE_AM &&
|
|
||||||
next === StatutAbsenceGardeType.REFUSE
|
|
||||||
) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
'Un arrêt maladie ne se refuse pas (accusé seulement)',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (row.statut !== StatutAbsenceGardeType.EN_ATTENTE) {
|
|
||||||
throw new BadRequestException('Cette demande n’est plus en attente');
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
throw new ForbiddenException(
|
|
||||||
'Pas de changement de statut sur ce type pour un parent',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
|
||||||
// Remise en attente après refus OU modification d’un congé déjà accepté (S2b)
|
|
||||||
if (
|
|
||||||
next === StatutAbsenceGardeType.EN_ATTENTE &&
|
|
||||||
(row.statut === StatutAbsenceGardeType.REFUSE ||
|
|
||||||
row.statut === StatutAbsenceGardeType.ACCEPTE)
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
throw new ForbiddenException(
|
|
||||||
'L’AM ne valide pas elle-même (sauf republication / modification)',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
throw new ForbiddenException('Changement de statut non autorisé');
|
|
||||||
}
|
|
||||||
|
|
||||||
private async resolvePlacementIds(
|
|
||||||
userId: string,
|
|
||||||
role: RoleType,
|
|
||||||
placementId?: string,
|
|
||||||
): Promise<string[]> {
|
|
||||||
if (placementId) {
|
|
||||||
await this.assertCanAccessPlacement(userId, role, placementId);
|
|
||||||
return [placementId];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (role === RoleType.PARENT) {
|
|
||||||
const liens = await this.parentsChildrenRepo.find({
|
|
||||||
where: { parentId: userId },
|
|
||||||
select: ['enfantId'],
|
|
||||||
});
|
|
||||||
const enfantIds = liens.map((l) => l.enfantId);
|
|
||||||
if (enfantIds.length === 0) return [];
|
|
||||||
const placements = await this.amChildrenRepo.find({
|
|
||||||
where: { enfantId: In(enfantIds), date_fin: IsNull() },
|
|
||||||
select: ['id'],
|
|
||||||
});
|
|
||||||
return placements.map((p) => p.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
|
||||||
const placements = await this.amChildrenRepo.find({
|
|
||||||
where: { amId: userId, date_fin: IsNull() },
|
|
||||||
select: ['id'],
|
|
||||||
});
|
|
||||||
return placements.map((p) => p.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new ForbiddenException('Rôle non autorisé');
|
|
||||||
}
|
|
||||||
|
|
||||||
private async assertCanAccessPlacement(
|
|
||||||
userId: string,
|
|
||||||
role: RoleType,
|
|
||||||
placementId: string,
|
|
||||||
): Promise<AmChildren> {
|
|
||||||
const placement = await this.amChildrenRepo.findOne({
|
|
||||||
where: { id: placementId, date_fin: IsNull() },
|
|
||||||
});
|
|
||||||
if (!placement) {
|
|
||||||
throw new NotFoundException('Placement / couple introuvable ou inactif');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
|
||||||
if (placement.amId !== userId) {
|
|
||||||
throw new ForbiddenException('Ce placement ne vous appartient pas');
|
|
||||||
}
|
|
||||||
return placement;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (role === RoleType.PARENT) {
|
|
||||||
const lien = await this.parentsChildrenRepo.findOne({
|
|
||||||
where: { parentId: userId, enfantId: placement.enfantId },
|
|
||||||
});
|
|
||||||
if (!lien) {
|
|
||||||
throw new ForbiddenException(
|
|
||||||
'Ce placement ne concerne pas un de vos enfants',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return placement;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new ForbiddenException('Rôle non autorisé');
|
|
||||||
}
|
|
||||||
|
|
||||||
private toDto(row: AbsencesGarde): AbsenceGardeDto {
|
|
||||||
const child = row.placement?.child;
|
|
||||||
const amUser = row.placement?.am?.user;
|
|
||||||
return {
|
|
||||||
id: row.id,
|
|
||||||
id_placement: row.id_placement,
|
|
||||||
type: row.type,
|
|
||||||
date_debut: row.date_debut,
|
|
||||||
date_fin: row.date_fin,
|
|
||||||
statut: row.statut,
|
|
||||||
expire_at: row.expire_at?.toISOString?.() ?? String(row.expire_at),
|
|
||||||
cree_par: row.cree_par ?? null,
|
|
||||||
motif: row.motif ?? null,
|
|
||||||
id_enfant: child?.id ?? row.placement?.enfantId ?? null,
|
|
||||||
prenom_enfant: child?.first_name ?? null,
|
|
||||||
id_am: row.placement?.amId ?? null,
|
|
||||||
prenom_am: amUser?.prenom ?? null,
|
|
||||||
nom_am: amUser?.nom ?? null,
|
|
||||||
cree_le: row.cree_le?.toISOString?.() ?? String(row.cree_le),
|
|
||||||
modifie_le: row.modifie_le?.toISOString?.() ?? String(row.modifie_le),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,119 +0,0 @@
|
|||||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
|
||||||
import {
|
|
||||||
IsDateString,
|
|
||||||
IsEnum,
|
|
||||||
IsOptional,
|
|
||||||
IsString,
|
|
||||||
IsUUID,
|
|
||||||
MaxLength,
|
|
||||||
MinLength,
|
|
||||||
} from 'class-validator';
|
|
||||||
import {
|
|
||||||
StatutAbsenceGardeType,
|
|
||||||
TypeAbsenceGardeType,
|
|
||||||
} from 'src/entities/absences_garde.entity';
|
|
||||||
|
|
||||||
export class CreerAbsenceGardeDto {
|
|
||||||
@ApiProperty({ description: 'Placement AM↔enfant (couple)' })
|
|
||||||
@IsUUID()
|
|
||||||
id_placement: string;
|
|
||||||
|
|
||||||
@ApiProperty({ enum: TypeAbsenceGardeType })
|
|
||||||
@IsEnum(TypeAbsenceGardeType)
|
|
||||||
type: TypeAbsenceGardeType;
|
|
||||||
|
|
||||||
@ApiProperty({ example: '2026-10-01' })
|
|
||||||
@IsDateString()
|
|
||||||
date_debut: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: '2026-10-05' })
|
|
||||||
@IsDateString()
|
|
||||||
date_fin: string;
|
|
||||||
|
|
||||||
@ApiPropertyOptional()
|
|
||||||
@IsOptional()
|
|
||||||
@IsString()
|
|
||||||
@MaxLength(2000)
|
|
||||||
motif?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class MajAbsenceGardeDto {
|
|
||||||
@ApiPropertyOptional({ example: '2026-10-02' })
|
|
||||||
@IsOptional()
|
|
||||||
@IsDateString()
|
|
||||||
date_debut?: string;
|
|
||||||
|
|
||||||
@ApiPropertyOptional({ example: '2026-10-06' })
|
|
||||||
@IsOptional()
|
|
||||||
@IsDateString()
|
|
||||||
date_fin?: string;
|
|
||||||
|
|
||||||
@ApiPropertyOptional({ enum: StatutAbsenceGardeType })
|
|
||||||
@IsOptional()
|
|
||||||
@IsEnum(StatutAbsenceGardeType)
|
|
||||||
statut?: StatutAbsenceGardeType;
|
|
||||||
|
|
||||||
@ApiPropertyOptional({
|
|
||||||
description: 'Motivation de refus (parent) ou motif créateur',
|
|
||||||
})
|
|
||||||
@IsOptional()
|
|
||||||
@IsString()
|
|
||||||
@MinLength(1)
|
|
||||||
@MaxLength(2000)
|
|
||||||
motif?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class AbsenceGardeDto {
|
|
||||||
@ApiProperty()
|
|
||||||
id: string;
|
|
||||||
|
|
||||||
@ApiProperty()
|
|
||||||
id_placement: string;
|
|
||||||
|
|
||||||
@ApiProperty({ enum: TypeAbsenceGardeType })
|
|
||||||
type: TypeAbsenceGardeType;
|
|
||||||
|
|
||||||
@ApiProperty()
|
|
||||||
date_debut: string;
|
|
||||||
|
|
||||||
@ApiProperty()
|
|
||||||
date_fin: string;
|
|
||||||
|
|
||||||
@ApiProperty({ enum: StatutAbsenceGardeType })
|
|
||||||
statut: StatutAbsenceGardeType;
|
|
||||||
|
|
||||||
@ApiProperty()
|
|
||||||
expire_at: string;
|
|
||||||
|
|
||||||
@ApiPropertyOptional()
|
|
||||||
cree_par?: string | null;
|
|
||||||
|
|
||||||
@ApiPropertyOptional()
|
|
||||||
motif?: string | null;
|
|
||||||
|
|
||||||
@ApiPropertyOptional()
|
|
||||||
id_enfant?: string | null;
|
|
||||||
|
|
||||||
@ApiPropertyOptional()
|
|
||||||
prenom_enfant?: string | null;
|
|
||||||
|
|
||||||
@ApiPropertyOptional()
|
|
||||||
id_am?: string | null;
|
|
||||||
|
|
||||||
@ApiPropertyOptional()
|
|
||||||
prenom_am?: string | null;
|
|
||||||
|
|
||||||
@ApiPropertyOptional()
|
|
||||||
nom_am?: string | null;
|
|
||||||
|
|
||||||
@ApiProperty()
|
|
||||||
cree_le: string;
|
|
||||||
|
|
||||||
@ApiProperty()
|
|
||||||
modifie_le: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ListeAbsencesGardeDto {
|
|
||||||
@ApiProperty({ type: [AbsenceGardeDto] })
|
|
||||||
items: AbsenceGardeDto[];
|
|
||||||
}
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
export { AbsencesGardeModule } from './absences-garde.module';
|
|
||||||
export { AbsencesGardeService } from './absences-garde.service';
|
|
||||||
@@ -65,7 +65,7 @@ export class CardsController {
|
|||||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
@HttpCode(HttpStatus.CREATED)
|
@HttpCode(HttpStatus.CREATED)
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: 'Créer une bulle (+ hook absences_garde) — #194',
|
summary: 'Créer une bulle (+ hook evenements_agenda) — #194',
|
||||||
})
|
})
|
||||||
@ApiBody({ type: CreerCarteDto })
|
@ApiBody({ type: CreerCarteDto })
|
||||||
@ApiResponse({ status: 201, type: CarteDto })
|
@ApiResponse({ status: 201, type: CarteDto })
|
||||||
@@ -79,6 +79,7 @@ export class CardsController {
|
|||||||
|
|
||||||
@Post(':id/respond')
|
@Post(':id/respond')
|
||||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
@ApiOperation({ summary: 'Répondre (accept / refuse / ack) — #194' })
|
@ApiOperation({ summary: 'Répondre (accept / refuse / ack) — #194' })
|
||||||
@ApiBody({ type: RepondreCarteDto })
|
@ApiBody({ type: RepondreCarteDto })
|
||||||
repondre(
|
repondre(
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { Module } from '@nestjs/common';
|
|||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
import { JwtModule } from '@nestjs/jwt';
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { AbsencesGardeModule } from '../absences-garde';
|
import { EvenementsAgendaModule } from '../evenements-agenda';
|
||||||
import { CardType } from 'src/entities/card_types.entity';
|
import { CardType } from 'src/entities/card_types.entity';
|
||||||
import { CardInstance } from 'src/entities/card_instances.entity';
|
import { CardInstance } from 'src/entities/card_instances.entity';
|
||||||
import { CardAudienceMember } from 'src/entities/card_audience_members.entity';
|
import { CardAudienceMember } from 'src/entities/card_audience_members.entity';
|
||||||
@@ -16,7 +16,7 @@ import { CardsRealtimeService } from './cards-realtime.service';
|
|||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
AbsencesGardeModule,
|
EvenementsAgendaModule,
|
||||||
TypeOrmModule.forFeature([
|
TypeOrmModule.forFeature([
|
||||||
CardType,
|
CardType,
|
||||||
CardInstance,
|
CardInstance,
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { getRepositoryToken } from '@nestjs/typeorm';
|
|||||||
import { ForbiddenException } from '@nestjs/common';
|
import { ForbiddenException } from '@nestjs/common';
|
||||||
import { CardsService } from './cards.service';
|
import { CardsService } from './cards.service';
|
||||||
import { CardsRealtimeService } from './cards-realtime.service';
|
import { CardsRealtimeService } from './cards-realtime.service';
|
||||||
import { AbsencesGardeService } from '../absences-garde/absences-garde.service';
|
import { EvenementsAgendaService } from '../evenements-agenda/evenements-agenda.service';
|
||||||
import { CardType, CardResponseModeType } from 'src/entities/card_types.entity';
|
import { CardType, CardResponseModeType } from 'src/entities/card_types.entity';
|
||||||
import {
|
import {
|
||||||
CardInstance,
|
CardInstance,
|
||||||
@@ -15,7 +15,7 @@ import { CardResponse } from 'src/entities/card_responses.entity';
|
|||||||
import { AmChildren } from 'src/entities/am_children.entity';
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
import { RoleType } from 'src/entities/users.entity';
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
import { StatutAbsenceGardeType, TypeAbsenceGardeType } from 'src/entities/absences_garde.entity';
|
import { StatutEvenementAgendaType, TypeEvenementAgendaType } from 'src/entities/evenements_agenda.entity';
|
||||||
|
|
||||||
describe('CardsService (#194)', () => {
|
describe('CardsService (#194)', () => {
|
||||||
let service: CardsService;
|
let service: CardsService;
|
||||||
@@ -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,11 +38,12 @@ 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() };
|
||||||
const absencesService = {
|
const evenementsService = {
|
||||||
creer: jest.fn(),
|
creer: jest.fn(),
|
||||||
maj: jest.fn(),
|
maj: jest.fn(),
|
||||||
supprimer: jest.fn(),
|
supprimer: jest.fn(),
|
||||||
@@ -58,7 +60,7 @@ describe('CardsService (#194)', () => {
|
|||||||
{ provide: getRepositoryToken(CardResponse), useValue: responsesRepo },
|
{ provide: getRepositoryToken(CardResponse), useValue: responsesRepo },
|
||||||
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo },
|
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo },
|
||||||
{ provide: getRepositoryToken(ParentsChildren), useValue: parentsChildrenRepo },
|
{ provide: getRepositoryToken(ParentsChildren), useValue: parentsChildrenRepo },
|
||||||
{ provide: AbsencesGardeService, useValue: absencesService },
|
{ provide: EvenementsAgendaService, useValue: evenementsService },
|
||||||
{ provide: CardsRealtimeService, useValue: realtime },
|
{ provide: CardsRealtimeService, useValue: realtime },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
@@ -80,7 +82,6 @@ describe('CardsService (#194)', () => {
|
|||||||
audience_resolver: 'couple_parents',
|
audience_resolver: 'couple_parents',
|
||||||
response_mode: CardResponseModeType.ACCEPT_REFUSE,
|
response_mode: CardResponseModeType.ACCEPT_REFUSE,
|
||||||
retention_days: 14,
|
retention_days: 14,
|
||||||
couleur: 'lavender',
|
|
||||||
});
|
});
|
||||||
amChildrenRepo.findOne.mockResolvedValue({
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
id: 'pl-1',
|
id: 'pl-1',
|
||||||
@@ -88,10 +89,10 @@ describe('CardsService (#194)', () => {
|
|||||||
enfantId: 'e-1',
|
enfantId: 'e-1',
|
||||||
date_fin: null,
|
date_fin: null,
|
||||||
});
|
});
|
||||||
absencesService.creer.mockResolvedValue({
|
evenementsService.creer.mockResolvedValue({
|
||||||
id: 'abs-1',
|
id: 'abs-1',
|
||||||
type: TypeAbsenceGardeType.CONGE_AM,
|
type: TypeEvenementAgendaType.CONGE_AM,
|
||||||
statut: StatutAbsenceGardeType.EN_ATTENTE,
|
statut: StatutEvenementAgendaType.EN_ATTENTE,
|
||||||
});
|
});
|
||||||
parentsChildrenRepo.find.mockResolvedValue([
|
parentsChildrenRepo.find.mockResolvedValue([
|
||||||
{ parentId: 'p-1', enfantId: 'e-1' },
|
{ parentId: 'p-1', enfantId: 'e-1' },
|
||||||
@@ -101,7 +102,7 @@ describe('CardsService (#194)', () => {
|
|||||||
id: 'card-1',
|
id: 'card-1',
|
||||||
type_code: 'conge_am',
|
type_code: 'conge_am',
|
||||||
id_placement: 'pl-1',
|
id_placement: 'pl-1',
|
||||||
id_absence: 'abs-1',
|
id_evenement: 'abs-1',
|
||||||
cree_par: 'am-1',
|
cree_par: 'am-1',
|
||||||
operation: CardOperationType.CREATE,
|
operation: CardOperationType.CREATE,
|
||||||
statut: CardInstanceStatutType.OUVERTE,
|
statut: CardInstanceStatutType.OUVERTE,
|
||||||
@@ -111,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,
|
||||||
},
|
},
|
||||||
@@ -130,7 +130,7 @@ describe('CardsService (#194)', () => {
|
|||||||
date_fin: '2026-11-07',
|
date_fin: '2026-11-07',
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(absencesService.creer).toHaveBeenCalled();
|
expect(evenementsService.creer).toHaveBeenCalled();
|
||||||
expect(audienceRepo.save).toHaveBeenCalled();
|
expect(audienceRepo.save).toHaveBeenCalled();
|
||||||
expect(realtime.emitToUsers).toHaveBeenCalledWith(
|
expect(realtime.emitToUsers).toHaveBeenCalledWith(
|
||||||
['am-1', 'p-1', 'p-2'],
|
['am-1', 'p-1', 'p-2'],
|
||||||
@@ -157,4 +157,296 @@ 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é
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('B2 — #216 soft-cancel + ack arrêt', () => {
|
||||||
|
it('ack arrêt maladie → pas de maj événement + carte traitée', async () => {
|
||||||
|
cardsRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'card-arret',
|
||||||
|
type_code: 'arret_maladie_am',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
id_evenement: 'ev-arret',
|
||||||
|
cree_par: 'am-1',
|
||||||
|
statut: CardInstanceStatutType.OUVERTE,
|
||||||
|
purge_at: new Date(Date.now() - 60_000), // déjà hors fil
|
||||||
|
payload: {},
|
||||||
|
type: {
|
||||||
|
titre: 'Arrêt',
|
||||||
|
response_mode: CardResponseModeType.ACK,
|
||||||
|
retention_days: 7,
|
||||||
|
},
|
||||||
|
responses: [],
|
||||||
|
audience: [
|
||||||
|
{ id_utilisateur: 'am-1' },
|
||||||
|
{ id_utilisateur: 'p-1' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
audienceRepo.findOne.mockResolvedValue({
|
||||||
|
id_card: 'card-arret',
|
||||||
|
id_utilisateur: 'p-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await service.repondre('p-1', RoleType.PARENT, 'card-arret', {
|
||||||
|
action: 'ack' as never,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(evenementsService.maj).not.toHaveBeenCalled();
|
||||||
|
expect(cardsRepo.update).toHaveBeenCalledWith(
|
||||||
|
{ id: 'card-arret' },
|
||||||
|
expect.objectContaining({ statut: CardInstanceStatutType.TRAITEE }),
|
||||||
|
);
|
||||||
|
expect(res.statut).toBe(CardInstanceStatutType.TRAITEE);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('supprimer carte → soft-cancel (update ANNULEE), pas delete', async () => {
|
||||||
|
cardsRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'card-1',
|
||||||
|
type_code: 'absence_enfant',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
id_evenement: 'ev-1',
|
||||||
|
cree_par: 'p-1',
|
||||||
|
statut: CardInstanceStatutType.OUVERTE,
|
||||||
|
cree_le: new Date(),
|
||||||
|
audience: [{ id_utilisateur: 'p-1' }, { id_utilisateur: 'am-1' }],
|
||||||
|
type: { retention_days: 14 },
|
||||||
|
});
|
||||||
|
evenementsService.supprimer.mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
await service.supprimer('p-1', RoleType.PARENT, 'card-1');
|
||||||
|
|
||||||
|
expect(cardsRepo.delete).not.toHaveBeenCalled();
|
||||||
|
expect(evenementsService.supprimer).toHaveBeenCalledWith(
|
||||||
|
'p-1',
|
||||||
|
RoleType.PARENT,
|
||||||
|
'ev-1',
|
||||||
|
);
|
||||||
|
expect(cardsRepo.update).toHaveBeenCalledWith(
|
||||||
|
{ id: 'card-1' },
|
||||||
|
expect.objectContaining({
|
||||||
|
statut: CardInstanceStatutType.ANNULEE,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(realtime.emitToUsers).toHaveBeenCalledWith(
|
||||||
|
expect.any(Array),
|
||||||
|
'card.deleted',
|
||||||
|
'card-1',
|
||||||
|
expect.any(Object),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,11 +6,11 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { IsNull, Repository } from 'typeorm';
|
import { IsNull, Repository } from 'typeorm';
|
||||||
import { AbsencesGardeService } from '../absences-garde/absences-garde.service';
|
import { EvenementsAgendaService } from '../evenements-agenda/evenements-agenda.service';
|
||||||
import {
|
import {
|
||||||
StatutAbsenceGardeType,
|
StatutEvenementAgendaType,
|
||||||
TypeAbsenceGardeType,
|
TypeEvenementAgendaType,
|
||||||
} from 'src/entities/absences_garde.entity';
|
} from 'src/entities/evenements_agenda.entity';
|
||||||
import { AmChildren } from 'src/entities/am_children.entity';
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
import { RoleType } from 'src/entities/users.entity';
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
@@ -49,13 +49,36 @@ export class CardsService {
|
|||||||
private readonly amChildrenRepo: Repository<AmChildren>,
|
private readonly amChildrenRepo: Repository<AmChildren>,
|
||||||
@InjectRepository(ParentsChildren)
|
@InjectRepository(ParentsChildren)
|
||||||
private readonly parentsChildrenRepo: Repository<ParentsChildren>,
|
private readonly parentsChildrenRepo: Repository<ParentsChildren>,
|
||||||
private readonly absencesService: AbsencesGardeService,
|
private readonly evenementsService: EvenementsAgendaService,
|
||||||
private readonly realtime: CardsRealtimeService,
|
private readonly realtime: CardsRealtimeService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async listerTypes(role: RoleType): Promise<CardType[]> {
|
async listerTypes(role: RoleType): Promise<
|
||||||
|
Pick<
|
||||||
|
CardType,
|
||||||
|
| 'code'
|
||||||
|
| 'system'
|
||||||
|
| 'titre'
|
||||||
|
| 'emitter_roles'
|
||||||
|
| 'recipient_roles'
|
||||||
|
| 'audience_resolver'
|
||||||
|
| 'response_mode'
|
||||||
|
| 'retention_days'
|
||||||
|
>[]
|
||||||
|
> {
|
||||||
const all = await this.typesRepo.find({ where: { system: true } });
|
const all = await this.typesRepo.find({ where: { system: true } });
|
||||||
return all.filter((t) => t.emitter_roles.includes(role));
|
return all
|
||||||
|
.filter((t) => t.emitter_roles.includes(role))
|
||||||
|
.map((t) => ({
|
||||||
|
code: t.code,
|
||||||
|
system: t.system,
|
||||||
|
titre: t.titre,
|
||||||
|
emitter_roles: t.emitter_roles,
|
||||||
|
recipient_roles: t.recipient_roles,
|
||||||
|
audience_resolver: t.audience_resolver,
|
||||||
|
response_mode: t.response_mode,
|
||||||
|
retention_days: t.retention_days,
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
async lister(
|
async lister(
|
||||||
@@ -69,11 +92,11 @@ export class CardsService {
|
|||||||
.leftJoinAndSelect('c.type', 'type')
|
.leftJoinAndSelect('c.type', 'type')
|
||||||
.leftJoinAndSelect('c.responses', 'responses')
|
.leftJoinAndSelect('c.responses', 'responses')
|
||||||
.where('c.purge_at > now()')
|
.where('c.purge_at > now()')
|
||||||
.orderBy(
|
.andWhere('c.statut != :annulee', {
|
||||||
`CASE c.statut WHEN 'refusee' THEN 0 WHEN 'ouverte' THEN 1 ELSE 2 END`,
|
annulee: CardInstanceStatutType.ANNULEE,
|
||||||
'ASC',
|
})
|
||||||
)
|
// Tri fil : COALESCE(remonte_le, cree_le) DESC (mini-spec §10)
|
||||||
.addOrderBy('c.modifie_le', 'DESC');
|
.orderBy('COALESCE(c.remonte_le, c.cree_le)', 'DESC');
|
||||||
|
|
||||||
if (placementId) {
|
if (placementId) {
|
||||||
await this.assertPlacementAccess(userId, role, placementId);
|
await this.assertPlacementAccess(userId, role, placementId);
|
||||||
@@ -110,30 +133,83 @@ export class CardsService {
|
|||||||
);
|
);
|
||||||
const operation = dto.operation ?? CardOperationType.CREATE;
|
const operation = dto.operation ?? CardOperationType.CREATE;
|
||||||
|
|
||||||
let absenceId = dto.id_absence;
|
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.absencesService.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 (!absenceId) {
|
if (dto.type_code === 'soin_enfant') {
|
||||||
throw new BadRequestException('id_absence requis pour operation=update');
|
throw new BadRequestException('operation=update interdite pour soin_enfant');
|
||||||
}
|
}
|
||||||
await this.absencesService.maj(userId, role, absenceId, {
|
if (!absenceId) {
|
||||||
|
throw new BadRequestException('id_evenement requis pour operation=update');
|
||||||
|
}
|
||||||
|
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'
|
||||||
? { statut: StatutAbsenceGardeType.EN_ATTENTE }
|
? { statut: StatutEvenementAgendaType.EN_ATTENTE }
|
||||||
: {}),
|
: {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -146,15 +222,11 @@ export class CardsService {
|
|||||||
const card = this.cardsRepo.create({
|
const card = this.cardsRepo.create({
|
||||||
type_code: type.code,
|
type_code: type.code,
|
||||||
id_placement: dto.id_placement,
|
id_placement: dto.id_placement,
|
||||||
id_absence: absenceId,
|
id_evenement: absenceId,
|
||||||
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);
|
||||||
@@ -179,6 +251,10 @@ export class CardsService {
|
|||||||
): Promise<CarteDto> {
|
): Promise<CarteDto> {
|
||||||
const card = await this.loadCard(cardId);
|
const card = await this.loadCard(cardId);
|
||||||
await this.assertInAudience(card, userId);
|
await this.assertInAudience(card, userId);
|
||||||
|
// Respond OK même après purge_at (sortie du fil) — AC #216
|
||||||
|
if (card.statut === CardInstanceStatutType.ANNULEE) {
|
||||||
|
throw new BadRequestException('Cette carte est annulée');
|
||||||
|
}
|
||||||
if (card.statut !== CardInstanceStatutType.OUVERTE) {
|
if (card.statut !== CardInstanceStatutType.OUVERTE) {
|
||||||
throw new BadRequestException('Cette carte n’est plus ouverte');
|
throw new BadRequestException('Cette carte n’est plus ouverte');
|
||||||
}
|
}
|
||||||
@@ -206,32 +282,38 @@ export class CardsService {
|
|||||||
|
|
||||||
await this.responsesRepo.save(
|
await this.responsesRepo.save(
|
||||||
this.responsesRepo.create({
|
this.responsesRepo.create({
|
||||||
id_card: card.id,
|
card: { id: card.id },
|
||||||
id_utilisateur: userId,
|
user: { id: userId },
|
||||||
action: dto.action,
|
action: dto.action,
|
||||||
comment: dto.comment?.trim(),
|
comment: dto.comment?.trim() || undefined,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (card.id_absence) {
|
// ACK informatif (arrêt / soin) : n’écrit plus sur l’événement (#216)
|
||||||
if (dto.action === CardResponseActionType.ACCEPT || dto.action === CardResponseActionType.ACK) {
|
if (dto.action === CardResponseActionType.ACK) {
|
||||||
await this.absencesService.maj(userId, role, card.id_absence, {
|
card.statut = CardInstanceStatutType.TRAITEE;
|
||||||
statut: StatutAbsenceGardeType.ACCEPTE,
|
} else if (card.id_evenement) {
|
||||||
|
if (dto.action === CardResponseActionType.ACCEPT) {
|
||||||
|
await this.evenementsService.maj(userId, role, card.id_evenement, {
|
||||||
|
statut: StatutEvenementAgendaType.ACCEPTE,
|
||||||
});
|
});
|
||||||
card.statut = CardInstanceStatutType.TRAITEE;
|
card.statut = CardInstanceStatutType.TRAITEE;
|
||||||
} else if (dto.action === CardResponseActionType.REFUSE) {
|
} else if (dto.action === CardResponseActionType.REFUSE) {
|
||||||
await this.absencesService.maj(userId, role, card.id_absence, {
|
await this.evenementsService.maj(userId, role, card.id_evenement, {
|
||||||
statut: StatutAbsenceGardeType.REFUSE,
|
statut: StatutEvenementAgendaType.REFUSE,
|
||||||
motif: dto.comment!.trim(),
|
motif: dto.comment!.trim(),
|
||||||
});
|
});
|
||||||
card.statut = CardInstanceStatutType.REFUSEE;
|
card.statut = CardInstanceStatutType.REFUSEE;
|
||||||
}
|
}
|
||||||
} else if (dto.action === CardResponseActionType.ACK) {
|
|
||||||
card.statut = CardInstanceStatutType.TRAITEE;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
card.purge_at = this.purgeAt(card.type.retention_days, card.statut);
|
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', {
|
||||||
@@ -252,12 +334,20 @@ 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.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é');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
if (
|
if (
|
||||||
card.statut !== CardInstanceStatutType.OUVERTE &&
|
card.statut !== CardInstanceStatutType.OUVERTE &&
|
||||||
card.statut !== CardInstanceStatutType.REFUSEE
|
card.statut !== CardInstanceStatutType.REFUSEE
|
||||||
) {
|
) {
|
||||||
throw new BadRequestException('Carte non modifiable dans cet état');
|
throw new BadRequestException('Carte non modifiable dans cet état');
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const debut =
|
const debut =
|
||||||
dto.date_debut ?? String(card.payload?.['date_debut'] ?? '');
|
dto.date_debut ?? String(card.payload?.['date_debut'] ?? '');
|
||||||
@@ -266,24 +356,87 @@ export class CardsService {
|
|||||||
throw new BadRequestException('Dates invalides');
|
throw new BadRequestException('Dates invalides');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (card.id_absence) {
|
let motif = dto.motif ?? card.payload?.['motif'] ?? null;
|
||||||
await this.absencesService.maj(userId, role, card.id_absence, {
|
let finalPayload: Record<string, any> = {
|
||||||
date_debut: debut,
|
|
||||||
date_fin: fin,
|
|
||||||
motif: dto.motif,
|
|
||||||
statut: StatutAbsenceGardeType.EN_ATTENTE,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
card.payload = {
|
|
||||||
...card.payload,
|
...card.payload,
|
||||||
date_debut: debut,
|
date_debut: debut,
|
||||||
date_fin: fin,
|
date_fin: fin,
|
||||||
motif: dto.motif ?? card.payload?.['motif'] ?? null,
|
...(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) {
|
||||||
|
await this.evenementsService.maj(userId, role, card.id_evenement, {
|
||||||
|
date_debut: debut,
|
||||||
|
date_fin: fin,
|
||||||
|
motif: motif ? String(motif) : undefined,
|
||||||
|
...(card.type_code !== 'soin_enfant' ? { statut: StatutEvenementAgendaType.EN_ATTENTE } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
card.payload = finalPayload;
|
||||||
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);
|
||||||
@@ -299,22 +452,30 @@ 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_absence) {
|
// Soft-cancel événement lié (matrice temporelle côté evenements) — #216
|
||||||
const absStatut =
|
if (card.id_evenement) {
|
||||||
card.statut === CardInstanceStatutType.TRAITEE
|
await this.evenementsService.supprimer(userId, role, card.id_evenement);
|
||||||
? null
|
|
||||||
: card.id_absence;
|
|
||||||
// Supprime l’absence liée si pas encore acceptée définitivement
|
|
||||||
if (
|
|
||||||
card.statut === CardInstanceStatutType.OUVERTE ||
|
|
||||||
card.statut === CardInstanceStatutType.REFUSEE
|
|
||||||
) {
|
|
||||||
await this.absencesService.supprimer(userId, role, card.id_absence);
|
|
||||||
}
|
}
|
||||||
void absStatut;
|
// Soft-cancel carte — aucun DELETE physique applicatif (#216)
|
||||||
}
|
const now = new Date();
|
||||||
await this.cardsRepo.delete({ id: cardId });
|
await this.cardsRepo.update(
|
||||||
|
{ id: cardId },
|
||||||
|
{
|
||||||
|
statut: CardInstanceStatutType.ANNULEE,
|
||||||
|
annule_le: now,
|
||||||
|
annule_par: userId,
|
||||||
|
purge_at: now,
|
||||||
|
},
|
||||||
|
);
|
||||||
this.realtime.emitToUsers(audienceIds, 'card.deleted', cardId, {
|
this.realtime.emitToUsers(audienceIds, 'card.deleted', cardId, {
|
||||||
id: cardId,
|
id: cardId,
|
||||||
});
|
});
|
||||||
@@ -338,13 +499,16 @@ export class CardsService {
|
|||||||
return rows.map((r) => r.id_utilisateur);
|
return rows.map((r) => r.id_utilisateur);
|
||||||
}
|
}
|
||||||
|
|
||||||
private mapAbsenceType(typeCode: string): TypeAbsenceGardeType {
|
private mapAbsenceType(typeCode: string): TypeEvenementAgendaType {
|
||||||
if (typeCode === 'absence_enfant' || typeCode === 'absence_enfant_modif') {
|
if (typeCode === 'absence_enfant' || typeCode === 'absence_enfant_modif') {
|
||||||
return TypeAbsenceGardeType.ABSENCE_ENFANT;
|
return TypeEvenementAgendaType.ABSENCE_ENFANT;
|
||||||
}
|
}
|
||||||
if (typeCode === 'conge_am') return TypeAbsenceGardeType.CONGE_AM;
|
if (typeCode === 'conge_am') return TypeEvenementAgendaType.CONGE_AM;
|
||||||
if (typeCode === 'arret_maladie_am') {
|
if (typeCode === 'arret_maladie_am') {
|
||||||
return TypeAbsenceGardeType.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}`);
|
||||||
}
|
}
|
||||||
@@ -352,7 +516,7 @@ export class CardsService {
|
|||||||
private async linkAbsenceCard(absenceId: string, cardId: string): Promise<void> {
|
private async linkAbsenceCard(absenceId: string, cardId: string): Promise<void> {
|
||||||
// Update direct pour éviter droits maj vides
|
// Update direct pour éviter droits maj vides
|
||||||
await this.cardsRepo.manager.query(
|
await this.cardsRepo.manager.query(
|
||||||
`UPDATE absences_garde SET id_card_instance = $1, modifie_le = now() WHERE id = $2`,
|
`UPDATE evenements_agenda SET id_card_instance = $1, modifie_le = now() WHERE id = $2`,
|
||||||
[cardId, absenceId],
|
[cardId, absenceId],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -374,12 +538,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 },
|
||||||
@@ -471,9 +648,8 @@ export class CardsService {
|
|||||||
id: card.id,
|
id: card.id,
|
||||||
type_code: card.type_code,
|
type_code: card.type_code,
|
||||||
titre: card.type?.titre ?? card.type_code,
|
titre: card.type?.titre ?? card.type_code,
|
||||||
couleur: card.type?.couleur ?? null,
|
|
||||||
id_placement: card.id_placement,
|
id_placement: card.id_placement,
|
||||||
id_absence: card.id_absence ?? null,
|
id_evenement: card.id_evenement ?? null,
|
||||||
operation: card.operation,
|
operation: card.operation,
|
||||||
statut: card.statut,
|
statut: card.statut,
|
||||||
payload: card.payload ?? {},
|
payload: card.payload ?? {},
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
IsDateString,
|
IsDateString,
|
||||||
IsEnum,
|
IsEnum,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
|
IsObject,
|
||||||
IsString,
|
IsString,
|
||||||
IsUUID,
|
IsUUID,
|
||||||
MaxLength,
|
MaxLength,
|
||||||
@@ -38,16 +39,21 @@ export class CreerCarteDto {
|
|||||||
motif?: string;
|
motif?: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
description: 'Requis pour operation=update (même id absences_garde)',
|
description: 'Requis pour operation=update (même id evenements_agenda)',
|
||||||
})
|
})
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsUUID()
|
@IsUUID()
|
||||||
id_absence?: string;
|
id_evenement?: string;
|
||||||
|
|
||||||
@ApiPropertyOptional({ enum: CardOperationType, default: CardOperationType.CREATE })
|
@ApiPropertyOptional({ enum: CardOperationType, default: CardOperationType.CREATE })
|
||||||
@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 {
|
||||||
@@ -91,14 +102,11 @@ export class CarteDto {
|
|||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
titre: string;
|
titre: string;
|
||||||
|
|
||||||
@ApiPropertyOptional()
|
|
||||||
couleur?: string | null;
|
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
id_placement: string;
|
id_placement: string;
|
||||||
|
|
||||||
@ApiPropertyOptional()
|
@ApiPropertyOptional()
|
||||||
id_absence?: string | null;
|
id_evenement?: string | null;
|
||||||
|
|
||||||
@ApiProperty({ enum: CardOperationType })
|
@ApiProperty({ enum: CardOperationType })
|
||||||
operation: CardOperationType;
|
operation: CardOperationType;
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
jest.mock('@nestjs/schedule', () => ({
|
||||||
|
Cron: () => () => undefined,
|
||||||
|
CronExpression: { EVERY_HOUR: '0 * * * *' },
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { AgendaExpirationCron } from './agenda-expiration.cron';
|
||||||
|
import { EvenementsAgendaService } from './evenements-agenda.service';
|
||||||
|
|
||||||
|
describe('AgendaExpirationCron (#216)', () => {
|
||||||
|
const evenements = {
|
||||||
|
autoValiderCongesExpires: jest.fn().mockResolvedValue(2),
|
||||||
|
softCancelRefusesExpires: jest.fn().mockResolvedValue(1),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => jest.clearAllMocks());
|
||||||
|
|
||||||
|
it('runOnce agrège auto-valid + soft-cancel', async () => {
|
||||||
|
const cron = new AgendaExpirationCron(
|
||||||
|
evenements as unknown as EvenementsAgendaService,
|
||||||
|
);
|
||||||
|
const res = await cron.runOnce();
|
||||||
|
expect(res).toEqual({ autoValid: 2, softCancel: 1 });
|
||||||
|
expect(evenements.autoValiderCongesExpires).toHaveBeenCalledTimes(1);
|
||||||
|
expect(evenements.softCancelRefusesExpires).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('double appel concurrent : 2e skip (lock)', async () => {
|
||||||
|
let release!: () => void;
|
||||||
|
const gate = new Promise<void>((r) => {
|
||||||
|
release = r;
|
||||||
|
});
|
||||||
|
evenements.autoValiderCongesExpires.mockImplementation(async () => {
|
||||||
|
await gate;
|
||||||
|
return 1;
|
||||||
|
});
|
||||||
|
evenements.softCancelRefusesExpires.mockResolvedValue(0);
|
||||||
|
|
||||||
|
const cron = new AgendaExpirationCron(
|
||||||
|
evenements as unknown as EvenementsAgendaService,
|
||||||
|
);
|
||||||
|
const p1 = cron.runOnce();
|
||||||
|
const p2 = cron.runOnce();
|
||||||
|
release();
|
||||||
|
const [a, b] = await Promise.all([p1, p2]);
|
||||||
|
const skipped = [a, b].filter((x) => x.autoValid === 0 && x.softCancel === 0);
|
||||||
|
const ran = [a, b].filter((x) => x.autoValid === 1);
|
||||||
|
expect(skipped).toHaveLength(1);
|
||||||
|
expect(ran).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||||
|
import { EvenementsAgendaService } from './evenements-agenda.service';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Échéances Agenda (#216) : auto-valid congés J+7, soft-cancel refusés J+7.
|
||||||
|
* Idempotent ; rattrapage au redémarrage via le prochain tick.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class AgendaExpirationCron {
|
||||||
|
private readonly logger = new Logger(AgendaExpirationCron.name);
|
||||||
|
private running = false;
|
||||||
|
|
||||||
|
constructor(private readonly evenements: EvenementsAgendaService) {}
|
||||||
|
|
||||||
|
@Cron(CronExpression.EVERY_HOUR)
|
||||||
|
async tick(): Promise<void> {
|
||||||
|
await this.runOnce();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Exposé pour tests / appel manuel (double-appel = no-op côté rows déjà traités). */
|
||||||
|
async runOnce(
|
||||||
|
now = new Date(),
|
||||||
|
): Promise<{ autoValid: number; softCancel: number }> {
|
||||||
|
if (this.running) {
|
||||||
|
this.logger.debug('Cron agenda déjà en cours — skip');
|
||||||
|
return { autoValid: 0, softCancel: 0 };
|
||||||
|
}
|
||||||
|
this.running = true;
|
||||||
|
try {
|
||||||
|
const autoValid = await this.evenements.autoValiderCongesExpires(now);
|
||||||
|
const softCancel = await this.evenements.softCancelRefusesExpires(now);
|
||||||
|
return { autoValid, softCancel };
|
||||||
|
} finally {
|
||||||
|
this.running = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import {
|
||||||
|
IsDateString,
|
||||||
|
IsEnum,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
IsUUID,
|
||||||
|
MaxLength,
|
||||||
|
MinLength,
|
||||||
|
} from 'class-validator';
|
||||||
|
import {
|
||||||
|
StatutEvenementAgendaType,
|
||||||
|
TypeEvenementAgendaType,
|
||||||
|
} from 'src/entities/evenements_agenda.entity';
|
||||||
|
import { AgendaLotStatutType } from 'src/entities/agenda_lots.entity';
|
||||||
|
|
||||||
|
export class CreerEvenementAgendaDto {
|
||||||
|
@ApiProperty({ description: 'Placement AM↔enfant (couple)' })
|
||||||
|
@IsUUID()
|
||||||
|
id_placement: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: TypeEvenementAgendaType })
|
||||||
|
@IsEnum(TypeEvenementAgendaType)
|
||||||
|
type: TypeEvenementAgendaType;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2026-10-01' })
|
||||||
|
@IsDateString()
|
||||||
|
date_debut: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2026-10-05' })
|
||||||
|
@IsDateString()
|
||||||
|
date_fin: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(2000)
|
||||||
|
motif?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MajEvenementAgendaDto {
|
||||||
|
@ApiPropertyOptional({ example: '2026-10-02' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
date_debut?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: '2026-10-06' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
date_fin?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ enum: StatutEvenementAgendaType })
|
||||||
|
@IsOptional()
|
||||||
|
@IsEnum(StatutEvenementAgendaType)
|
||||||
|
statut?: StatutEvenementAgendaType;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Motivation de refus (parent) ou motif créateur',
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(2000)
|
||||||
|
motif?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Droits calculés pour l’utilisateur courant — #215 */
|
||||||
|
export class EvenementAgendaActionsDto {
|
||||||
|
@ApiProperty({ description: 'Peut modifier dates / resoumettre (créateur)' })
|
||||||
|
peut_modifier: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Peut annuler / soft-cancel (créateur)' })
|
||||||
|
peut_supprimer: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'Peut accept/refuse (parent habilité, congé en attente)',
|
||||||
|
})
|
||||||
|
peut_accepter_refuser: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'Peut ack informatif (ex. arrêt maladie)',
|
||||||
|
})
|
||||||
|
peut_ack: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class EvenementAgendaDto {
|
||||||
|
@ApiProperty()
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
id_placement: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Lot collectif (congé/arrêt/absence groupés)',
|
||||||
|
nullable: true,
|
||||||
|
})
|
||||||
|
id_lot?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Carte de collecte liée',
|
||||||
|
nullable: true,
|
||||||
|
})
|
||||||
|
id_card_instance?: string | null;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: TypeEvenementAgendaType })
|
||||||
|
type: TypeEvenementAgendaType;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2026-10-01' })
|
||||||
|
date_debut: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2026-10-05' })
|
||||||
|
date_fin: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
example: '18:19',
|
||||||
|
description: 'Heure métier (soin), HH:mm',
|
||||||
|
nullable: true,
|
||||||
|
})
|
||||||
|
heure?: string | null;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
enum: StatutEvenementAgendaType,
|
||||||
|
description: 'Statut de cet événement (membre du lot si lot)',
|
||||||
|
})
|
||||||
|
statut: StatutEvenementAgendaType;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
enum: AgendaLotStatutType,
|
||||||
|
description: 'Statut global du lot ; null si hors lot',
|
||||||
|
nullable: true,
|
||||||
|
})
|
||||||
|
statut_lot?: AgendaLotStatutType | null;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
enum: StatutEvenementAgendaType,
|
||||||
|
description:
|
||||||
|
'Statut à afficher pour l’utilisateur courant (peut différer du membre si lot refusé / nouvel accueil)',
|
||||||
|
})
|
||||||
|
statut_effectif: StatutEvenementAgendaType;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
expire_at: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ nullable: true })
|
||||||
|
verrouille_le?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ nullable: true })
|
||||||
|
refuse_le?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ nullable: true })
|
||||||
|
annule_le?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
cree_par?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Motif créateur ou texte de refus (sans nommer la famille)',
|
||||||
|
nullable: true,
|
||||||
|
})
|
||||||
|
motif?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description:
|
||||||
|
'Libellé de refus anonymisé : « Refusé par une autre famille » / « Refusé par l\'autre parent »',
|
||||||
|
nullable: true,
|
||||||
|
})
|
||||||
|
libelle_refus?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
id_enfant?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
prenom_enfant?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
id_am?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
prenom_am?: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
nom_am?: string | null;
|
||||||
|
|
||||||
|
@ApiProperty({ type: EvenementAgendaActionsDto })
|
||||||
|
actions: EvenementAgendaActionsDto;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
cree_le: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
modifie_le: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ListeEvenementsAgendaDto {
|
||||||
|
@ApiProperty({ type: [EvenementAgendaDto] })
|
||||||
|
items: EvenementAgendaDto[];
|
||||||
|
}
|
||||||
@@ -1,15 +1,16 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { AbsencesGardeController } from './absences-garde.controller';
|
import { EvenementsAgendaController } from './evenements-agenda.controller';
|
||||||
import { AbsencesGardeService } from './absences-garde.service';
|
import { EvenementsAgendaService } from './evenements-agenda.service';
|
||||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
import { RoleType } from 'src/entities/users.entity';
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
import { TypeAbsenceGardeType } from 'src/entities/absences_garde.entity';
|
import { TypeEvenementAgendaType } from 'src/entities/evenements_agenda.entity';
|
||||||
|
|
||||||
describe('AbsencesGardeController (#172)', () => {
|
describe('EvenementsAgendaController (#172)', () => {
|
||||||
let controller: AbsencesGardeController;
|
let controller: EvenementsAgendaController;
|
||||||
const serviceMock = {
|
const serviceMock = {
|
||||||
lister: jest.fn(),
|
lister: jest.fn(),
|
||||||
|
getById: jest.fn(),
|
||||||
creer: jest.fn(),
|
creer: jest.fn(),
|
||||||
maj: jest.fn(),
|
maj: jest.fn(),
|
||||||
supprimer: jest.fn(),
|
supprimer: jest.fn(),
|
||||||
@@ -17,8 +18,8 @@ describe('AbsencesGardeController (#172)', () => {
|
|||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
controllers: [AbsencesGardeController],
|
controllers: [EvenementsAgendaController],
|
||||||
providers: [{ provide: AbsencesGardeService, useValue: serviceMock }],
|
providers: [{ provide: EvenementsAgendaService, useValue: serviceMock }],
|
||||||
})
|
})
|
||||||
.overrideGuard(AuthGuard)
|
.overrideGuard(AuthGuard)
|
||||||
.useValue({ canActivate: () => true })
|
.useValue({ canActivate: () => true })
|
||||||
@@ -26,7 +27,7 @@ describe('AbsencesGardeController (#172)', () => {
|
|||||||
.useValue({ canActivate: () => true })
|
.useValue({ canActivate: () => true })
|
||||||
.compile();
|
.compile();
|
||||||
|
|
||||||
controller = module.get(AbsencesGardeController);
|
controller = module.get(EvenementsAgendaController);
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -59,7 +60,7 @@ describe('AbsencesGardeController (#172)', () => {
|
|||||||
serviceMock.creer.mockResolvedValue({ id: 'a1' });
|
serviceMock.creer.mockResolvedValue({ id: 'a1' });
|
||||||
const dto = {
|
const dto = {
|
||||||
id_placement: 'pl-1',
|
id_placement: 'pl-1',
|
||||||
type: TypeAbsenceGardeType.ABSENCE_ENFANT,
|
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
|
||||||
date_debut: '2026-10-01',
|
date_debut: '2026-10-01',
|
||||||
date_fin: '2026-10-02',
|
date_fin: '2026-10-02',
|
||||||
};
|
};
|
||||||
@@ -70,4 +71,14 @@ describe('AbsencesGardeController (#172)', () => {
|
|||||||
dto,
|
dto,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('getById délègue au service — #215', async () => {
|
||||||
|
serviceMock.getById.mockResolvedValue({ id: 'ev-1', actions: {} });
|
||||||
|
await controller.getById('u1', RoleType.PARENT, 'ev-1');
|
||||||
|
expect(serviceMock.getById).toHaveBeenCalledWith(
|
||||||
|
'ev-1',
|
||||||
|
'u1',
|
||||||
|
RoleType.PARENT,
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
|
Param,
|
||||||
|
ParseUUIDPipe,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiBody,
|
||||||
|
ApiOperation,
|
||||||
|
ApiQuery,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from '@nestjs/swagger';
|
||||||
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||||
|
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||||
|
import { Roles } from 'src/common/decorators/roles.decorator';
|
||||||
|
import { User } from 'src/common/decorators/user.decorator';
|
||||||
|
import {
|
||||||
|
StatutEvenementAgendaType,
|
||||||
|
TypeEvenementAgendaType,
|
||||||
|
} from 'src/entities/evenements_agenda.entity';
|
||||||
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
import { EvenementsAgendaService } from './evenements-agenda.service';
|
||||||
|
import {
|
||||||
|
EvenementAgendaDto,
|
||||||
|
CreerEvenementAgendaDto,
|
||||||
|
ListeEvenementsAgendaDto,
|
||||||
|
MajEvenementAgendaDto,
|
||||||
|
} from './dto/evenements-agenda.dto';
|
||||||
|
|
||||||
|
@ApiTags('Événements agenda')
|
||||||
|
@ApiBearerAuth('access-token')
|
||||||
|
@Controller('evenements-agenda')
|
||||||
|
@UseGuards(AuthGuard, RolesGuard)
|
||||||
|
export class EvenementsAgendaController {
|
||||||
|
constructor(private readonly evenementsAgendaService: EvenementsAgendaService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Lister les événements agenda — #217 / #205',
|
||||||
|
description:
|
||||||
|
'Sans placementId : tous les placements du user (actifs **et** terminés — historique). ' +
|
||||||
|
'Avec placementId : un couple enfant–AM (terminé OK). ' +
|
||||||
|
'Filtres from/to inclusifs (chevauchement). Annulés exclus sauf si statut=annule. ' +
|
||||||
|
'Dates YYYY-MM-DD calendaires (DST-safe).',
|
||||||
|
})
|
||||||
|
@ApiQuery({ name: 'placementId', required: false })
|
||||||
|
@ApiQuery({ name: 'type', required: false, enum: TypeEvenementAgendaType })
|
||||||
|
@ApiQuery({ name: 'statut', required: false, enum: StatutEvenementAgendaType })
|
||||||
|
@ApiQuery({ name: 'from', required: false, description: 'YYYY-MM-DD (inclus)' })
|
||||||
|
@ApiQuery({ name: 'to', required: false, description: 'YYYY-MM-DD (inclus)' })
|
||||||
|
@ApiResponse({ status: 200, type: ListeEvenementsAgendaDto })
|
||||||
|
lister(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Query('placementId') placementId?: string,
|
||||||
|
@Query('type') type?: TypeEvenementAgendaType,
|
||||||
|
@Query('statut') statut?: StatutEvenementAgendaType,
|
||||||
|
@Query('from') from?: string,
|
||||||
|
@Query('to') to?: string,
|
||||||
|
): Promise<ListeEvenementsAgendaDto> {
|
||||||
|
return this.evenementsAgendaService.lister(userId, role, {
|
||||||
|
placementId,
|
||||||
|
type,
|
||||||
|
statut,
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':id')
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Détail d’un événement agenda — #215',
|
||||||
|
description:
|
||||||
|
'DTO enrichi : id_lot, heure, statut_lot, statut_effectif, actions. ' +
|
||||||
|
'Lecture autorisée sur placement terminé (historique). ' +
|
||||||
|
'Aucun secret sur l’auteur d’un refus d’une autre famille.',
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: 200, type: EvenementAgendaDto })
|
||||||
|
getById(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
): Promise<EvenementAgendaDto> {
|
||||||
|
return this.evenementsAgendaService.getById(id, userId, role);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiOperation({ summary: 'Créer une période d’absence / congé / arrêt — #172' })
|
||||||
|
@ApiBody({ type: CreerEvenementAgendaDto })
|
||||||
|
@ApiResponse({ status: 201, type: EvenementAgendaDto })
|
||||||
|
@HttpCode(HttpStatus.CREATED)
|
||||||
|
creer(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Body() dto: CreerEvenementAgendaDto,
|
||||||
|
): Promise<EvenementAgendaDto> {
|
||||||
|
return this.evenementsAgendaService.creer(userId, role, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':id')
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Mettre à jour dates / statut / motif — #172',
|
||||||
|
description:
|
||||||
|
'Parent : accept/refuse congé (motivation si refus), ack arrêt. ' +
|
||||||
|
'AM : modifier dates (en attente / refuse / accepté), republication après refus.',
|
||||||
|
})
|
||||||
|
@ApiBody({ type: MajEvenementAgendaDto })
|
||||||
|
@ApiResponse({ status: 200, type: EvenementAgendaDto })
|
||||||
|
maj(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
@Body() dto: MajEvenementAgendaDto,
|
||||||
|
): Promise<EvenementAgendaDto> {
|
||||||
|
return this.evenementsAgendaService.maj(userId, role, id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':id')
|
||||||
|
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||||
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
|
@ApiOperation({ summary: 'Supprimer une absence (hard delete) — #172' })
|
||||||
|
@ApiResponse({ status: 204 })
|
||||||
|
async supprimer(
|
||||||
|
@User('id') userId: string,
|
||||||
|
@User('role') role: RoleType,
|
||||||
|
@Param('id', ParseUUIDPipe) id: string,
|
||||||
|
): Promise<void> {
|
||||||
|
await this.evenementsAgendaService.supprimer(userId, role, id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { EvenementsAgenda } from 'src/entities/evenements_agenda.entity';
|
||||||
|
import { AgendaLots } from 'src/entities/agenda_lots.entity';
|
||||||
|
import { CardInstance } from 'src/entities/card_instances.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { EvenementsAgendaController } from './evenements-agenda.controller';
|
||||||
|
import { EvenementsAgendaService } from './evenements-agenda.service';
|
||||||
|
import { AgendaExpirationCron } from './agenda-expiration.cron';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
TypeOrmModule.forFeature([
|
||||||
|
EvenementsAgenda,
|
||||||
|
AgendaLots,
|
||||||
|
CardInstance,
|
||||||
|
AmChildren,
|
||||||
|
ParentsChildren,
|
||||||
|
]),
|
||||||
|
JwtModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: (config: ConfigService) => ({
|
||||||
|
secret: config.get('jwt.accessSecret'),
|
||||||
|
signOptions: { expiresIn: config.get('jwt.accessExpiresIn') },
|
||||||
|
}),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
controllers: [EvenementsAgendaController],
|
||||||
|
providers: [EvenementsAgendaService, AgendaExpirationCron],
|
||||||
|
exports: [EvenementsAgendaService],
|
||||||
|
})
|
||||||
|
export class EvenementsAgendaModule {}
|
||||||
@@ -0,0 +1,668 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
|
import { ForbiddenException, BadRequestException } from '@nestjs/common';
|
||||||
|
import { EvenementsAgendaService } from './evenements-agenda.service';
|
||||||
|
import {
|
||||||
|
EvenementsAgenda,
|
||||||
|
StatutEvenementAgendaType,
|
||||||
|
TypeEvenementAgendaType,
|
||||||
|
} from 'src/entities/evenements_agenda.entity';
|
||||||
|
import { AgendaLots } from 'src/entities/agenda_lots.entity';
|
||||||
|
import { CardInstance } from 'src/entities/card_instances.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
import { todayParis, yesterdayParis } from 'src/common/utils/paris-date';
|
||||||
|
|
||||||
|
function qbUpdateMock() {
|
||||||
|
const chain: Record<string, jest.Mock> = {};
|
||||||
|
chain.update = jest.fn().mockReturnValue(chain);
|
||||||
|
chain.set = jest.fn().mockReturnValue(chain);
|
||||||
|
chain.where = jest.fn().mockReturnValue(chain);
|
||||||
|
chain.andWhere = jest.fn().mockReturnValue(chain);
|
||||||
|
chain.execute = jest.fn().mockResolvedValue({ affected: 1 });
|
||||||
|
return chain;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('EvenementsAgendaService (#172)', () => {
|
||||||
|
let service: EvenementsAgendaService;
|
||||||
|
const absencesRepo = {
|
||||||
|
create: jest.fn((x) => x),
|
||||||
|
save: jest.fn(async (x) => ({
|
||||||
|
...x,
|
||||||
|
id: x.id ?? 'abs-1',
|
||||||
|
cree_le: new Date(),
|
||||||
|
modifie_le: new Date(),
|
||||||
|
})),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
find: jest.fn(),
|
||||||
|
update: jest.fn(async () => ({ affected: 1 })),
|
||||||
|
delete: jest.fn(),
|
||||||
|
createQueryBuilder: jest.fn(),
|
||||||
|
};
|
||||||
|
const lotsRepo = {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
update: jest.fn(async () => ({ affected: 1 })),
|
||||||
|
createQueryBuilder: jest.fn(() => qbUpdateMock()),
|
||||||
|
};
|
||||||
|
const cardsRepo = {
|
||||||
|
createQueryBuilder: jest.fn(() => qbUpdateMock()),
|
||||||
|
};
|
||||||
|
const amChildrenRepo = {
|
||||||
|
find: jest.fn(),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
const parentsChildrenRepo = {
|
||||||
|
find: jest.fn(),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
EvenementsAgendaService,
|
||||||
|
{ provide: getRepositoryToken(EvenementsAgenda), useValue: absencesRepo },
|
||||||
|
{ provide: getRepositoryToken(AgendaLots), useValue: lotsRepo },
|
||||||
|
{ provide: getRepositoryToken(CardInstance), useValue: cardsRepo },
|
||||||
|
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo },
|
||||||
|
{
|
||||||
|
provide: getRepositoryToken(ParentsChildren),
|
||||||
|
useValue: parentsChildrenRepo,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
service = module.get(EvenementsAgendaService);
|
||||||
|
jest.clearAllMocks();
|
||||||
|
lotsRepo.createQueryBuilder.mockImplementation(() => qbUpdateMock());
|
||||||
|
cardsRepo.createQueryBuilder.mockImplementation(() => qbUpdateMock());
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(service).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parent crée absence_enfant → statut accepte', async () => {
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
parentsChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
parentId: 'p-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
});
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'abs-1',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
|
||||||
|
date_debut: '2026-10-01',
|
||||||
|
date_fin: '2026-10-02',
|
||||||
|
statut: StatutEvenementAgendaType.ACCEPTE,
|
||||||
|
expire_at: new Date('9999-12-31'),
|
||||||
|
cree_le: new Date(),
|
||||||
|
modifie_le: new Date(),
|
||||||
|
placement: {
|
||||||
|
enfantId: 'e-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
child: { id: 'e-1', first_name: 'Léo' },
|
||||||
|
am: { user: { prenom: 'Marie', nom: 'AM' } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await service.creer('p-1', RoleType.PARENT, {
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
|
||||||
|
date_debut: '2026-10-01',
|
||||||
|
date_fin: '2026-10-02',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(absencesRepo.save).toHaveBeenCalled();
|
||||||
|
const savedArg = absencesRepo.save.mock.calls[0][0];
|
||||||
|
expect(savedArg.statut).toBe(StatutEvenementAgendaType.ACCEPTE);
|
||||||
|
expect(res.type).toBe(TypeEvenementAgendaType.ABSENCE_ENFANT);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parent ne peut pas créer un congé AM', async () => {
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
parentsChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
parentId: 'p-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
service.creer('p-1', RoleType.PARENT, {
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.CONGE_AM,
|
||||||
|
date_debut: '2026-10-01',
|
||||||
|
date_fin: '2026-10-05',
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(ForbiddenException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refus congé sans motif → BadRequest', async () => {
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'abs-1',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.CONGE_AM,
|
||||||
|
date_debut: '2026-10-01',
|
||||||
|
date_fin: '2026-10-05',
|
||||||
|
statut: StatutEvenementAgendaType.EN_ATTENTE,
|
||||||
|
expire_at: new Date(),
|
||||||
|
});
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
parentsChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
parentId: 'p-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.maj('p-1', RoleType.PARENT, 'abs-1', {
|
||||||
|
statut: StatutEvenementAgendaType.REFUSE,
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dates invalides → BadRequest', async () => {
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
parentsChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
parentId: 'p-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
service.creer('p-1', RoleType.PARENT, {
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
|
||||||
|
date_debut: '2026-10-10',
|
||||||
|
date_fin: '2026-10-01',
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getById enrichit le DTO — #215', async () => {
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'ev-1',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
id_lot: 'lot-1',
|
||||||
|
id_card_instance: 'card-1',
|
||||||
|
type: TypeEvenementAgendaType.SOIN_ENFANT,
|
||||||
|
date_debut: '2026-10-16',
|
||||||
|
date_fin: '2026-10-16',
|
||||||
|
heure: '18:19:00',
|
||||||
|
statut: StatutEvenementAgendaType.ACCEPTE,
|
||||||
|
expire_at: new Date('9999-12-31'),
|
||||||
|
cree_par: 'am-1',
|
||||||
|
motif: 'Piqûre',
|
||||||
|
cree_le: new Date(),
|
||||||
|
modifie_le: new Date(),
|
||||||
|
lot: null,
|
||||||
|
placement: {
|
||||||
|
enfantId: 'e-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
child: { id: 'e-1', first_name: 'Léo' },
|
||||||
|
am: { user: { prenom: 'Marie', nom: 'AM' } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: '2026-12-01',
|
||||||
|
});
|
||||||
|
parentsChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
parentId: 'p-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await service.getById('ev-1', 'p-1', RoleType.PARENT);
|
||||||
|
expect(res.id_lot).toBe('lot-1');
|
||||||
|
expect(res.id_card_instance).toBe('card-1');
|
||||||
|
expect(res.heure).toBe('18:19');
|
||||||
|
expect(res.statut_effectif).toBe(StatutEvenementAgendaType.ACCEPTE);
|
||||||
|
expect(res.actions.peut_ack).toBe(true);
|
||||||
|
expect(res.actions.peut_accepter_refuser).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getById autorise placement terminé (historique) — #215', async () => {
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'ev-old',
|
||||||
|
id_placement: 'pl-ended',
|
||||||
|
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
|
||||||
|
date_debut: '2026-01-01',
|
||||||
|
date_fin: '2026-01-05',
|
||||||
|
statut: StatutEvenementAgendaType.ACCEPTE,
|
||||||
|
expire_at: new Date('9999-12-31'),
|
||||||
|
cree_par: 'p-1',
|
||||||
|
cree_le: new Date(),
|
||||||
|
modifie_le: new Date(),
|
||||||
|
placement: {
|
||||||
|
enfantId: 'e-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
child: { id: 'e-1', first_name: 'Léo' },
|
||||||
|
am: { user: { prenom: 'Marie', nom: 'AM' } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-ended',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: '2026-06-01',
|
||||||
|
});
|
||||||
|
parentsChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
parentId: 'p-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await service.getById('ev-old', 'p-1', RoleType.PARENT);
|
||||||
|
expect(res.id).toBe('ev-old');
|
||||||
|
expect(res.actions.peut_modifier).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('lister — #217', () => {
|
||||||
|
const andWhere = jest.fn().mockReturnThis();
|
||||||
|
const qb = {
|
||||||
|
leftJoinAndSelect: jest.fn().mockReturnThis(),
|
||||||
|
where: jest.fn().mockReturnThis(),
|
||||||
|
andWhere,
|
||||||
|
orderBy: jest.fn().mockReturnThis(),
|
||||||
|
getMany: jest.fn().mockResolvedValue([]),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
andWhere.mockClear();
|
||||||
|
absencesRepo.createQueryBuilder.mockReturnValue(qb);
|
||||||
|
amChildrenRepo.find.mockResolvedValue([{ id: 'pl-1' }, { id: 'pl-ended' }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('from > to → BadRequest', async () => {
|
||||||
|
await expect(
|
||||||
|
service.lister('am-1', RoleType.ASSISTANTE_MATERNELLE, {
|
||||||
|
from: '2026-10-31',
|
||||||
|
to: '2026-10-01',
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('date invalide (31 nov) → BadRequest', async () => {
|
||||||
|
await expect(
|
||||||
|
service.lister('am-1', RoleType.ASSISTANTE_MATERNELLE, {
|
||||||
|
from: '2026-11-31',
|
||||||
|
to: '2026-12-01',
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('exclut les annulés par défaut + bornes inclusives', async () => {
|
||||||
|
await service.lister('am-1', RoleType.ASSISTANTE_MATERNELLE, {
|
||||||
|
from: '2026-10-01',
|
||||||
|
to: '2026-10-31',
|
||||||
|
});
|
||||||
|
expect(amChildrenRepo.find).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
where: expect.objectContaining({ amId: 'am-1' }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
// pas de date_fin: IsNull() → historique inclus
|
||||||
|
const whereArg = amChildrenRepo.find.mock.calls[0][0].where;
|
||||||
|
expect(whereArg.date_fin).toBeUndefined();
|
||||||
|
expect(andWhere).toHaveBeenCalledWith('ag.statut != :annule', {
|
||||||
|
annule: StatutEvenementAgendaType.ANNULE,
|
||||||
|
});
|
||||||
|
expect(andWhere).toHaveBeenCalledWith('ag.date_fin >= :from', {
|
||||||
|
from: '2026-10-01',
|
||||||
|
});
|
||||||
|
expect(andWhere).toHaveBeenCalledWith('ag.date_debut <= :to', {
|
||||||
|
to: '2026-10-31',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('DST octobre : bornes calendaires acceptées (2026-10-25)', async () => {
|
||||||
|
// dernier dimanche d’octobre 2026 = 25 oct. — strings YYYY-MM-DD, pas Date UTC
|
||||||
|
await expect(
|
||||||
|
service.lister('am-1', RoleType.ASSISTANTE_MATERNELLE, {
|
||||||
|
from: '2026-10-25',
|
||||||
|
to: '2026-10-26',
|
||||||
|
}),
|
||||||
|
).resolves.toEqual({ items: [] });
|
||||||
|
expect(andWhere).toHaveBeenCalledWith('ag.date_fin >= :from', {
|
||||||
|
from: '2026-10-25',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('année bissextile : 2024-02-29 valide', async () => {
|
||||||
|
await expect(
|
||||||
|
service.lister('am-1', RoleType.ASSISTANTE_MATERNELLE, {
|
||||||
|
from: '2024-02-29',
|
||||||
|
to: '2024-03-01',
|
||||||
|
}),
|
||||||
|
).resolves.toEqual({ items: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('2025-02-29 invalide (non bissextile)', async () => {
|
||||||
|
await expect(
|
||||||
|
service.lister('am-1', RoleType.ASSISTANTE_MATERNELLE, {
|
||||||
|
from: '2025-02-29',
|
||||||
|
to: '2025-03-01',
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('libelle_refus n’expose pas l’auteur — #215', async () => {
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'ev-ref',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.CONGE_AM,
|
||||||
|
date_debut: '2026-11-01',
|
||||||
|
date_fin: '2026-11-10',
|
||||||
|
statut: StatutEvenementAgendaType.REFUSE,
|
||||||
|
expire_at: new Date(),
|
||||||
|
cree_par: 'am-1',
|
||||||
|
motif: 'Vacances scolaires',
|
||||||
|
cree_le: new Date(),
|
||||||
|
modifie_le: new Date(),
|
||||||
|
lot: { statut: 'refuse' },
|
||||||
|
placement: {
|
||||||
|
enfantId: 'e-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
child: { id: 'e-1', first_name: 'Léo' },
|
||||||
|
am: { user: { prenom: 'Marie', nom: 'AM' } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
parentsChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
parentId: 'p-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await service.getById('ev-ref', 'p-1', RoleType.PARENT);
|
||||||
|
expect(res.libelle_refus).toBe('Refusé par une autre famille');
|
||||||
|
expect(res.statut_effectif).toBe(StatutEvenementAgendaType.REFUSE);
|
||||||
|
expect(res.libelle_refus).not.toMatch(/p-2|Dupont|famille B/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('B2 — #216 matrice + soft-cancel + cron', () => {
|
||||||
|
it('arrêt maladie créé → statut accepte + verrouille_le', async () => {
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'abs-1',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.ARRET_MALADIE_AM,
|
||||||
|
date_debut: '2026-10-01',
|
||||||
|
date_fin: '2026-10-05',
|
||||||
|
statut: StatutEvenementAgendaType.ACCEPTE,
|
||||||
|
expire_at: new Date('9999-12-31'),
|
||||||
|
verrouille_le: new Date(),
|
||||||
|
cree_le: new Date(),
|
||||||
|
modifie_le: new Date(),
|
||||||
|
placement: {
|
||||||
|
enfantId: 'e-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
child: { id: 'e-1', first_name: 'Léo' },
|
||||||
|
am: { user: { prenom: 'Marie', nom: 'AM' } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await service.creer('am-1', RoleType.ASSISTANTE_MATERNELLE, {
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.ARRET_MALADIE_AM,
|
||||||
|
date_debut: '2026-10-01',
|
||||||
|
date_fin: '2026-10-05',
|
||||||
|
});
|
||||||
|
|
||||||
|
const saved = absencesRepo.save.mock.calls[0][0];
|
||||||
|
expect(saved.statut).toBe(StatutEvenementAgendaType.ACCEPTE);
|
||||||
|
expect(saved.verrouille_le).toBeInstanceOf(Date);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parent maj statut arrêt → 400 (ack n’écrit pas sur l’événement)', async () => {
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'abs-1',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.ARRET_MALADIE_AM,
|
||||||
|
date_debut: '2026-10-01',
|
||||||
|
date_fin: '2026-10-05',
|
||||||
|
statut: StatutEvenementAgendaType.ACCEPTE,
|
||||||
|
expire_at: new Date('9999-12-31'),
|
||||||
|
cree_le: new Date(),
|
||||||
|
verrouille_le: new Date(),
|
||||||
|
});
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
parentsChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
parentId: 'p-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.maj('p-1', RoleType.PARENT, 'abs-1', {
|
||||||
|
statut: StatutEvenementAgendaType.ACCEPTE,
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('soin hors [hier, auj.] → BadRequest', async () => {
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
service.creer('am-1', RoleType.ASSISTANTE_MATERNELLE, {
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.SOIN_ENFANT,
|
||||||
|
date_debut: '2020-01-01',
|
||||||
|
date_fin: '2020-01-01',
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(BadRequestException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('soin daté aujourd’hui (Paris) → OK', async () => {
|
||||||
|
const auj = todayParis();
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'abs-1',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.SOIN_ENFANT,
|
||||||
|
date_debut: auj,
|
||||||
|
date_fin: auj,
|
||||||
|
statut: StatutEvenementAgendaType.ACCEPTE,
|
||||||
|
expire_at: new Date('9999-12-31'),
|
||||||
|
cree_le: new Date(),
|
||||||
|
modifie_le: new Date(),
|
||||||
|
placement: {
|
||||||
|
enfantId: 'e-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
child: { id: 'e-1', first_name: 'Léo' },
|
||||||
|
am: { user: { prenom: 'Marie', nom: 'AM' } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
service.creer('am-1', RoleType.ASSISTANTE_MATERNELLE, {
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.SOIN_ENFANT,
|
||||||
|
date_debut: auj,
|
||||||
|
date_fin: auj,
|
||||||
|
}),
|
||||||
|
).resolves.toBeDefined();
|
||||||
|
// hier aussi OK
|
||||||
|
const hier = yesterdayParis();
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'abs-2',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.SOIN_ENFANT,
|
||||||
|
date_debut: hier,
|
||||||
|
date_fin: hier,
|
||||||
|
statut: StatutEvenementAgendaType.ACCEPTE,
|
||||||
|
expire_at: new Date('9999-12-31'),
|
||||||
|
cree_le: new Date(),
|
||||||
|
modifie_le: new Date(),
|
||||||
|
placement: {
|
||||||
|
enfantId: 'e-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
child: { id: 'e-1', first_name: 'Léo' },
|
||||||
|
am: { user: { prenom: 'Marie', nom: 'AM' } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
service.creer('am-1', RoleType.ASSISTANTE_MATERNELLE, {
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.SOIN_ENFANT,
|
||||||
|
date_debut: hier,
|
||||||
|
date_fin: hier,
|
||||||
|
}),
|
||||||
|
).resolves.toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('supprimer → soft-cancel (update ANNULE), pas delete physique', async () => {
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'abs-1',
|
||||||
|
id_placement: 'pl-1',
|
||||||
|
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
|
||||||
|
date_debut: '2026-10-01',
|
||||||
|
date_fin: '2026-10-02',
|
||||||
|
statut: StatutEvenementAgendaType.ACCEPTE,
|
||||||
|
cree_le: new Date(),
|
||||||
|
verrouille_le: new Date(),
|
||||||
|
cree_par: 'p-1',
|
||||||
|
});
|
||||||
|
amChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'pl-1',
|
||||||
|
amId: 'am-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
date_fin: null,
|
||||||
|
});
|
||||||
|
parentsChildrenRepo.findOne.mockResolvedValue({
|
||||||
|
parentId: 'p-1',
|
||||||
|
enfantId: 'e-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
await service.supprimer('p-1', RoleType.PARENT, 'abs-1');
|
||||||
|
expect(absencesRepo.delete).not.toHaveBeenCalled();
|
||||||
|
expect(absencesRepo.update).toHaveBeenCalledWith(
|
||||||
|
{ id: 'abs-1' },
|
||||||
|
expect.objectContaining({
|
||||||
|
statut: StatutEvenementAgendaType.ANNULE,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cron auto-valid + soft-cancel refusés ; double appel idempotent', async () => {
|
||||||
|
const old = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000);
|
||||||
|
absencesRepo.find.mockResolvedValue([
|
||||||
|
{
|
||||||
|
id: 'c1',
|
||||||
|
type: TypeEvenementAgendaType.CONGE_AM,
|
||||||
|
statut: StatutEvenementAgendaType.EN_ATTENTE,
|
||||||
|
verrouille_le: old,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
const legacyQb = {
|
||||||
|
where: jest.fn().mockReturnThis(),
|
||||||
|
andWhere: jest.fn().mockReturnThis(),
|
||||||
|
getMany: jest.fn().mockResolvedValue([]),
|
||||||
|
};
|
||||||
|
const refuseQb = {
|
||||||
|
where: jest.fn().mockReturnThis(),
|
||||||
|
andWhere: jest.fn().mockReturnThis(),
|
||||||
|
getMany: jest.fn().mockResolvedValue([
|
||||||
|
{
|
||||||
|
id: 'r1',
|
||||||
|
statut: StatutEvenementAgendaType.REFUSE,
|
||||||
|
refuse_le: old,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
absencesRepo.createQueryBuilder
|
||||||
|
.mockReturnValueOnce(legacyQb) // autoValider legacy
|
||||||
|
.mockReturnValueOnce(refuseQb); // softCancelRefuses
|
||||||
|
absencesRepo.findOne.mockImplementation(async ({ where }) => {
|
||||||
|
if (where?.id === 'r1') {
|
||||||
|
return {
|
||||||
|
id: 'r1',
|
||||||
|
statut: StatutEvenementAgendaType.REFUSE,
|
||||||
|
refuse_le: old,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
|
const n1 = await service.autoValiderCongesExpires();
|
||||||
|
expect(n1).toBe(1);
|
||||||
|
expect(absencesRepo.update).toHaveBeenCalledWith(
|
||||||
|
{ id: 'c1', statut: StatutEvenementAgendaType.EN_ATTENTE },
|
||||||
|
expect.objectContaining({
|
||||||
|
statut: StatutEvenementAgendaType.ACCEPTE,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
absencesRepo.find.mockResolvedValue([]); // déjà validés
|
||||||
|
const emptyQb = {
|
||||||
|
where: jest.fn().mockReturnThis(),
|
||||||
|
andWhere: jest.fn().mockReturnThis(),
|
||||||
|
getMany: jest.fn().mockResolvedValue([]),
|
||||||
|
};
|
||||||
|
absencesRepo.createQueryBuilder.mockReset();
|
||||||
|
absencesRepo.createQueryBuilder.mockReturnValue(emptyQb);
|
||||||
|
const n2 = await service.autoValiderCongesExpires();
|
||||||
|
expect(n2).toBe(0);
|
||||||
|
|
||||||
|
// soft-cancel refusés
|
||||||
|
absencesRepo.createQueryBuilder.mockReturnValue(refuseQb);
|
||||||
|
refuseQb.getMany.mockResolvedValue([
|
||||||
|
{ id: 'r1', statut: StatutEvenementAgendaType.REFUSE, refuse_le: old },
|
||||||
|
]);
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'r1',
|
||||||
|
statut: StatutEvenementAgendaType.REFUSE,
|
||||||
|
refuse_le: old,
|
||||||
|
});
|
||||||
|
const sc1 = await service.softCancelRefusesExpires();
|
||||||
|
expect(sc1).toBe(1);
|
||||||
|
// 2e passage : déjà ANNULE → 0
|
||||||
|
absencesRepo.findOne.mockResolvedValue({
|
||||||
|
id: 'r1',
|
||||||
|
statut: StatutEvenementAgendaType.ANNULE,
|
||||||
|
});
|
||||||
|
refuseQb.getMany.mockResolvedValue([
|
||||||
|
{ id: 'r1', statut: StatutEvenementAgendaType.ANNULE },
|
||||||
|
]);
|
||||||
|
const sc2 = await service.softCancelRefusesExpires();
|
||||||
|
expect(sc2).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,987 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
ForbiddenException,
|
||||||
|
Injectable,
|
||||||
|
Logger,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { In, IsNull, LessThanOrEqual, Repository } from 'typeorm';
|
||||||
|
import {
|
||||||
|
EvenementsAgenda,
|
||||||
|
StatutEvenementAgendaType,
|
||||||
|
TypeEvenementAgendaType,
|
||||||
|
} from 'src/entities/evenements_agenda.entity';
|
||||||
|
import {
|
||||||
|
AgendaLots,
|
||||||
|
AgendaLotStatutType,
|
||||||
|
} from 'src/entities/agenda_lots.entity';
|
||||||
|
import {
|
||||||
|
CardInstance,
|
||||||
|
CardInstanceStatutType,
|
||||||
|
} from 'src/entities/card_instances.entity';
|
||||||
|
import { AmChildren } from 'src/entities/am_children.entity';
|
||||||
|
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||||
|
import { RoleType } from 'src/entities/users.entity';
|
||||||
|
import {
|
||||||
|
EvenementAgendaDto,
|
||||||
|
EvenementAgendaActionsDto,
|
||||||
|
CreerEvenementAgendaDto,
|
||||||
|
ListeEvenementsAgendaDto,
|
||||||
|
MajEvenementAgendaDto,
|
||||||
|
} from './dto/evenements-agenda.dto';
|
||||||
|
import {
|
||||||
|
MS_24H,
|
||||||
|
MS_7X24H,
|
||||||
|
todayParis,
|
||||||
|
yesterdayParis,
|
||||||
|
} from 'src/common/utils/paris-date';
|
||||||
|
|
||||||
|
/** Auto-valid / soft-cancel refusés = 7×24 h (mini-spec §5). */
|
||||||
|
const TTL_EN_ATTENTE_MS = MS_7X24H;
|
||||||
|
const TTL_REFUSE_MS = MS_7X24H;
|
||||||
|
/** Sentinel « pas de purge » pour les périodes acceptées */
|
||||||
|
const EXPIRE_ACCEPTE = new Date('9999-12-31T23:59:59.999Z');
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class EvenementsAgendaService {
|
||||||
|
private readonly logger = new Logger(EvenementsAgendaService.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(EvenementsAgenda)
|
||||||
|
private readonly absencesRepo: Repository<EvenementsAgenda>,
|
||||||
|
@InjectRepository(AgendaLots)
|
||||||
|
private readonly lotsRepo: Repository<AgendaLots>,
|
||||||
|
@InjectRepository(CardInstance)
|
||||||
|
private readonly cardsRepo: Repository<CardInstance>,
|
||||||
|
@InjectRepository(AmChildren)
|
||||||
|
private readonly amChildrenRepo: Repository<AmChildren>,
|
||||||
|
@InjectRepository(ParentsChildren)
|
||||||
|
private readonly parentsChildrenRepo: Repository<ParentsChildren>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async lister(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
opts: {
|
||||||
|
placementId?: string;
|
||||||
|
type?: TypeEvenementAgendaType;
|
||||||
|
statut?: StatutEvenementAgendaType;
|
||||||
|
from?: string;
|
||||||
|
to?: string;
|
||||||
|
},
|
||||||
|
): Promise<ListeEvenementsAgendaDto> {
|
||||||
|
this.assertDateRange(opts.from, opts.to);
|
||||||
|
|
||||||
|
// Agenda : historique inclus (placements terminés) — #217
|
||||||
|
const placementIds = await this.resolvePlacementIds(
|
||||||
|
userId,
|
||||||
|
role,
|
||||||
|
opts.placementId,
|
||||||
|
{ includeEnded: true },
|
||||||
|
);
|
||||||
|
if (placementIds.length === 0) {
|
||||||
|
return { items: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const qb = this.absencesRepo
|
||||||
|
.createQueryBuilder('ag')
|
||||||
|
.leftJoinAndSelect('ag.placement', 'placement')
|
||||||
|
.leftJoinAndSelect('placement.child', 'child')
|
||||||
|
.leftJoinAndSelect('placement.am', 'am')
|
||||||
|
.leftJoinAndSelect('am.user', 'amUser')
|
||||||
|
.leftJoinAndSelect('ag.lot', 'lot')
|
||||||
|
.where('ag.id_placement IN (:...placementIds)', { placementIds })
|
||||||
|
.orderBy('ag.date_debut', 'DESC');
|
||||||
|
|
||||||
|
if (opts.type) {
|
||||||
|
qb.andWhere('ag.type = :type', { type: opts.type });
|
||||||
|
}
|
||||||
|
// Exclusion des annulés par défaut ; statut=annule demande explicitement les annulés
|
||||||
|
if (opts.statut) {
|
||||||
|
qb.andWhere('ag.statut = :statut', { statut: opts.statut });
|
||||||
|
} else {
|
||||||
|
qb.andWhere('ag.statut != :annule', {
|
||||||
|
annule: StatutEvenementAgendaType.ANNULE,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Chevauchement inclusif : date_debut <= to AND date_fin >= from
|
||||||
|
if (opts.from) {
|
||||||
|
qb.andWhere('ag.date_fin >= :from', { from: opts.from });
|
||||||
|
}
|
||||||
|
if (opts.to) {
|
||||||
|
qb.andWhere('ag.date_debut <= :to', { to: opts.to });
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await qb.getMany();
|
||||||
|
return {
|
||||||
|
items: rows.map((r) => this.toDto(r, userId, role)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET :id — #215 */
|
||||||
|
async getById(
|
||||||
|
id: string,
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
): Promise<EvenementAgendaDto> {
|
||||||
|
return this.getByIdForUser(id, userId, role);
|
||||||
|
}
|
||||||
|
|
||||||
|
async creer(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
dto: CreerEvenementAgendaDto,
|
||||||
|
): Promise<EvenementAgendaDto> {
|
||||||
|
this.assertDates(dto.date_debut, dto.date_fin);
|
||||||
|
this.assertCalendarDate(dto.date_debut, 'date_debut');
|
||||||
|
this.assertCalendarDate(dto.date_fin, 'date_fin');
|
||||||
|
await this.assertCanAccessPlacement(userId, role, dto.id_placement);
|
||||||
|
this.assertCanCreateType(role, dto.type);
|
||||||
|
this.assertTemporalCreate(dto.type, dto.date_debut, dto.date_fin);
|
||||||
|
|
||||||
|
const statut = this.statutInitial(dto.type);
|
||||||
|
const now = new Date();
|
||||||
|
const entity = this.absencesRepo.create({
|
||||||
|
id_placement: dto.id_placement,
|
||||||
|
type: dto.type,
|
||||||
|
date_debut: dto.date_debut,
|
||||||
|
date_fin: dto.date_fin,
|
||||||
|
statut,
|
||||||
|
expire_at: this.expireAtFor(statut, now),
|
||||||
|
// verrouille_le à la soumission seulement — jamais en GET (#216)
|
||||||
|
verrouille_le: now,
|
||||||
|
cree_par: userId,
|
||||||
|
motif: dto.motif?.trim() || undefined,
|
||||||
|
});
|
||||||
|
const saved = await this.absencesRepo.save(entity);
|
||||||
|
return this.getByIdForUser(saved.id, userId, role);
|
||||||
|
}
|
||||||
|
|
||||||
|
async maj(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
id: string,
|
||||||
|
dto: MajEvenementAgendaDto,
|
||||||
|
): Promise<EvenementAgendaDto> {
|
||||||
|
const row = await this.absencesRepo.findOne({ where: { id } });
|
||||||
|
if (!row) {
|
||||||
|
throw new NotFoundException('Absence introuvable');
|
||||||
|
}
|
||||||
|
if (row.statut === StatutEvenementAgendaType.ANNULE) {
|
||||||
|
throw new BadRequestException('Événement annulé');
|
||||||
|
}
|
||||||
|
await this.assertCanAccessPlacement(userId, role, row.id_placement);
|
||||||
|
|
||||||
|
const datesChange =
|
||||||
|
(dto.date_debut !== undefined && dto.date_debut !== row.date_debut) ||
|
||||||
|
(dto.date_fin !== undefined && dto.date_fin !== row.date_fin);
|
||||||
|
|
||||||
|
if (dto.date_debut !== undefined || dto.date_fin !== undefined) {
|
||||||
|
const debut = dto.date_debut ?? row.date_debut;
|
||||||
|
const fin = dto.date_fin ?? row.date_fin;
|
||||||
|
this.assertDates(debut, fin);
|
||||||
|
this.assertCalendarDate(debut, 'date_debut');
|
||||||
|
this.assertCalendarDate(fin, 'date_fin');
|
||||||
|
this.assertCanEditDates(role, row);
|
||||||
|
this.assertTemporalEdit(row);
|
||||||
|
row.date_debut = debut;
|
||||||
|
row.date_fin = fin;
|
||||||
|
|
||||||
|
// Toute modif de dates d’un événement soumis à validation → nouvelle revision
|
||||||
|
if (datesChange && this.needsRevalidationOnDateChange(row)) {
|
||||||
|
await this.bumpRevisionForDateChange(row, userId);
|
||||||
|
} else if (row.statut === StatutEvenementAgendaType.EN_ATTENTE) {
|
||||||
|
row.expire_at = this.expireAtFor(
|
||||||
|
StatutEvenementAgendaType.EN_ATTENTE,
|
||||||
|
row.verrouille_le ?? row.cree_le,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dto.statut !== undefined) {
|
||||||
|
// Ack arrêt = informatif carte seulement — toute maj statut parent sur arrêt → 400
|
||||||
|
if (
|
||||||
|
role === RoleType.PARENT &&
|
||||||
|
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM
|
||||||
|
) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'L’accusé de réception d’un arrêt maladie n’écrit pas sur l’événement',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (dto.statut !== row.statut) {
|
||||||
|
this.assertCanChangeStatut(role, row, dto.statut, dto.motif);
|
||||||
|
if (
|
||||||
|
dto.statut === StatutEvenementAgendaType.REFUSE &&
|
||||||
|
(!dto.motif || !dto.motif.trim())
|
||||||
|
) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Une motivation est obligatoire en cas de refus',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const now = new Date();
|
||||||
|
row.statut = dto.statut;
|
||||||
|
row.expire_at = this.expireAtFor(dto.statut, now);
|
||||||
|
if (dto.statut === StatutEvenementAgendaType.REFUSE) {
|
||||||
|
row.refuse_le = now;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
dto.statut === StatutEvenementAgendaType.EN_ATTENTE &&
|
||||||
|
datesChange
|
||||||
|
) {
|
||||||
|
// resoumission : nouveau verrou (pas un GET)
|
||||||
|
row.verrouille_le = now;
|
||||||
|
}
|
||||||
|
if (dto.motif?.trim()) {
|
||||||
|
row.motif = dto.motif.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (dto.motif !== undefined) {
|
||||||
|
// Motif seul ne relance pas l’unanimité
|
||||||
|
row.motif = dto.motif.trim() || undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.absencesRepo.save(row);
|
||||||
|
return this.getByIdForUser(id, userId, role);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Soft-cancel applicatif — remplace tout DELETE physique événement (#216).
|
||||||
|
* Idempotent si déjà annulé.
|
||||||
|
*/
|
||||||
|
async supprimer(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
id: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const row = await this.absencesRepo.findOne({ where: { id } });
|
||||||
|
if (!row) {
|
||||||
|
throw new NotFoundException('Absence introuvable');
|
||||||
|
}
|
||||||
|
await this.assertCanAccessPlacement(userId, role, row.id_placement);
|
||||||
|
|
||||||
|
if (
|
||||||
|
role === RoleType.PARENT &&
|
||||||
|
row.type !== TypeEvenementAgendaType.ABSENCE_ENFANT
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Un parent ne peut supprimer que les absences enfant',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.assertCanSoftCancel(role, row);
|
||||||
|
await this.softCancelEvent(row, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Soft-cancel sans re-check role (cron / carte liée). Idempotent. */
|
||||||
|
async softCancelById(id: string, userId?: string | null): Promise<boolean> {
|
||||||
|
const row = await this.absencesRepo.findOne({ where: { id } });
|
||||||
|
if (!row) return false;
|
||||||
|
return this.softCancelEvent(row, userId ?? null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async softCancelEvent(
|
||||||
|
row: EvenementsAgenda,
|
||||||
|
userId: string | null,
|
||||||
|
): Promise<boolean> {
|
||||||
|
if (row.statut === StatutEvenementAgendaType.ANNULE) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const now = new Date();
|
||||||
|
await this.absencesRepo.update(
|
||||||
|
{ id: row.id },
|
||||||
|
{
|
||||||
|
statut: StatutEvenementAgendaType.ANNULE,
|
||||||
|
annule_le: now,
|
||||||
|
annule_par: userId ?? undefined,
|
||||||
|
expire_at: now,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
// Cartes liées : soft-cancel (pas de DELETE physique)
|
||||||
|
await this.cardsRepo
|
||||||
|
.createQueryBuilder()
|
||||||
|
.update(CardInstance)
|
||||||
|
.set({
|
||||||
|
statut: CardInstanceStatutType.ANNULEE,
|
||||||
|
annule_le: now,
|
||||||
|
annule_par: userId ?? undefined,
|
||||||
|
purge_at: now,
|
||||||
|
})
|
||||||
|
.where('id_evenement = :eid', { eid: row.id })
|
||||||
|
.andWhere('statut != :annulee', {
|
||||||
|
annulee: CardInstanceStatutType.ANNULEE,
|
||||||
|
})
|
||||||
|
.execute();
|
||||||
|
if (row.id_lot) {
|
||||||
|
await this.lotsRepo
|
||||||
|
.createQueryBuilder()
|
||||||
|
.update(AgendaLots)
|
||||||
|
.set({
|
||||||
|
statut: AgendaLotStatutType.ANNULE,
|
||||||
|
annule_le: now,
|
||||||
|
annule_par: userId ?? undefined,
|
||||||
|
})
|
||||||
|
.where('id = :id', { id: row.id_lot })
|
||||||
|
.andWhere('statut != :annule', { annule: AgendaLotStatutType.ANNULE })
|
||||||
|
.execute();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cron : auto-valide les congés encore en_attente après 7×24 h depuis verrouille_le.
|
||||||
|
* Idempotent. Retourne le nombre mis à jour.
|
||||||
|
*/
|
||||||
|
async autoValiderCongesExpires(now = new Date()): Promise<number> {
|
||||||
|
const threshold = new Date(now.getTime() - TTL_EN_ATTENTE_MS);
|
||||||
|
const rows = await this.absencesRepo.find({
|
||||||
|
where: {
|
||||||
|
type: TypeEvenementAgendaType.CONGE_AM,
|
||||||
|
statut: StatutEvenementAgendaType.EN_ATTENTE,
|
||||||
|
verrouille_le: LessThanOrEqual(threshold),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// Fallback cree_le si verrouille_le null (données pré-B2)
|
||||||
|
const legacy = await this.absencesRepo
|
||||||
|
.createQueryBuilder('ag')
|
||||||
|
.where('ag.type = :type', { type: TypeEvenementAgendaType.CONGE_AM })
|
||||||
|
.andWhere('ag.statut = :statut', {
|
||||||
|
statut: StatutEvenementAgendaType.EN_ATTENTE,
|
||||||
|
})
|
||||||
|
.andWhere('ag.verrouille_le IS NULL')
|
||||||
|
.andWhere('ag.cree_le <= :threshold', { threshold })
|
||||||
|
.getMany();
|
||||||
|
|
||||||
|
const byId = new Map<string, EvenementsAgenda>();
|
||||||
|
for (const r of [...rows, ...legacy]) byId.set(r.id, r);
|
||||||
|
|
||||||
|
let n = 0;
|
||||||
|
for (const row of byId.values()) {
|
||||||
|
await this.absencesRepo.update(
|
||||||
|
{ id: row.id, statut: StatutEvenementAgendaType.EN_ATTENTE },
|
||||||
|
{
|
||||||
|
statut: StatutEvenementAgendaType.ACCEPTE,
|
||||||
|
expire_at: EXPIRE_ACCEPTE,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (row.id_lot) {
|
||||||
|
await this.lotsRepo.update(
|
||||||
|
{ id: row.id_lot, statut: AgendaLotStatutType.EN_ATTENTE },
|
||||||
|
{ statut: AgendaLotStatutType.ACCEPTE },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
n += 1;
|
||||||
|
}
|
||||||
|
if (n > 0) {
|
||||||
|
this.logger.log(`Cron auto-valid congés : ${n} événement(s)`);
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cron : soft-cancel des refusés après 7×24 h (refuse_le / expire_at).
|
||||||
|
* Idempotent.
|
||||||
|
*/
|
||||||
|
async softCancelRefusesExpires(now = new Date()): Promise<number> {
|
||||||
|
const threshold = new Date(now.getTime() - TTL_REFUSE_MS);
|
||||||
|
const rows = await this.absencesRepo
|
||||||
|
.createQueryBuilder('ag')
|
||||||
|
.where('ag.statut = :statut', {
|
||||||
|
statut: StatutEvenementAgendaType.REFUSE,
|
||||||
|
})
|
||||||
|
.andWhere(
|
||||||
|
'(ag.refuse_le IS NOT NULL AND ag.refuse_le <= :threshold) OR (ag.refuse_le IS NULL AND ag.expire_at <= :now)',
|
||||||
|
{ threshold, now },
|
||||||
|
)
|
||||||
|
.getMany();
|
||||||
|
|
||||||
|
let n = 0;
|
||||||
|
for (const row of rows) {
|
||||||
|
if (await this.softCancelEvent(row, null)) n += 1;
|
||||||
|
}
|
||||||
|
if (n > 0) {
|
||||||
|
this.logger.log(`Cron soft-cancel refusés : ${n} événement(s)`);
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getByIdForUser(
|
||||||
|
id: string,
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
): Promise<EvenementAgendaDto> {
|
||||||
|
const row = await this.absencesRepo.findOne({
|
||||||
|
where: { id },
|
||||||
|
relations: [
|
||||||
|
'placement',
|
||||||
|
'placement.child',
|
||||||
|
'placement.am',
|
||||||
|
'placement.am.user',
|
||||||
|
'lot',
|
||||||
|
],
|
||||||
|
});
|
||||||
|
if (!row) {
|
||||||
|
throw new NotFoundException('Événement introuvable');
|
||||||
|
}
|
||||||
|
// Lecture : historique autorisé même si placement terminé (B1 / prépare B3)
|
||||||
|
await this.assertCanAccessPlacement(userId, role, row.id_placement, {
|
||||||
|
allowEnded: true,
|
||||||
|
});
|
||||||
|
return this.toDto(row, userId, role);
|
||||||
|
}
|
||||||
|
|
||||||
|
private statutInitial(type: TypeEvenementAgendaType): StatutEvenementAgendaType {
|
||||||
|
// Arrêt maladie : accepté dès soumission (ack parent informatif seulement) — #216
|
||||||
|
if (
|
||||||
|
type === TypeEvenementAgendaType.ABSENCE_ENFANT ||
|
||||||
|
type === TypeEvenementAgendaType.SOIN_ENFANT ||
|
||||||
|
type === TypeEvenementAgendaType.ARRET_MALADIE_AM
|
||||||
|
) {
|
||||||
|
return StatutEvenementAgendaType.ACCEPTE;
|
||||||
|
}
|
||||||
|
return StatutEvenementAgendaType.EN_ATTENTE;
|
||||||
|
}
|
||||||
|
|
||||||
|
private expireAtFor(
|
||||||
|
statut: StatutEvenementAgendaType,
|
||||||
|
from: Date = new Date(),
|
||||||
|
): Date {
|
||||||
|
const t = from.getTime();
|
||||||
|
if (
|
||||||
|
statut === StatutEvenementAgendaType.ACCEPTE ||
|
||||||
|
statut === StatutEvenementAgendaType.ANNULE
|
||||||
|
) {
|
||||||
|
return statut === StatutEvenementAgendaType.ANNULE
|
||||||
|
? from
|
||||||
|
: EXPIRE_ACCEPTE;
|
||||||
|
}
|
||||||
|
if (statut === StatutEvenementAgendaType.REFUSE) {
|
||||||
|
return new Date(t + TTL_REFUSE_MS);
|
||||||
|
}
|
||||||
|
return new Date(t + TTL_EN_ATTENTE_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Soin : date ∈ [hier, aujourd’hui] Paris. Autres : passé OK. */
|
||||||
|
private assertTemporalCreate(
|
||||||
|
type: TypeEvenementAgendaType,
|
||||||
|
debut: string,
|
||||||
|
fin: string,
|
||||||
|
): void {
|
||||||
|
if (type !== TypeEvenementAgendaType.SOIN_ENFANT) return;
|
||||||
|
const hier = yesterdayParis();
|
||||||
|
const auj = todayParis();
|
||||||
|
if (debut < hier || debut > auj || fin < hier || fin > auj) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Un soin enfant doit être daté entre hier et aujourd’hui',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fenêtres d’édition (#216) :
|
||||||
|
* - soin : ≤ 24 h depuis cree_le
|
||||||
|
* - congé futur accepté : libre tant que date_debut non commencé
|
||||||
|
* - sinon congé/arrêt/absence : ≤ 7×24 h depuis verrouille_le (soumission)
|
||||||
|
*/
|
||||||
|
private assertTemporalEdit(row: EvenementsAgenda): void {
|
||||||
|
const now = Date.now();
|
||||||
|
if (row.type === TypeEvenementAgendaType.SOIN_ENFANT) {
|
||||||
|
const since = now - new Date(row.cree_le).getTime();
|
||||||
|
if (since > MS_24H) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Délai de correction de 24 h dépassé pour ce soin',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const today = todayParis();
|
||||||
|
if (
|
||||||
|
row.type === TypeEvenementAgendaType.CONGE_AM &&
|
||||||
|
row.statut === StatutEvenementAgendaType.ACCEPTE &&
|
||||||
|
row.date_debut > today
|
||||||
|
) {
|
||||||
|
return; // futur validé : modifiable/annulable
|
||||||
|
}
|
||||||
|
|
||||||
|
const anchor = row.verrouille_le ?? row.cree_le;
|
||||||
|
const since = now - new Date(anchor).getTime();
|
||||||
|
if (since > MS_7X24H) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Délai d’édition de 7×24 h dépassé pour cet événement',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertCanSoftCancel(role: RoleType, row: EvenementsAgenda): void {
|
||||||
|
if (row.statut === StatutEvenementAgendaType.ANNULE) return;
|
||||||
|
if (row.type === TypeEvenementAgendaType.SOIN_ENFANT) {
|
||||||
|
const since = Date.now() - new Date(row.cree_le).getTime();
|
||||||
|
if (since > MS_24H) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Délai de suppression de 24 h dépassé pour ce soin',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const today = todayParis();
|
||||||
|
if (
|
||||||
|
row.type === TypeEvenementAgendaType.CONGE_AM &&
|
||||||
|
row.statut === StatutEvenementAgendaType.ACCEPTE &&
|
||||||
|
row.date_debut > today
|
||||||
|
) {
|
||||||
|
return; // congé futur validé annulable
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
row.statut === StatutEvenementAgendaType.EN_ATTENTE ||
|
||||||
|
row.statut === StatutEvenementAgendaType.REFUSE
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Absence / arrêt acceptés : fenêtre 7×24 h
|
||||||
|
const anchor = row.verrouille_le ?? row.cree_le;
|
||||||
|
if (Date.now() - new Date(anchor).getTime() <= MS_7X24H) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new BadRequestException('Cet événement ne peut plus être annulé');
|
||||||
|
}
|
||||||
|
|
||||||
|
private needsRevalidationOnDateChange(row: EvenementsAgenda): boolean {
|
||||||
|
return (
|
||||||
|
row.type === TypeEvenementAgendaType.CONGE_AM &&
|
||||||
|
row.statut !== StatutEvenementAgendaType.ANNULE
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Nouvelle revision + repasse en_attente + nouveau verrouille_le. */
|
||||||
|
private async bumpRevisionForDateChange(
|
||||||
|
row: EvenementsAgenda,
|
||||||
|
_userId: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const now = new Date();
|
||||||
|
row.statut = StatutEvenementAgendaType.EN_ATTENTE;
|
||||||
|
row.verrouille_le = now;
|
||||||
|
row.expire_at = this.expireAtFor(StatutEvenementAgendaType.EN_ATTENTE, now);
|
||||||
|
row.refuse_le = undefined;
|
||||||
|
if (row.id_lot) {
|
||||||
|
await this.lotsRepo
|
||||||
|
.createQueryBuilder()
|
||||||
|
.update(AgendaLots)
|
||||||
|
.set({
|
||||||
|
revision: () => 'revision + 1',
|
||||||
|
statut: AgendaLotStatutType.EN_ATTENTE,
|
||||||
|
verrouille_le: now,
|
||||||
|
soumis_le: now,
|
||||||
|
refuse_le: () => 'NULL',
|
||||||
|
})
|
||||||
|
.where('id = :id', { id: row.id_lot })
|
||||||
|
.execute();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertDates(debut: string, fin: string): void {
|
||||||
|
if (fin < debut) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'date_fin doit être supérieure ou égale à date_debut',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bornes calendaires YYYY-MM-DD (comparaison lexicographique = calendaire, DST-safe). #217 */
|
||||||
|
private assertDateRange(from?: string, to?: string): void {
|
||||||
|
if (from) this.assertCalendarDate(from, 'from');
|
||||||
|
if (to) this.assertCalendarDate(to, 'to');
|
||||||
|
if (from && to && from > to) {
|
||||||
|
throw new BadRequestException('from doit être inférieure ou égale à to');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertCalendarDate(value: string, field: string): void {
|
||||||
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
`${field} doit être une date YYYY-MM-DD`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const [y, m, d] = value.split('-').map(Number);
|
||||||
|
// UTC : évite qu’un parse local fasse glisser le jour à l’heure d’hiver
|
||||||
|
const dt = new Date(Date.UTC(y, m - 1, d));
|
||||||
|
if (
|
||||||
|
dt.getUTCFullYear() !== y ||
|
||||||
|
dt.getUTCMonth() !== m - 1 ||
|
||||||
|
dt.getUTCDate() !== d
|
||||||
|
) {
|
||||||
|
throw new BadRequestException(`${field} n’est pas une date calendaire valide`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertCanCreateType(role: RoleType, type: TypeEvenementAgendaType): void {
|
||||||
|
if (role === RoleType.PARENT) {
|
||||||
|
if (type !== TypeEvenementAgendaType.ABSENCE_ENFANT) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Un parent ne peut créer que des absences enfant',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
if (
|
||||||
|
type !== TypeEvenementAgendaType.CONGE_AM &&
|
||||||
|
type !== TypeEvenementAgendaType.ARRET_MALADIE_AM &&
|
||||||
|
type !== TypeEvenementAgendaType.SOIN_ENFANT
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Une AM ne peut créer que congé, arrêt maladie ou soin enfant',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new ForbiddenException('Rôle non autorisé à créer une absence');
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertCanEditDates(
|
||||||
|
role: RoleType,
|
||||||
|
row: EvenementsAgenda,
|
||||||
|
): void {
|
||||||
|
if (role === RoleType.PARENT) {
|
||||||
|
if (row.type !== TypeEvenementAgendaType.ABSENCE_ENFANT) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Un parent ne peut modifier que les absences enfant',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
if (row.type === TypeEvenementAgendaType.SOIN_ENFANT) {
|
||||||
|
return; // fenêtre 24 h gérée par assertTemporalEdit
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
row.type === TypeEvenementAgendaType.CONGE_AM ||
|
||||||
|
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM
|
||||||
|
) {
|
||||||
|
if (
|
||||||
|
row.statut !== StatutEvenementAgendaType.EN_ATTENTE &&
|
||||||
|
row.statut !== StatutEvenementAgendaType.REFUSE &&
|
||||||
|
row.statut !== StatutEvenementAgendaType.ACCEPTE
|
||||||
|
) {
|
||||||
|
throw new ForbiddenException('Statut incompatible avec une modification');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new ForbiddenException('Type non modifiable par l’AM');
|
||||||
|
}
|
||||||
|
throw new ForbiddenException('Modification non autorisée');
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertCanChangeStatut(
|
||||||
|
role: RoleType,
|
||||||
|
row: EvenementsAgenda,
|
||||||
|
next: StatutEvenementAgendaType,
|
||||||
|
_motif?: string,
|
||||||
|
): void {
|
||||||
|
if (role === RoleType.PARENT) {
|
||||||
|
// Arrêt : déjà accepté à la soumission — ack carte n’écrit plus ici (#216)
|
||||||
|
if (row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'L’accusé de réception d’un arrêt maladie n’écrit pas sur l’événement',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Accept / refuse congé uniquement
|
||||||
|
if (row.type === TypeEvenementAgendaType.CONGE_AM) {
|
||||||
|
if (
|
||||||
|
next !== StatutEvenementAgendaType.ACCEPTE &&
|
||||||
|
next !== StatutEvenementAgendaType.REFUSE
|
||||||
|
) {
|
||||||
|
throw new BadRequestException('Transition de statut invalide');
|
||||||
|
}
|
||||||
|
if (row.statut !== StatutEvenementAgendaType.EN_ATTENTE) {
|
||||||
|
throw new BadRequestException('Cette demande n’est plus en attente');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Pas de changement de statut sur ce type pour un parent',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
// Remise en attente après refus OU modification d’un congé déjà accepté (S2b)
|
||||||
|
if (
|
||||||
|
next === StatutEvenementAgendaType.EN_ATTENTE &&
|
||||||
|
(row.statut === StatutEvenementAgendaType.REFUSE ||
|
||||||
|
row.statut === StatutEvenementAgendaType.ACCEPTE)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'L’AM ne valide pas elle-même (sauf republication / modification)',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw new ForbiddenException('Changement de statut non autorisé');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolvePlacementIds(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
placementId?: string,
|
||||||
|
opts?: { includeEnded?: boolean },
|
||||||
|
): Promise<string[]> {
|
||||||
|
if (placementId) {
|
||||||
|
await this.assertCanAccessPlacement(userId, role, placementId, {
|
||||||
|
allowEnded: opts?.includeEnded === true,
|
||||||
|
});
|
||||||
|
return [placementId];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (role === RoleType.PARENT) {
|
||||||
|
const liens = await this.parentsChildrenRepo.find({
|
||||||
|
where: { parentId: userId },
|
||||||
|
select: ['enfantId'],
|
||||||
|
});
|
||||||
|
const enfantIds = liens.map((l) => l.enfantId);
|
||||||
|
if (enfantIds.length === 0) return [];
|
||||||
|
const placements = await this.amChildrenRepo.find({
|
||||||
|
where: opts?.includeEnded
|
||||||
|
? { enfantId: In(enfantIds) }
|
||||||
|
: { enfantId: In(enfantIds), date_fin: IsNull() },
|
||||||
|
select: ['id'],
|
||||||
|
});
|
||||||
|
return placements.map((p) => p.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
const placements = await this.amChildrenRepo.find({
|
||||||
|
where: opts?.includeEnded
|
||||||
|
? { amId: userId }
|
||||||
|
: { amId: userId, date_fin: IsNull() },
|
||||||
|
select: ['id'],
|
||||||
|
});
|
||||||
|
return placements.map((p) => p.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new ForbiddenException('Rôle non autorisé');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertCanAccessPlacement(
|
||||||
|
userId: string,
|
||||||
|
role: RoleType,
|
||||||
|
placementId: string,
|
||||||
|
opts?: { allowEnded?: boolean },
|
||||||
|
): Promise<AmChildren> {
|
||||||
|
const placement = await this.amChildrenRepo.findOne({
|
||||||
|
where: opts?.allowEnded
|
||||||
|
? { id: placementId }
|
||||||
|
: { id: placementId, date_fin: IsNull() },
|
||||||
|
});
|
||||||
|
if (!placement) {
|
||||||
|
throw new NotFoundException(
|
||||||
|
opts?.allowEnded
|
||||||
|
? 'Placement / couple introuvable'
|
||||||
|
: 'Placement / couple introuvable ou inactif',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
if (placement.amId !== userId) {
|
||||||
|
throw new ForbiddenException('Ce placement ne vous appartient pas');
|
||||||
|
}
|
||||||
|
return placement;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (role === RoleType.PARENT) {
|
||||||
|
const lien = await this.parentsChildrenRepo.findOne({
|
||||||
|
where: { parentId: userId, enfantId: placement.enfantId },
|
||||||
|
});
|
||||||
|
if (!lien) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
'Ce placement ne concerne pas un de vos enfants',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return placement;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new ForbiddenException('Rôle non autorisé');
|
||||||
|
}
|
||||||
|
|
||||||
|
private toDto(
|
||||||
|
row: EvenementsAgenda,
|
||||||
|
userId?: string,
|
||||||
|
role?: RoleType,
|
||||||
|
): EvenementAgendaDto {
|
||||||
|
const child = row.placement?.child;
|
||||||
|
const amUser = row.placement?.am?.user;
|
||||||
|
const statutLot = (row.lot?.statut as AgendaLotStatutType | undefined) ?? null;
|
||||||
|
const statutEffectif = this.statutEffectif(row, statutLot);
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
id_placement: row.id_placement,
|
||||||
|
id_lot: row.id_lot ?? null,
|
||||||
|
id_card_instance: row.id_card_instance ?? null,
|
||||||
|
type: row.type,
|
||||||
|
date_debut: row.date_debut,
|
||||||
|
date_fin: row.date_fin,
|
||||||
|
heure: this.formatHeure(row.heure),
|
||||||
|
statut: row.statut,
|
||||||
|
statut_lot: statutLot,
|
||||||
|
statut_effectif: statutEffectif,
|
||||||
|
expire_at: row.expire_at?.toISOString?.() ?? String(row.expire_at),
|
||||||
|
verrouille_le: row.verrouille_le
|
||||||
|
? row.verrouille_le.toISOString?.() ?? String(row.verrouille_le)
|
||||||
|
: null,
|
||||||
|
refuse_le: row.refuse_le
|
||||||
|
? row.refuse_le.toISOString?.() ?? String(row.refuse_le)
|
||||||
|
: null,
|
||||||
|
annule_le: row.annule_le
|
||||||
|
? row.annule_le.toISOString?.() ?? String(row.annule_le)
|
||||||
|
: null,
|
||||||
|
cree_par: row.cree_par ?? null,
|
||||||
|
motif: row.motif ?? null,
|
||||||
|
libelle_refus: this.libelleRefus(row, statutLot, userId, role),
|
||||||
|
id_enfant: child?.id ?? row.placement?.enfantId ?? null,
|
||||||
|
prenom_enfant: child?.first_name ?? null,
|
||||||
|
id_am: row.placement?.amId ?? null,
|
||||||
|
prenom_am: amUser?.prenom ?? null,
|
||||||
|
nom_am: amUser?.nom ?? null,
|
||||||
|
actions: this.actionsPour(row, statutLot, userId, role),
|
||||||
|
cree_le: row.cree_le?.toISOString?.() ?? String(row.cree_le),
|
||||||
|
modifie_le: row.modifie_le?.toISOString?.() ?? String(row.modifie_le),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatHeure(heure?: string | null): string | null {
|
||||||
|
if (!heure) return null;
|
||||||
|
const s = String(heure);
|
||||||
|
return s.length >= 5 ? s.slice(0, 5) : s;
|
||||||
|
}
|
||||||
|
|
||||||
|
private statutEffectif(
|
||||||
|
row: EvenementsAgenda,
|
||||||
|
statutLot: AgendaLotStatutType | null,
|
||||||
|
): StatutEvenementAgendaType {
|
||||||
|
if (row.statut === StatutEvenementAgendaType.ANNULE) {
|
||||||
|
return StatutEvenementAgendaType.ANNULE;
|
||||||
|
}
|
||||||
|
if (statutLot === AgendaLotStatutType.ANNULE) {
|
||||||
|
return StatutEvenementAgendaType.ANNULE;
|
||||||
|
}
|
||||||
|
if (statutLot === AgendaLotStatutType.REFUSE) {
|
||||||
|
return StatutEvenementAgendaType.REFUSE;
|
||||||
|
}
|
||||||
|
return row.statut;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Anonymise l’auteur du refus : jamais le nom d’une autre famille.
|
||||||
|
* B1 : si refusé et viewer ≠ créateur → « autre famille » ;
|
||||||
|
* si viewer est parent créateur/foyer et motif présent → « autre parent » pour co-parent
|
||||||
|
* (sans id répondant en B1 : défaut « autre famille » pour parent destinataire).
|
||||||
|
*/
|
||||||
|
private libelleRefus(
|
||||||
|
row: EvenementsAgenda,
|
||||||
|
statutLot: AgendaLotStatutType | null,
|
||||||
|
userId?: string,
|
||||||
|
role?: RoleType,
|
||||||
|
): string | null {
|
||||||
|
const refuse =
|
||||||
|
row.statut === StatutEvenementAgendaType.REFUSE ||
|
||||||
|
statutLot === AgendaLotStatutType.REFUSE;
|
||||||
|
if (!refuse) return null;
|
||||||
|
if (!userId || !role) return 'Refusé';
|
||||||
|
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||||
|
return 'Refusé par une famille';
|
||||||
|
}
|
||||||
|
// Parent : ne jamais citer quelle famille. Si ce n’est pas le créateur AM, message générique.
|
||||||
|
if (row.cree_par && row.cree_par === userId) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return 'Refusé par une autre famille';
|
||||||
|
}
|
||||||
|
|
||||||
|
private actionsPour(
|
||||||
|
row: EvenementsAgenda,
|
||||||
|
statutLot: AgendaLotStatutType | null,
|
||||||
|
userId?: string,
|
||||||
|
role?: RoleType,
|
||||||
|
): EvenementAgendaActionsDto {
|
||||||
|
const none: EvenementAgendaActionsDto = {
|
||||||
|
peut_modifier: false,
|
||||||
|
peut_supprimer: false,
|
||||||
|
peut_accepter_refuser: false,
|
||||||
|
peut_ack: false,
|
||||||
|
};
|
||||||
|
if (!userId || !role) return none;
|
||||||
|
if (
|
||||||
|
row.statut === StatutEvenementAgendaType.ANNULE ||
|
||||||
|
statutLot === AgendaLotStatutType.ANNULE
|
||||||
|
) {
|
||||||
|
return none;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isCreator = row.cree_par === userId;
|
||||||
|
const today = new Date().toISOString().slice(0, 10);
|
||||||
|
const notStarted = row.date_debut > today;
|
||||||
|
const enAttente =
|
||||||
|
row.statut === StatutEvenementAgendaType.EN_ATTENTE ||
|
||||||
|
statutLot === AgendaLotStatutType.EN_ATTENTE;
|
||||||
|
const refuse =
|
||||||
|
row.statut === StatutEvenementAgendaType.REFUSE ||
|
||||||
|
statutLot === AgendaLotStatutType.REFUSE;
|
||||||
|
const accepte =
|
||||||
|
row.statut === StatutEvenementAgendaType.ACCEPTE ||
|
||||||
|
statutLot === AgendaLotStatutType.ACCEPTE;
|
||||||
|
|
||||||
|
if (role === RoleType.ASSISTANTE_MATERNELLE && isCreator) {
|
||||||
|
const congeFuturModifiable =
|
||||||
|
row.type === TypeEvenementAgendaType.CONGE_AM &&
|
||||||
|
accepte &&
|
||||||
|
notStarted;
|
||||||
|
return {
|
||||||
|
peut_modifier:
|
||||||
|
enAttente || refuse || congeFuturModifiable ||
|
||||||
|
(row.type !== TypeEvenementAgendaType.CONGE_AM &&
|
||||||
|
row.type !== TypeEvenementAgendaType.SOIN_ENFANT &&
|
||||||
|
accepte),
|
||||||
|
peut_supprimer:
|
||||||
|
enAttente ||
|
||||||
|
refuse ||
|
||||||
|
(row.type === TypeEvenementAgendaType.CONGE_AM &&
|
||||||
|
accepte &&
|
||||||
|
notStarted) ||
|
||||||
|
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM ||
|
||||||
|
row.type === TypeEvenementAgendaType.SOIN_ENFANT,
|
||||||
|
peut_accepter_refuser: false,
|
||||||
|
peut_ack: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (role === RoleType.PARENT && !isCreator) {
|
||||||
|
// ANNULE déjà exclu en tête de actionsPour (narrowing TS)
|
||||||
|
const congeEnAttente =
|
||||||
|
row.type === TypeEvenementAgendaType.CONGE_AM &&
|
||||||
|
row.statut === StatutEvenementAgendaType.EN_ATTENTE &&
|
||||||
|
statutLot !== AgendaLotStatutType.REFUSE;
|
||||||
|
const arretAck =
|
||||||
|
row.type === TypeEvenementAgendaType.ARRET_MALADIE_AM;
|
||||||
|
const soinAck = row.type === TypeEvenementAgendaType.SOIN_ENFANT;
|
||||||
|
return {
|
||||||
|
peut_modifier: false,
|
||||||
|
peut_supprimer: false,
|
||||||
|
peut_accepter_refuser: congeEnAttente,
|
||||||
|
peut_ack: arretAck || soinAck,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
role === RoleType.PARENT &&
|
||||||
|
isCreator &&
|
||||||
|
row.type === TypeEvenementAgendaType.ABSENCE_ENFANT
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
peut_modifier: true,
|
||||||
|
peut_supprimer: true,
|
||||||
|
peut_accepter_refuser: false,
|
||||||
|
peut_ack: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return none;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export { EvenementsAgendaModule } from './evenements-agenda.module';
|
||||||
|
export { EvenementsAgendaService } from './evenements-agenda.service';
|
||||||
@@ -157,7 +157,7 @@ export class AssistantesMaternellesService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (Object.keys(amPatch).length > 0) {
|
if (Object.keys(amPatch).length > 0) {
|
||||||
await this.assistantesMaternelleRepository.update(amUserId, amPatch);
|
await this.assistantesMaternelleRepository.update(amUserId, amPatch as any);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.findOne(amUserId);
|
return this.findOne(amUserId);
|
||||||
|
|||||||
@@ -217,7 +217,7 @@ export class EnfantsService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.childrenRepository.update(id, patch);
|
await this.childrenRepository.update(id, patch as any);
|
||||||
return this.findOne(id, currentUser);
|
return this.findOne(id, currentUser);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
Stack trace:
|
||||||
|
Frame Function Args
|
||||||
|
0007FFFFAC10 00021005FEBA (000210285F48, 00021026AB6E, 000000000000, 0007FFFF9B10) msys-2.0.dll+0x1FEBA
|
||||||
|
0007FFFFAC10 0002100467F9 (000000000000, 000000000000, 000000000000, 0007FFFFAEE8) msys-2.0.dll+0x67F9
|
||||||
|
0007FFFFAC10 000210046832 (000210285FF9, 0007FFFFAAC8, 000000000000, 000000000000) msys-2.0.dll+0x6832
|
||||||
|
0007FFFFAC10 000210068F86 (000000000000, 000000000000, 000000000000, 000000000000) msys-2.0.dll+0x28F86
|
||||||
|
0007FFFFAC10 0002100690B4 (0007FFFFAC20, 000000000000, 000000000000, 000000000000) msys-2.0.dll+0x290B4
|
||||||
|
0007FFFFAEF0 00021006A49D (0007FFFFAC20, 000000000000, 000000000000, 000000000000) msys-2.0.dll+0x2A49D
|
||||||
|
End of stack trace
|
||||||
|
Loaded modules:
|
||||||
|
000100400000 bash.exe
|
||||||
|
7FFE2CD00000 ntdll.dll
|
||||||
|
7FFE2C1F0000 KERNEL32.DLL
|
||||||
|
7FFE29C90000 KERNELBASE.dll
|
||||||
|
7FFE2B8C0000 USER32.dll
|
||||||
|
7FFE2A090000 win32u.dll
|
||||||
|
7FFE2C410000 GDI32.dll
|
||||||
|
7FFE29730000 gdi32full.dll
|
||||||
|
7FFE29860000 msvcp_win.dll
|
||||||
|
7FFE2A930000 ucrtbase.dll
|
||||||
|
000210040000 msys-2.0.dll
|
||||||
|
7FFE2C350000 advapi32.dll
|
||||||
|
7FFE2B810000 msvcrt.dll
|
||||||
|
7FFE2CC10000 sechost.dll
|
||||||
|
7FFE2AB30000 RPCRT4.dll
|
||||||
|
7FFE28D10000 CRYPTBASE.DLL
|
||||||
|
7FFE29B50000 bcryptPrimitives.dll
|
||||||
|
7FFE2CAD0000 IMM32.DLL
|
||||||
@@ -35,14 +35,19 @@ DO $$ BEGIN
|
|||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_avenant_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_avenant_type') THEN
|
||||||
CREATE TYPE statut_avenant_type AS ENUM ('propose', 'accepte', 'refuse');
|
CREATE TYPE statut_avenant_type AS ENUM ('propose', 'accepte', 'refuse');
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_absence_garde_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_evenement_agenda_type') THEN
|
||||||
CREATE TYPE type_absence_garde_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_absence_garde_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_evenement_agenda_type') THEN
|
||||||
CREATE TYPE statut_absence_garde_type AS ENUM (
|
CREATE TYPE statut_evenement_agenda_type AS ENUM (
|
||||||
'en_attente', 'accepte', 'refuse'
|
'en_attente', 'accepte', 'refuse', 'annule'
|
||||||
|
);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'agenda_lot_statut_type') THEN
|
||||||
|
CREATE TYPE agenda_lot_statut_type AS ENUM (
|
||||||
|
'en_attente', 'accepte', 'refuse', 'annule'
|
||||||
);
|
);
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_validation_type') THEN
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_validation_type') THEN
|
||||||
@@ -109,7 +114,8 @@ CREATE TABLE utilisateurs (
|
|||||||
ville VARCHAR(150),
|
ville VARCHAR(150),
|
||||||
code_postal VARCHAR(10),
|
code_postal VARCHAR(10),
|
||||||
profession VARCHAR(150),
|
profession VARCHAR(150),
|
||||||
situation_familiale situation_familiale_type
|
situation_familiale situation_familiale_type,
|
||||||
|
preferences JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX idx_utilisateurs_token_creation_mdp
|
CREATE INDEX idx_utilisateurs_token_creation_mdp
|
||||||
@@ -322,33 +328,67 @@ CREATE TABLE avenants_contrats (
|
|||||||
);
|
);
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Table : absences_garde (vérité métier absences/congés/arrêt)
|
-- Table : agenda_lots (cycles collectifs versionnés — #214)
|
||||||
-- 1 ligne = 1 période ; rattachement = placement AM↔enfant (#193)
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
CREATE TABLE absences_garde (
|
CREATE TABLE agenda_lots (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
type type_evenement_agenda_type NOT NULL,
|
||||||
|
statut agenda_lot_statut_type NOT NULL DEFAULT 'en_attente',
|
||||||
|
revision INT NOT NULL DEFAULT 1,
|
||||||
|
soumis_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
verrouille_le TIMESTAMPTZ,
|
||||||
|
refuse_le TIMESTAMPTZ,
|
||||||
|
annule_le TIMESTAMPTZ,
|
||||||
|
annule_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
||||||
|
cree_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
||||||
|
cree_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
modifie_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT chk_agenda_lots_revision CHECK (revision >= 1)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_agenda_lots_type_statut ON agenda_lots (type, statut);
|
||||||
|
CREATE INDEX idx_agenda_lots_soumis_le ON agenda_lots (soumis_le);
|
||||||
|
|
||||||
|
-- ==========================================================
|
||||||
|
-- Table : evenements_agenda (vérité métier agenda (absences/congés/arrêt + futurs types))
|
||||||
|
-- 1 ligne = 1 période ; rattachement = placement AM↔enfant (#193 / #214)
|
||||||
|
-- ==========================================================
|
||||||
|
CREATE TABLE evenements_agenda (
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
id_placement UUID NOT NULL
|
id_placement UUID NOT NULL
|
||||||
REFERENCES enfants_assistantes_maternelles(id) ON DELETE CASCADE,
|
REFERENCES enfants_assistantes_maternelles(id) ON DELETE CASCADE,
|
||||||
type type_absence_garde_type NOT NULL,
|
type type_evenement_agenda_type NOT NULL,
|
||||||
date_debut DATE NOT NULL,
|
date_debut DATE NOT NULL,
|
||||||
date_fin DATE NOT NULL,
|
date_fin DATE NOT NULL,
|
||||||
statut statut_absence_garde_type NOT NULL DEFAULT 'en_attente',
|
statut statut_evenement_agenda_type NOT NULL DEFAULT 'en_attente',
|
||||||
expire_at TIMESTAMPTZ NOT NULL,
|
expire_at TIMESTAMPTZ NOT NULL,
|
||||||
cree_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
cree_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
||||||
id_card_instance UUID,
|
id_card_instance UUID,
|
||||||
motif TEXT,
|
motif TEXT,
|
||||||
|
heure TIME,
|
||||||
|
id_lot UUID REFERENCES agenda_lots(id) ON DELETE SET NULL,
|
||||||
|
verrouille_le TIMESTAMPTZ,
|
||||||
|
refuse_le TIMESTAMPTZ,
|
||||||
|
annule_le TIMESTAMPTZ,
|
||||||
|
annule_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
||||||
cree_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
cree_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
modifie_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
modifie_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
CONSTRAINT chk_absences_garde_dates CHECK (date_fin >= date_debut)
|
CONSTRAINT chk_evenements_agenda_dates CHECK (date_fin >= date_debut)
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX idx_absences_garde_placement_dates
|
CREATE INDEX idx_evenements_agenda_placement_dates
|
||||||
ON absences_garde (id_placement, date_debut, date_fin);
|
ON evenements_agenda (id_placement, date_debut, date_fin);
|
||||||
CREATE INDEX idx_absences_garde_placement_type_statut
|
CREATE INDEX idx_evenements_agenda_placement_type_statut
|
||||||
ON absences_garde (id_placement, type, statut);
|
ON evenements_agenda (id_placement, type, statut);
|
||||||
CREATE INDEX idx_absences_garde_expire_at
|
CREATE INDEX idx_evenements_agenda_expire_at
|
||||||
ON absences_garde (expire_at)
|
ON evenements_agenda (expire_at)
|
||||||
WHERE statut IN ('en_attente', 'refuse');
|
WHERE statut IN ('en_attente', 'refuse');
|
||||||
|
CREATE INDEX idx_evenements_agenda_id_lot
|
||||||
|
ON evenements_agenda (id_lot)
|
||||||
|
WHERE id_lot IS NOT NULL;
|
||||||
|
CREATE INDEX idx_evenements_agenda_placement_dates_actif
|
||||||
|
ON evenements_agenda (id_placement, date_debut, date_fin)
|
||||||
|
WHERE statut IS DISTINCT FROM 'annule';
|
||||||
|
|
||||||
-- ==========================================================
|
-- ==========================================================
|
||||||
-- Table : signalements_bugs
|
-- Table : signalements_bugs
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ Ce document recense **toutes les valeurs énumérées** utilisées dans la base
|
|||||||
|
|
||||||
## 7) Type d’absence de garde — `type`
|
## 7) Type d’absence de garde — `type`
|
||||||
|
|
||||||
**Tables/colonnes** : `absences_garde.type`
|
**Tables/colonnes** : `evenements_agenda.type`
|
||||||
**Valeurs autorisées** :
|
**Valeurs autorisées** :
|
||||||
|
|
||||||
| Valeur | Description |
|
| Valeur | Description |
|
||||||
@@ -115,20 +115,35 @@ Ce document recense **toutes les valeurs énumérées** utilisées dans la base
|
|||||||
| `conge_am` | Congé de l’assistante maternelle |
|
| `conge_am` | Congé de l’assistante maternelle |
|
||||||
| `arret_maladie_am` | Arrêt maladie AM |
|
| `arret_maladie_am` | Arrêt maladie AM |
|
||||||
|
|
||||||
> Remplace l’ancien enum `type_evenement_type` / table `evenements` (supprimés ticket #193).
|
> Remplace l’ancien enum `type_evenement_type` / table `evenements` (supprimés ticket #205 / ex-#193).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 8) Statut d’absence de garde — `statut`
|
## 8) Statut d’événement agenda — `statut`
|
||||||
|
|
||||||
**Tables/colonnes** : `absences_garde.statut`
|
**Tables/colonnes** : `evenements_agenda.statut`
|
||||||
**Valeurs autorisées** :
|
**Valeurs autorisées** :
|
||||||
|
|
||||||
| Valeur | Description |
|
| Valeur | Description |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `en_attente` | En attente de validation / ack |
|
| `en_attente` | En attente de validation / ack |
|
||||||
| `accepte` | Accepté / acté (conservé en historique métier) |
|
| `accepte` | Accepté / acté (conservé en historique métier) |
|
||||||
| `refuse` | Refusé (temporaire ; purge TTL) |
|
| `refuse` | Refusé (temporaire ; visible barré puis soft-cancel) |
|
||||||
|
| `annule` | Annulation douce (#214) — hors vues normales, auditable |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8bis) Statut de lot agenda — `agenda_lots.statut`
|
||||||
|
|
||||||
|
**Enum** : `agenda_lot_statut_type`
|
||||||
|
**Valeurs** : `en_attente` · `accepte` · `refuse` · `annule` (issue globale du lot versionné, #214)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8ter) Cartes — soft-cancel / opération
|
||||||
|
|
||||||
|
**`card_instance_statut_type`** : `ouverte` · `refusee` · `traitee` · `annulee` (#214)
|
||||||
|
**`card_operation_type`** : `create` · `update` · `cancel` (#214)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -42,8 +42,8 @@ Documenter, de façon unique et partagée, les règles de suppression/mise à jo
|
|||||||
| **contrats(id_dossier)** → `dossiers(id)` | **CASCADE** | 1:1, contrat détruit si dossier supprimé |
|
| **contrats(id_dossier)** → `dossiers(id)` | **CASCADE** | 1:1, contrat détruit si dossier supprimé |
|
||||||
| **avenants_contrats(id_contrat)** → `contrats(id)` | **CASCADE** | Avenants détruits avec le contrat |
|
| **avenants_contrats(id_contrat)** → `contrats(id)` | **CASCADE** | Avenants détruits avec le contrat |
|
||||||
| **avenants_contrats(initie_par)** → `utilisateurs(id)` | **SET NULL** | Historiser l’avenant sans bloquer |
|
| **avenants_contrats(initie_par)** → `utilisateurs(id)` | **SET NULL** | Historiser l’avenant sans bloquer |
|
||||||
| **absences_garde(id_placement)** → `enfants_assistantes_maternelles(id)` | **CASCADE** | Plus de couple = plus d’absences |
|
| **evenements_agenda(id_placement)** → `enfants_assistantes_maternelles(id)` | **CASCADE** | Plus de couple = plus d’absences |
|
||||||
| **absences_garde(cree_par)** → `utilisateurs(id)` | **SET NULL** | Conserver la période si user supprimé |
|
| **evenements_agenda(cree_par)** → `utilisateurs(id)` | **SET NULL** | Conserver la période si user supprimé |
|
||||||
| **signalements_bugs(id_utilisateur)** → `utilisateurs(id)` | **SET NULL** | Conserver le ticket même si compte supprimé |
|
| **signalements_bugs(id_utilisateur)** → `utilisateurs(id)` | **SET NULL** | Conserver le ticket même si compte supprimé |
|
||||||
| **uploads(id_utilisateur)** → `utilisateurs(id)` | **SET NULL** | Fichier reste référencé sans l’auteur |
|
| **uploads(id_utilisateur)** → `utilisateurs(id)` | **SET NULL** | Fichier reste référencé sans l’auteur |
|
||||||
| **notifications(id_utilisateur)** → `utilisateurs(id)` | **CASCADE** | Notifications propres à l’utilisateur |
|
| **notifications(id_utilisateur)** → `utilisateurs(id)` | **CASCADE** | Notifications propres à l’utilisateur |
|
||||||
@@ -77,8 +77,8 @@ Documenter, de façon unique et partagée, les règles de suppression/mise à jo
|
|||||||
- `avenants_contrats.initie_par` → **SET NULL**
|
- `avenants_contrats.initie_par` → **SET NULL**
|
||||||
|
|
||||||
### Événements
|
### Événements
|
||||||
- `absences_garde.id_placement` → **CASCADE**
|
- `evenements_agenda.id_placement` → **CASCADE**
|
||||||
- `absences_garde.cree_par` → **SET NULL**
|
- `evenements_agenda.cree_par` → **SET NULL**
|
||||||
|
|
||||||
### Divers
|
### Divers
|
||||||
- `signalements_bugs.id_utilisateur` → **SET NULL**
|
- `signalements_bugs.id_utilisateur` → **SET NULL**
|
||||||
@@ -105,7 +105,7 @@ Documenter, de façon unique et partagée, les règles de suppression/mise à jo
|
|||||||
|
|
||||||
4. **Suppression d’un enfant**
|
4. **Suppression d’un enfant**
|
||||||
- Supprimer `enfants(id=childA)`
|
- Supprimer `enfants(id=childA)`
|
||||||
- Attendu : `enfants_parents` (CASCADE), `dossiers` du childA (CASCADE), `absences_garde` des placements du childA (CASCADE via EAM).
|
- Attendu : `enfants_parents` (CASCADE), `dossiers` du childA (CASCADE), `evenements_agenda` des placements du childA (CASCADE via EAM).
|
||||||
|
|
||||||
5. **Suppression d’un utilisateur AM**
|
5. **Suppression d’un utilisateur AM**
|
||||||
- Supprimer `utilisateurs(id=amB)`
|
- Supprimer `utilisateurs(id=amB)`
|
||||||
|
|||||||
@@ -0,0 +1,174 @@
|
|||||||
|
-- Ticket #214 — Agenda B0 : lots versionnés, soft-cancel, prefs, remonte_le
|
||||||
|
-- Migration base live. Idempotent.
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 1. Enums
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'agenda_lot_statut_type') THEN
|
||||||
|
CREATE TYPE agenda_lot_statut_type AS ENUM (
|
||||||
|
'en_attente', 'accepte', 'refuse', 'annule'
|
||||||
|
);
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- PG : ADD VALUE IF NOT EXISTS (hors sous-transaction fragile)
|
||||||
|
ALTER TYPE statut_evenement_agenda_type ADD VALUE IF NOT EXISTS 'annule';
|
||||||
|
ALTER TYPE card_instance_statut_type ADD VALUE IF NOT EXISTS 'annulee';
|
||||||
|
ALTER TYPE card_operation_type ADD VALUE IF NOT EXISTS 'cancel';
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 2. Table agenda_lots
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS agenda_lots (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
type type_evenement_agenda_type NOT NULL,
|
||||||
|
statut agenda_lot_statut_type NOT NULL DEFAULT 'en_attente',
|
||||||
|
revision INT NOT NULL DEFAULT 1,
|
||||||
|
soumis_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
verrouille_le TIMESTAMPTZ,
|
||||||
|
refuse_le TIMESTAMPTZ,
|
||||||
|
annule_le TIMESTAMPTZ,
|
||||||
|
annule_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
||||||
|
cree_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
||||||
|
cree_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
modifie_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT chk_agenda_lots_revision CHECK (revision >= 1)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_agenda_lots_type_statut
|
||||||
|
ON agenda_lots (type, statut);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_agenda_lots_soumis_le
|
||||||
|
ON agenda_lots (soumis_le);
|
||||||
|
|
||||||
|
COMMENT ON TABLE agenda_lots IS
|
||||||
|
'Lots collectifs Agenda (congé/arrêt/absence groupés) — cycle versionné (#214).';
|
||||||
|
COMMENT ON COLUMN agenda_lots.revision IS
|
||||||
|
'Incrémenté à chaque resoumission ; les card_responses.revision_lot doivent correspondre.';
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 3. evenements_agenda — soft-cancel + lot + heure
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
ALTER TABLE evenements_agenda
|
||||||
|
ADD COLUMN IF NOT EXISTS annule_le TIMESTAMPTZ,
|
||||||
|
ADD COLUMN IF NOT EXISTS annule_par UUID,
|
||||||
|
ADD COLUMN IF NOT EXISTS verrouille_le TIMESTAMPTZ,
|
||||||
|
ADD COLUMN IF NOT EXISTS refuse_le TIMESTAMPTZ,
|
||||||
|
ADD COLUMN IF NOT EXISTS heure TIME,
|
||||||
|
ADD COLUMN IF NOT EXISTS id_lot UUID;
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = 'evenements_agenda_annule_par_fkey'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE evenements_agenda
|
||||||
|
ADD CONSTRAINT evenements_agenda_annule_par_fkey
|
||||||
|
FOREIGN KEY (annule_par) REFERENCES utilisateurs(id) ON DELETE SET NULL;
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = 'evenements_agenda_id_lot_fkey'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE evenements_agenda
|
||||||
|
ADD CONSTRAINT evenements_agenda_id_lot_fkey
|
||||||
|
FOREIGN KEY (id_lot) REFERENCES agenda_lots(id) ON DELETE SET NULL;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_evenements_agenda_id_lot
|
||||||
|
ON evenements_agenda (id_lot)
|
||||||
|
WHERE id_lot IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_evenements_agenda_verrouille_le
|
||||||
|
ON evenements_agenda (verrouille_le)
|
||||||
|
WHERE verrouille_le IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_evenements_agenda_refuse_le
|
||||||
|
ON evenements_agenda (refuse_le)
|
||||||
|
WHERE refuse_le IS NOT NULL;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN evenements_agenda.heure IS
|
||||||
|
'Heure métier (soin) — durable hors payload carte purgeable.';
|
||||||
|
COMMENT ON COLUMN evenements_agenda.verrouille_le IS
|
||||||
|
'Écrit à la soumission/resoumission — jamais pendant un GET.';
|
||||||
|
COMMENT ON COLUMN evenements_agenda.id_lot IS
|
||||||
|
'Lot collectif optionnel (unanimité congé / envoi groupé arrêt-absence).';
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 4. card_instances — soft-cancel + id_lot + remonte_le
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
ALTER TABLE card_instances
|
||||||
|
ADD COLUMN IF NOT EXISTS id_lot UUID,
|
||||||
|
ADD COLUMN IF NOT EXISTS annule_le TIMESTAMPTZ,
|
||||||
|
ADD COLUMN IF NOT EXISTS annule_par UUID,
|
||||||
|
ADD COLUMN IF NOT EXISTS remonte_le TIMESTAMPTZ;
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = 'card_instances_id_lot_fkey'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE card_instances
|
||||||
|
ADD CONSTRAINT card_instances_id_lot_fkey
|
||||||
|
FOREIGN KEY (id_lot) REFERENCES agenda_lots(id) ON DELETE SET NULL;
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = 'card_instances_annule_par_fkey'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE card_instances
|
||||||
|
ADD CONSTRAINT card_instances_annule_par_fkey
|
||||||
|
FOREIGN KEY (annule_par) REFERENCES utilisateurs(id) ON DELETE SET NULL;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_card_instances_id_lot
|
||||||
|
ON card_instances (id_lot)
|
||||||
|
WHERE id_lot IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_card_instances_remonte_le
|
||||||
|
ON card_instances (remonte_le DESC NULLS LAST);
|
||||||
|
|
||||||
|
COMMENT ON COLUMN card_instances.remonte_le IS
|
||||||
|
'Renseigné uniquement à la réanimation d''une carte sortie du fil ; tri fil = COALESCE(remonte_le, cree_le).';
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 5. card_responses — revision_lot
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
ALTER TABLE card_responses
|
||||||
|
ADD COLUMN IF NOT EXISTS revision_lot INT NOT NULL DEFAULT 1;
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = 'chk_card_responses_revision_lot'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE card_responses
|
||||||
|
ADD CONSTRAINT chk_card_responses_revision_lot CHECK (revision_lot >= 1);
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_card_responses_card_revision
|
||||||
|
ON card_responses (id_card, revision_lot);
|
||||||
|
|
||||||
|
COMMENT ON COLUMN card_responses.revision_lot IS
|
||||||
|
'Doit matcher agenda_lots.revision courante pour compter dans l''unanimité.';
|
||||||
|
|
||||||
|
-- Backfill : réponses existantes = revision 1 (déjà DEFAULT)
|
||||||
|
UPDATE card_responses SET revision_lot = 1 WHERE revision_lot IS NULL;
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 6. utilisateurs.preferences
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
ALTER TABLE utilisateurs
|
||||||
|
ADD COLUMN IF NOT EXISTS preferences JSONB NOT NULL DEFAULT '{}'::jsonb;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN utilisateurs.preferences IS
|
||||||
|
'Préférences UI (ex. jours_affiches_semaine). PATCH fusionne les clés.';
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 7. Index lecture Agenda (statut hors annule côté app ; index utile quand même)
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_evenements_agenda_placement_dates_actif
|
||||||
|
ON evenements_agenda (id_placement, date_debut, date_fin)
|
||||||
|
WHERE statut IS DISTINCT FROM 'annule';
|
||||||
@@ -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,106 @@
|
|||||||
|
-- Ticket #205 — Renommer absences_garde → evenements_agenda
|
||||||
|
-- Migration base live. Idempotent autant que possible.
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 1. Table + enums
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'absences_garde')
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'evenements_agenda') THEN
|
||||||
|
ALTER TABLE absences_garde RENAME TO evenements_agenda;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_absence_garde_type')
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_evenement_agenda_type') THEN
|
||||||
|
ALTER TYPE type_absence_garde_type RENAME TO type_evenement_agenda_type;
|
||||||
|
END IF;
|
||||||
|
IF EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_absence_garde_type')
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_evenement_agenda_type') THEN
|
||||||
|
ALTER TYPE statut_absence_garde_type RENAME TO statut_evenement_agenda_type;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- Contraintes / index (noms)
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'chk_absences_garde_dates') THEN
|
||||||
|
ALTER TABLE evenements_agenda RENAME CONSTRAINT chk_absences_garde_dates TO chk_evenements_agenda_dates;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
ALTER INDEX IF EXISTS idx_absences_garde_placement_dates
|
||||||
|
RENAME TO idx_evenements_agenda_placement_dates;
|
||||||
|
ALTER INDEX IF EXISTS idx_absences_garde_placement_type_statut
|
||||||
|
RENAME TO idx_evenements_agenda_placement_type_statut;
|
||||||
|
ALTER INDEX IF EXISTS idx_absences_garde_expire_at
|
||||||
|
RENAME TO idx_evenements_agenda_expire_at;
|
||||||
|
ALTER INDEX IF EXISTS absences_garde_pkey
|
||||||
|
RENAME TO evenements_agenda_pkey;
|
||||||
|
|
||||||
|
COMMENT ON TABLE evenements_agenda IS
|
||||||
|
'Vérité métier agenda (absences, congés, arrêts, futurs soins/école/mairie/sorties…) par placement. Les cartes collectent ; cette table historise.';
|
||||||
|
COMMENT ON COLUMN evenements_agenda.expire_at IS
|
||||||
|
'Purge auto (job) pour en_attente/refuse. accepte → infinity.';
|
||||||
|
COMMENT ON COLUMN evenements_agenda.id_card_instance IS
|
||||||
|
'Réf. carte de collecte (module Cartes).';
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 2. card_instances.id_absence → id_evenement
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'card_instances' AND column_name = 'id_absence'
|
||||||
|
) AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'card_instances' AND column_name = 'id_evenement'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE card_instances RENAME COLUMN id_absence TO id_evenement;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- Recréer index si ancien nom
|
||||||
|
ALTER INDEX IF EXISTS idx_card_instances_absence
|
||||||
|
RENAME TO idx_card_instances_evenement;
|
||||||
|
|
||||||
|
-- FK : drop ancienne (nom variable) puis recreate
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
fk_name text;
|
||||||
|
BEGIN
|
||||||
|
SELECT conname INTO fk_name
|
||||||
|
FROM pg_constraint
|
||||||
|
WHERE conrelid = 'card_instances'::regclass
|
||||||
|
AND contype = 'f'
|
||||||
|
AND pg_get_constraintdef(oid) ILIKE '%id_evenement%'
|
||||||
|
LIMIT 1;
|
||||||
|
|
||||||
|
IF fk_name IS NULL THEN
|
||||||
|
SELECT conname INTO fk_name
|
||||||
|
FROM pg_constraint
|
||||||
|
WHERE conrelid = 'card_instances'::regclass
|
||||||
|
AND contype = 'f'
|
||||||
|
AND pg_get_constraintdef(oid) ILIKE '%id_absence%'
|
||||||
|
LIMIT 1;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
IF fk_name IS NOT NULL THEN
|
||||||
|
EXECUTE format('ALTER TABLE card_instances DROP CONSTRAINT %I', fk_name);
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint
|
||||||
|
WHERE conname = 'card_instances_id_evenement_fkey'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE card_instances
|
||||||
|
ADD CONSTRAINT card_instances_id_evenement_fkey
|
||||||
|
FOREIGN KEY (id_evenement)
|
||||||
|
REFERENCES evenements_agenda(id)
|
||||||
|
ON DELETE SET NULL;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
@@ -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';
|
||||||
@@ -79,12 +79,42 @@ LEFT JOIN avenants_contrats a ON a.id_contrat = c.id
|
|||||||
GROUP BY c.id, c.id_dossier, c.statut
|
GROUP BY c.id, c.id_dossier, c.statut
|
||||||
ORDER BY c.cree_le DESC;
|
ORDER BY c.cree_le DESC;
|
||||||
|
|
||||||
\echo '=== 9) Absences_garde (30 derniers jours) ====================='
|
\echo '=== 9) Événements agenda (30 derniers jours) ==================='
|
||||||
SELECT ag.id, ag.type, ag.id_placement, ag.date_debut, ag.date_fin, ag.statut, ag.expire_at
|
SELECT ag.id, ag.type, ag.id_placement, ag.date_debut, ag.date_fin, ag.statut,
|
||||||
FROM absences_garde ag
|
ag.id_lot, ag.heure, ag.verrouille_le, ag.expire_at
|
||||||
|
FROM evenements_agenda ag
|
||||||
WHERE ag.date_debut >= (NOW()::date - INTERVAL '30 days')
|
WHERE ag.date_debut >= (NOW()::date - INTERVAL '30 days')
|
||||||
ORDER BY ag.date_debut DESC;
|
ORDER BY ag.date_debut DESC;
|
||||||
|
|
||||||
|
\echo '=== 9b) Agenda B0 (#214) — schéma lots / soft-cancel / prefs ==='
|
||||||
|
SELECT COUNT(*) AS nb_lots FROM agenda_lots;
|
||||||
|
SELECT column_name
|
||||||
|
FROM information_schema.columns
|
||||||
|
WHERE table_name = 'evenements_agenda'
|
||||||
|
AND column_name IN ('id_lot', 'heure', 'verrouille_le', 'refuse_le', 'annule_le', 'annule_par')
|
||||||
|
ORDER BY column_name;
|
||||||
|
SELECT column_name
|
||||||
|
FROM information_schema.columns
|
||||||
|
WHERE table_name = 'card_instances'
|
||||||
|
AND column_name IN ('id_lot', 'annule_le', 'annule_par', 'remonte_le')
|
||||||
|
ORDER BY column_name;
|
||||||
|
SELECT column_name
|
||||||
|
FROM information_schema.columns
|
||||||
|
WHERE table_name = 'card_responses' AND column_name = 'revision_lot';
|
||||||
|
SELECT column_name
|
||||||
|
FROM information_schema.columns
|
||||||
|
WHERE table_name = 'utilisateurs' AND column_name = 'preferences';
|
||||||
|
SELECT enumlabel
|
||||||
|
FROM pg_enum e
|
||||||
|
JOIN pg_type t ON t.oid = e.enumtypid
|
||||||
|
WHERE t.typname IN (
|
||||||
|
'statut_evenement_agenda_type',
|
||||||
|
'agenda_lot_statut_type',
|
||||||
|
'card_instance_statut_type',
|
||||||
|
'card_operation_type'
|
||||||
|
)
|
||||||
|
ORDER BY t.typname, e.enumsortorder;
|
||||||
|
|
||||||
\echo '=== 10) Uploads & notifications récentes ======================='
|
\echo '=== 10) Uploads & notifications récentes ======================='
|
||||||
SELECT u.courriel, up.fichier_url, up.type_fichier, up.cree_le
|
SELECT u.courriel, up.fichier_url, up.type_fichier, up.cree_le
|
||||||
FROM uploads up
|
FROM uploads up
|
||||||
@@ -136,7 +166,7 @@ WHERE c.id IS NULL;
|
|||||||
|
|
||||||
-- Absences sans placement
|
-- Absences sans placement
|
||||||
SELECT ag.*
|
SELECT ag.*
|
||||||
FROM absences_garde ag
|
FROM evenements_agenda ag
|
||||||
LEFT JOIN enfants_assistantes_maternelles eam ON eam.id = ag.id_placement
|
LEFT JOIN enfants_assistantes_maternelles eam ON eam.id = ag.id_placement
|
||||||
WHERE eam.id IS NULL;
|
WHERE eam.id IS NULL;
|
||||||
|
|
||||||
@@ -150,10 +180,10 @@ WHERE m.id_dossier = 'dddddddd-dddd-dddd-dddd-dddddddddddd'
|
|||||||
ORDER BY m.cree_le DESC
|
ORDER BY m.cree_le DESC
|
||||||
LIMIT 20;
|
LIMIT 20;
|
||||||
|
|
||||||
-- Absences par placement et période (idx_absences_garde_placement_dates)
|
-- Absences par placement et période (idx_evenements_agenda_placement_dates)
|
||||||
EXPLAIN ANALYZE
|
EXPLAIN ANALYZE
|
||||||
SELECT ag.*
|
SELECT ag.*
|
||||||
FROM absences_garde ag
|
FROM evenements_agenda ag
|
||||||
WHERE ag.id_placement IS NOT NULL
|
WHERE ag.id_placement IS NOT NULL
|
||||||
AND ag.date_debut >= '2025-01-01';
|
AND ag.date_debut >= '2025-01-01';
|
||||||
|
|
||||||
@@ -198,7 +228,7 @@ SELECT
|
|||||||
(SELECT COUNT(*) FROM messages) AS nb_messages,
|
(SELECT COUNT(*) FROM messages) AS nb_messages,
|
||||||
(SELECT COUNT(*) FROM contrats) AS nb_contrats,
|
(SELECT COUNT(*) FROM contrats) AS nb_contrats,
|
||||||
(SELECT COUNT(*) FROM avenants_contrats) AS nb_avenants,
|
(SELECT COUNT(*) FROM avenants_contrats) AS nb_avenants,
|
||||||
(SELECT COUNT(*) FROM absences_garde) AS nb_absences_garde,
|
(SELECT COUNT(*) FROM evenements_agenda) AS nb_evenements_agenda,
|
||||||
(SELECT COUNT(*) FROM uploads) AS nb_uploads,
|
(SELECT COUNT(*) FROM uploads) AS nb_uploads,
|
||||||
(SELECT COUNT(*) FROM notifications) AS nb_notifications,
|
(SELECT COUNT(*) FROM notifications) AS nb_notifications,
|
||||||
(SELECT COUNT(*) FROM validations) AS nb_validations;
|
(SELECT COUNT(*) FROM validations) AS nb_validations;
|
||||||
|
|||||||
@@ -14,10 +14,12 @@ services:
|
|||||||
networks:
|
networks:
|
||||||
- ptitspas_network
|
- ptitspas_network
|
||||||
|
|
||||||
# Interface d'administration DB
|
# Interface d'administration DB (optionnel — pas démarré par défaut)
|
||||||
|
# Relancer : docker compose --profile tools up -d pgadmin
|
||||||
pgadmin:
|
pgadmin:
|
||||||
image: dpage/pgadmin4
|
image: dpage/pgadmin4
|
||||||
container_name: ptitspas-pgadmin
|
container_name: ptitspas-pgadmin
|
||||||
|
profiles: ["tools"]
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
|
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ Index de navigation du dépôt. Dernière révision : **septembre 2026** (CDC V1
|
|||||||
| [29 — Bilan version 0.1.0](./29_BILAN-VERSION-0.1.0.md) | Tickets livrés 0.1.0 |
|
| [29 — Bilan version 0.1.0](./29_BILAN-VERSION-0.1.0.md) | Tickets livrés 0.1.0 |
|
||||||
| [30 — Découpage tickets quotidien](./30_DECOUPAGE-TICKETS-QUOTIDIEN.md) | Brouillon / backlog tickets parent/AM |
|
| [30 — Découpage tickets quotidien](./30_DECOUPAGE-TICKETS-QUOTIDIEN.md) | Brouillon / backlog tickets parent/AM |
|
||||||
| [31 — Mini-spec quotidien parent/AM](./31_MINI-SPEC-QUOTIDIEN-PARENT-AM.md) | Besoin figé atelier sept. 2026 |
|
| [31 — Mini-spec quotidien parent/AM](./31_MINI-SPEC-QUOTIDIEN-PARENT-AM.md) | Besoin figé atelier sept. 2026 |
|
||||||
|
| [32 — Mini-spec bulles / cartes](./32_MINI-SPEC-BULLES-CARTES.md) | File d’attention + palette UI |
|
||||||
|
| [33 — Mini-spec Agenda vue semaine](./33_MINI-SPEC-AGENDA.md) | Agenda desktop (oct. 2026) — remplace règles Agenda 31/32 |
|
||||||
| [04 — Roadmap générale](./04_ROADMAP-GENERALE.md) | Vision phases long terme |
|
| [04 — Roadmap générale](./04_ROADMAP-GENERALE.md) | Vision phases long terme |
|
||||||
| [28 — Évolution famille / responsables](./28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md) | Limites modèle foyer / contournements |
|
| [28 — Évolution famille / responsables](./28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md) | Limites modèle foyer / contournements |
|
||||||
|
|
||||||
@@ -38,7 +40,7 @@ Index de navigation du dépôt. Dernière révision : **septembre 2026** (CDC V1
|
|||||||
| Doc | Contenu |
|
| Doc | Contenu |
|
||||||
|-----|---------|
|
|-----|---------|
|
||||||
| [CHARTE_GRAPHIQUE.md](./CHARTE_GRAPHIQUE.md) | Charte UI |
|
| [CHARTE_GRAPHIQUE.md](./CHARTE_GRAPHIQUE.md) | Charte UI |
|
||||||
| [maquettes/](./maquettes/README.md) | Maquettes TdB quotidien (réf. v4 + historique) |
|
| [maquettes/](./maquettes/README.md) | Maquettes TdB quotidien + Agenda semaine (réf. v4) |
|
||||||
|
|
||||||
## Projet & outillage
|
## Projet & outillage
|
||||||
|
|
||||||
|
|||||||
@@ -572,14 +572,28 @@ POST /repos/jmartin/petitspas/pulls/{index}/merge
|
|||||||
|
|
||||||
### 32. Module Absences + Cartes (séparation back / collecte)
|
### 32. Module Absences + Cartes (séparation back / collecte)
|
||||||
|
|
||||||
**Décision** : ✅ **Back `absences_garde` = vérité métier** ; **Cartes = file d’attention / collecte** (plugin isolé). Types SYSTEM (absence, congé, arrêt) indéboulonnables ; types OPTIONNELS (sondages…) plus tard. Annulation = DELETE. `expire_at` dès V1.
|
**Décision** : ✅ **Back `evenements_agenda` = vérité métier / agenda** ; **Cartes = file d’attention** (plugin isolé). Types SYSTEM (absence, congé, arrêt) indéboulonnables ; types OPTIONNELS (sondages, soins enfant, école, mairie, sorties…) plus tard. Annulation = DELETE. `expire_at` dès V1.
|
||||||
|
|
||||||
**Justification** :
|
**Justification** :
|
||||||
- Premier vrai module d’interaction multi-acteurs
|
- Premier vrai module d’interaction multi-acteurs
|
||||||
- Évite de stocker l’historique congés dans des bulles éphémères
|
- Évite de stocker l’historique dans des bulles éphémères
|
||||||
- Portabilité / généricité des cartes sans coupler le métier garde
|
- Portabilité / généricité des cartes sans coupler le métier
|
||||||
|
- **Différence avec le blog** : les cartes du fil = **événements d’agenda** (période + placement + historique) ; le blog = récit narratif du jour
|
||||||
|
|
||||||
**Flux V1** : BDD absences → API liste/CRUD → module Cartes SYSTEM → front bulles (séparé).
|
**Modèle données** :
|
||||||
|
- Table **`evenements_agenda`** (ex-`absences_garde`, rename [#205](https://git.ptits-pas.fr/jmartin/petitspas/issues/205)) — nom volontairement ouvert
|
||||||
|
|
||||||
|
**UI** : la **couleur** des bulles est un mapping **front** (`type_code` → teinte). L’API n’expose pas `couleur`.
|
||||||
|
|
||||||
|
**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`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -615,7 +629,7 @@ POST /repos/jmartin/petitspas/pulls/{index}/merge
|
|||||||
| 25/11/2025 | 1.0 | Création du document - Toutes les décisions initiales |
|
| 25/11/2025 | 1.0 | Création du document - Toutes les décisions initiales |
|
||||||
| 09/02/2026 | 1.1 | Configuration initiale : un seul panneau Paramètres (3 sections) dans le dashboard, plus de Setup Wizard dédié ; navigation bloquée jusqu'à sauvegarde |
|
| 09/02/2026 | 1.1 | Configuration initiale : un seul panneau Paramètres (3 sections) dans le dashboard, plus de Setup Wizard dédié ; navigation bloquée jusqu'à sauvegarde |
|
||||||
| 16/06/2026 | 1.2 | Décision 5bis — familles recomposées, contournement v1.0.0 ; lien doc [28](./28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md) |
|
| 16/06/2026 | 1.2 | Décision 5bis — familles recomposées, contournement v1.0.0 ; lien doc [28](./28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md) |
|
||||||
| 24/09/2026 | 1.4 | Décision 32 — Absences (`absences_garde`) ≠ Cartes ; Epic C recentré ; drop `evenements` |
|
| 24/09/2026 | 1.4 | Décision 32 — Absences (`evenements_agenda`) ≠ Cartes ; Epic C recentré ; drop `evenements` |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -98,13 +98,13 @@ Liste des enfants / foyers pour l’AM + contexte courant (symétrique A3).
|
|||||||
|
|
||||||
## Epic C — Absences + Cartes (file d’attention)
|
## Epic C — Absences + Cartes (file d’attention)
|
||||||
|
|
||||||
**Séparation :** back **`absences_garde`** = vérité métier (périodes / placement) ; module **Cartes** = collecte / bulles / workflow. Annulation = DELETE. `expire_at` dès le modèle.
|
**Séparation :** back **`evenements_agenda`** = vérité métier (périodes / placement) ; module **Cartes** = collecte / bulles / workflow. Annulation = DELETE. `expire_at` dès le modèle.
|
||||||
|
|
||||||
### Back (ordre)
|
### Back (ordre)
|
||||||
|
|
||||||
| Étape | Contenu |
|
| Étape | Contenu |
|
||||||
|-------|---------|
|
|-------|---------|
|
||||||
| BDD | Table `absences_garde` + drop `evenements` |
|
| BDD | Table `evenements_agenda` + drop `evenements` |
|
||||||
| API | CRUD + **GET liste** (`placementId` \| tous les placements du user) |
|
| API | CRUD + **GET liste** (`placementId` \| tous les placements du user) |
|
||||||
| Cartes SYSTEM | Module `cards/` types S1–S3 (sans sondages V1) |
|
| Cartes SYSTEM | Module `cards/` types S1–S3 (sans sondages V1) |
|
||||||
| Realtime | WS/SSE bulles → **SSE** `GET /cards/stream` (#195) |
|
| Realtime | WS/SSE bulles → **SSE** `GET /cards/stream` (#195) |
|
||||||
|
|||||||
@@ -63,6 +63,8 @@ Bandeau : **TdB** · **Agenda** · **Contrat** · menu user (recherche AM, param
|
|||||||
|
|
||||||
## 5. Règles métier V1 (absences / congés)
|
## 5. Règles métier V1 (absences / congés)
|
||||||
|
|
||||||
|
> **Obsolète pour Agenda / workflows collectifs.** Les règles ci-dessous sont **remplacées** par [`33_MINI-SPEC-AGENDA.md`](./33_MINI-SPEC-AGENDA.md) (oct. 2026) : annulation douce (plus de DELETE), congé AM à l’**unanimité** (plus « 1 parent suffit »), nouvelles dates appliquées immédiatement, arrêt validé dès soumission, `absence_enfant_modif` abandonné.
|
||||||
|
|
||||||
| Type | Qui initie | Validation / effet |
|
| Type | Qui initie | Validation / effet |
|
||||||
|------|------------|-------------------|
|
|------|------------|-------------------|
|
||||||
| Absence enfant | Parent | Pas de veto AM ; période **acceptée** tout de suite ; bulle info AM |
|
| Absence enfant | Parent | Pas de veto AM ; période **acceptée** tout de suite ; bulle info AM |
|
||||||
@@ -72,7 +74,7 @@ Bandeau : **TdB** · **Agenda** · **Contrat** · menu user (recherche AM, param
|
|||||||
| Maladie AM | AM | Parent **ack** (« bien reçu ») ; **aucun** doc médical |
|
| Maladie AM | AM | Parent **ack** (« bien reçu ») ; **aucun** doc médical |
|
||||||
| Sortie / sondage | — | **Plus tard** (types optionnels) |
|
| Sortie / sondage | — | **Plus tard** (types optionnels) |
|
||||||
|
|
||||||
**Stockage :** table `absences_garde` (1 ligne = période, `id_placement`, `expire_at`). Les **cartes** collectent ; elles ne sont pas la source de vérité. Annulation = DELETE.
|
**Stockage :** table `evenements_agenda` (1 ligne = période, `id_placement`, `expire_at`). Les **cartes** collectent ; elles ne sont pas la source de vérité. Annulation = DELETE.
|
||||||
|
|
||||||
**Péremption cartes :** mémoire courte (`retention_days` / `purge_at`) — pas un historique de vie (≠ messagerie).
|
**Péremption cartes :** mémoire courte (`retention_days` / `purge_at`) — pas un historique de vie (≠ messagerie).
|
||||||
|
|
||||||
@@ -83,7 +85,7 @@ Bandeau : **TdB** · **Agenda** · **Contrat** · menu user (recherche AM, param
|
|||||||
## 6. Hors périmètre de ce jalon
|
## 6. Hors périmètre de ce jalon
|
||||||
|
|
||||||
- Page **Contrat** riche (Pajemploi, CP…) — stub bandeau OK
|
- Page **Contrat** riche (Pajemploi, CP…) — stub bandeau OK
|
||||||
- **Agenda** calendrier riche — stub bandeau OK
|
- **Agenda** calendrier riche — voir [`33_MINI-SPEC-AGENDA.md`](./33_MINI-SPEC-AGENDA.md) (vue semaine)
|
||||||
- Notifications CDC fourre-tout (paiement, dossier…)
|
- Notifications CDC fourre-tout (paiement, dossier…)
|
||||||
- Masquage messages ; posts blog parent
|
- Masquage messages ; posts blog parent
|
||||||
- Carnet repas/sieste (roadmap Phase 4)
|
- Carnet repas/sieste (roadmap Phase 4)
|
||||||
@@ -103,7 +105,7 @@ Avec données peuplées, sur au moins 2 supports :
|
|||||||
|
|
||||||
- Parent : `frontend/lib/screens/home/parent_screen/ParentDashboardScreen.dart` + `dashbord_parent/`
|
- Parent : `frontend/lib/screens/home/parent_screen/ParentDashboardScreen.dart` + `dashbord_parent/`
|
||||||
- AM : `frontend/lib/screens/am/am_dashboard_screen.dart` (placeholder)
|
- AM : `frontend/lib/screens/am/am_dashboard_screen.dart` (placeholder)
|
||||||
- Cartes couleurs : `frontend/assets/cards/` (7 teintes max)
|
- Cartes couleurs : `frontend/assets/cards/` (8 teintes max)
|
||||||
|
|
||||||
## 9. Ordre de build suggéré
|
## 9. Ordre de build suggéré
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
# Mini-spec · Bulles / file d’attention (#173)
|
||||||
|
|
||||||
|
*Front · octobre 2026 — alignement product / API.*
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Contexte / objectif
|
||||||
|
|
||||||
|
Les bulles (cartes) sont la **file d’attention** du quotidien parent / AM : décisions et infos proches (congés, arrêt maladie AM, absences, soins / bobos enfant…).
|
||||||
|
|
||||||
|
**Différence fondamentale avec le blog :**
|
||||||
|
les cartes de ce fil sont des **événements d’agenda** (période, placement, historique métier loggé).
|
||||||
|
Le **blog** = récit / mémoire narrative du jour (photos, texte) — pas une ligne d’agenda.
|
||||||
|
|
||||||
|
Les cartes restent une **mémoire courte** de file (`purge_at` sur la bulle) ; la **source de vérité agenda** reste le back métier.
|
||||||
|
|
||||||
|
Table agenda : **`evenements_agenda`** (ex-`absences_garde`, [#205](https://git.ptits-pas.fr/jmartin/petitspas/issues/205) fait) — conteneur ouvert (absences, congés, soins, école, mairie, sorties…). Les bulles notifient ; l’agenda historise.
|
||||||
|
|
||||||
|
Voir aussi `31_MINI-SPEC-QUOTIDIEN-PARENT-AM.md`.
|
||||||
|
|
||||||
|
Cette note formalise :
|
||||||
|
1. Ce qui est en place côté front (#173).
|
||||||
|
2. Le contrat API (sans couleur).
|
||||||
|
3. La **palette UI** (front only, dérivée du `type_code`).
|
||||||
|
4. La nouvelle famille **soins / bobo enfant** (rose) — AM → parents.
|
||||||
|
5. Idées futures.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Contrat API
|
||||||
|
|
||||||
|
Endpoint principal : `GET /api/v1/cards` (filtre couple / placement).
|
||||||
|
|
||||||
|
| Champ | Rôle UI |
|
||||||
|
|-------|---------|
|
||||||
|
| `type_code` | Layout + libellé + **couleur / icône (mapping front)** |
|
||||||
|
| `titre` | Fallback si `type_code` inconnu |
|
||||||
|
| `statut` | `ouverte` · `refusee` · `traitee` |
|
||||||
|
| `response_mode` | `none` · `ack` · `accept_refuse` |
|
||||||
|
| `is_creator` | Masque les boutons réponse pour le créateur |
|
||||||
|
| `payload.date_debut` / `date_fin` | Période (agenda) |
|
||||||
|
| `payload.motif` | Texte libre / détail |
|
||||||
|
| `last_refuse_comment` | Si `refusee` |
|
||||||
|
| `id_evenement` | Lien métier agenda (`evenements_agenda`, si applicable) — ex-`id_absence` (#205) |
|
||||||
|
| `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.**
|
||||||
|
La teinte pastel est **100 % front** : table de mapping `type_code` → asset (`card_*_h.png`). Le back ne gère pas la charte graphique.
|
||||||
|
|
||||||
|
**Règle front :** le destinataire peut répondre si `!is_creator && statut == ouverte && response_mode != none`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Évolutions front déjà livrées (#173)
|
||||||
|
|
||||||
|
### 3.1 Feed
|
||||||
|
|
||||||
|
- Widget partagé `CartesFeed` (parent + AM).
|
||||||
|
- Fond via widget `Carte` (9-slice horizontal) selon mapping local.
|
||||||
|
- Actions via **modales** accepter / refuser / ack.
|
||||||
|
- Libellés UI :
|
||||||
|
- `conge_am` → « Demande de congés »
|
||||||
|
- `arret_maladie_am` → « Arrêt maladie »
|
||||||
|
- `absence_enfant` → « Notification d’absence »
|
||||||
|
|
||||||
|
### 3.2 Carte **congés** (`conge_am`)
|
||||||
|
|
||||||
|
| Élément | Comportement |
|
||||||
|
|---------|----------------|
|
||||||
|
| Fond | **Aqua** (mapping front) |
|
||||||
|
| Encre | Pétrole `#315F63` / dates `#4A7276` |
|
||||||
|
| Icône | Valise |
|
||||||
|
| Période | « Du … au … » + calendrier |
|
||||||
|
| Actions | Pilules ✓ / ✕ si `accept_refuse` |
|
||||||
|
| Lien | « Ouvrir dans l’agenda ↗ » |
|
||||||
|
| Opacité | Atténuée si `traitee` (sauf règle arrêt ci-dessous) |
|
||||||
|
|
||||||
|
### 3.3 Arrêt maladie AM (`arret_maladie_am`)
|
||||||
|
|
||||||
|
- Reste **visible / opaque** tant que `date_fin` (jour inclus) n’est pas passée, même si `traitee`.
|
||||||
|
- Fond **bleu** (mapping front).
|
||||||
|
|
||||||
|
### 3.4 Assets
|
||||||
|
|
||||||
|
Teintes UI : `red` · `pink` · `peach` · `lime` · `lavender` · `green` · `blue` · `aqua`.
|
||||||
|
Clé = **choix front**, pas une valeur API.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Palette UI (front only — dérivée du `type_code`)
|
||||||
|
|
||||||
|
| Couleur UI | Famille | Types |
|
||||||
|
|------------|---------|--------|
|
||||||
|
| **`aqua`** | Congés AM | `conge_am` |
|
||||||
|
| **`blue`** | Arrêt maladie AM | `arret_maladie_am` |
|
||||||
|
| **`peach`** | Absence enfant / info pratique | `absence_enfant` |
|
||||||
|
| **`pink`** | Soins / bobo / problème **enfant** (AM → parents) | `soin_enfant` *(nouveau — voir §5)* |
|
||||||
|
| **`lavender`** | Admin / divers | futurs types admin |
|
||||||
|
|
||||||
|
**Hors scope V1 cartes** : `absence_enfant_modif` (ack AM sur modif) — **abandonné** ; voir [`33_MINI-SPEC-AGENDA.md`](./33_MINI-SPEC-AGENDA.md).
|
||||||
|
Les **modifications d’absence / congés** se font via l’**Agenda** (annulation douce, lots versionnés, unanimité congé AM). Cette mini-spec 32 reste la référence **UI bulles / palette** ; les règles métier Agenda de la §7 ci-dessous cèdent à la 33 en cas de conflit.
|
||||||
|
|
||||||
|
**Principes**
|
||||||
|
|
||||||
|
- Couleur = famille visuelle (lisible sans tout lire).
|
||||||
|
- Icône précise l’événement (surtout sur rose : thermomètre, pansement, flacon…).
|
||||||
|
- Rose = doux / rassurant, **pas** une alerte médicale forte.
|
||||||
|
- Congés ≠ lavande (trop « admin »).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Nouvelle bulle rose — soins / bobo enfant (AM → parents)
|
||||||
|
|
||||||
|
### Intention produit
|
||||||
|
|
||||||
|
La nounou signale un **événement concernant l’enfant** (maladie légère, bobo, crème, température, souci du jour…) **vers les parents**.
|
||||||
|
|
||||||
|
Pourquoi **pas seulement la messagerie** ?
|
||||||
|
- C’est **loggé** dans la file d’attention.
|
||||||
|
- C’est un **événement d’agenda** (période / jour, placement, historique).
|
||||||
|
- Les parents peuvent **acquitter** (`ack`) sans noyer le chat.
|
||||||
|
|
||||||
|
### Proposition V1 (à brancher ultérieurement)
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|--|--|
|
||||||
|
| `type_code` | `soin_enfant` (nom exact à figer) |
|
||||||
|
| Émetteur | AM |
|
||||||
|
| Destinataires | parents du couple / placement |
|
||||||
|
| `response_mode` | `ack` |
|
||||||
|
| Couleur UI | `pink` |
|
||||||
|
| Back métier | ligne agenda liée (même esprit que `absences_garde` : période + placement + motif) ; la bulle = collecte / notification |
|
||||||
|
| Payload | `date_debut` / `date_fin` (+ motif / sous-type optionnel : temperature, bobo, medicament…) |
|
||||||
|
|
||||||
|
**Hors scope immédiat #173** : implémentation complète ; cette section fige l’intention pour le contrat types + UI.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Idées futures (hors scope)
|
||||||
|
|
||||||
|
| Famille | Couleur UI | Exemples | `response_mode` |
|
||||||
|
|---------|------------|----------|-----------------|
|
||||||
|
| 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` |
|
||||||
|
| Admin | `lavender` | `info_admin`, `document_a_fournir` | `ack` / `none` |
|
||||||
|
|
||||||
|
Variante soins : un seul fond rose ; l’icône / sous-type change.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Comportements métier à ne pas casser
|
||||||
|
|
||||||
|
> Pour le workflow Agenda (soft-cancel, lots, unanimité, ack arrêt sans maj événement, tri fil) → **[`33_MINI-SPEC-AGENDA.md`](./33_MINI-SPEC-AGENDA.md)**.
|
||||||
|
|
||||||
|
- Créateur : pas de boutons réponse ; éventuel « En attente de réponse ».
|
||||||
|
- Refus : afficher `last_refuse_comment`.
|
||||||
|
- Congé : `accept_refuse` côté destinataire (**unanimité des placements** — voir 33).
|
||||||
|
- 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 ; carte purgée reste adressable depuis l’Agenda (33).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Fichiers front de référence
|
||||||
|
|
||||||
|
- `frontend/lib/models/carte_bulle.dart` — mapping type → libellé / icône / fond
|
||||||
|
- `frontend/lib/widgets/quotidien/cartes_feed.dart`
|
||||||
|
- `frontend/lib/models/card_assets.dart`
|
||||||
|
- Assets : `frontend/assets/cards/`, `valise.png`, `btn_*_pilule.png`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Recettes
|
||||||
|
|
||||||
|
- [ ] API cartes **sans** champ `couleur` (ni feed ni `/types`).
|
||||||
|
- [ ] 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.
|
||||||
|
- [ ] Arrêt : ack parent « Bien reçu » ; traité + période en cours → reste visible.
|
||||||
|
- [ ] Absence enfant : pas de bouton (info).
|
||||||
|
- [ ] Filtre couple / placement.
|
||||||
|
- [ ] (Plus tard) `soin_enfant` rose AM → parents + ligne agenda.
|
||||||
|
- [ ] (Plus tard / calendrier) modifs d’absence + éventuel `absence_enfant_modif`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Références
|
||||||
|
|
||||||
|
- Ticket front : **#173**
|
||||||
|
- Module cartes : **#194**
|
||||||
|
- Quotidien : `docs/31_MINI-SPEC-QUOTIDIEN-PARENT-AM.md`
|
||||||
|
- Décision projet : `docs/24_DECISIONS-PROJET.md` §32
|
||||||
|
- Maquette congés : `ressources/bulle_congés.jpg`
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
# Mini-spec — Agenda desktop (vue semaine)
|
||||||
|
|
||||||
|
> **Statut :** figée pour backlog (oct. 2026) — **vue semaine uniquement**
|
||||||
|
> **Réf. visuelle :** [maquettes/courantes/maquette-agenda-semaine-v4.jpg](./maquettes/courantes/maquette-agenda-semaine-v4.jpg)
|
||||||
|
> **Remplace :** règles Agenda / absences des [31](./31_MINI-SPEC-QUOTIDIEN-PARENT-AM.md) §5 et [32](./32_MINI-SPEC-BULLES-CARTES.md) quand elles contredisent ce document
|
||||||
|
> **Hors lot :** vue mois, mobile, RPE, export Contrat, filtres type (F8 V1.1), Google/offline
|
||||||
|
|
||||||
|
## 1. Objectif
|
||||||
|
|
||||||
|
Remplacer le corps du TdB par un **Agenda desktop** (parent + AM) en **vue semaine** : lecture dense du planning, création / modification / annulation douce des événements métier, accept/refus via la **même API cartes** que le Cahier.
|
||||||
|
|
||||||
|
La **source de vérité** est `evenements_agenda`. Les cartes du fil Cahier sont une **projection éphémère** (`purge_at`) du même objet.
|
||||||
|
|
||||||
|
## 2. Sous-bandeau
|
||||||
|
|
||||||
|
`Ajouter` · `Semaine` · `Mois` · `Tous mes agendas` · `Aujourd’hui` · `−3` · `+3`
|
||||||
|
|
||||||
|
| Bouton | V1 |
|
||||||
|
|--------|-----|
|
||||||
|
| Semaine | Vue active (défaut) |
|
||||||
|
| Mois | Présent ; message « Vue mois bientôt disponible » ; reste en semaine |
|
||||||
|
| Tous mes agendas | Superposition multi-placements (fantômes multi-agendas + regroupement `id_lot`) |
|
||||||
|
| Aujourd’hui | Recentré : semaine ISO courante au milieu de la zone visible (1–4 lignes) |
|
||||||
|
| −3 / +3 | Exactement **trois semaines ISO** (`Europe/Paris`) |
|
||||||
|
| Ajouter | Modale type Bulletin : congé/arrêt AM → toutes les familles ; soin → choix enfant ; absence → choix enfant + case « toutes mes nounous » (décochée) |
|
||||||
|
|
||||||
|
Préférence V1 : `jours_affiches_semaine` seulement (défaut lun–ven). `vue_agenda_defaut` reportée au lot mois.
|
||||||
|
|
||||||
|
## 3. Grammaire vue semaine
|
||||||
|
|
||||||
|
### Structure
|
||||||
|
|
||||||
|
- 1 **ligne** = 1 **semaine ISO** (`Europe/Paris`) ; n° à gauche (`S41`…).
|
||||||
|
- En-têtes colonnes **une seule fois** : Lundi…Vendredi (selon prefs).
|
||||||
|
- Case : libellé **`5 oct`** (jour + mois 3 lettres) + contenu.
|
||||||
|
- Scroll rouleau + fade haut/bas.
|
||||||
|
- **Hauteur d’une ligne** = hauteur du jour le plus chargé de cette semaine ; les autres colonnes prennent la même hauteur.
|
||||||
|
|
||||||
|
### Ordre dans une journée
|
||||||
|
|
||||||
|
1. Événements journée entière / multi-jours (maître ou fantôme).
|
||||||
|
2. Événements avec heure, ordre chronologique.
|
||||||
|
3. À égalité : `cree_le`.
|
||||||
|
|
||||||
|
### Multi-jours (fantômes de plage)
|
||||||
|
|
||||||
|
- **Carte maître** (infos + actions) sur le 1er jour de la plage **dans les colonnes affichées**.
|
||||||
|
- Si le vrai début est hors viewport : le **premier jour visible** devient maître temporaire.
|
||||||
|
- Autres jours : fantôme même teinte, plus léger, libellé court (`Congé`) — pas de détails.
|
||||||
|
- Clic fantôme → **même fiche** que la maître ; aucune action sur le fantôme.
|
||||||
|
- A11y : `Semantics` complet sur la maître ; `ExcludeSemantics` sur fantômes et illustrations. Un maître temporaire ne duplique pas les actions dans l’arbre sémantique.
|
||||||
|
|
||||||
|
### Densité des cartes Agenda
|
||||||
|
|
||||||
|
- Texte + couleur ; grosse illustre métier **interdite**.
|
||||||
|
- Ex. soin : `18h19 · Piqûre` + motif court.
|
||||||
|
- Pas de lien « Ouvrir dans l’agenda » (réservé au Cahier).
|
||||||
|
|
||||||
|
### Jour vide
|
||||||
|
|
||||||
|
- Illustre décorative **uniquement** si la case n’a ni événement ni fantôme.
|
||||||
|
- Choix **déterministe** dérivé de la date.
|
||||||
|
- Pack ~10 assets (ticket D1) ; F4 peut démarrer avec 2 provisoire.
|
||||||
|
|
||||||
|
### Chargement
|
||||||
|
|
||||||
|
- Préchargement **2–3 semaines** avant et après le visible ; cache ; debounce ; **pas d’éviction** V1.
|
||||||
|
- Même store pour scroll, −3/+3, Aujourd’hui.
|
||||||
|
- Dédupliquer les requêtes concurrentes ; après reconnexion socket, recharger la fenêtre visible.
|
||||||
|
- Ancre de scroll = première semaine visible (pas un offset pixel).
|
||||||
|
|
||||||
|
### Jours masqués
|
||||||
|
|
||||||
|
- Indicateur discret « N événements samedi » cliquable → liste accessible.
|
||||||
|
- Prefs invalides → repli lun–ven.
|
||||||
|
|
||||||
|
### Dates / DST
|
||||||
|
|
||||||
|
- Dates métier = type `date` calendaire ; API = `YYYY-MM-DD` (+ `HH:mm` pour l’heure soin).
|
||||||
|
- Le front **ne parse jamais** une date jour via `Date` UTC.
|
||||||
|
- Tests autour du dernier dimanche d’octobre.
|
||||||
|
|
||||||
|
## 4. Sources de vérité & annulation douce
|
||||||
|
|
||||||
|
| Couche | Rôle |
|
||||||
|
|--------|------|
|
||||||
|
| `evenements_agenda` | Vérité durable |
|
||||||
|
| `card_instances` | Projection file d’attention (`purge_at`) |
|
||||||
|
| `agenda_lots` | Cycle collectif (congé / arrêt / absence groupée) |
|
||||||
|
|
||||||
|
**Annulation douce = norme applicative** : jamais de `DELETE` physique carte/événement sur action utilisateur. Statut `annule` / `annulee` + timestamps. Cascades compte/placement = chantier RGPD (hors promesse ici).
|
||||||
|
|
||||||
|
**AC critique :** après sortie du fil (`purge_at`), `POST /cards/:id/respond` et la lecture Agenda fonctionnent encore.
|
||||||
|
|
||||||
|
Fin de placement : l’accès historique **ne dépend plus** de `date_fin IS NULL`.
|
||||||
|
|
||||||
|
## 5. Matrice temporelle
|
||||||
|
|
||||||
|
| Type | Création | Édition | Verrou |
|
||||||
|
|------|----------|---------|--------|
|
||||||
|
| `soin_enfant` | Date ∈ [hier, aujourd’hui] | Correction/suppression ≤ **24 h** depuis `cree_le` | Gelé après 24 h |
|
||||||
|
| `conge_am` | Passé OK (pas la norme) | Dates → **nouvelle `revision`** (unanimité, +7 j) ; motif seul ne relance pas | Gelé 7×24 h après soumission **sauf** congé **futur** (modifiable/annulable tant que `date_debut` non commencé) |
|
||||||
|
| `arret_maladie_am` | Passé OK | Dates ≤ 7×24 h ; **accepté dès soumission** | Pas de cycle de validation |
|
||||||
|
| `absence_enfant` | Passé OK | ≤ 7×24 h | Acceptée à la création |
|
||||||
|
|
||||||
|
- `verrouille_le` écrit à la soumission/resoumission — **jamais pendant un GET**.
|
||||||
|
- Échéances (auto-valid J+7 congé, disparition refusés J+7) : tâche `@nestjs/schedule` idempotente, rattrapée au redémarrage, fanout sockets.
|
||||||
|
- Auto-validation J+7 = **statut opérationnel P’titsPas**, pas un accord juridique.
|
||||||
|
|
||||||
|
## 6. Congé AM — unanimité (V1)
|
||||||
|
|
||||||
|
Cadre légal (IDCC 3239 art. 102.1.1) : hors V1 pour le cas « AM fixe seule ». Le RPE futur = médiateur avec bouton inaltérable dans l’outil ; côté parents = **carte AM**.
|
||||||
|
|
||||||
|
### Création
|
||||||
|
|
||||||
|
- Envoyée à tous les **placements connus et non terminés** au moment de la soumission.
|
||||||
|
- Technique : 1 lot versionné + 1 carte + 1 événement **par placement** (y compris 2 enfants d’un même foyer = 2 validations).
|
||||||
|
- Co-parents d’un placement : première réponse gagne.
|
||||||
|
|
||||||
|
### Unanimité
|
||||||
|
|
||||||
|
- Tous acceptent → validé pour tous.
|
||||||
|
- Un refus → **tout le lot refusé** (barré partout).
|
||||||
|
- Silence 7 j → auto-validé (statut P’titsPas).
|
||||||
|
|
||||||
|
### Modification / resoumission
|
||||||
|
|
||||||
|
- **Toute modification de dates** (attente, refusé ou validé futur) → nouvelle `revision`, toutes les familles revalident, nouveau cycle 7 j.
|
||||||
|
- Nouvelles dates **remplacent immédiatement** les anciennes (affichées en attente).
|
||||||
|
- Refusé visible 7 j (« refusé — à resoumettre ») puis soft-cancel auto.
|
||||||
|
- AM : Resoumettre / Modifier / Supprimer + « Disparaît dans N j ».
|
||||||
|
- Parents : « Refusé par une autre famille » / « Refusé par l’autre parent » — sans action.
|
||||||
|
|
||||||
|
### Nouvelle famille
|
||||||
|
|
||||||
|
- À la création d’un placement : congés futurs (validés ou en attente) de l’AM ajoutés **en attente** pour ce seul placement.
|
||||||
|
- Si le lot était validé : anciens parents gardent « validé » (pas de carte) ; AM voit « validé — réponse du nouvel accueil en attente ».
|
||||||
|
- Si le nouveau refuse : lot refusé ; **cartes des anciens parents ranimées** (`remonte_le` + `purge_at` recalculés).
|
||||||
|
|
||||||
|
### Annulation d’un congé futur validé
|
||||||
|
|
||||||
|
- Soft-cancel du lot + **carte ranimée** opération `cancel` (info, sans réponse) par placement — pas un socket seul.
|
||||||
|
|
||||||
|
## 7. Arrêt maladie AM
|
||||||
|
|
||||||
|
- Envoi collectif (`id_lot`) à toutes les familles.
|
||||||
|
- **Validé dès la soumission** (`accepte`) — aucun cycle ni délai 7 j de validation.
|
||||||
|
- Pastille « Bien reçu » = **informatif seulement** (ack carte ; **n’écrit plus** sur l’événement — sinon 400 avec le code actuel).
|
||||||
|
- Prolongation : édition des dates ≤ 7 j, ou second arrêt **consécutif** (pas de chevauchement).
|
||||||
|
|
||||||
|
## 8. Absence enfant
|
||||||
|
|
||||||
|
- Défaut : couple courant.
|
||||||
|
- Case « toutes mes nounous » : 1 absence par placement actif des enfants du parent, même `id_lot` (affichage groupé seulement).
|
||||||
|
- Acceptée à la création.
|
||||||
|
|
||||||
|
## 9. Chevauchements
|
||||||
|
|
||||||
|
Même placement, même famille de type, périodes qui se recoupent, hors annulés :
|
||||||
|
|
||||||
|
| Situation | Effet |
|
||||||
|
|-----------|--------|
|
||||||
|
| Nouvelle demande chevauche un **refusé** (congé) | Ancien soft-cancel + message « remplace… » |
|
||||||
|
| Chevauche **en attente / validé** | Création **bloquée** : « modifiez-le » |
|
||||||
|
| Arrêt / absence | Seule branche « bloqué » (pas de refus) |
|
||||||
|
| Dates qui se suivent | OK (pas un chevauchement) |
|
||||||
|
| Soins | Pas de règle |
|
||||||
|
|
||||||
|
## 10. Fil Cahier
|
||||||
|
|
||||||
|
- Tri : **`COALESCE(remonte_le, cree_le) DESC`** (plus de tri par statut).
|
||||||
|
- `remonte_le` nul en vie normale ; renseigné uniquement à la **réanimation**.
|
||||||
|
- Ranimer = aussi recalculer `purge_at`.
|
||||||
|
- `absence_enfant_modif` **abandonné**.
|
||||||
|
|
||||||
|
## 11. Contrat API (enrichissements)
|
||||||
|
|
||||||
|
### Événement (DTO)
|
||||||
|
|
||||||
|
`id`, `id_placement`, `id_lot`, `id_card_instance`, `type`, `date_debut`, `date_fin`, `heure`, `statut`, `statut_effectif` (vue utilisateur), motif, identité enfant/AM, droits/actions calculés, timestamps.
|
||||||
|
**Aucun secret** sur l’auteur d’un refus d’une autre famille.
|
||||||
|
|
||||||
|
### Liste
|
||||||
|
|
||||||
|
`GET` filtrable `from`/`to` inclusifs : `date_debut <= to AND date_fin >= from` ; exclusion `annule` ; historique post-fin de placement.
|
||||||
|
|
||||||
|
### Cartes
|
||||||
|
|
||||||
|
Accept/refus/ack = **`POST /cards/:id/respond`**.
|
||||||
|
PATCH/DELETE/resoumission créateur = **lot-aware** depuis n’importe quelle carte représentante.
|
||||||
|
|
||||||
|
### Préférences
|
||||||
|
|
||||||
|
`users.preferences` JSONB ; PATCH fusionne `jours_affiches_semaine` (1–7 jours ISO uniques) sans écraser le reste.
|
||||||
|
|
||||||
|
## 12. Schéma BDD (ticket B0 — premier)
|
||||||
|
|
||||||
|
- Table `agenda_lots` : `id`, type, statut global, `revision`, `soumis_le`, `verrouille_le`, `refuse_le`, `annule_*`, créateur, timestamps.
|
||||||
|
- `evenements_agenda` : enum `annule`, champs soft-cancel, `verrouille_le`, `refuse_le`, `heure`, `id_lot` FK.
|
||||||
|
- `card_instances` : `id_lot`, opération `cancel`, statut soft-cancel, `remonte_le`.
|
||||||
|
- `card_responses` : `revision_lot`.
|
||||||
|
- `users.preferences` JSONB défaut `{}`.
|
||||||
|
- Index lecture + backfill + `BDD.sql` + migration + `verify.sql`.
|
||||||
|
|
||||||
|
## 13. Invariants de recette
|
||||||
|
|
||||||
|
1. Mutation carte/événement/lot **atomique**.
|
||||||
|
2. Une réponse comptée une fois, placement + `revision` courante ; première réponse co-parents gagne.
|
||||||
|
3. Aucun GET ne change un statut.
|
||||||
|
4. Événement annulé hors vues normales, auditable ; carte purgée adressable depuis Agenda / ranimable.
|
||||||
|
5. Fin d’accueil ≠ perte d’historique autorisé.
|
||||||
|
6. Mini-specs 31/32 ne contredisent plus silencieusement la 33.
|
||||||
|
|
||||||
|
## 14. Découpage tickets
|
||||||
|
|
||||||
|
| Id | Issue | Périmètre |
|
||||||
|
|----|-------|-----------|
|
||||||
|
| **B0** | [#214](https://git.ptits-pas.fr/jmartin/petitspas/issues/214) | Migration BDD (bloquant) |
|
||||||
|
| **B1** | [#215](https://git.ptits-pas.fr/jmartin/petitspas/issues/215) | GET :id + DTO enrichi |
|
||||||
|
| **B2** | [#216](https://git.ptits-pas.fr/jmartin/petitspas/issues/216) | Matrice + soft-cancel + no-DELETE carte + cron + ack arrêt sans maj événement + tests |
|
||||||
|
| **B3** | [#217](https://git.ptits-pas.fr/jmartin/petitspas/issues/217) | Filtres from/to, historique placement terminé |
|
||||||
|
| **B4** | [#218](https://git.ptits-pas.fr/jmartin/petitspas/issues/218) | Prefs `jours_affiches_semaine` |
|
||||||
|
| **B5** | [#219](https://git.ptits-pas.fr/jmartin/petitspas/issues/219) | Lots / unanimité / chevauchements / nouvel accueil / cartes ranimées |
|
||||||
|
| **B6** | [#220](https://git.ptits-pas.fr/jmartin/petitspas/issues/220) | Tri fil `COALESCE(remonte_le, cree_le) DESC` |
|
||||||
|
| **D1** | [#221](https://git.ptits-pas.fr/jmartin/petitspas/issues/221) | Pack ~10 illustrations jour vide |
|
||||||
|
| **F1** | [#222](https://git.ptits-pas.fr/jmartin/petitspas/issues/222) | Coquille + sous-bandeau + store |
|
||||||
|
| **F4** | [#223](https://git.ptits-pas.fr/jmartin/petitspas/issues/223) | Vue semaine (prioritaire) — maquette v4 |
|
||||||
|
| **F5** | [#224](https://git.ptits-pas.fr/jmartin/petitspas/issues/224) | Multi-agendas + dédoublonnage `id_lot` |
|
||||||
|
| **F6** | [#225](https://git.ptits-pas.fr/jmartin/petitspas/issues/225) | Prefs UI |
|
||||||
|
| **F7** | [#226](https://git.ptits-pas.fr/jmartin/petitspas/issues/226) | Sockets + recalc hauteur ligne |
|
||||||
|
| **F8** | [#227](https://git.ptits-pas.fr/jmartin/petitspas/issues/227) | Filtres type — **V1.1** |
|
||||||
|
| Hygiène | [#187](https://git.ptits-pas.fr/jmartin/petitspas/issues/187) fermé ; [#165](https://git.ptits-pas.fr/jmartin/petitspas/issues/165) commenté ; notes 31/32 | Stub Contrat ; croisement quotidien |
|
||||||
|
|
||||||
|
**Ordre :** B0 → B1–B6 + D1 → F1 → F4 → F5–F7.
|
||||||
|
|
||||||
|
## 15. Hors périmètre
|
||||||
|
|
||||||
|
Mobile ; vue mois ; RPE / congé inaltérable ; export Contrat ; redesign modales ; deep-link ; F8 ; sync Google / offline.
|
||||||
@@ -1,29 +1,31 @@
|
|||||||
# Maquettes — espaces parent / AM (quotidien)
|
# Maquettes — espaces parent / AM
|
||||||
|
|
||||||
Références visuelles issues de l’atelier de cadrage (sept. 2026).
|
Références visuelles issues des ateliers de cadrage (sept.–oct. 2026).
|
||||||
|
|
||||||
## Organisation
|
## Organisation
|
||||||
|
|
||||||
| Dossier | Contenu |
|
| Dossier | Contenu |
|
||||||
|---------|---------|
|
|---------|---------|
|
||||||
| [`courantes/`](./courantes/) | **Référence active** — à utiliser pour tickets / implémentation |
|
| [`courantes/`](./courantes/) | **Référence active** — à utiliser pour tickets / implémentation |
|
||||||
| [`historique/`](./historique/) | Itérations précédentes + croquis manuscrit (conservées pour traçabilité) |
|
| [`historique/`](./historique/) | Itérations précédentes + croquis (traçabilité) |
|
||||||
|
|
||||||
## Référence active
|
## Références actives
|
||||||
|
|
||||||
| Fichier | Description |
|
| Fichier | Description |
|
||||||
|---------|-------------|
|
|---------|-------------|
|
||||||
| [`courantes/maquette-dashboard-parent-quotidien-v4.png`](./courantes/maquette-dashboard-parent-quotidien-v4.png) | TdB parent PC — **3 colonnes** : cartes + couple · blog (défaut) · messagerie (AM / RPE) |
|
| [`courantes/maquette-dashboard-parent-quotidien-v4.png`](./courantes/maquette-dashboard-parent-quotidien-v4.png) | TdB parent PC — **3 colonnes** : cartes + couple · blog · messagerie |
|
||||||
|
| [`courantes/maquette-agenda-semaine-v4.jpg`](./courantes/maquette-agenda-semaine-v4.jpg) | **Agenda vue semaine** — lignes = semaines ISO, maître + fantômes, illustres jours vides |
|
||||||
|
|
||||||
## Historique
|
## Historique
|
||||||
|
|
||||||
| Fichier | Note |
|
| Fichier | Note |
|
||||||
|---------|------|
|
|---------|------|
|
||||||
| [`historique/croquis-dashboard-parent-2026-09-23.jpg`](./historique/croquis-dashboard-parent-2026-09-23.jpg) | Wireframe manuscrit (WhatsApp) — point de départ layout |
|
| [`historique/croquis-dashboard-parent-2026-09-23.jpg`](./historique/croquis-dashboard-parent-2026-09-23.jpg) | Wireframe manuscrit TdB |
|
||||||
| `…-v1.png` | Première génération IA (~50/50) |
|
| `…-quotidien-v1.png` … `v3.png` | Itérations TdB |
|
||||||
| `…-v2.png` | Recadrage 1/3 + 2/3 (onglets Mess/Blog à droite) |
|
| `historique/maquette-agenda-semaine-v2.jpg` | Première synthèse Agenda semaine |
|
||||||
| `…-v3.png` | Couple enfant–nounou (encore 2 colonnes) |
|
| `historique/maquette-agenda-semaine-v3.jpg` | En-têtes jour une seule fois |
|
||||||
|
|
||||||
## Suite éventuelle
|
## Suite éventuelle
|
||||||
|
|
||||||
- Maquette **TdB AM** (miroir : bandeau enfant \| parent(s)) — pas encore générée.
|
- Maquette **vue mois** Agenda (grille + feed) — lot de spec séparé.
|
||||||
|
- Maquette **TdB AM** (miroir couple) — pas encore générée.
|
||||||
|
|||||||
|
After Width: | Height: | Size: 208 KiB |
|
After Width: | Height: | Size: 204 KiB |
|
After Width: | Height: | Size: 194 KiB |
@@ -0,0 +1,89 @@
|
|||||||
|
# Mini-spec API — POST /parents/dossier (#129)
|
||||||
|
|
||||||
|
Contrat pour le **plan front** (wizard création dossier famille staff).
|
||||||
|
|
||||||
|
Miroir de **#156** (`POST /assistantes-maternelles/dossier`).
|
||||||
|
|
||||||
|
## Endpoint
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|--|--|
|
||||||
|
| **Méthode** | `POST` |
|
||||||
|
| **URL** | `{base}/parents/dossier` |
|
||||||
|
| **Auth** | Bearer JWT |
|
||||||
|
| **Rôles** | `gestionnaire`, `administrateur`, `super_admin` |
|
||||||
|
| **Content-Type** | `application/json` |
|
||||||
|
|
||||||
|
Ne **pas** appeler `POST /auth/register/parent` depuis le dashboard.
|
||||||
|
|
||||||
|
## Body (JSON)
|
||||||
|
|
||||||
|
Aligné `RegisterParentCompletDto`, **sans** CGU/privacy obligatoires (acceptées serveur).
|
||||||
|
|
||||||
|
### Parent 1 (obligatoire)
|
||||||
|
|
||||||
|
| Champ | Type | Obligatoire | Notes |
|
||||||
|
|-------|------|-------------|--------|
|
||||||
|
| `email` | string | oui | unique |
|
||||||
|
| `prenom` | string | oui | |
|
||||||
|
| `nom` | string | oui | |
|
||||||
|
| `telephone` | string | oui | `0X…` ou `+33…` |
|
||||||
|
| `adresse` | string | non | |
|
||||||
|
| `code_postal` | string | non | |
|
||||||
|
| `ville` | string | non | |
|
||||||
|
|
||||||
|
### Co-parent (optionnel)
|
||||||
|
|
||||||
|
`co_parent_email`, `co_parent_prenom`, `co_parent_nom`, `co_parent_telephone`,
|
||||||
|
`co_parent_meme_adresse`, `co_parent_adresse`, `co_parent_code_postal`, `co_parent_ville`.
|
||||||
|
|
||||||
|
Si co-parent fourni : e-mail distinct ; mêmes règles téléphone / adresse que register.
|
||||||
|
|
||||||
|
### Enfants (≥ 1)
|
||||||
|
|
||||||
|
| Champ | Type | Notes |
|
||||||
|
|-------|------|--------|
|
||||||
|
| `enfants` | `EnfantInscriptionDto[]` | `prenom`, `nom`, `date_naissance` / `date_previsionnelle_naissance`, `genre`, `photo_base64`, `photo_filename`, etc. |
|
||||||
|
|
||||||
|
### Présentation
|
||||||
|
|
||||||
|
| Champ | Type | Obligatoire |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| `presentation_dossier` | string | non (max 2000) |
|
||||||
|
|
||||||
|
## Réponses
|
||||||
|
|
||||||
|
### 201 Created
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"message": "Dossier famille créé et validé. Un e-mail de création de mot de passe a été envoyé.",
|
||||||
|
"numero_dossier": "2026-000043",
|
||||||
|
"parent_user_id": "uuid-pivot",
|
||||||
|
"co_parent_user_id": "uuid-ou-null",
|
||||||
|
"statut": "actif",
|
||||||
|
"enfant_ids": ["uuid", "..."]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Effets serveur : user(s) parent **actif**, fiches `parents`, enfants + foyer, n° dossier,
|
||||||
|
**e-mail création MDP** pour chaque compte sans MDP (pas d’accusé « en attente »).
|
||||||
|
|
||||||
|
### Erreurs
|
||||||
|
|
||||||
|
| Code | Cas |
|
||||||
|
|------|-----|
|
||||||
|
| 400 | Validation DTO / métier (enfants vides, dates, etc.) |
|
||||||
|
| 401 | Token manquant / invalide |
|
||||||
|
| 403 | Rôle non staff |
|
||||||
|
| 409 | Conflit e-mail (pivot et/ou co-parent) |
|
||||||
|
|
||||||
|
## Front
|
||||||
|
|
||||||
|
- `UserService.createParentDossier(body)` → cet endpoint
|
||||||
|
- Wizard create basé sur `ValidationFamilyWizard`
|
||||||
|
- Ne pas envoyer `acceptation_cgu` / `acceptation_privacy` (optionnels)
|
||||||
|
|
||||||
|
## Branche
|
||||||
|
|
||||||
|
`feature/129-creation-dossier-parent`
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# Mini-spec API — POST /parents/:id/co-parent (#135)
|
||||||
|
|
||||||
|
Contrat back pour l’ajout d’un **2ᵉ parent** sur un foyer mono-parent (staff).
|
||||||
|
|
||||||
|
## Endpoint
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|--|--|
|
||||||
|
| **Méthode** | `POST` |
|
||||||
|
| **URL** | `{base}/api/v1/parents/{parentUserId}/co-parent` |
|
||||||
|
| **Auth** | Bearer JWT |
|
||||||
|
| **Rôles** | `gestionnaire`, `administrateur`, `super_admin` |
|
||||||
|
| **Succès** | **201** |
|
||||||
|
|
||||||
|
`parentUserId` = UUID du **parent pivot** (déjà dans le dossier).
|
||||||
|
|
||||||
|
Ne **pas** appeler `POST /auth/register/parent` ni `POST /parents/dossier`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Body (JSON)
|
||||||
|
|
||||||
|
| Champ | Type | Obligatoire | Notes |
|
||||||
|
|-------|------|-------------|--------|
|
||||||
|
| `email` | string | oui | unique |
|
||||||
|
| `prenom` | string | oui | |
|
||||||
|
| `nom` | string | oui | |
|
||||||
|
| `telephone` | string | oui | `0X…` ou `+33…` |
|
||||||
|
| `meme_adresse` | bool | non | défaut **true** → copie adresse du pivot |
|
||||||
|
| `adresse` | string | si `meme_adresse=false` | |
|
||||||
|
| `code_postal` | string | si `meme_adresse=false` | |
|
||||||
|
| `ville` | string | si `meme_adresse=false` | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Comportement 201
|
||||||
|
|
||||||
|
- User co-parent **actif** + token création MDP
|
||||||
|
- Fiche `parents` + liens pivot ↔ co-parent + même `numero_dossier`
|
||||||
|
- Enfants du foyer rattachés au co-parent
|
||||||
|
- E-mail **création MDP** (pas mail « en attente »)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"message": "Co-parent ajouté au foyer. Un e-mail de création de mot de passe a été envoyé.",
|
||||||
|
"numero_dossier": "2026-000043",
|
||||||
|
"parent_user_id": "uuid-pivot",
|
||||||
|
"co_parent_user_id": "uuid-co",
|
||||||
|
"statut": "actif"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Erreurs
|
||||||
|
|
||||||
|
| Code | Cas |
|
||||||
|
|------|-----|
|
||||||
|
| 400 | Déjà un co-parent / 2 responsables / validation adresse |
|
||||||
|
| 401 | Token invalide |
|
||||||
|
| 403 | Rôle non staff |
|
||||||
|
| 404 | Pivot introuvable |
|
||||||
|
| 409 | Email déjà pris |
|
||||||
|
|
||||||
|
## Réemploi édition identité
|
||||||
|
|
||||||
|
| Endpoint | Usage |
|
||||||
|
|----------|--------|
|
||||||
|
| `GET /dossiers/:numero` | Préremplir wizard edit |
|
||||||
|
| `PATCH /parents/:id/fiche` | Sauver identité pivot / co-parent existant |
|
||||||
|
| `PATCH /assistantes-maternelles/:id/fiche` | Édition AM |
|
||||||
|
|
||||||
|
## Branche
|
||||||
|
|
||||||
|
`feature/135-edition-dossier`
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# Mini-spec front — Mode édition dossier + ajout 2ᵉ parent (#135)
|
||||||
|
|
||||||
|
Branche : `feature/135-edition-dossier`
|
||||||
|
Ticket : **#135** (full-stack)
|
||||||
|
|
||||||
|
Prérequis : **#153** (liste Dossiers) livré.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Objectif
|
||||||
|
|
||||||
|
1. Clic sur un dossier (liste #153) → ouvrir le wizard en mode **`edit`**
|
||||||
|
2. Foyer **mono-parent** : page co-parent → **switch** ajouter un 2ᵉ parent
|
||||||
|
3. Sauvegarder les champs via APIs existantes + nouvel endpoint co-parent
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Modes wizard
|
||||||
|
|
||||||
|
| Mode | Famille | AM |
|
||||||
|
|------|---------|-----|
|
||||||
|
| `review` | déjà | déjà |
|
||||||
|
| `create` | déjà (#129) | déjà (#156) |
|
||||||
|
| **`edit`** | **à faire** | **à faire** |
|
||||||
|
|
||||||
|
Factories : `ParentDossierWizard.edit(...)` / `AmDossierWizard.edit(...)`
|
||||||
|
Préremplir via `UserService.getDossierByNumero(numero)`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## APIs
|
||||||
|
|
||||||
|
| Action | Endpoint |
|
||||||
|
|--------|----------|
|
||||||
|
| Charger | `GET /dossiers/:numero` |
|
||||||
|
| Sauver parent | `PATCH /parents/:id/fiche` |
|
||||||
|
| Sauver AM | `PATCH /assistantes-maternelles/:id/fiche` |
|
||||||
|
| **Ajouter co-parent** | **`POST /parents/:pivotUserId/co-parent`** — voir `docs/tmp/135-contrat-api-ajout-co-parent.md` |
|
||||||
|
|
||||||
|
Body co-parent :
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"email": "thomas@…",
|
||||||
|
"prenom": "Thomas",
|
||||||
|
"nom": "MARTIN",
|
||||||
|
"telephone": "0678456789",
|
||||||
|
"meme_adresse": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`UserService.addCoParent(pivotUserId, body)` → cet endpoint.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## UX
|
||||||
|
|
||||||
|
- Depuis `DossiersManagementWidget` / carte liste : clic → edit (plus seulement review pending)
|
||||||
|
- Pending : garder validation (review) ; dossiers actifs → edit
|
||||||
|
- Mono-parent : switch « Ajouter un co-parent » (comme create) → au save, `POST …/co-parent` si nouveau
|
||||||
|
- Déjà 2 parents : éditer les deux fiches ; pas de 3ᵉ
|
||||||
|
- Pas de bouton créer dans l’onglet Dossiers
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hors scope
|
||||||
|
|
||||||
|
- Famille N responsables (#139)
|
||||||
|
- Suppressions (#154)
|
||||||
|
- Création dossier initial (#129 / #156)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Critères d’acceptation
|
||||||
|
|
||||||
|
- [ ] Clic dossier actif → wizard edit prérempli
|
||||||
|
- [ ] PATCH fiche enregistre les modifs
|
||||||
|
- [ ] Mono-parent + switch → co-parent créé (actif + mail MDP)
|
||||||
|
- [ ] review / create inchangés
|
||||||
|
|
||||||
|
## Branche
|
||||||
|
|
||||||
|
`feature/135-edition-dossier`
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# Mini-spec — Suppression complète grossesse multiple / `est_multiple`
|
||||||
|
|
||||||
|
**Ticket** : **#152** — https://git.ptits-pas.fr/jmartin/petitspas/issues/152
|
||||||
|
**Branche** : `feature/152-remove-est-multiple` (depuis `develop`)
|
||||||
|
**Périmètre** : **full stack** — BDD + back + front + scripts + docs. **Aucun fantôme.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Décision
|
||||||
|
|
||||||
|
On **supprime tout**. Pas de DTO « ignorés », pas de compat payload.
|
||||||
|
|
||||||
|
`forbidNonWhitelisted: true` ⇒ back et front **partent ensemble** (même feature / même déploiement).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Alias retirés
|
||||||
|
|
||||||
|
`est_multiple` · `is_multiple` · `grossesse_multiple` · `multipleBirth` · `estMultiple` · `isMultiple` · `jumeau_multiple`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Back / BDD (fait sur la branche)
|
||||||
|
|
||||||
|
- [x] Migration `database/migrations/2026_drop_enfants_est_multiple.sql`
|
||||||
|
- [x] `BDD.sql`, seeds, CSV test
|
||||||
|
- [x] Entity `Children` sans colonne
|
||||||
|
- [x] DTO create/inscription/réponse/dossier famille **sans** le champ
|
||||||
|
- [x] Services auth / enfants / parents : plus de mapping
|
||||||
|
- [x] Prisma legacy `isMultiple` retiré
|
||||||
|
|
||||||
|
## Front (fait sur la branche)
|
||||||
|
|
||||||
|
- [x] Modèles admin / dossier / inscription
|
||||||
|
- [x] Payloads inscription + reprise
|
||||||
|
- [x] Modale enfant + wizard dossier famille
|
||||||
|
- [x] Step3 inscription parent
|
||||||
|
|
||||||
|
## Scripts / docs
|
||||||
|
|
||||||
|
- [x] `tests/scripts/register-parent-*.mjs`
|
||||||
|
- [x] `docs/10_DATABASE.md`, `docs/99_REGLES-CODAGE.md`
|
||||||
|
- Docs tmp/archive #112 : mentions historiques OK (archive)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Déploiement
|
||||||
|
|
||||||
|
1. Appliquer la migration SQL sur la BDD vivante
|
||||||
|
2. Deploy back **et** front de cette branche
|
||||||
|
3. Smoke : création enfant staff, inscription parent, reprise, wizard famille
|
||||||
|
|
||||||
|
## Vérif
|
||||||
|
|
||||||
|
```bash
|
||||||
|
rg -n 'est_multiple|is_multiple|grossesse_multiple|multipleBirth|estMultiple|isMultiple|jumeau_multiple' \
|
||||||
|
backend/src frontend/lib database tests/scripts docs/10_DATABASE.md docs/99_REGLES-CODAGE.md
|
||||||
|
```
|
||||||
|
→ **0** hit (hors ce fichier mini-spec / archives).
|
||||||
|
|
||||||
|
## Hors scope
|
||||||
|
|
||||||
|
- Métier futur « fratrie / jumeaux » → nouveau ticket
|
||||||
|
- #155 rename Admin*
|
||||||
|
- Ticket modales staff
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# Mini-spec API — GET /dossiers (#153)
|
||||||
|
|
||||||
|
Contrat pour le **plan front** (onglet permanent Dossiers).
|
||||||
|
|
||||||
|
## Endpoint
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|--|--|
|
||||||
|
| **Méthode** | `GET` |
|
||||||
|
| **URL** | `{base}/api/v1/dossiers` |
|
||||||
|
| **Auth** | Bearer JWT |
|
||||||
|
| **Rôles** | `gestionnaire`, `administrateur`, `super_admin` |
|
||||||
|
| **Query** | `q` (optionnel) — recherche n° / libellé / email |
|
||||||
|
|
||||||
|
Complète `GET /dossiers/:numeroDossier` (#119) déjà existant.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Réponse 200
|
||||||
|
|
||||||
|
Tableau de lignes (1 entrée = 1 `numero_dossier`) :
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"type": "famille",
|
||||||
|
"numero_dossier": "2026-000043",
|
||||||
|
"libelle": "Claire MARTIN & Thomas MARTIN",
|
||||||
|
"emails": ["claire@test.fr", "thomas@test.fr"],
|
||||||
|
"user_ids": ["uuid-pivot", "uuid-co"],
|
||||||
|
"statut": "actif",
|
||||||
|
"a_valider": false,
|
||||||
|
"date_reference": "2026-01-12T10:00:00.000Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "assistante_maternelle",
|
||||||
|
"numero_dossier": "2026-000042",
|
||||||
|
"libelle": "Marie DUPONT",
|
||||||
|
"emails": ["marie@test.fr"],
|
||||||
|
"user_ids": ["uuid-am"],
|
||||||
|
"statut": "en_attente",
|
||||||
|
"a_valider": true,
|
||||||
|
"date_reference": "2026-02-01T08:00:00.000Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Champs
|
||||||
|
|
||||||
|
| Champ | Notes |
|
||||||
|
|-------|--------|
|
||||||
|
| `type` | `famille` \| `assistante_maternelle` |
|
||||||
|
| `numero_dossier` | Clé d’unité |
|
||||||
|
| `libelle` | Noms formatés (foyer : `A & B`) |
|
||||||
|
| `emails` / `user_ids` | Membres du foyer ou AM |
|
||||||
|
| `statut` | Agrégé : `en_attente` si au moins un user pending |
|
||||||
|
| `a_valider` | `true` si pending → section haute UI |
|
||||||
|
| `date_reference` | `MIN(cree_le)` des users |
|
||||||
|
|
||||||
|
**Tri** : `a_valider` d’abord, puis `numero_dossier` décroissant.
|
||||||
|
|
||||||
|
**Famille** : dédupliquée par `numero_dossier` (pivot + co-parent = 1 ligne).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Front
|
||||||
|
|
||||||
|
- `UserService.getDossiers({ q? })` → cet endpoint
|
||||||
|
- Section haute : filtrer `a_valider == true` **ou** continuer pending APIs existantes
|
||||||
|
- Section basse : liste complète (ou hors pending selon règle UX)
|
||||||
|
- Clic → `GET /dossiers/:numero` (détail) / validation review
|
||||||
|
|
||||||
|
Composition client `getParents`+`getAM` **plus nécessaire** si cet endpoint est déployé.
|
||||||
|
|
||||||
|
## Branche
|
||||||
|
|
||||||
|
`feature/153-onglet-dossiers`
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
# Mini-spec front — Onglet permanent « Dossiers » (#153)
|
||||||
|
|
||||||
|
Branche Git (front + back) : `feature/153-onglet-dossiers`
|
||||||
|
Ticket Gitea : **#153** (ticket normal, plus epic)
|
||||||
|
|
||||||
|
> Suite prévue : **#135** = au clic, mode **édition** wizard + ajout 2ᵉ parent.
|
||||||
|
> **#153** = onglet + listes + navigation / validation pending. **Pas** de création, **pas** d’édition complète.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contexte / objectif
|
||||||
|
|
||||||
|
Remplacer l’onglet conditionnel **« À valider »** (apparaît/disparaît selon pending) par un onglet **permanent « Dossiers »** dans le dashboard admin/gestionnaire.
|
||||||
|
|
||||||
|
Quand on ouvre **Dossiers** :
|
||||||
|
|
||||||
|
1. **En haut** — section **Dossiers à valider** (AM + familles pending)
|
||||||
|
2. **En dessous** — liste de **tous les dossiers** (familles **et** AM), 1 ligne = 1 `numero_dossier`
|
||||||
|
3. Différenciation visuelle famille vs AM : **couleur + icône**
|
||||||
|
4. **Barre de recherche** (n° dossier, nom, email…)
|
||||||
|
|
||||||
|
**Pas** de bouton « Créer un dossier » ici (création via **+ Parents** #129 / **+ Asmat** #156).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## UX cible
|
||||||
|
|
||||||
|
### Onglets dashboard (`UserManagementPanel`)
|
||||||
|
|
||||||
|
| Avant (#107) | Après (#153) |
|
||||||
|
|--------------|--------------|
|
||||||
|
| « À valider » **conditionnel** si pending | **« Dossiers » toujours visible** (admin + gestionnaire) |
|
||||||
|
| Contenu = seulement pending | Pending **en haut** + liste complète **en bas** |
|
||||||
|
|
||||||
|
Ordre suggéré des onglets :
|
||||||
|
|
||||||
|
`Dossiers` | `Parents` | `Enfants` | `Assistantes maternelles` | `Gestionnaires` | (`Administrateurs`)
|
||||||
|
|
||||||
|
### Section haute — À valider
|
||||||
|
|
||||||
|
- Réutiliser / adapter `PendingValidationWidget` (ou extraire la liste dans un sous-widget).
|
||||||
|
- Sources déjà branchées :
|
||||||
|
- `UserService.getPendingUsers(role: 'assistante_maternelle')`
|
||||||
|
- `UserService.getPendingFamilies()`
|
||||||
|
- Clic ligne pending → **`ValidationDossierModal`** / wizards `.review` (inchangé).
|
||||||
|
- Si section vide : ne pas afficher de gros vide ; masquer la section ou message court « Aucun dossier en attente ».
|
||||||
|
|
||||||
|
### Section basse — Tous les dossiers
|
||||||
|
|
||||||
|
1 ligne = **1 dossier** (`numero_dossier`), type :
|
||||||
|
|
||||||
|
| Type | Libellé UI | Couleur (suggestion) |
|
||||||
|
|------|------------|----------------------|
|
||||||
|
| `famille` | Famille / Parents | teinte existante parents (ex. violet / rose dashboard) |
|
||||||
|
| `assistante_maternelle` | AM | teinte existante AM (ex. teal / bleu) |
|
||||||
|
|
||||||
|
Colonnes / infos utiles (cartes style `AdminUserCard` ou lignes type pending) :
|
||||||
|
|
||||||
|
- n° dossier
|
||||||
|
- type (pastille couleur + icône)
|
||||||
|
- libellé (noms parents ou AM)
|
||||||
|
- email(s) principal(aux)
|
||||||
|
- statut user / dossier si dispo (`actif`, `en_attente`, …)
|
||||||
|
- date utile si dispo
|
||||||
|
|
||||||
|
**Déduplication** : un foyer (pivot + co-parent) = **une** ligne famille (même `numero_dossier`). Idem AM.
|
||||||
|
|
||||||
|
### Recherche
|
||||||
|
|
||||||
|
- La search bar du panel (aujourd’hui désactivée / hint « pas de recherche » sur À valider) doit **filtrer la liste unifiée** (et idéalement aussi le pending affiché).
|
||||||
|
- Critères **minimum** : `numero_dossier`, nom, prénom, email.
|
||||||
|
- Harmoniser le hint : `Rechercher un dossier (n°, nom, email)…`
|
||||||
|
|
||||||
|
### État vide liste complète
|
||||||
|
|
||||||
|
Aide optionnelle : *« Pour créer un dossier → onglet Parents (+ Parents) ou Assistantes maternelles (+ Asmat) »*.
|
||||||
|
|
||||||
|
### Clic sur un dossier de la liste complète (#153)
|
||||||
|
|
||||||
|
| Cas | Comportement #153 |
|
||||||
|
|-----|-------------------|
|
||||||
|
| Pending | Ouvrir validation (review) — déjà en place |
|
||||||
|
| Dossier **actif** / non pending | Ouvrir consultation via `GET /dossiers/:numeroDossier` (`UserService.getDossierByNumero`) en **lecture / review** si possible **sans** save édition |
|
||||||
|
|
||||||
|
**Ne pas** implémenter le mode `edit` ni le switch 2ᵉ parent → **#135**.
|
||||||
|
|
||||||
|
Si l’ouverture « review » d’un dossier actif est trop lourde pour ce ticket : clic peut temporairement no-op / snackbar *« Édition dossier : prochainement (#135) »* — **à éviter** si `getDossierByNumero` + wizard review marche déjà pour les deux types.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Données / APIs (front)
|
||||||
|
|
||||||
|
### Déjà disponibles (préférer composer côté front pour #153)
|
||||||
|
|
||||||
|
| Besoin | API / service |
|
||||||
|
|--------|----------------|
|
||||||
|
| Pending AM | `getPendingUsers(role: assistante_maternelle)` |
|
||||||
|
| Pending familles | `getPendingFamilies()` |
|
||||||
|
| Parents (avec `numero_dossier`) | `getParents()` |
|
||||||
|
| AM (avec `numero_dossier`) | `getAssistantesMaternelles()` |
|
||||||
|
| Détail unifié | `getDossierByNumero(numero)` → `GET /dossiers/:numeroDossier` |
|
||||||
|
|
||||||
|
**Pas d’endpoint `GET /dossiers` liste** aujourd’hui. Pour #153 :
|
||||||
|
|
||||||
|
- Construire la liste unifiée **côté client** à partir de `getParents()` + `getAssistantesMaternelles()` (group by `numero_dossier`).
|
||||||
|
- Exclure ou marquer les pending déjà dans la section haute (éviter doublons visuels, ou les laisser dans les deux avec badge « à valider » — **préférence** : pending **uniquement** en haut ; liste basse = tous **hors** pending **ou** tous avec badge ; choisir une règle claire et documenter dans le PR).
|
||||||
|
|
||||||
|
**Règle recommandée** :
|
||||||
|
- Haut = pending only
|
||||||
|
- Bas = **tous** les dossiers ayant un `numero_dossier` (y compris pending) **OU** bas = non-pending only
|
||||||
|
→ **Recommandation produit** : bas = **tous** (vision complète), pending aussi en haut pour action rapide. Si doublon gênant : bas = non-pending only.
|
||||||
|
|
||||||
|
### Si le back ajoute plus tard `GET /dossiers`
|
||||||
|
|
||||||
|
Brancher `UserService.getDossiers()` — hors scope bloquant #153 front si composition client OK.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fichiers front probables
|
||||||
|
|
||||||
|
| Fichier | Rôle |
|
||||||
|
|---------|------|
|
||||||
|
| `frontend/lib/widgets/admin/user_management_panel.dart` | Onglet permanent **Dossiers** ; retirer logique conditionnelle À valider ; search sur cet onglet |
|
||||||
|
| `frontend/lib/widgets/admin/pending_validation_widget.dart` | Réemploi section haute (ou refactor léger) |
|
||||||
|
| **Nouveau** `…/dossiers_management_widget.dart` (nom libre) | Shell onglet : pending + liste unifiée + refresh |
|
||||||
|
| **Nouveau** modèle léger `DossierListItem` (type, numero, libelle, emails, statut…) | Mapping parents/AM → ligne |
|
||||||
|
| `user_service.dart` / `api_config.dart` | Seulement si helper `getDossiersUnified()` côté client (pas forcément nouvel endpoint) |
|
||||||
|
| `validation_dossier_modal.dart` | Réemploi ouverture pending / détail |
|
||||||
|
|
||||||
|
Réutiliser look & feel cartes / hover « Ouvrir » de `_PendingValidationRow` / `AdminUserCard`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hors scope (#153)
|
||||||
|
|
||||||
|
- Bouton créer dossier
|
||||||
|
- Mode `edit` wizard + ajout 2ᵉ parent → **#135**
|
||||||
|
- Suppressions → **#154**
|
||||||
|
- Famille N responsables → **#139**
|
||||||
|
- Changer les onglets Parents / AM / Enfants (restent)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Critères d’acceptation front
|
||||||
|
|
||||||
|
- [ ] Onglet **Dossiers** toujours visible (même 0 pending)
|
||||||
|
- [ ] Plus d’onglet conditionnel **« À valider »**
|
||||||
|
- [ ] Section haute pending si non vide ; validation au clic OK
|
||||||
|
- [ ] Liste unifiée familles + AM en dessous ; 1 ligne / `numero_dossier`
|
||||||
|
- [ ] Couleur + icône différencient famille / AM
|
||||||
|
- [ ] Recherche filtre (n° + nom + email minimum)
|
||||||
|
- [ ] **Aucun** bouton créer dans cet onglet
|
||||||
|
- [ ] Pas de régression validation pending (valider / refuser)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Back (info — Cursor back séparé si besoin)
|
||||||
|
|
||||||
|
- Liste unifiée : **pas bloquante** si composition front
|
||||||
|
- Optionnel : `GET /api/v1/dossiers` (liste) pour perf / pagination plus tard
|
||||||
|
- `GET /dossiers/:numero` déjà là (#119)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Branche
|
||||||
|
|
||||||
|
`feature/153-onglet-dossiers` (depuis `develop`)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Matrice suppression — #154 / back **#159** / front **#160**
|
||||||
|
|
||||||
|
**Statut** : cadrage PO validé (sept. 2026)
|
||||||
|
**Milestone** : 0.1.0
|
||||||
|
**Email** : pas d’email de suppression (cas rare)
|
||||||
|
|
||||||
|
## Droits
|
||||||
|
|
||||||
|
| Cible | Qui peut supprimer |
|
||||||
|
|-------|-------------------|
|
||||||
|
| Dossier / parent / enfant / AM | `GESTIONNAIRE`, `ADMINISTRATEUR`, `SUPER_ADMIN` |
|
||||||
|
| Gestionnaire (user) | `ADMINISTRATEUR`, `SUPER_ADMIN` |
|
||||||
|
| Administrateur (user) | Autre admin OK ; **self interdit** ; **dernier admin** = `SUPER_ADMIN` only ; `SUPER_ADMIN` non supprimable |
|
||||||
|
|
||||||
|
## Matrice métier
|
||||||
|
|
||||||
|
| Point d’entrée | Action | Effet |
|
||||||
|
|----------------|--------|--------|
|
||||||
|
| Dossiers | Delete dossier **famille** | Tous **parents** + tous **enfants** ; clore placements AM des enfants |
|
||||||
|
| Dossiers / AM | Delete dossier **AM** ou compte AM | **Compte AM + dossier AM** ; enfants **conservés** ; placements **clos** |
|
||||||
|
| Parents | Co-parent (autre parent reste) | Compte parent seul ; dossier + enfants restent |
|
||||||
|
| Parents | Dernier parent | Parent + **enfants** rattachés |
|
||||||
|
| Enfants | Pas dernier | Enfant seul (retiré du dossier) |
|
||||||
|
| Enfants | Dernier + `deleteDossier=true` | Cascade dossier famille (parents + enfants) |
|
||||||
|
| Enfants | Dernier + `deleteDossier=false` | Enfant seul ; dossier peut apparaître **`sans_enfant`** |
|
||||||
|
| Pending / validé | — | **Mêmes règles** (pas de différenciation) |
|
||||||
|
|
||||||
|
## Warning
|
||||||
|
|
||||||
|
- `sans_enfant` sur liste `GET /dossiers` (dossier famille sans enfant lié).
|
||||||
|
- Miroir de `sans_responsable` (#157) côté enfants.
|
||||||
|
|
||||||
|
## Hors scope
|
||||||
|
|
||||||
|
Soft-delete RGPD, audit (#128), famille N (#139), restriction admin-only métier (plus tard).
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
# Mini-spec front — Suppressions dashboard
|
||||||
|
|
||||||
|
**Ticket front** : **#160** — https://git.ptits-pas.fr/jmartin/petitspas/issues/160
|
||||||
|
**Ticket back** : **#159** — https://git.ptits-pas.fr/jmartin/petitspas/issues/159
|
||||||
|
**Epic** : #154 (complète #133)
|
||||||
|
**Branche back** : `feature/159-suppressions-backend`
|
||||||
|
**Doc matrice** : [154-matrice-suppression.md](./154-matrice-suppression.md)
|
||||||
|
|
||||||
|
Travail **en parallèle** : ce contrat est la source de vérité UI ↔ API.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## UX commune
|
||||||
|
|
||||||
|
Sur chaque ligne / carte des listes :
|
||||||
|
|
||||||
|
- Icône **poubelle** en bout de ligne
|
||||||
|
- Clic → **dialog de confirmation** (texte d’impact) → DELETE → **refresh** liste
|
||||||
|
- Pending = **mêmes** règles que validés
|
||||||
|
- **Pas** d’email
|
||||||
|
|
||||||
|
| Liste | Poubelle visible si |
|
||||||
|
|-------|---------------------|
|
||||||
|
| Dossiers, Parents, Enfants, AM | gestionnaire **ou** admin |
|
||||||
|
| Gestionnaires | **admin** only |
|
||||||
|
| Administrateurs | admin+ ; **pas** sur sa propre ligne ; dernier admin : UI warning + réservé super_admin |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contrat API
|
||||||
|
|
||||||
|
Base : auth Bearer. Erreurs : `400` / `403` / `404` / `409` avec `message` FR.
|
||||||
|
|
||||||
|
### 1. `DELETE /dossiers/:numeroDossier`
|
||||||
|
|
||||||
|
- **Famille** → supprime tous parents + enfants du n° ; clos placements AM des enfants.
|
||||||
|
- **AM** → compte AM + dossier AM ; enfants gardés ; placements clos.
|
||||||
|
|
||||||
|
**Réponse 200** (exemple) :
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "famille",
|
||||||
|
"numero_dossier": "2026-000043",
|
||||||
|
"deleted_user_ids": ["…"],
|
||||||
|
"deleted_enfant_ids": ["…"],
|
||||||
|
"message": "Dossier famille supprimé."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
ou
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "assistante_maternelle",
|
||||||
|
"numero_dossier": "2026-000015",
|
||||||
|
"deleted_user_ids": ["…"],
|
||||||
|
"deleted_enfant_ids": [],
|
||||||
|
"message": "Dossier assistante maternelle supprimé."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Dialog UI** : lister libellé + n° + « X parent(s), Y enfant(s) » (ou « compte AM, enfants conservés »).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2. `DELETE /users/:id`
|
||||||
|
|
||||||
|
Comportement selon le **rôle** de la cible :
|
||||||
|
|
||||||
|
| Cible | Effet |
|
||||||
|
|-------|--------|
|
||||||
|
| Parent **co-parent** | Delete ce user seul |
|
||||||
|
| Parent **dernier** du dossier | Delete user + enfants du foyer |
|
||||||
|
| AM | Delete user AM + dossier AM ; enfants conservés ; placements clos |
|
||||||
|
| Gestionnaire | Admin only ; self → 403 |
|
||||||
|
| Administrateur | Self → 403 ; dernier admin → super_admin only sinon 403 ; super_admin → 403 |
|
||||||
|
|
||||||
|
**Réponse 200** :
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"deleted_user_ids": ["…"],
|
||||||
|
"deleted_enfant_ids": ["…"],
|
||||||
|
"message": "…"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Dialogs** :
|
||||||
|
|
||||||
|
- Co-parent : « Ce parent sera retiré / supprimé du dossier {n°}. Les enfants restent avec le co-parent. »
|
||||||
|
- Dernier parent : « Dernier parent du dossier {n°}. Les enfants rattachés seront aussi supprimés. »
|
||||||
|
- AM : « Le compte et le dossier AM seront supprimés. Les enfants accueillis ne seront pas supprimés. »
|
||||||
|
|
||||||
|
Optionnel (si exposé) : `GET /users/:id/suppression-impact` — sinon calculer depuis données déjà en liste / détail dossier.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3. `DELETE /enfants/:id?deleteDossier=true|false`
|
||||||
|
|
||||||
|
- Pas dernier enfant → delete enfant (`deleteDossier` ignoré ou false).
|
||||||
|
- Dernier enfant + `deleteDossier=false` → delete enfant ; dossier famille peut passer `sans_enfant`.
|
||||||
|
- Dernier enfant + `deleteDossier=true` → cascade dossier famille (parents + enfants).
|
||||||
|
|
||||||
|
**Réponse 200** :
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"deleted_enfant_ids": ["…"],
|
||||||
|
"deleted_user_ids": ["…"],
|
||||||
|
"dossier_supprime": false,
|
||||||
|
"message": "…"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Dialog** :
|
||||||
|
|
||||||
|
- Standard : « L’enfant sera supprimé du dossier de {famille} ({n°}). »
|
||||||
|
- Dernier : proposer **deux actions** :
|
||||||
|
1. Supprimer l’enfant seulement (`deleteDossier=false`)
|
||||||
|
2. Supprimer aussi le dossier / parents (`deleteDossier=true`)
|
||||||
|
|
||||||
|
Pour savoir si dernier : compter enfants du `numero_dossier` (détail dossier ou champ impact API).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4. `GET /dossiers` — flag `sans_enfant`
|
||||||
|
|
||||||
|
Chaque item famille peut exposer :
|
||||||
|
|
||||||
|
```json
|
||||||
|
"sans_enfant": true
|
||||||
|
```
|
||||||
|
|
||||||
|
- `true` si dossier **famille** sans enfant lié.
|
||||||
|
- AM : `false` ou omis.
|
||||||
|
|
||||||
|
**UI** : badge / warning vigilance (comme `sans_responsable` / alertes AM).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## UserService (Flutter) — signatures cibles
|
||||||
|
|
||||||
|
```dart
|
||||||
|
Future<void> deleteDossier(String numeroDossier);
|
||||||
|
Future<Map<String, dynamic>> deleteUser(String userId);
|
||||||
|
Future<Map<String, dynamic>> deleteEnfant(String enfantId, {bool deleteDossier = false});
|
||||||
|
```
|
||||||
|
|
||||||
|
(Adapter le parsing au JSON réel une fois le back mergé ; en parallèle, stubber sur ce contrat.)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fichiers front probables
|
||||||
|
|
||||||
|
- Cartes listes : `admin_user_card.dart`, `admin_enfant_user_card.dart`, cartes dossiers
|
||||||
|
- Listes : `dossiers_management_widget.dart`, `parent_managmant_widget.dart`, `enfant_management_widget.dart`, `assistante_maternelle_management_widget.dart`, `gestionnaire_management_widget.dart`, `admin_management_widget.dart`
|
||||||
|
- `user_service.dart`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Critères front (#160)
|
||||||
|
|
||||||
|
- [ ] Poubelle selon droits
|
||||||
|
- [ ] Confirmations avec impact
|
||||||
|
- [ ] Refresh après succès
|
||||||
|
- [ ] Dernier enfant : choix dossier oui/non
|
||||||
|
- [ ] Warning `sans_enfant`
|
||||||
|
- [ ] Self-admin / dernier admin gérés côté UI (masquer ou message 403)
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# Mini-spec — Rename préfixe `Admin*` dashboard partagé (#155)
|
||||||
|
|
||||||
|
**Ticket** : **#155**
|
||||||
|
**Branche** : `feature/155-rename-admin-prefix-dashboard` (depuis `develop`)
|
||||||
|
**Décision naming** : **option C** — dossier neutre `widgets/dashboard/` + noms **sans** préfixe `Admin`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Principe
|
||||||
|
|
||||||
|
Les widgets partagés **admin + gestionnaire** ne doivent plus s’appeler `Admin*`.
|
||||||
|
On garde `Admin*` seulement là où c’est vraiment le rôle administrateur.
|
||||||
|
|
||||||
|
## Gardé `Admin*` (hors rename)
|
||||||
|
|
||||||
|
| Élément | Raison |
|
||||||
|
|---------|--------|
|
||||||
|
| `AdminManagementWidget` | Onglet **Administrateurs** |
|
||||||
|
| `screens/administrateurs/*` | `AdminDashboardScreen`, `AdminCreateDialog`, `AdminUserFormDialog` |
|
||||||
|
| `EnfantAdminModel` | Modèle API (pas un widget) — hors scope ticket |
|
||||||
|
|
||||||
|
## Renames faits
|
||||||
|
|
||||||
|
| Avant | Après |
|
||||||
|
|-------|--------|
|
||||||
|
| `widgets/admin/common/admin_child_detail_modal.dart` → `AdminChildDetailModal` | `widgets/dashboard/child_detail_modal.dart` → `ChildDetailModal` |
|
||||||
|
| `admin_am_edit_modal` → `AdminAmEditModal` | `am_edit_modal` → `AmEditModal` |
|
||||||
|
| `admin_parent_edit_modal` → `AdminParentEditModal` | `parent_edit_modal` → `ParentEditModal` |
|
||||||
|
| `admin_user_card` → `AdminUserCard` | `user_card` → `UserCard` |
|
||||||
|
| `admin_enfant_user_card` → `AdminEnfantUserCard` | `enfant_user_card` → `EnfantUserCard` |
|
||||||
|
| `admin_am_photo_frame` → `AdminAmPhotoFrame` | `am_photo_frame` → `AmPhotoFrame` |
|
||||||
|
| `admin_am_children_capacity_grid` | `am_children_capacity_grid` → `AmChildrenCapacityGrid` |
|
||||||
|
| `admin_children_affiliation_panel` | `children_affiliation_panel` → `ChildrenAffiliationPanel` |
|
||||||
|
| `admin_select_*` / `AdminSelect*` / `AdminFamilleFoyer` | `select_*` / `Select*` / `FamilleFoyer` |
|
||||||
|
| `admin_status_capsule` | `status_capsule` → `StatusCapsule` |
|
||||||
|
| `admin_list_state` → `AdminListState` | `user_list_state` → `UserListState` |
|
||||||
|
| `admin_detail_modal` → `AdminDetailModal` / `AdminDetailField` | `detail_modal` → `DetailModal` / `DetailField` |
|
||||||
|
| `dashboard_admin.dart` | `user_management_sub_bar.dart` (`DashboardUserManagementSubBar` inchangé) |
|
||||||
|
|
||||||
|
Dossier `widgets/admin/` conserve encore les panels métier (`user_management_panel`, wizards, etc.) + `AdminManagementWidget`.
|
||||||
|
|
||||||
|
**Phase 2** (même ticket #155) : déplacer ces panels → `widgets/dashboard/` — voir [155-suite-move-admin-panels-to-dashboard.md](./155-suite-move-admin-panels-to-dashboard.md).
|
||||||
|
|
||||||
|
## Hors scope
|
||||||
|
|
||||||
|
- Refonte UX modales (ticket dédié)
|
||||||
|
- Rename API / back
|
||||||
|
- Déplacer tout `widgets/admin/` → `widgets/dashboard/` (panels) — possible follow-up
|
||||||
|
|
||||||
|
## Critères
|
||||||
|
|
||||||
|
- [x] Plus de préfixe `Admin` sur les composants **partagés** listés
|
||||||
|
- [ ] Build Flutter / recette dashboard admin + gestionnaire OK
|
||||||
|
- [x] Pas de changement comportemental (rename mécanique)
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
# Mini-spec — Déplacer les panels `widgets/admin/` → `widgets/dashboard/`
|
||||||
|
|
||||||
|
**Ticket** : **#155** (phase 2 — même ticket que le rename `Admin*`)
|
||||||
|
**Phase 1** : widgets `Admin*` → `widgets/dashboard/` (déjà sur `feature/155-rename-admin-prefix-dashboard`)
|
||||||
|
**Branche** : poursuivre / rebaser `feature/155-rename-admin-prefix-dashboard` (ou nouvelle branche depuis `develop` après merge phase 1)
|
||||||
|
**Nature** : rename / move mécanique — **zéro** changement UX / métier
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contexte
|
||||||
|
|
||||||
|
Après la phase 1 (#155), la situation est **hybride** :
|
||||||
|
|
||||||
|
| Emplacement | Contenu |
|
||||||
|
|-------------|---------|
|
||||||
|
| `widgets/dashboard/` | Composants partagés sans préfixe `Admin*` (modales, cartes, selects, sub-bar…) |
|
||||||
|
| `widgets/admin/` | **Panels** du dashboard staff (listes, wizards, validation, shell `UserManagementPanel`…) + `AdminManagementWidget` |
|
||||||
|
|
||||||
|
Le dossier `admin/` laisse encore croire « réservé administrateur », alors que **gestionnaire** consomme les mêmes panels (`GestionnaireDashboardScreen` → `UserManagementPanel`).
|
||||||
|
|
||||||
|
Ce ticket **termine l’option C** au niveau dossier : tout le dashboard staff vit sous `widgets/dashboard/`, sauf ce qui est **vraiment** rôle admin.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Objectif
|
||||||
|
|
||||||
|
```
|
||||||
|
frontend/lib/widgets/admin/<panels & common partagés>
|
||||||
|
↓ git mv + update imports
|
||||||
|
frontend/lib/widgets/dashboard/…
|
||||||
|
```
|
||||||
|
|
||||||
|
Critère : un nouveau dev ne doit plus ouvrir `widgets/admin/` pour du code partagé admin+gestionnaire.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cible d’arborescence (proposée)
|
||||||
|
|
||||||
|
```
|
||||||
|
widgets/dashboard/
|
||||||
|
├── (déjà là #155) child_detail_modal.dart, am_edit_modal.dart, user_card.dart, …
|
||||||
|
├── user_management_panel.dart ← shell onglets
|
||||||
|
├── user_management_sub_bar.dart ← déjà déplacé #155
|
||||||
|
├── dossiers_management_widget.dart
|
||||||
|
├── dossier_list_card.dart
|
||||||
|
├── parent_management_widget.dart ← corriger le typo managmant au passage ?
|
||||||
|
├── enfant_management_widget.dart
|
||||||
|
├── assistante_maternelle_management_widget.dart
|
||||||
|
├── gestionnaire_management_widget.dart
|
||||||
|
├── pending_validation_widget.dart
|
||||||
|
├── parent_dossier_create_modal.dart
|
||||||
|
├── parent_dossier_wizard.dart
|
||||||
|
├── am_dossier_create_modal.dart
|
||||||
|
├── am_dossier_wizard.dart
|
||||||
|
├── validation_*.dart ← family/am wizards, refus, theme, confirm
|
||||||
|
├── parametres_panel.dart ← utilisé par écran admin (OK dans dashboard)
|
||||||
|
├── relais_management_panel.dart
|
||||||
|
├── common/ ← sous-dossier optionnel
|
||||||
|
│ ├── suppression_confirm_dialog.dart
|
||||||
|
│ ├── user_list.dart
|
||||||
|
│ └── validation_detail_section.dart
|
||||||
|
└── …
|
||||||
|
|
||||||
|
widgets/admin/ ← mince, rôle admin seulement
|
||||||
|
└── admin_management_widget.dart ← onglet Administrateurs
|
||||||
|
```
|
||||||
|
|
||||||
|
### Variante B (plus stricte)
|
||||||
|
|
||||||
|
`AdminManagementWidget` + éventuels helpers purement admin →
|
||||||
|
`screens/administrateurs/widgets/`
|
||||||
|
et **suppression** du dossier `widgets/admin/`.
|
||||||
|
|
||||||
|
**Reco** : **variante A** (garder `widgets/admin/` minimal avec seulement `AdminManagementWidget`) — moins de churn screens, clair.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Inventaire à déplacer (état actuel)
|
||||||
|
|
||||||
|
### Racine `widgets/admin/` → `widgets/dashboard/`
|
||||||
|
|
||||||
|
| Fichier actuel | Notes |
|
||||||
|
|----------------|--------|
|
||||||
|
| `user_management_panel.dart` | Shell partagé admin + gestionnaire |
|
||||||
|
| `dossiers_management_widget.dart` | |
|
||||||
|
| `dossier_list_card.dart` | |
|
||||||
|
| `parent_managmant_widget.dart` | Typo historique `managmant` — **option** : renommer → `parent_management_widget.dart` dans le même ticket ou ticket typo séparé |
|
||||||
|
| `enfant_management_widget.dart` | |
|
||||||
|
| `assistante_maternelle_management_widget.dart` | |
|
||||||
|
| `gestionnaire_management_widget.dart` | |
|
||||||
|
| `pending_validation_widget.dart` | |
|
||||||
|
| `parent_dossier_create_modal.dart` | |
|
||||||
|
| `parent_dossier_wizard.dart` | |
|
||||||
|
| `am_dossier_create_modal.dart` | |
|
||||||
|
| `am_dossier_wizard.dart` | |
|
||||||
|
| `validation_am_wizard.dart` | |
|
||||||
|
| `validation_family_wizard.dart` | |
|
||||||
|
| `validation_dossier_modal.dart` | |
|
||||||
|
| `validation_modal_theme.dart` | |
|
||||||
|
| `validation_refus_form.dart` | |
|
||||||
|
| `validation_valider_confirm_dialog.dart` | |
|
||||||
|
| `parametres_panel.dart` | Écran admin seulement, mais pas préfixé Admin — OK dashboard |
|
||||||
|
| `relais_management_panel.dart` | |
|
||||||
|
|
||||||
|
### `widgets/admin/common/` → `widgets/dashboard/common/` (ou plat)
|
||||||
|
|
||||||
|
| Fichier | Notes |
|
||||||
|
|---------|--------|
|
||||||
|
| `suppression_confirm_dialog.dart` | Partagé (y compris `screens/administrateurs/creation/*`) |
|
||||||
|
| `user_list.dart` | |
|
||||||
|
| `validation_detail_section.dart` | |
|
||||||
|
|
||||||
|
### **Ne pas** déplacer
|
||||||
|
|
||||||
|
| Fichier | Destination |
|
||||||
|
|---------|-------------|
|
||||||
|
| `admin_management_widget.dart` | Reste `widgets/admin/` (ou variante B → screens) |
|
||||||
|
|
||||||
|
### Déjà fait (#155) — ne pas retraiter
|
||||||
|
|
||||||
|
Tout ce qui est déjà sous `widgets/dashboard/` (`child_detail_modal`, `am_edit_modal`, `user_card`, `select_*`, `user_management_sub_bar`, …).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Consommateurs d’imports (à mettre à jour)
|
||||||
|
|
||||||
|
### Screens
|
||||||
|
- `screens/administrateurs/admin_dashboardScreen.dart` — `UserManagementPanel`, `ParametresPanel`
|
||||||
|
- `screens/gestionnaire/gestionnaire_dashboard_screen.dart` — `UserManagementPanel`
|
||||||
|
- `screens/administrateurs/creation/admin_create.dart` — `suppression_confirm_dialog`
|
||||||
|
- `screens/administrateurs/creation/gestionnaires_create.dart` — idem
|
||||||
|
|
||||||
|
### Widgets déjà en `dashboard/`
|
||||||
|
- `am_edit_modal`, `child_detail_modal`, `parent_edit_modal`, `select_*` — imports vers `widgets/admin/common/*` ou panels
|
||||||
|
|
||||||
|
### Divers
|
||||||
|
- `widgets/common/identity_block.dart` (si import admin)
|
||||||
|
- Tous les fichiers **déplacés** entre eux (imports relatifs / package)
|
||||||
|
|
||||||
|
### Hors scope rename classes
|
||||||
|
Sauf décision explicite sur le typo `parent_managmant_widget` → pas de rename de **classes** métier dans ce ticket (seulement chemins de fichiers + imports).
|
||||||
|
`AdminManagementWidget` **conserve** son nom.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Plan d’exécution
|
||||||
|
|
||||||
|
1. Partir de `feature/155-rename-admin-prefix-dashboard` (phase 1) **ou** `develop` si phase 1 déjà mergée
|
||||||
|
2. `git mv` fichiers selon inventaire
|
||||||
|
3. Remplacer globalement
|
||||||
|
`package:p_tits_pas/widgets/admin/` → `package:p_tits_pas/widgets/dashboard/`
|
||||||
|
**sauf** `…/widgets/admin/admin_management_widget.dart`
|
||||||
|
4. Corriger imports relatifs cassés
|
||||||
|
5. Grep de contrôle (ci-dessous)
|
||||||
|
6. Build Flutter web (Docker) + smoke dashboard admin **et** gestionnaire
|
||||||
|
7. Merge → squash master si flux habituel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Vérifs
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Plus de panels partagés sous admin (seul AdminManagement attendu)
|
||||||
|
find frontend/lib/widgets/admin -name '*.dart'
|
||||||
|
|
||||||
|
# Plus d’imports panels vers l’ancien chemin (sauf AdminManagement)
|
||||||
|
rg -n "widgets/admin/(user_management|dossiers_|parent_|enfant_|assistante|gestionnaire|pending|validation_|parametres|relais|am_dossier|parent_dossier|dossier_list|common/)" frontend/lib
|
||||||
|
|
||||||
|
# Screens OK
|
||||||
|
rg -n "widgets/admin/" frontend/lib/screens
|
||||||
|
```
|
||||||
|
|
||||||
|
Attendu screens : **0** hit vers panels ; éventuellement plus aucun hit `widgets/admin/` sauf si import explicite `AdminManagementWidget` depuis `user_management_panel` (chemin `widgets/admin/admin_management_widget.dart`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hors scope
|
||||||
|
|
||||||
|
- Refonte UX des modales / panels (ticket dédié annoncé)
|
||||||
|
- Rename `EnfantAdminModel`
|
||||||
|
- Rename `screens/administrateurs/`
|
||||||
|
- Rename `AdminUserFormDialog` / `AdminCreateDialog`
|
||||||
|
- Changement API / back
|
||||||
|
- #152 (`est_multiple`) — autre branche
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Critères d’acceptation
|
||||||
|
|
||||||
|
- [ ] Inventaire déplacé selon tableau
|
||||||
|
- [ ] `widgets/admin/` ne contient plus que `admin_management_widget.dart` (variante A)
|
||||||
|
- [ ] Imports screens + widgets à jour
|
||||||
|
- [ ] Build Flutter OK
|
||||||
|
- [ ] Recette : dashboard **administrateur** et **gestionnaire** (listes, ouverture fiches, validation, création dossier) sans régression
|
||||||
|
- [ ] Aucun changement comportemental volontaire
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Risques / notes
|
||||||
|
|
||||||
|
- **Conflits de merge** si d’autres features touchent les panels → faire ce ticket quand la surface dashboard est calme (fin 0.1.0 OK)
|
||||||
|
- Typo `parent_managmant_widget` : soit inclus (bonus), soit ticket cleanup 1-ligne séparé
|
||||||
|
- Docs d’archive citant `widgets/admin/…` : pas obligatoire de mettre à jour ; `docs/27_BRIEFING-FRONTEND.md` oui si encore listé
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# Mini-spec API — POST /assistantes-maternelles/dossier (#156)
|
||||||
|
|
||||||
|
Contrat pour le **plan front** (wizard création AM staff).
|
||||||
|
|
||||||
|
## Endpoint
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|--|--|
|
||||||
|
| **Méthode** | `POST` |
|
||||||
|
| **URL** | `{base}/assistantes-maternelles/dossier` |
|
||||||
|
| **Auth** | Bearer JWT |
|
||||||
|
| **Rôles** | `gestionnaire`, `administrateur`, `super_admin` |
|
||||||
|
| **Content-Type** | `application/json` |
|
||||||
|
|
||||||
|
Ne **pas** appeler `POST /auth/register/am` depuis le dashboard.
|
||||||
|
|
||||||
|
## Body (JSON)
|
||||||
|
|
||||||
|
Aligné inscription AM publique, **sans** CGU/privacy obligatoires (acceptées serveur).
|
||||||
|
|
||||||
|
| Champ | Type | Obligatoire | Notes |
|
||||||
|
|-------|------|-------------|--------|
|
||||||
|
| `email` | string | oui | unique |
|
||||||
|
| `prenom` | string | oui | |
|
||||||
|
| `nom` | string | oui | |
|
||||||
|
| `telephone` | string | oui | `0X…` ou `+33…` |
|
||||||
|
| `adresse` | string | non | |
|
||||||
|
| `code_postal` | string | non | |
|
||||||
|
| `ville` | string | non | |
|
||||||
|
| `photo_base64` | string | non | data-URL `data:image/…;base64,…` |
|
||||||
|
| `photo_filename` | string | non | hint nom fichier |
|
||||||
|
| `consentement_photo` | bool | oui | |
|
||||||
|
| `date_naissance` | date ISO | non | `YYYY-MM-DD` |
|
||||||
|
| `lieu_naissance_ville` | string | oui | |
|
||||||
|
| `lieu_naissance_pays` | string | oui | |
|
||||||
|
| `nir` | string | oui | 15 car. (Corse 2A/2B OK) |
|
||||||
|
| `numero_agrement` | string | oui | unique |
|
||||||
|
| `date_agrement` | date ISO | non | |
|
||||||
|
| `capacite_accueil` | int | oui | 1–10 |
|
||||||
|
| `places_disponibles` | int | oui | 0–10, ≤ capacité |
|
||||||
|
| `biographie` | string | non | max 2000 |
|
||||||
|
|
||||||
|
## Réponses
|
||||||
|
|
||||||
|
### 201 Created
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"message": "Dossier AM créé et validé. Un e-mail de création de mot de passe a été envoyé.",
|
||||||
|
"user_id": "uuid",
|
||||||
|
"statut": "actif",
|
||||||
|
"numero_dossier": "2026-000042"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Effets serveur : user AM **actif**, fiche `assistantes_maternelles`, n° dossier, **e-mail création MDP** (pas d’accusé « en attente »).
|
||||||
|
|
||||||
|
### Erreurs
|
||||||
|
|
||||||
|
| Code | Cas |
|
||||||
|
|------|-----|
|
||||||
|
| 400 | Validation / NIR / places > capacité |
|
||||||
|
| 403 | Rôle non staff |
|
||||||
|
| 409 | Email, NIR ou agrément déjà pris |
|
||||||
|
| 401 | Token manquant / invalide |
|
||||||
|
|
||||||
|
## Front
|
||||||
|
|
||||||
|
- `UserService.createAmDossier(body)` → cet endpoint
|
||||||
|
- Après 201 : refresh liste AM ; snackbar OK
|
||||||
|
- Wizard create : ne pas envoyer `acceptation_cgu` / `acceptation_privacy` (optionnels)
|
||||||
|
|
||||||
|
## Branche
|
||||||
|
|
||||||
|
`feature/156-creation-dossier-am`
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# Mini-spec — Uniformisation modale staff (Gestionnaire / Administrateur)
|
||||||
|
|
||||||
|
**Ticket** : **#164** — https://git.ptits-pas.fr/jmartin/petitspas/issues/164
|
||||||
|
**Branche** : `feature/164-staff-modal-uniformisation` (depuis `develop`)
|
||||||
|
**Périmètre** : **front only** — pas d’API / BDD
|
||||||
|
**Milestone** : **0.1.0**
|
||||||
|
|
||||||
|
Voir le corps du ticket #164 pour la spec complète.
|
||||||
|
|
||||||
|
## Livré
|
||||||
|
|
||||||
|
- `frontend/lib/widgets/dashboard/staff_user_form_modal.dart` → `StaffUserFormModal`
|
||||||
|
- Ancien `AdminUserFormDialog` / `gestionnaires_create.dart` retiré
|
||||||
|
- Imports : `user_management_panel`, `gestionnaire_management_widget`, `admin_management_widget`
|
||||||
|
After Width: | Height: | Size: 741 KiB |
|
After Width: | Height: | Size: 692 KiB |
|
After Width: | Height: | Size: 785 KiB |
|
After Width: | Height: | Size: 261 KiB |
|
After Width: | Height: | Size: 310 KiB |
|
After Width: | Height: | Size: 195 KiB |
|
After Width: | Height: | Size: 231 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
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 |
|
After Width: | Height: | Size: 365 KiB |
|
After Width: | Height: | Size: 276 KiB |
@@ -5,7 +5,8 @@ enum CardColorVertical {
|
|||||||
lime('assets/cards/card_lime.png'),
|
lime('assets/cards/card_lime.png'),
|
||||||
lavender('assets/cards/card_lavender.png'),
|
lavender('assets/cards/card_lavender.png'),
|
||||||
green('assets/cards/card_green.png'),
|
green('assets/cards/card_green.png'),
|
||||||
blue('assets/cards/card_blue.png');
|
blue('assets/cards/card_blue.png'),
|
||||||
|
aqua('assets/cards/card_aqua.png');
|
||||||
|
|
||||||
final String path;
|
final String path;
|
||||||
const CardColorVertical(this.path);
|
const CardColorVertical(this.path);
|
||||||
@@ -18,7 +19,8 @@ enum CardColorHorizontal {
|
|||||||
lime('assets/cards/card_lime_h.png'),
|
lime('assets/cards/card_lime_h.png'),
|
||||||
lavender('assets/cards/card_lavender_h.png'),
|
lavender('assets/cards/card_lavender_h.png'),
|
||||||
green('assets/cards/card_green_h.png'),
|
green('assets/cards/card_green_h.png'),
|
||||||
blue('assets/cards/card_blue_h.png');
|
blue('assets/cards/card_blue_h.png'),
|
||||||
|
aqua('assets/cards/card_aqua_h.png');
|
||||||
|
|
||||||
final String path;
|
final String path;
|
||||||
const CardColorHorizontal(this.path);
|
const CardColorHorizontal(this.path);
|
||||||
|
|||||||
@@ -0,0 +1,303 @@
|
|||||||
|
import 'package:p_tits_pas/models/card_assets.dart';
|
||||||
|
|
||||||
|
/// Statut d'une instance de carte (file d'attention) — contrat #194 / #173.
|
||||||
|
enum CarteStatut {
|
||||||
|
ouverte('ouverte'),
|
||||||
|
refusee('refusee'),
|
||||||
|
traitee('traitee');
|
||||||
|
|
||||||
|
final String apiValue;
|
||||||
|
const CarteStatut(this.apiValue);
|
||||||
|
|
||||||
|
static CarteStatut fromApi(String? raw) {
|
||||||
|
switch (raw) {
|
||||||
|
case 'refusee':
|
||||||
|
return CarteStatut.refusee;
|
||||||
|
case 'fermee':
|
||||||
|
case 'traitee':
|
||||||
|
return CarteStatut.traitee;
|
||||||
|
case 'ouverte':
|
||||||
|
default:
|
||||||
|
return CarteStatut.ouverte;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mode de réponse attendu selon le type SYSTEM.
|
||||||
|
enum CarteResponseMode {
|
||||||
|
none('none'),
|
||||||
|
ack('ack'),
|
||||||
|
acceptRefuse('accept_refuse');
|
||||||
|
|
||||||
|
final String apiValue;
|
||||||
|
const CarteResponseMode(this.apiValue);
|
||||||
|
|
||||||
|
static CarteResponseMode fromApi(String? raw) {
|
||||||
|
switch (raw) {
|
||||||
|
case 'ack':
|
||||||
|
return CarteResponseMode.ack;
|
||||||
|
case 'accept_refuse':
|
||||||
|
return CarteResponseMode.acceptRefuse;
|
||||||
|
case 'none':
|
||||||
|
default:
|
||||||
|
return CarteResponseMode.none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bulle / carte de la file d'attention.
|
||||||
|
class CarteBulle {
|
||||||
|
final String id;
|
||||||
|
final String typeCode;
|
||||||
|
final String titre;
|
||||||
|
final String idPlacement;
|
||||||
|
final String? idAbsence;
|
||||||
|
final String operation;
|
||||||
|
final CarteStatut statut;
|
||||||
|
final Map<String, dynamic> payload;
|
||||||
|
final DateTime? purgeAt;
|
||||||
|
final String? creePar;
|
||||||
|
final bool isCreator;
|
||||||
|
final CarteResponseMode responseMode;
|
||||||
|
final String? lastRefuseComment;
|
||||||
|
final DateTime? creeLe;
|
||||||
|
final DateTime? modifieLe;
|
||||||
|
|
||||||
|
const CarteBulle({
|
||||||
|
required this.id,
|
||||||
|
required this.typeCode,
|
||||||
|
required this.titre,
|
||||||
|
required this.idPlacement,
|
||||||
|
this.idAbsence,
|
||||||
|
this.operation = 'create',
|
||||||
|
required this.statut,
|
||||||
|
this.payload = const {},
|
||||||
|
this.purgeAt,
|
||||||
|
this.creePar,
|
||||||
|
this.isCreator = false,
|
||||||
|
this.responseMode = CarteResponseMode.none,
|
||||||
|
this.lastRefuseComment,
|
||||||
|
this.creeLe,
|
||||||
|
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 dateFin => payload['date_fin']?.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.
|
||||||
|
String get titreAffiche {
|
||||||
|
switch (typeCode) {
|
||||||
|
case 'conge_am':
|
||||||
|
return 'Demande de congés';
|
||||||
|
case 'arret_maladie_am':
|
||||||
|
return 'Arrêt maladie';
|
||||||
|
case 'absence_enfant':
|
||||||
|
case 'absence_enfant_modif':
|
||||||
|
return 'Notification d’absence';
|
||||||
|
case 'soin_enfant':
|
||||||
|
return 'Soin / bobo';
|
||||||
|
default:
|
||||||
|
return titre;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get isArretMaladie => typeCode == 'arret_maladie_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.
|
||||||
|
String? get iconAsset {
|
||||||
|
switch (typeCode) {
|
||||||
|
case 'conge_am':
|
||||||
|
return 'assets/images/valise.png';
|
||||||
|
case 'arret_maladie_am':
|
||||||
|
return 'assets/images/thermo_croix.png';
|
||||||
|
case 'absence_enfant':
|
||||||
|
case 'absence_enfant_modif':
|
||||||
|
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:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fin de période (jour inclus). Null si dates absentes / invalides.
|
||||||
|
DateTime? get dateFinJour {
|
||||||
|
final raw = dateFin;
|
||||||
|
if (raw == null || raw.isEmpty) return null;
|
||||||
|
final dt = DateTime.tryParse(raw);
|
||||||
|
if (dt == null) return null;
|
||||||
|
return DateTime(dt.year, dt.month, dt.day);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Vrai tant que la date de fin n’est pas dépassée (jour courant inclus).
|
||||||
|
bool get periodeEncoreActive {
|
||||||
|
final fin = dateFinJour;
|
||||||
|
if (fin == null) return true;
|
||||||
|
final today = DateTime.now();
|
||||||
|
final todayDay = DateTime(today.year, today.month, today.day);
|
||||||
|
return !todayDay.isAfter(fin);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Teinte pastel UI dérivée du `type_code` (pas de `couleur` API).
|
||||||
|
/// Voir `docs/32_MINI-SPEC-BULLES-CARTES.md` §4.
|
||||||
|
CardColorHorizontal get colorFamily {
|
||||||
|
switch (typeCode) {
|
||||||
|
case 'conge_am':
|
||||||
|
return CardColorHorizontal.aqua;
|
||||||
|
case 'arret_maladie_am':
|
||||||
|
return CardColorHorizontal.blue;
|
||||||
|
case 'absence_enfant':
|
||||||
|
case 'absence_enfant_modif':
|
||||||
|
return CardColorHorizontal.peach;
|
||||||
|
case 'soin_enfant':
|
||||||
|
return CardColorHorizontal.pink;
|
||||||
|
default:
|
||||||
|
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).
|
||||||
|
bool get peutRepondre =>
|
||||||
|
!isCreator &&
|
||||||
|
statut == CarteStatut.ouverte &&
|
||||||
|
responseMode != CarteResponseMode.none;
|
||||||
|
|
||||||
|
factory CarteBulle.fromJson(Map<String, dynamic> json) {
|
||||||
|
final rawPayload = json['payload'];
|
||||||
|
return CarteBulle(
|
||||||
|
id: (json['id'] ?? '').toString(),
|
||||||
|
typeCode: (json['type_code'] ?? '').toString(),
|
||||||
|
titre: (json['titre'] ?? json['type_code'] ?? 'Carte').toString(),
|
||||||
|
idPlacement: (json['id_placement'] ?? '').toString(),
|
||||||
|
idAbsence: json['id_absence']?.toString(),
|
||||||
|
operation: (json['operation'] ?? 'create').toString(),
|
||||||
|
statut: CarteStatut.fromApi(json['statut']?.toString()),
|
||||||
|
payload: rawPayload is Map
|
||||||
|
? Map<String, dynamic>.from(rawPayload)
|
||||||
|
: const {},
|
||||||
|
purgeAt: _parseDate(json['purge_at']),
|
||||||
|
creePar: json['cree_par']?.toString(),
|
||||||
|
isCreator: json['is_creator'] == true,
|
||||||
|
responseMode: CarteResponseMode.fromApi(json['response_mode']?.toString()),
|
||||||
|
lastRefuseComment: json['last_refuse_comment']?.toString(),
|
||||||
|
creeLe: _parseDate(json['cree_le']),
|
||||||
|
modifieLe: _parseDate(json['modifie_le']),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static DateTime? _parseDate(dynamic v) {
|
||||||
|
if (v == null) return null;
|
||||||
|
return DateTime.tryParse(v.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;
|
||||||
|
}
|
||||||
@@ -39,13 +39,15 @@ class CoupleMembre {
|
|||||||
class CoupleGarde {
|
class CoupleGarde {
|
||||||
final String id;
|
final String id;
|
||||||
final CoupleMembre enfant;
|
final CoupleMembre enfant;
|
||||||
final CoupleMembre am;
|
final CoupleMembre? am;
|
||||||
|
final List<CoupleMembre> parents;
|
||||||
final bool courant;
|
final bool courant;
|
||||||
|
|
||||||
const CoupleGarde({
|
const CoupleGarde({
|
||||||
required this.id,
|
required this.id,
|
||||||
required this.enfant,
|
required this.enfant,
|
||||||
required this.am,
|
this.am,
|
||||||
|
this.parents = const [],
|
||||||
this.courant = false,
|
this.courant = false,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -55,9 +57,15 @@ class CoupleGarde {
|
|||||||
enfant: CoupleMembre.fromJson(
|
enfant: CoupleMembre.fromJson(
|
||||||
Map<String, dynamic>.from(json['enfant'] ?? const {}),
|
Map<String, dynamic>.from(json['enfant'] ?? const {}),
|
||||||
),
|
),
|
||||||
am: CoupleMembre.fromJson(
|
am: json['am'] != null
|
||||||
Map<String, dynamic>.from(json['am'] ?? const {}),
|
? CoupleMembre.fromJson(Map<String, dynamic>.from(json['am']))
|
||||||
),
|
: null,
|
||||||
|
parents: json['parents'] != null
|
||||||
|
? (json['parents'] as List)
|
||||||
|
.whereType<Map>()
|
||||||
|
.map((e) => CoupleMembre.fromJson(Map<String, dynamic>.from(e)))
|
||||||
|
.toList()
|
||||||
|
: const [],
|
||||||
courant: json['courant'] == true,
|
courant: json['courant'] == true,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -67,6 +75,7 @@ class CoupleGarde {
|
|||||||
id: id,
|
id: id,
|
||||||
enfant: enfant,
|
enfant: enfant,
|
||||||
am: am,
|
am: am,
|
||||||
|
parents: parents,
|
||||||
courant: courant ?? this.courant,
|
courant: courant ?? this.courant,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
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/widgets/app_footer.dart';
|
import 'package:p_tits_pas/services/couple_garde_service.dart';
|
||||||
import 'package:p_tits_pas/widgets/dashboard/dashboard_bandeau.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/quotidien_shell.dart';
|
||||||
|
import 'package:p_tits_pas/widgets/quotidien/quotidien_theme.dart';
|
||||||
|
import 'package:p_tits_pas/screens/home/parent_screen/agenda_absences_stub.dart';
|
||||||
|
|
||||||
/// Dashboard assistante maternelle – page blanche avec bandeau générique.
|
/// Dashboard assistante maternelle – coquille 3 colonnes quotidien (#169).
|
||||||
/// Contenu détaillé à venir.
|
/// Contexte couple dans le bandeau (#211) ; colonne gauche = feed (#174).
|
||||||
|
/// 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});
|
||||||
|
|
||||||
@@ -14,13 +20,19 @@ class AmDashboardScreen extends StatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _AmDashboardScreenState extends State<AmDashboardScreen> {
|
class _AmDashboardScreenState extends State<AmDashboardScreen> {
|
||||||
int selectedTabIndex = 0;
|
QuotidienNavSection _section = QuotidienNavSection.liaison;
|
||||||
AppUser? _user;
|
AppUser? _user;
|
||||||
|
|
||||||
|
List<CoupleGarde> _couples = const [];
|
||||||
|
String? _selectedCoupleId;
|
||||||
|
bool _couplesLoading = true;
|
||||||
|
String? _couplesError;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_loadUser();
|
_loadUser();
|
||||||
|
_loadCouples();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _loadUser() async {
|
Future<void> _loadUser() async {
|
||||||
@@ -28,51 +40,117 @@ class _AmDashboardScreenState extends State<AmDashboardScreen> {
|
|||||||
if (mounted) setState(() => _user = user);
|
if (mounted) setState(() => _user = user);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _loadCouples() async {
|
||||||
|
setState(() {
|
||||||
|
_couplesLoading = true;
|
||||||
|
_couplesError = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final res = await CoupleGardeService.getAmCouplesGarde();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_couples = res.couples;
|
||||||
|
_selectedCoupleId = res.coupleCourant?.id;
|
||||||
|
_couplesLoading = false;
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_couplesError = e.toString().replaceFirst('Exception: ', '');
|
||||||
|
_couplesLoading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _selectCouple(CoupleGarde couple) async {
|
||||||
|
if (couple.id == _selectedCoupleId) return;
|
||||||
|
setState(() => _selectedCoupleId = couple.id);
|
||||||
|
try {
|
||||||
|
final res = await CoupleGardeService.definirAmCoupleCourant(couple.id);
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_couples = res.couples;
|
||||||
|
_selectedCoupleId = res.coupleCourant?.id ?? couple.id;
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(
|
||||||
|
"Impossible de changer d'enfant : "
|
||||||
|
'${e.toString().replaceFirst('Exception: ', '')}',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String get _displayName {
|
||||||
|
final n = _user?.fullName.trim() ?? '';
|
||||||
|
if (n.isNotEmpty) return n;
|
||||||
|
final email = _user?.email.trim() ?? '';
|
||||||
|
if (email.isNotEmpty) return email.split('@').first;
|
||||||
|
return 'Assistante maternelle';
|
||||||
|
}
|
||||||
|
|
||||||
|
void _soon(String label) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('$label — à venir')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return QuotidienShell(
|
||||||
appBar: PreferredSize(
|
selectedSection: _section,
|
||||||
preferredSize: const Size.fromHeight(60.0),
|
onSectionSelected: (s) => setState(() => _section = s),
|
||||||
child: DashboardBandeau(
|
userDisplayName: _displayName,
|
||||||
tabItems: const [
|
|
||||||
DashboardTabItem(label: 'Mon tableau de bord'),
|
|
||||||
DashboardTabItem(label: 'Paramètres'),
|
|
||||||
],
|
|
||||||
selectedTabIndex: selectedTabIndex,
|
|
||||||
onTabSelected: (index) => setState(() => selectedTabIndex = index),
|
|
||||||
userDisplayName: _user?.fullName.isNotEmpty == true
|
|
||||||
? _user!.fullName
|
|
||||||
: 'Assistante maternelle',
|
|
||||||
userEmail: _user?.email,
|
userEmail: _user?.email,
|
||||||
userRole: _user?.role,
|
onProfileTap: () => _soon('Profil'),
|
||||||
onProfileTap: () {
|
onSettingsTap: () => _soon('Paramètres'),
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
onSearchAmTap: null,
|
||||||
const SnackBar(
|
contextSelector: CoupleSelectorBandeau(
|
||||||
content: Text('Modification du profil – à venir')),
|
mode: CoupleBandeauMode.assistanteMaternelle,
|
||||||
);
|
couples: _couples,
|
||||||
},
|
selectedCoupleId: _selectedCoupleId,
|
||||||
onSettingsTap: () {
|
loading: _couplesLoading,
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
errorMessage: _couplesError,
|
||||||
const SnackBar(content: Text('Paramètres – à venir')),
|
onRetry: _loadCouples,
|
||||||
);
|
onCoupleSelected: _selectCouple,
|
||||||
},
|
|
||||||
onLogout: () {},
|
|
||||||
showLogoutConfirmation: true,
|
|
||||||
),
|
),
|
||||||
|
leftColumn: _LeftColumn(selectedCoupleId: _selectedCoupleId),
|
||||||
|
centerColumn: const QuotidienColumnPlaceholder(
|
||||||
|
title: 'Blog',
|
||||||
|
subtitle:
|
||||||
|
'Fil du quotidien (affichage par défaut)\n(à brancher — ticket #179).',
|
||||||
|
icon: Icons.auto_stories_outlined,
|
||||||
),
|
),
|
||||||
body: Column(
|
rightColumn: const QuotidienColumnPlaceholder(
|
||||||
children: [
|
title: 'Messagerie',
|
||||||
Expanded(
|
subtitle:
|
||||||
child: Center(
|
'Mess. Parents · Mess. RPE\n(à brancher — ticket #185).',
|
||||||
child: Text(
|
icon: Icons.chat_bubble_outline,
|
||||||
'Dashboard AM – à venir',
|
|
||||||
style: Theme.of(context).textTheme.titleLarge,
|
|
||||||
),
|
),
|
||||||
),
|
agendaBody: AgendaAbsencesStub(placementId: _selectedCoupleId),
|
||||||
),
|
contratBody: const QuotidienStubPage(
|
||||||
const AppFooter(),
|
title: 'Contrat',
|
||||||
],
|
message: 'Contrat — contenu à venir (stub #187).',
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Colonne gauche : flux de cartes (#174 / #175). Couple = bandeau (#211).
|
||||||
|
class _LeftColumn extends StatelessWidget {
|
||||||
|
final String? selectedCoupleId;
|
||||||
|
|
||||||
|
const _LeftColumn({required this.selectedCoupleId});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.all(14),
|
||||||
|
child: CartesFeed(placementId: selectedCoupleId),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ class _ParentRegisterStep3ScreenState extends State<ParentRegisterStep3Screen> {
|
|||||||
CardColorVertical.red,
|
CardColorVertical.red,
|
||||||
CardColorVertical.green,
|
CardColorVertical.green,
|
||||||
CardColorVertical.blue,
|
CardColorVertical.blue,
|
||||||
|
CardColorVertical.aqua,
|
||||||
];
|
];
|
||||||
|
|
||||||
// Garder une trace des couleurs déjà utilisées
|
// Garder une trace des couleurs déjà utilisées
|
||||||
|
|||||||
@@ -3,14 +3,14 @@ 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';
|
||||||
|
|
||||||
/// Tableau de bord parent — coquille 3 colonnes quotidien (#166).
|
/// Tableau de bord parent — coquille 3 colonnes quotidien (#166).
|
||||||
/// Colonne gauche : sélecteur de couple enfant–nounou (#167).
|
/// Contexte couple dans le bandeau (#211) ; colonne gauche = feed (#173).
|
||||||
/// Métier cartes / blog / messagerie : tickets C/D/E.
|
|
||||||
class ParentDashboardScreen extends StatefulWidget {
|
class ParentDashboardScreen extends StatefulWidget {
|
||||||
const ParentDashboardScreen({super.key});
|
const ParentDashboardScreen({super.key});
|
||||||
|
|
||||||
@@ -63,7 +63,6 @@ class _ParentDashboardScreenState extends State<ParentDashboardScreen> {
|
|||||||
|
|
||||||
Future<void> _selectCouple(CoupleGarde couple) async {
|
Future<void> _selectCouple(CoupleGarde couple) async {
|
||||||
if (couple.id == _selectedCoupleId) return;
|
if (couple.id == _selectedCoupleId) return;
|
||||||
// Optimiste : on bascule tout de suite, l'API persiste ensuite.
|
|
||||||
setState(() => _selectedCoupleId = couple.id);
|
setState(() => _selectedCoupleId = couple.id);
|
||||||
try {
|
try {
|
||||||
final res = await CoupleGardeService.definirCoupleCourant(couple.id);
|
final res = await CoupleGardeService.definirCoupleCourant(couple.id);
|
||||||
@@ -109,14 +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,
|
||||||
),
|
),
|
||||||
|
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 à venir).
|
/// 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;
|
|
||||||
|
|
||||||
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(
|
|
||||||
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 #173).',
|
|
||||||
icon: Icons.style_outlined,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ class AbsencesGardeService {
|
|||||||
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
|
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
|
||||||
|
|
||||||
final uri = Uri.parse(ApiConfig.baseUrl +
|
final uri = Uri.parse(ApiConfig.baseUrl +
|
||||||
'/absences-garde' +
|
'/evenements-agenda' +
|
||||||
(placementId != null ? '?placementId=$placementId' : ''));
|
(placementId != null ? '?placementId=$placementId' : ''));
|
||||||
|
|
||||||
final res = await http.get(uri, headers: headers);
|
final res = await http.get(uri, headers: headers);
|
||||||
@@ -33,7 +33,7 @@ class AbsencesGardeService {
|
|||||||
final token = await TokenService.getToken();
|
final token = await TokenService.getToken();
|
||||||
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
|
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
|
||||||
|
|
||||||
final uri = Uri.parse('${ApiConfig.baseUrl}/absences-garde');
|
final uri = Uri.parse('${ApiConfig.baseUrl}/evenements-agenda');
|
||||||
final res = await http.post(
|
final res = await http.post(
|
||||||
uri,
|
uri,
|
||||||
headers: headers,
|
headers: headers,
|
||||||
@@ -62,7 +62,7 @@ class AbsencesGardeService {
|
|||||||
final token = await TokenService.getToken();
|
final token = await TokenService.getToken();
|
||||||
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
|
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
|
||||||
|
|
||||||
final uri = Uri.parse('${ApiConfig.baseUrl}/absences-garde/$id');
|
final uri = Uri.parse('${ApiConfig.baseUrl}/evenements-agenda/$id');
|
||||||
final Map<String, dynamic> body = {};
|
final Map<String, dynamic> body = {};
|
||||||
if (dateDebut != null) body['date_debut'] = dateDebut;
|
if (dateDebut != null) body['date_debut'] = dateDebut;
|
||||||
if (dateFin != null) body['date_fin'] = dateFin;
|
if (dateFin != null) body['date_fin'] = dateFin;
|
||||||
@@ -85,7 +85,7 @@ class AbsencesGardeService {
|
|||||||
final token = await TokenService.getToken();
|
final token = await TokenService.getToken();
|
||||||
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
|
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
|
||||||
|
|
||||||
final uri = Uri.parse('${ApiConfig.baseUrl}/absences-garde/$id');
|
final uri = Uri.parse('${ApiConfig.baseUrl}/evenements-agenda/$id');
|
||||||
final res = await http.delete(uri, headers: headers);
|
final res = await http.delete(uri, headers: headers);
|
||||||
if (res.statusCode != 204) {
|
if (res.statusCode != 204) {
|
||||||
throw Exception("Erreur de suppression d'absence : ${res.statusCode}");
|
throw Exception("Erreur de suppression d'absence : ${res.statusCode}");
|
||||||
|
|||||||
@@ -67,7 +67,11 @@ class ApiConfig {
|
|||||||
static const String parentsCoupleGardeCourant =
|
static const String parentsCoupleGardeCourant =
|
||||||
'/parents/me/couples-garde/courant';
|
'/parents/me/couples-garde/courant';
|
||||||
static const String assistantesMaternelles = '/assistantes-maternelles';
|
static const String assistantesMaternelles = '/assistantes-maternelles';
|
||||||
/// Création dossier AM actif par le staff (#156) — body type register AM.
|
/// Couples de garde de l'AM connectée (#170 / #171).
|
||||||
|
static const String assistantesMaternellesCouplesGarde =
|
||||||
|
'/assistantes-maternelles/me/couples-garde';
|
||||||
|
static const String assistantesMaternellesCoupleGardeCourant =
|
||||||
|
'/assistantes-maternelles/me/couples-garde/courant';
|
||||||
static const String assistantesMaternellesDossier =
|
static const String assistantesMaternellesDossier =
|
||||||
'/assistantes-maternelles/dossier';
|
'/assistantes-maternelles/dossier';
|
||||||
static const String enfants = '/enfants';
|
static const String enfants = '/enfants';
|
||||||
@@ -89,6 +93,10 @@ class ApiConfig {
|
|||||||
static const String conversations = '/conversations';
|
static const String conversations = '/conversations';
|
||||||
static const String notifications = '/notifications';
|
static const String notifications = '/notifications';
|
||||||
|
|
||||||
|
/// File d'attention / bulles (#173 / #194).
|
||||||
|
static const String cards = '/cards';
|
||||||
|
static const String cardsStream = '/cards/stream';
|
||||||
|
|
||||||
// Headers
|
// Headers
|
||||||
static Map<String, String> get headers => {
|
static Map<String, String> get headers => {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
|
|||||||
@@ -0,0 +1,189 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
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/tokenService.dart';
|
||||||
|
|
||||||
|
/// Accès API Cartes (file d'attention) — tickets #173 / #175 / #194.
|
||||||
|
/// - GET /cards?placementId=
|
||||||
|
/// - GET /cards/types
|
||||||
|
/// - POST /cards
|
||||||
|
/// - POST /cards/:id/respond
|
||||||
|
class CardsService {
|
||||||
|
static Future<Map<String, String>> _headers() async {
|
||||||
|
final token = await TokenService.getToken();
|
||||||
|
return token != null
|
||||||
|
? ApiConfig.authHeaders(token)
|
||||||
|
: Map<String, String>.from(ApiConfig.headers);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _extractError(String body, String fallback) {
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(body);
|
||||||
|
if (decoded is Map<String, dynamic>) {
|
||||||
|
final message = decoded['message'];
|
||||||
|
if (message is String && message.trim().isNotEmpty) {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
if (message is Map && message['message'] is String) {
|
||||||
|
return message['message'] as String;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Feed de bulles pour l'utilisateur (filtré par couple / placement).
|
||||||
|
static Future<List<CarteBulle>> lister({String? placementId}) async {
|
||||||
|
final query = <String, String>{};
|
||||||
|
if (placementId != null && placementId.isNotEmpty) {
|
||||||
|
query['placementId'] = placementId;
|
||||||
|
}
|
||||||
|
final uri = Uri.parse(
|
||||||
|
'${ApiConfig.baseUrl}${ApiConfig.cards}',
|
||||||
|
).replace(queryParameters: query.isEmpty ? null : query);
|
||||||
|
|
||||||
|
final response = await http.get(uri, headers: await _headers());
|
||||||
|
if (response.statusCode != 200) {
|
||||||
|
throw Exception(
|
||||||
|
_extractError(response.body, 'Erreur chargement des cartes'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final decoded = jsonDecode(response.body);
|
||||||
|
final list = (decoded is Map ? decoded['items'] as List? : null) ?? const [];
|
||||||
|
return list
|
||||||
|
.whereType<Map>()
|
||||||
|
.map((e) => CarteBulle.fromJson(Map<String, dynamic>.from(e)))
|
||||||
|
.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.
|
||||||
|
static Future<CarteBulle> repondre({
|
||||||
|
required String cardId,
|
||||||
|
required String action,
|
||||||
|
String? comment,
|
||||||
|
}) async {
|
||||||
|
final response = await http.post(
|
||||||
|
Uri.parse(
|
||||||
|
'${ApiConfig.baseUrl}${ApiConfig.cards}/$cardId/respond',
|
||||||
|
),
|
||||||
|
headers: await _headers(),
|
||||||
|
body: jsonEncode({
|
||||||
|
'action': action,
|
||||||
|
if (comment != null && comment.trim().isNotEmpty)
|
||||||
|
'comment': comment.trim(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode != 200 && response.statusCode != 201) {
|
||||||
|
throw Exception(
|
||||||
|
_extractError(response.body, 'Erreur lors de la réponse'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final decoded = jsonDecode(response.body);
|
||||||
|
return CarteBulle.fromJson(Map<String, dynamic>.from(decoded as Map));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -73,4 +73,45 @@ class CoupleGardeService {
|
|||||||
Map<String, dynamic>.from(decoded as Map),
|
Map<String, dynamic>.from(decoded as Map),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Liste les couples de garde et le couple courant de l'AM connectée.
|
||||||
|
static Future<CouplesGardeResponse> getAmCouplesGarde() async {
|
||||||
|
final response = await http.get(
|
||||||
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.assistantesMaternellesCouplesGarde}'),
|
||||||
|
headers: await _headers(),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode != 200) {
|
||||||
|
throw Exception(
|
||||||
|
_extractError(response.body, 'Erreur chargement des couples de garde (AM)'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final decoded = jsonDecode(response.body);
|
||||||
|
return CouplesGardeResponse.fromJson(
|
||||||
|
Map<String, dynamic>.from(decoded as Map),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Persiste le couple courant (AM) et renvoie la liste à jour.
|
||||||
|
static Future<CouplesGardeResponse> definirAmCoupleCourant(
|
||||||
|
String coupleId,
|
||||||
|
) async {
|
||||||
|
final response = await http.put(
|
||||||
|
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.assistantesMaternellesCoupleGardeCourant}'),
|
||||||
|
headers: await _headers(),
|
||||||
|
body: jsonEncode({'couple_id': coupleId}),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode != 200) {
|
||||||
|
throw Exception(
|
||||||
|
_extractError(response.body, 'Erreur sélection du couple de garde (AM)'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final decoded = jsonDecode(response.body);
|
||||||
|
return CouplesGardeResponse.fromJson(
|
||||||
|
Map<String, dynamic>.from(decoded as Map),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ class RepriseMapper {
|
|||||||
CardColorVertical.red,
|
CardColorVertical.red,
|
||||||
CardColorVertical.green,
|
CardColorVertical.green,
|
||||||
CardColorVertical.blue,
|
CardColorVertical.blue,
|
||||||
|
CardColorVertical.aqua,
|
||||||
];
|
];
|
||||||
|
|
||||||
static ParentData parentFromDossier(ParentDossier p) {
|
static ParentData parentFromDossier(ParentDossier p) {
|
||||||
|
|||||||
@@ -185,6 +185,8 @@ class BaseFormScreen extends StatelessWidget {
|
|||||||
return CardColorVertical.pink.path;
|
return CardColorVertical.pink.path;
|
||||||
case CardColorHorizontal.red:
|
case CardColorHorizontal.red:
|
||||||
return CardColorVertical.red.path;
|
return CardColorVertical.red.path;
|
||||||
|
case CardColorHorizontal.aqua:
|
||||||
|
return CardColorVertical.aqua.path;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -205,9 +205,14 @@ class _ChildCardWidgetState extends State<ChildCardWidget> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
final Color baseCardColorForShadow = widget.childData.cardColor == CardColorVertical.lavender
|
final Color baseCardColorForShadow =
|
||||||
|
widget.childData.cardColor == CardColorVertical.lavender
|
||||||
? Colors.purple.shade200
|
? Colors.purple.shade200
|
||||||
: (widget.childData.cardColor == CardColorVertical.pink ? Colors.pink.shade200 : Colors.grey.shade200);
|
: (widget.childData.cardColor == CardColorVertical.pink
|
||||||
|
? Colors.pink.shade200
|
||||||
|
: (widget.childData.cardColor == CardColorVertical.aqua
|
||||||
|
? Colors.teal.shade200
|
||||||
|
: Colors.grey.shade200));
|
||||||
final double photoSide = 200.0 * (config.isMobile ? 0.8 : 1.0);
|
final double photoSide = 200.0 * (config.isMobile ? 0.8 : 1.0);
|
||||||
final double editableCardWidth = config.isMobile
|
final double editableCardWidth = config.isMobile
|
||||||
? double.infinity
|
? double.infinity
|
||||||
@@ -340,6 +345,7 @@ class _ChildCardWidgetState extends State<ChildCardWidget> {
|
|||||||
|
|
||||||
// Mapping manuel simple
|
// Mapping manuel simple
|
||||||
if (widget.childData.cardColor.path.contains('lavender')) horizontalCardAsset = CardColorHorizontal.lavender.path;
|
if (widget.childData.cardColor.path.contains('lavender')) horizontalCardAsset = CardColorHorizontal.lavender.path;
|
||||||
|
else if (widget.childData.cardColor.path.contains('aqua')) horizontalCardAsset = CardColorHorizontal.aqua.path;
|
||||||
else if (widget.childData.cardColor.path.contains('blue')) horizontalCardAsset = CardColorHorizontal.blue.path;
|
else if (widget.childData.cardColor.path.contains('blue')) horizontalCardAsset = CardColorHorizontal.blue.path;
|
||||||
else if (widget.childData.cardColor.path.contains('green')) horizontalCardAsset = CardColorHorizontal.green.path;
|
else if (widget.childData.cardColor.path.contains('green')) horizontalCardAsset = CardColorHorizontal.green.path;
|
||||||
else if (widget.childData.cardColor.path.contains('lime')) horizontalCardAsset = CardColorHorizontal.lime.path;
|
else if (widget.childData.cardColor.path.contains('lime')) horizontalCardAsset = CardColorHorizontal.lime.path;
|
||||||
|
|||||||
@@ -1302,6 +1302,8 @@ class _PersonalInfoFormScreenState extends State<PersonalInfoFormScreen> {
|
|||||||
return CardColorVertical.pink.path;
|
return CardColorVertical.pink.path;
|
||||||
case CardColorHorizontal.red:
|
case CardColorHorizontal.red:
|
||||||
return CardColorVertical.red.path;
|
return CardColorVertical.red.path;
|
||||||
|
case CardColorHorizontal.aqua:
|
||||||
|
return CardColorVertical.aqua.path;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -642,6 +642,8 @@ class _PresentationFormScreenState extends State<PresentationFormScreen> {
|
|||||||
return CardColorVertical.pink.path;
|
return CardColorVertical.pink.path;
|
||||||
case CardColorHorizontal.red:
|
case CardColorHorizontal.red:
|
||||||
return CardColorVertical.red.path;
|
return CardColorVertical.red.path;
|
||||||
|
case CardColorHorizontal.aqua:
|
||||||
|
return CardColorVertical.aqua.path;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||