Compare commits
152
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f8974d65e | ||
|
|
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 | ||
|
|
da71803852 | ||
|
|
2380aa9826 | ||
|
|
c952113099 | ||
|
|
8204669ec9 | ||
|
|
76ab0f340a | ||
|
|
a0a5e15b04 | ||
|
|
823ea6cd22 | ||
|
|
dfac075a74 | ||
|
|
2d8b857a84 | ||
|
|
ba6078feab | ||
|
|
147051821a | ||
|
|
9240d35d9e | ||
|
|
41f7006073 | ||
|
|
7a3ba178ec | ||
|
|
8d8627cf38 | ||
|
|
77832d53c4 | ||
|
|
6a586110e7 | ||
|
|
d127ab4ecb | ||
|
|
f9fd8d73a8 | ||
|
|
93ee3a5549 | ||
|
|
db08aca714 | ||
|
|
f4fce0a1ef | ||
|
|
494f0e4c19 | ||
|
|
9a4664a8ea | ||
|
|
bf00933f65 | ||
|
|
7b4650b81b | ||
|
|
b7ae07f5aa | ||
|
|
a88f791317 | ||
|
|
138398a4a0 | ||
|
|
7cf30643aa | ||
|
|
5eb3468fe0 | ||
|
|
df4f48e864 | ||
|
|
2daf6c9cda | ||
|
|
6f9136aae5 | ||
|
|
461c70df05 | ||
|
|
fa88d00657 | ||
|
|
6e18956a63 | ||
|
|
745349bc83 | ||
|
|
aeda636983 | ||
|
|
a7c0864279 | ||
|
|
89f65356d1 | ||
|
|
aae2beeac8 | ||
|
|
71b1897678 | ||
|
|
f745079f0a | ||
|
|
3218daa12e | ||
|
|
1d6261b312 | ||
|
|
5b83102a59 | ||
|
|
9557cf9947 | ||
|
|
939e7777ac | ||
|
|
b474842e19 | ||
|
|
a312d9c0fa | ||
|
|
b5b32062b3 | ||
|
|
946d8edcd2 | ||
|
|
eb5e4aa915 | ||
|
|
c8cb82dd24 | ||
|
|
9cd180bf6a | ||
|
|
d6d8b299dd | ||
|
|
ca07d2e111 | ||
|
|
67336c64fe | ||
|
|
97afbbcf9a | ||
|
|
e235b30140 | ||
|
|
ea0e97d930 | ||
|
|
84e46162fd | ||
|
|
14580c34e0 | ||
|
|
ae610733cc | ||
|
|
846afed86c | ||
|
|
99a6c17c23 | ||
|
|
04f49cb62f | ||
|
|
3c7f4f6e16 | ||
|
|
dcd407a3da | ||
|
|
fde63f8e72 | ||
|
|
1f8f1b9507 |
Generated
+49
@@ -15,6 +15,7 @@
|
||||
"@nestjs/jwt": "^11.0.0",
|
||||
"@nestjs/mapped-types": "^2.1.0",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@nestjs/schedule": "^12.0.2",
|
||||
"@nestjs/swagger": "^11.2.0",
|
||||
"@nestjs/typeorm": "^11.0.0",
|
||||
"@sentry/nestjs": "^10.10.0",
|
||||
@@ -2544,6 +2545,22 @@
|
||||
"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": {
|
||||
"version": "11.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-11.0.7.tgz",
|
||||
@@ -3767,6 +3784,12 @@
|
||||
"@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": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",
|
||||
@@ -5856,6 +5879,23 @@
|
||||
"devOptional": true,
|
||||
"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": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
@@ -8786,6 +8826,15 @@
|
||||
"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": {
|
||||
"version": "0.30.17",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz",
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
"@nestjs/jwt": "^11.0.0",
|
||||
"@nestjs/mapped-types": "^2.1.0",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@nestjs/schedule": "^12.0.2",
|
||||
"@nestjs/swagger": "^11.2.0",
|
||||
"@nestjs/typeorm": "^11.0.0",
|
||||
"@sentry/nestjs": "^10.10.0",
|
||||
|
||||
@@ -33,7 +33,6 @@ model Child {
|
||||
dateOfBirth DateTime
|
||||
photoUrl String?
|
||||
photoConsent Boolean @default(false)
|
||||
isMultiple Boolean @default(false)
|
||||
isUnborn Boolean @default(false)
|
||||
parentId String
|
||||
parent Parent @relation(fields: [parentId], references: [id])
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { ScheduleModule } from '@nestjs/schedule';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import appConfig from './config/app.config';
|
||||
@@ -16,6 +17,8 @@ import { AllExceptionsFilter } from './common/filters/all_exceptions.filters';
|
||||
import { EnfantsModule } from './routes/enfants/enfants.module';
|
||||
import { AppConfigModule } from './modules/config/config.module';
|
||||
import { DocumentsLegauxModule } from './modules/documents-legaux';
|
||||
import { EvenementsAgendaModule } from './modules/evenements-agenda';
|
||||
import { CardsModule } from './modules/cards';
|
||||
import { RelaisModule } from './routes/relais/relais.module';
|
||||
import { DossiersModule } from './routes/dossiers/dossiers.module';
|
||||
import { SuppressionsModule } from './routes/suppressions/suppressions.module';
|
||||
@@ -56,6 +59,9 @@ import { SuppressionsModule } from './routes/suppressions/suppressions.module';
|
||||
AuthModule,
|
||||
AppConfigModule,
|
||||
DocumentsLegauxModule,
|
||||
ScheduleModule.forRoot(),
|
||||
EvenementsAgendaModule,
|
||||
CardsModule,
|
||||
RelaisModule,
|
||||
DossiersModule,
|
||||
SuppressionsModule,
|
||||
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Entity, PrimaryColumn, Column, OneToOne, OneToMany, JoinColumn } from 'typeorm';
|
||||
import { Entity, PrimaryColumn, Column, OneToOne, OneToMany, JoinColumn, ManyToOne } from 'typeorm';
|
||||
import { Users } from './users.entity';
|
||||
import { AmChildren } from './am_children.entity';
|
||||
|
||||
@@ -37,22 +37,32 @@ export class AssistanteMaternelle {
|
||||
@Column({ name: 'ville_residence', length: 100, nullable: true })
|
||||
residence_city?: string;
|
||||
|
||||
@Column( { name: 'date_agrement', type: 'date', nullable: true })
|
||||
@Column({ name: 'date_agrement', type: 'date', nullable: true })
|
||||
agreement_date?: Date;
|
||||
|
||||
@Column( { name: 'annee_experience', type: 'smallint', nullable: true })
|
||||
@Column({ name: 'annee_experience', type: 'smallint', nullable: true })
|
||||
years_experience?: number;
|
||||
|
||||
@Column( { name: 'specialite', length: 100, nullable: true })
|
||||
|
||||
@Column({ name: 'specialite', length: 100, nullable: true })
|
||||
specialty?: string;
|
||||
|
||||
@Column( { name: 'place_disponible', type: 'integer', nullable: true })
|
||||
@Column({ name: 'place_disponible', type: 'integer', nullable: true })
|
||||
places_available?: number;
|
||||
|
||||
/** Numéro de dossier (format AAAA-NNNNNN), même valeur que sur utilisateurs (ticket #103) */
|
||||
@Column({ name: 'numero_dossier', length: 20, nullable: true })
|
||||
numero_dossier?: string;
|
||||
|
||||
/**
|
||||
* Placement AM↔enfant sélectionné sur le TdB AM (couple actif) — ticket #171.
|
||||
*/
|
||||
@Column({ name: 'id_placement_garde_courant', type: 'uuid', nullable: true })
|
||||
id_placement_garde_courant?: string;
|
||||
|
||||
@ManyToOne(() => AmChildren, { nullable: true, onDelete: 'SET NULL' })
|
||||
@JoinColumn({ name: 'id_placement_garde_courant', referencedColumnName: 'id' })
|
||||
placement_garde_courant?: AmChildren;
|
||||
|
||||
@OneToMany(() => AmChildren, (ac) => ac.am)
|
||||
amChildren: AmChildren[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import {
|
||||
Column,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
} from 'typeorm';
|
||||
import { CardInstance } from './card_instances.entity';
|
||||
import { Users } from './users.entity';
|
||||
|
||||
@Entity('card_audience_members', { schema: 'public' })
|
||||
export class CardAudienceMember {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ name: 'id_card', type: 'uuid' })
|
||||
id_card: string;
|
||||
|
||||
@ManyToOne(() => CardInstance, (c) => c.audience, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'id_card', referencedColumnName: 'id' })
|
||||
card: CardInstance;
|
||||
|
||||
@Column({ name: 'id_utilisateur', type: 'uuid' })
|
||||
id_utilisateur: string;
|
||||
|
||||
@ManyToOne(() => Users, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'id_utilisateur', referencedColumnName: 'id' })
|
||||
user: Users;
|
||||
|
||||
@Column({ name: 'role_snapshot', type: 'varchar', length: 64 })
|
||||
role_snapshot: string;
|
||||
|
||||
@Column({ name: 'is_creator', type: 'boolean', default: false })
|
||||
is_creator: boolean;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
OneToMany,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { AmChildren } from './am_children.entity';
|
||||
import { EvenementsAgenda } from './evenements_agenda.entity';
|
||||
import { Users } from './users.entity';
|
||||
import { CardType } from './card_types.entity';
|
||||
import { CardAudienceMember } from './card_audience_members.entity';
|
||||
import { CardResponse } from './card_responses.entity';
|
||||
import { AgendaLots } from './agenda_lots.entity';
|
||||
|
||||
export enum CardInstanceStatutType {
|
||||
OUVERTE = 'ouverte',
|
||||
REFUSEE = 'refusee',
|
||||
TRAITEE = 'traitee',
|
||||
ANNULEE = 'annulee',
|
||||
}
|
||||
|
||||
export enum CardOperationType {
|
||||
CREATE = 'create',
|
||||
UPDATE = 'update',
|
||||
CANCEL = 'cancel',
|
||||
}
|
||||
|
||||
@Entity('card_instances', { schema: 'public' })
|
||||
export class CardInstance {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ name: 'type_code', type: 'varchar', length: 64 })
|
||||
type_code: string;
|
||||
|
||||
@ManyToOne(() => CardType, { onDelete: 'RESTRICT' })
|
||||
@JoinColumn({ name: 'type_code', referencedColumnName: 'code' })
|
||||
type: CardType;
|
||||
|
||||
@Column({ name: 'id_placement', type: 'uuid' })
|
||||
id_placement: string;
|
||||
|
||||
@ManyToOne(() => AmChildren, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'id_placement', referencedColumnName: 'id' })
|
||||
placement: AmChildren;
|
||||
|
||||
@Column({ name: 'id_evenement', type: 'uuid', nullable: true })
|
||||
id_evenement?: string;
|
||||
|
||||
@ManyToOne(() => EvenementsAgenda, { nullable: true, onDelete: 'SET NULL' })
|
||||
@JoinColumn({ name: 'id_evenement', referencedColumnName: 'id' })
|
||||
evenement?: EvenementsAgenda;
|
||||
|
||||
@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;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: CardOperationType,
|
||||
enumName: 'card_operation_type',
|
||||
name: 'operation',
|
||||
default: CardOperationType.CREATE,
|
||||
})
|
||||
operation: CardOperationType;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: CardInstanceStatutType,
|
||||
enumName: 'card_instance_statut_type',
|
||||
name: 'statut',
|
||||
default: CardInstanceStatutType.OUVERTE,
|
||||
})
|
||||
statut: CardInstanceStatutType;
|
||||
|
||||
@Column({ name: 'payload', type: 'jsonb', default: {} })
|
||||
payload: Record<string, unknown>;
|
||||
|
||||
@Column({ name: 'purge_at', type: 'timestamptz' })
|
||||
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)
|
||||
audience: CardAudienceMember[];
|
||||
|
||||
@OneToMany(() => CardResponse, (r) => r.card)
|
||||
responses: CardResponse[];
|
||||
|
||||
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||
cree_le: Date;
|
||||
|
||||
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
|
||||
modifie_le: Date;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
RelationId,
|
||||
} from 'typeorm';
|
||||
import { CardInstance } from './card_instances.entity';
|
||||
import { Users } from './users.entity';
|
||||
|
||||
export enum CardResponseActionType {
|
||||
ACCEPT = 'accept',
|
||||
REFUSE = 'refuse',
|
||||
ACK = 'ack',
|
||||
}
|
||||
|
||||
@Entity('card_responses', { schema: 'public' })
|
||||
export class CardResponse {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
/** FK carte — une seule source de vérité via @JoinColumn (pas de @Column doublon). */
|
||||
@ManyToOne(() => CardInstance, (c) => c.responses, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'id_card', referencedColumnName: 'id' })
|
||||
card: CardInstance;
|
||||
|
||||
@RelationId((r: CardResponse) => r.card)
|
||||
id_card: string;
|
||||
|
||||
@ManyToOne(() => Users, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'id_utilisateur', referencedColumnName: 'id' })
|
||||
user: Users;
|
||||
|
||||
@RelationId((r: CardResponse) => r.user)
|
||||
id_utilisateur: string;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: CardResponseActionType,
|
||||
enumName: 'card_response_action_type',
|
||||
name: 'action',
|
||||
})
|
||||
action: CardResponseActionType;
|
||||
|
||||
@Column({ name: 'comment', type: 'text', nullable: true })
|
||||
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' })
|
||||
cree_le: Date;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
PrimaryColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
export enum CardResponseModeType {
|
||||
NONE = 'none',
|
||||
ACK = 'ack',
|
||||
ACCEPT_REFUSE = 'accept_refuse',
|
||||
}
|
||||
|
||||
@Entity('card_types', { schema: 'public' })
|
||||
export class CardType {
|
||||
@PrimaryColumn({ name: 'code', type: 'varchar', length: 64 })
|
||||
code: string;
|
||||
|
||||
@Column({ name: 'system', type: 'boolean', default: true })
|
||||
system: boolean;
|
||||
|
||||
@Column({ name: 'titre', type: 'varchar', length: 120 })
|
||||
titre: string;
|
||||
|
||||
@Column({ name: 'emitter_roles', type: 'text', array: true })
|
||||
emitter_roles: string[];
|
||||
|
||||
@Column({ name: 'recipient_roles', type: 'text', array: true })
|
||||
recipient_roles: string[];
|
||||
|
||||
@Column({ name: 'audience_resolver', type: 'varchar', length: 64 })
|
||||
audience_resolver: string;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: CardResponseModeType,
|
||||
enumName: 'card_response_mode_type',
|
||||
name: 'response_mode',
|
||||
})
|
||||
response_mode: CardResponseModeType;
|
||||
|
||||
@Column({ name: 'retention_days', type: 'int', default: 14 })
|
||||
retention_days: number;
|
||||
|
||||
@Column({ name: 'couleur', type: 'varchar', length: 32, nullable: true })
|
||||
couleur?: string;
|
||||
|
||||
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||
cree_le: Date;
|
||||
|
||||
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
|
||||
modifie_le: Date;
|
||||
}
|
||||
@@ -63,9 +63,6 @@ export class Children {
|
||||
@Column({ type: 'timestamptz', nullable: true, name: 'date_consentement_photo' })
|
||||
consent_photo_at?: Date;
|
||||
|
||||
@Column({ default: false, name: 'est_multiple', type: 'boolean' })
|
||||
is_multiple: boolean;
|
||||
|
||||
// Lien via table de jointure enfants_parents
|
||||
@OneToMany(() => ParentsChildren, pc => pc.child)
|
||||
parentLinks: ParentsChildren[];
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
import { Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
|
||||
import { Children } from "./children.entity";
|
||||
import { Users } from "./users.entity";
|
||||
import { Parents } from "./parents.entity";
|
||||
|
||||
export enum TypeEvenementType {
|
||||
ABSENCE_ENFANT = 'absence_enfant',
|
||||
CONGE_AM = 'conge_am',
|
||||
CONGE_PARENT = 'conge_parent',
|
||||
ARRET_MALADIE_AM = 'arret_maladie_am',
|
||||
EVENEMENT_RPE = 'evenement_rpe',
|
||||
}
|
||||
|
||||
export enum StatutEvenementType {
|
||||
PROPOSE = 'propose',
|
||||
VALIDE = 'valide',
|
||||
REFUSE = 'refuse',
|
||||
}
|
||||
|
||||
@Entity('evenements')
|
||||
export class Evenement {
|
||||
// Define your columns and relationships here
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: TypeEvenementType,
|
||||
enumName: 'type_evenement_type',
|
||||
name: 'type'
|
||||
})
|
||||
type: TypeEvenementType;
|
||||
|
||||
@ManyToOne(() => Children, { onDelete: 'CASCADE', nullable: true })
|
||||
@JoinColumn({ name: 'id_enfant', referencedColumnName: 'id' })
|
||||
child?: Children;
|
||||
|
||||
@ManyToOne(() => Users, { nullable: true })
|
||||
@JoinColumn({ name: 'id_am', referencedColumnName: 'id' })
|
||||
assistanteMaternelle?: Users;
|
||||
|
||||
@ManyToOne(() => Parents, { nullable: true })
|
||||
@JoinColumn({ name: 'id_parent', referencedColumnName: 'user_id' })
|
||||
parent?: Parents;
|
||||
|
||||
@ManyToOne(() => Users, { nullable: true })
|
||||
@JoinColumn({ name: 'cree_par', referencedColumnName: 'id' })
|
||||
created_by?: Users;
|
||||
|
||||
@Column({ type: 'timestamptz', nullable: true, name: 'date_debut' })
|
||||
start_date?: Date;
|
||||
|
||||
@Column({ type: 'timestamptz', nullable: true, name: 'date_fin' })
|
||||
end_date?: Date;
|
||||
|
||||
@Column({ type: 'text', nullable: true, name: 'commentaires' })
|
||||
comments?: string;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: StatutEvenementType,
|
||||
enumName: 'statut_evenement_type',
|
||||
name: 'statut',
|
||||
default: StatutEvenementType.PROPOSE
|
||||
})
|
||||
status: StatutEvenementType;
|
||||
|
||||
@Column({type: 'timestamptz', nullable: true, name: 'delai_grace'})
|
||||
grace_deadline?: Date;
|
||||
|
||||
@Column({type: 'boolean', default: false, name: 'urgent'})
|
||||
urgent: boolean;
|
||||
|
||||
@CreateDateColumn({ name: 'cree_le', type: 'timestamptz' })
|
||||
created_at: Date;
|
||||
|
||||
@UpdateDateColumn({ name: 'modifie_le', type: 'timestamptz' })
|
||||
updated_at: 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;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
import { Users } from './users.entity';
|
||||
import { ParentsChildren } from './parents_children.entity';
|
||||
import { Dossier } from './dossiers.entity';
|
||||
import { AmChildren } from './am_children.entity';
|
||||
|
||||
@Entity('parents', { schema: 'public' })
|
||||
export class Parents {
|
||||
@@ -25,6 +26,17 @@ export class Parents {
|
||||
@Column({ name: 'numero_dossier', length: 20, nullable: true })
|
||||
numero_dossier?: string;
|
||||
|
||||
/**
|
||||
* Placement AM↔enfant sélectionné sur le TdB parent (couple actif) — ticket #168.
|
||||
* Null / absent = le front prend le premier couple actif retourné par l’API.
|
||||
*/
|
||||
@Column({ name: 'id_placement_garde_courant', type: 'uuid', nullable: true })
|
||||
id_placement_garde_courant?: string;
|
||||
|
||||
@ManyToOne(() => AmChildren, { nullable: true, onDelete: 'SET NULL' })
|
||||
@JoinColumn({ name: 'id_placement_garde_courant', referencedColumnName: 'id' })
|
||||
placement_garde_courant?: AmChildren;
|
||||
|
||||
// Lien vers enfants via la table enfants_parents
|
||||
@OneToMany(() => ParentsChildren, pc => pc.parent)
|
||||
parentChildren: ParentsChildren[];
|
||||
|
||||
@@ -177,6 +177,10 @@ export class Users {
|
||||
@Column({ nullable: true, name: 'numero_dossier', length: 20 })
|
||||
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 })
|
||||
@JoinColumn({ name: 'relais_id' })
|
||||
relais?: Relais;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Headers,
|
||||
MessageEvent,
|
||||
Query,
|
||||
Sse,
|
||||
UnauthorizedException,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ApiBearerAuth,
|
||||
ApiOperation,
|
||||
ApiQuery,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { Observable } from 'rxjs';
|
||||
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 { Public } from 'src/common/decorators/public.decorator';
|
||||
import { User } from 'src/common/decorators/user.decorator';
|
||||
import { RoleType } from 'src/entities/users.entity';
|
||||
import { CardsRealtimeService } from './cards-realtime.service';
|
||||
|
||||
/**
|
||||
* SSE Cartes — #195
|
||||
* Auth : Bearer (recommandé) ou `?access_token=` (EventSource navigateur).
|
||||
*/
|
||||
@ApiTags('Cartes')
|
||||
@Controller('cards')
|
||||
export class CardsRealtimeController {
|
||||
constructor(
|
||||
private readonly realtime: CardsRealtimeService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
@Sse('stream')
|
||||
@Public()
|
||||
@ApiOperation({
|
||||
summary: 'Flux SSE bulles (card.created|updated|deleted, response.added) — #195',
|
||||
})
|
||||
@ApiQuery({
|
||||
name: 'access_token',
|
||||
required: false,
|
||||
description: 'JWT si pas de header Authorization (EventSource)',
|
||||
})
|
||||
@ApiBearerAuth('access-token')
|
||||
async stream(
|
||||
@Headers('authorization') authorization?: string,
|
||||
@Query('access_token') accessToken?: string,
|
||||
): Promise<Observable<MessageEvent>> {
|
||||
const userId = await this.resolveUserId(authorization, accessToken);
|
||||
return this.realtime.streamFor(userId);
|
||||
}
|
||||
|
||||
/** Variante gardée (clients qui envoient Bearer correctement). */
|
||||
@Get('stream/info')
|
||||
@UseGuards(AuthGuard, RolesGuard)
|
||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||
@ApiBearerAuth('access-token')
|
||||
@ApiOperation({ summary: 'Debug : abonnés SSE pour mon user — #195' })
|
||||
info(@User('id') userId: string) {
|
||||
return {
|
||||
user_id: userId,
|
||||
subscribers: this.realtime.subscriberCount(userId),
|
||||
};
|
||||
}
|
||||
|
||||
private async resolveUserId(
|
||||
authorization?: string,
|
||||
accessToken?: string,
|
||||
): Promise<string> {
|
||||
let token = accessToken?.trim();
|
||||
if (!token && authorization?.startsWith('Bearer ')) {
|
||||
token = authorization.slice(7).trim();
|
||||
}
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Token manquant (Bearer ou access_token)');
|
||||
}
|
||||
try {
|
||||
const payload = await this.jwtService.verifyAsync<{ sub: string }>(token, {
|
||||
secret: this.configService.get<string>('jwt.accessSecret'),
|
||||
});
|
||||
if (!payload?.sub) throw new UnauthorizedException('Token invalide');
|
||||
return payload.sub;
|
||||
} catch {
|
||||
throw new UnauthorizedException('Token invalide ou expiré');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { MessageEvent } from '@nestjs/common';
|
||||
import { CardsRealtimeService } from './cards-realtime.service';
|
||||
|
||||
describe('CardsRealtimeService (#195)', () => {
|
||||
let service: CardsRealtimeService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new CardsRealtimeService();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
service.onModuleDestroy();
|
||||
});
|
||||
|
||||
it('émet card.created aux abonnés du user', async () => {
|
||||
const events: MessageEvent[] = [];
|
||||
const sub = service.streamFor('user-a').subscribe((e) => events.push(e));
|
||||
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(events[0]?.type).toBe('heartbeat');
|
||||
expect(service.subscriberCount('user-a')).toBe(1);
|
||||
|
||||
service.emitToUsers(['user-a', 'user-b'], 'card.created', 'card-1', {
|
||||
id: 'card-1',
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
|
||||
const created = events.find((e) => e.type === 'card.created');
|
||||
expect(created).toBeDefined();
|
||||
expect((created!.data as { card_id: string }).card_id).toBe('card-1');
|
||||
expect(service.subscriberCount('user-b')).toBe(0);
|
||||
|
||||
sub.unsubscribe();
|
||||
expect(service.subscriberCount('user-a')).toBe(0);
|
||||
});
|
||||
|
||||
it('ne diffuse pas aux users non abonnés', async () => {
|
||||
const events: MessageEvent[] = [];
|
||||
const sub = service.streamFor('user-a').subscribe((e) => events.push(e));
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
const before = events.length;
|
||||
service.emitToUsers(['user-b'], 'card.updated', 'x');
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(events.length).toBe(before);
|
||||
sub.unsubscribe();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Injectable, MessageEvent, OnModuleDestroy } from '@nestjs/common';
|
||||
import { Observable, Subject, interval, merge, takeUntil } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
export type CardRealtimeEventType =
|
||||
| 'card.created'
|
||||
| 'card.updated'
|
||||
| 'card.deleted'
|
||||
| 'response.added'
|
||||
| 'heartbeat';
|
||||
|
||||
export interface CardRealtimePayload {
|
||||
event: CardRealtimeEventType;
|
||||
card_id?: string;
|
||||
data?: unknown;
|
||||
at: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bus SSE in-memory par utilisateur (V1 mono-instance).
|
||||
* Rooms = userId (audience carte).
|
||||
*/
|
||||
@Injectable()
|
||||
export class CardsRealtimeService implements OnModuleDestroy {
|
||||
private readonly byUser = new Map<string, Set<Subject<CardRealtimePayload>>>();
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
onModuleDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
for (const set of this.byUser.values()) {
|
||||
for (const s of set) s.complete();
|
||||
}
|
||||
this.byUser.clear();
|
||||
}
|
||||
|
||||
/** Flux SSE pour un utilisateur authentifié. */
|
||||
streamFor(userId: string): Observable<MessageEvent> {
|
||||
const subject = new Subject<CardRealtimePayload>();
|
||||
let set = this.byUser.get(userId);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
this.byUser.set(userId, set);
|
||||
}
|
||||
set.add(subject);
|
||||
|
||||
const heartbeat$ = interval(25_000).pipe(
|
||||
map(
|
||||
(): CardRealtimePayload => ({
|
||||
event: 'heartbeat',
|
||||
at: new Date().toISOString(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return new Observable<MessageEvent>((observer) => {
|
||||
const sub = merge(subject, heartbeat$)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe({
|
||||
next: (payload) =>
|
||||
observer.next({
|
||||
type: payload.event,
|
||||
data: payload,
|
||||
} as MessageEvent),
|
||||
error: (err) => observer.error(err),
|
||||
complete: () => observer.complete(),
|
||||
});
|
||||
|
||||
// ping initial
|
||||
subject.next({
|
||||
event: 'heartbeat',
|
||||
at: new Date().toISOString(),
|
||||
});
|
||||
|
||||
return () => {
|
||||
sub.unsubscribe();
|
||||
set!.delete(subject);
|
||||
subject.complete();
|
||||
if (set!.size === 0) this.byUser.delete(userId);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
emitToUsers(
|
||||
userIds: string[],
|
||||
event: Exclude<CardRealtimeEventType, 'heartbeat'>,
|
||||
cardId: string | undefined,
|
||||
data?: unknown,
|
||||
): void {
|
||||
const unique = [...new Set(userIds.filter(Boolean))];
|
||||
const payload: CardRealtimePayload = {
|
||||
event,
|
||||
card_id: cardId,
|
||||
data,
|
||||
at: new Date().toISOString(),
|
||||
};
|
||||
for (const uid of unique) {
|
||||
const set = this.byUser.get(uid);
|
||||
if (!set) continue;
|
||||
for (const s of set) s.next(payload);
|
||||
}
|
||||
}
|
||||
|
||||
/** Test / debug : nombre d’abonnés actifs. */
|
||||
subscriberCount(userId?: string): number {
|
||||
if (userId) return this.byUser.get(userId)?.size ?? 0;
|
||||
let n = 0;
|
||||
for (const s of this.byUser.values()) n += s.size;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
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 { RoleType } from 'src/entities/users.entity';
|
||||
import { CardsService } from './cards.service';
|
||||
import {
|
||||
CarteDto,
|
||||
CreerCarteDto,
|
||||
ListeCartesDto,
|
||||
MajCarteDto,
|
||||
RepondreCarteDto,
|
||||
} from './dto/cards.dto';
|
||||
|
||||
@ApiTags('Cartes')
|
||||
@ApiBearerAuth('access-token')
|
||||
@Controller('cards')
|
||||
@UseGuards(AuthGuard, RolesGuard)
|
||||
export class CardsController {
|
||||
constructor(private readonly cardsService: CardsService) {}
|
||||
|
||||
@Get('types')
|
||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||
@ApiOperation({ summary: 'Types SYSTEM émissibles pour mon rôle — #194' })
|
||||
listerTypes(@User('role') role: RoleType) {
|
||||
return this.cardsService.listerTypes(role);
|
||||
}
|
||||
|
||||
@Get()
|
||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||
@ApiOperation({ summary: 'Feed bulles de l’utilisateur — #194' })
|
||||
@ApiQuery({ name: 'placementId', required: false })
|
||||
@ApiResponse({ status: 200, type: ListeCartesDto })
|
||||
lister(
|
||||
@User('id') userId: string,
|
||||
@User('role') role: RoleType,
|
||||
@Query('placementId') placementId?: string,
|
||||
): Promise<ListeCartesDto> {
|
||||
return this.cardsService.lister(userId, role, placementId);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
@ApiOperation({
|
||||
summary: 'Créer une bulle (+ hook evenements_agenda) — #194',
|
||||
})
|
||||
@ApiBody({ type: CreerCarteDto })
|
||||
@ApiResponse({ status: 201, type: CarteDto })
|
||||
creer(
|
||||
@User('id') userId: string,
|
||||
@User('role') role: RoleType,
|
||||
@Body() dto: CreerCarteDto,
|
||||
): Promise<CarteDto> {
|
||||
return this.cardsService.creer(userId, role, dto);
|
||||
}
|
||||
|
||||
@Post(':id/respond')
|
||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'Répondre (accept / refuse / ack) — #194' })
|
||||
@ApiBody({ type: RepondreCarteDto })
|
||||
repondre(
|
||||
@User('id') userId: string,
|
||||
@User('role') role: RoleType,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body() dto: RepondreCarteDto,
|
||||
): Promise<CarteDto> {
|
||||
return this.cardsService.repondre(userId, role, id, dto);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||
@ApiOperation({
|
||||
summary: 'Modifier dates (créateur, ouverte/refusée) — #194',
|
||||
})
|
||||
@ApiBody({ type: MajCarteDto })
|
||||
maj(
|
||||
@User('id') userId: string,
|
||||
@User('role') role: RoleType,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body() dto: MajCarteDto,
|
||||
): Promise<CarteDto> {
|
||||
return this.cardsService.majEnAttente(userId, role, id, dto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@Roles(RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE)
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
@ApiOperation({ summary: 'Supprimer bulle (+ absence si non traitée) — #194' })
|
||||
async supprimer(
|
||||
@User('id') userId: string,
|
||||
@User('role') role: RoleType,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
): Promise<void> {
|
||||
await this.cardsService.supprimer(userId, role, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { EvenementsAgendaModule } from '../evenements-agenda';
|
||||
import { CardType } from 'src/entities/card_types.entity';
|
||||
import { CardInstance } from 'src/entities/card_instances.entity';
|
||||
import { CardAudienceMember } from 'src/entities/card_audience_members.entity';
|
||||
import { CardResponse } from 'src/entities/card_responses.entity';
|
||||
import { AmChildren } from 'src/entities/am_children.entity';
|
||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||
import { CardsController } from './cards.controller';
|
||||
import { CardsRealtimeController } from './cards-realtime.controller';
|
||||
import { CardsService } from './cards.service';
|
||||
import { CardsRealtimeService } from './cards-realtime.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
EvenementsAgendaModule,
|
||||
TypeOrmModule.forFeature([
|
||||
CardType,
|
||||
CardInstance,
|
||||
CardAudienceMember,
|
||||
CardResponse,
|
||||
AmChildren,
|
||||
ParentsChildren,
|
||||
]),
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
secret: config.get('jwt.accessSecret'),
|
||||
signOptions: { expiresIn: config.get('jwt.accessExpiresIn') },
|
||||
}),
|
||||
inject: [ConfigService],
|
||||
}),
|
||||
],
|
||||
controllers: [CardsController, CardsRealtimeController],
|
||||
providers: [CardsService, CardsRealtimeService],
|
||||
exports: [CardsService, CardsRealtimeService],
|
||||
})
|
||||
export class CardsModule {}
|
||||
@@ -0,0 +1,452 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||
import { ForbiddenException } from '@nestjs/common';
|
||||
import { CardsService } from './cards.service';
|
||||
import { CardsRealtimeService } from './cards-realtime.service';
|
||||
import { EvenementsAgendaService } from '../evenements-agenda/evenements-agenda.service';
|
||||
import { CardType, CardResponseModeType } from 'src/entities/card_types.entity';
|
||||
import {
|
||||
CardInstance,
|
||||
CardInstanceStatutType,
|
||||
CardOperationType,
|
||||
} from 'src/entities/card_instances.entity';
|
||||
import { CardAudienceMember } from 'src/entities/card_audience_members.entity';
|
||||
import { CardResponse } from 'src/entities/card_responses.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 { StatutEvenementAgendaType, TypeEvenementAgendaType } from 'src/entities/evenements_agenda.entity';
|
||||
|
||||
describe('CardsService (#194)', () => {
|
||||
let service: CardsService;
|
||||
|
||||
const typesRepo = { find: jest.fn(), findOne: jest.fn() };
|
||||
const cardsRepo = {
|
||||
create: jest.fn((x) => x),
|
||||
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(),
|
||||
delete: jest.fn(),
|
||||
createQueryBuilder: jest.fn(),
|
||||
manager: { query: jest.fn() },
|
||||
};
|
||||
const audienceRepo = {
|
||||
create: jest.fn((x) => x),
|
||||
save: jest.fn(),
|
||||
findOne: jest.fn(),
|
||||
find: jest.fn(),
|
||||
};
|
||||
const responsesRepo = {
|
||||
create: jest.fn((x) => x),
|
||||
save: jest.fn(async (x) => x),
|
||||
insert: jest.fn(),
|
||||
};
|
||||
const amChildrenRepo = { findOne: jest.fn() };
|
||||
const parentsChildrenRepo = { find: jest.fn(), findOne: jest.fn() };
|
||||
const evenementsService = {
|
||||
creer: jest.fn(),
|
||||
maj: jest.fn(),
|
||||
supprimer: jest.fn(),
|
||||
};
|
||||
const realtime = { emitToUsers: jest.fn() };
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
CardsService,
|
||||
{ provide: getRepositoryToken(CardType), useValue: typesRepo },
|
||||
{ provide: getRepositoryToken(CardInstance), useValue: cardsRepo },
|
||||
{ provide: getRepositoryToken(CardAudienceMember), useValue: audienceRepo },
|
||||
{ provide: getRepositoryToken(CardResponse), useValue: responsesRepo },
|
||||
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo },
|
||||
{ provide: getRepositoryToken(ParentsChildren), useValue: parentsChildrenRepo },
|
||||
{ provide: EvenementsAgendaService, useValue: evenementsService },
|
||||
{ provide: CardsRealtimeService, useValue: realtime },
|
||||
],
|
||||
}).compile();
|
||||
service = module.get(CardsService);
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
it('AM crée congé → absence + carte ouverte + audience parents', async () => {
|
||||
typesRepo.findOne.mockResolvedValue({
|
||||
code: 'conge_am',
|
||||
system: true,
|
||||
titre: 'Congé AM',
|
||||
emitter_roles: [RoleType.ASSISTANTE_MATERNELLE],
|
||||
recipient_roles: [RoleType.PARENT],
|
||||
audience_resolver: 'couple_parents',
|
||||
response_mode: CardResponseModeType.ACCEPT_REFUSE,
|
||||
retention_days: 14,
|
||||
});
|
||||
amChildrenRepo.findOne.mockResolvedValue({
|
||||
id: 'pl-1',
|
||||
amId: 'am-1',
|
||||
enfantId: 'e-1',
|
||||
date_fin: null,
|
||||
});
|
||||
evenementsService.creer.mockResolvedValue({
|
||||
id: 'abs-1',
|
||||
type: TypeEvenementAgendaType.CONGE_AM,
|
||||
statut: StatutEvenementAgendaType.EN_ATTENTE,
|
||||
});
|
||||
parentsChildrenRepo.find.mockResolvedValue([
|
||||
{ parentId: 'p-1', enfantId: 'e-1' },
|
||||
{ parentId: 'p-2', enfantId: 'e-1' },
|
||||
]);
|
||||
cardsRepo.findOne.mockResolvedValue({
|
||||
id: 'card-1',
|
||||
type_code: 'conge_am',
|
||||
id_placement: 'pl-1',
|
||||
id_evenement: 'abs-1',
|
||||
cree_par: 'am-1',
|
||||
operation: CardOperationType.CREATE,
|
||||
statut: CardInstanceStatutType.OUVERTE,
|
||||
payload: { date_debut: '2026-11-01', date_fin: '2026-11-07' },
|
||||
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' },
|
||||
],
|
||||
});
|
||||
|
||||
const res = await service.creer('am-1', RoleType.ASSISTANTE_MATERNELLE, {
|
||||
type_code: 'conge_am',
|
||||
id_placement: 'pl-1',
|
||||
date_debut: '2026-11-01',
|
||||
date_fin: '2026-11-07',
|
||||
});
|
||||
|
||||
expect(evenementsService.creer).toHaveBeenCalled();
|
||||
expect(audienceRepo.save).toHaveBeenCalled();
|
||||
expect(realtime.emitToUsers).toHaveBeenCalledWith(
|
||||
['am-1', 'p-1', 'p-2'],
|
||||
'card.created',
|
||||
'card-1',
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(res.type_code).toBe('conge_am');
|
||||
expect(res.statut).toBe(CardInstanceStatutType.OUVERTE);
|
||||
});
|
||||
|
||||
it('parent ne peut pas émettre conge_am', async () => {
|
||||
typesRepo.findOne.mockResolvedValue({
|
||||
code: 'conge_am',
|
||||
system: true,
|
||||
emitter_roles: [RoleType.ASSISTANTE_MATERNELLE],
|
||||
});
|
||||
await expect(
|
||||
service.creer('p-1', RoleType.PARENT, {
|
||||
type_code: 'conge_am',
|
||||
id_placement: 'pl-1',
|
||||
date_debut: '2026-11-01',
|
||||
date_fin: '2026-11-07',
|
||||
}),
|
||||
).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),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,665 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { IsNull, Repository } from 'typeorm';
|
||||
import { EvenementsAgendaService } from '../evenements-agenda/evenements-agenda.service';
|
||||
import {
|
||||
StatutEvenementAgendaType,
|
||||
TypeEvenementAgendaType,
|
||||
} from 'src/entities/evenements_agenda.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 { CardType, CardResponseModeType } from 'src/entities/card_types.entity';
|
||||
import {
|
||||
CardInstance,
|
||||
CardInstanceStatutType,
|
||||
CardOperationType,
|
||||
} from 'src/entities/card_instances.entity';
|
||||
import { CardAudienceMember } from 'src/entities/card_audience_members.entity';
|
||||
import {
|
||||
CardResponse,
|
||||
CardResponseActionType,
|
||||
} from 'src/entities/card_responses.entity';
|
||||
import {
|
||||
CarteDto,
|
||||
CreerCarteDto,
|
||||
ListeCartesDto,
|
||||
MajCarteDto,
|
||||
RepondreCarteDto,
|
||||
} from './dto/cards.dto';
|
||||
import { CardsRealtimeService } from './cards-realtime.service';
|
||||
|
||||
@Injectable()
|
||||
export class CardsService {
|
||||
constructor(
|
||||
@InjectRepository(CardType)
|
||||
private readonly typesRepo: Repository<CardType>,
|
||||
@InjectRepository(CardInstance)
|
||||
private readonly cardsRepo: Repository<CardInstance>,
|
||||
@InjectRepository(CardAudienceMember)
|
||||
private readonly audienceRepo: Repository<CardAudienceMember>,
|
||||
@InjectRepository(CardResponse)
|
||||
private readonly responsesRepo: Repository<CardResponse>,
|
||||
@InjectRepository(AmChildren)
|
||||
private readonly amChildrenRepo: Repository<AmChildren>,
|
||||
@InjectRepository(ParentsChildren)
|
||||
private readonly parentsChildrenRepo: Repository<ParentsChildren>,
|
||||
private readonly evenementsService: EvenementsAgendaService,
|
||||
private readonly realtime: CardsRealtimeService,
|
||||
) {}
|
||||
|
||||
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 } });
|
||||
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(
|
||||
userId: string,
|
||||
role: RoleType,
|
||||
placementId?: string,
|
||||
): Promise<ListeCartesDto> {
|
||||
const qb = this.cardsRepo
|
||||
.createQueryBuilder('c')
|
||||
.innerJoin('c.audience', 'aud', 'aud.id_utilisateur = :userId', { userId })
|
||||
.leftJoinAndSelect('c.type', 'type')
|
||||
.leftJoinAndSelect('c.responses', 'responses')
|
||||
.where('c.purge_at > now()')
|
||||
.andWhere('c.statut != :annulee', {
|
||||
annulee: CardInstanceStatutType.ANNULEE,
|
||||
})
|
||||
// Tri fil : COALESCE(remonte_le, cree_le) DESC (mini-spec §10)
|
||||
.orderBy('COALESCE(c.remonte_le, c.cree_le)', 'DESC');
|
||||
|
||||
if (placementId) {
|
||||
await this.assertPlacementAccess(userId, role, placementId);
|
||||
qb.andWhere('c.id_placement = :placementId', { placementId });
|
||||
}
|
||||
|
||||
const rows = await qb.getMany();
|
||||
return {
|
||||
items: rows.map((c) => this.toDto(c, userId)),
|
||||
};
|
||||
}
|
||||
|
||||
async creer(
|
||||
userId: string,
|
||||
role: RoleType,
|
||||
dto: CreerCarteDto,
|
||||
): Promise<CarteDto> {
|
||||
if (dto.date_fin < dto.date_debut) {
|
||||
throw new BadRequestException('date_fin < date_debut');
|
||||
}
|
||||
|
||||
const type = await this.typesRepo.findOne({ where: { code: dto.type_code } });
|
||||
if (!type || !type.system) {
|
||||
throw new NotFoundException('Type de carte inconnu');
|
||||
}
|
||||
if (!type.emitter_roles.includes(role)) {
|
||||
throw new ForbiddenException('Vous ne pouvez pas émettre ce type de carte');
|
||||
}
|
||||
|
||||
const placement = await this.assertPlacementAccess(
|
||||
userId,
|
||||
role,
|
||||
dto.id_placement,
|
||||
);
|
||||
const operation = dto.operation ?? CardOperationType.CREATE;
|
||||
|
||||
let absenceId = dto.id_evenement;
|
||||
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) {
|
||||
const absence = await this.evenementsService.creer(userId, role, {
|
||||
id_placement: dto.id_placement,
|
||||
type: absenceType,
|
||||
date_debut: dto.date_debut,
|
||||
date_fin: dto.date_fin,
|
||||
motif: motif ? String(motif) : undefined,
|
||||
});
|
||||
absenceId = absence.id;
|
||||
} else {
|
||||
if (dto.type_code === 'soin_enfant') {
|
||||
throw new BadRequestException('operation=update interdite pour soin_enfant');
|
||||
}
|
||||
if (!absenceId) {
|
||||
throw new BadRequestException('id_evenement requis pour operation=update');
|
||||
}
|
||||
await this.evenementsService.maj(userId, role, absenceId, {
|
||||
date_debut: dto.date_debut,
|
||||
date_fin: dto.date_fin,
|
||||
motif: motif ? String(motif) : undefined,
|
||||
// Congé accepté modifié → repasse en attente via cartes respond flow;
|
||||
// pour absence enfant update immédiat déjà fait.
|
||||
...(dto.type_code === 'conge_am'
|
||||
? { statut: StatutEvenementAgendaType.EN_ATTENTE }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
const statutInitial =
|
||||
type.response_mode === CardResponseModeType.NONE
|
||||
? CardInstanceStatutType.TRAITEE
|
||||
: CardInstanceStatutType.OUVERTE;
|
||||
|
||||
const card = this.cardsRepo.create({
|
||||
type_code: type.code,
|
||||
id_placement: dto.id_placement,
|
||||
id_evenement: absenceId,
|
||||
cree_par: userId,
|
||||
operation,
|
||||
statut: statutInitial,
|
||||
payload: finalPayload,
|
||||
purge_at: this.purgeAt(type.retention_days, statutInitial),
|
||||
});
|
||||
const saved = await this.cardsRepo.save(card);
|
||||
|
||||
if (absenceId) {
|
||||
await this.linkAbsenceCard(absenceId, saved.id);
|
||||
}
|
||||
|
||||
await this.buildAudience(saved, type, placement, userId, role);
|
||||
|
||||
const full = await this.loadCard(saved.id);
|
||||
const dtoOut = this.toDto(full, userId);
|
||||
this.emitAudience(full, 'card.created', dtoOut);
|
||||
return dtoOut;
|
||||
}
|
||||
|
||||
async repondre(
|
||||
userId: string,
|
||||
role: RoleType,
|
||||
cardId: string,
|
||||
dto: RepondreCarteDto,
|
||||
): Promise<CarteDto> {
|
||||
const card = await this.loadCard(cardId);
|
||||
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) {
|
||||
throw new BadRequestException('Cette carte n’est plus ouverte');
|
||||
}
|
||||
if (card.cree_par === userId) {
|
||||
throw new ForbiddenException('Le créateur ne répond pas à sa propre carte');
|
||||
}
|
||||
|
||||
const mode = card.type.response_mode;
|
||||
if (mode === CardResponseModeType.NONE) {
|
||||
throw new BadRequestException('Ce type de carte ne demande pas de réponse');
|
||||
}
|
||||
if (mode === CardResponseModeType.ACK && dto.action !== CardResponseActionType.ACK) {
|
||||
throw new BadRequestException('Action attendue : ack');
|
||||
}
|
||||
if (
|
||||
mode === CardResponseModeType.ACCEPT_REFUSE &&
|
||||
dto.action !== CardResponseActionType.ACCEPT &&
|
||||
dto.action !== CardResponseActionType.REFUSE
|
||||
) {
|
||||
throw new BadRequestException('Action attendue : accept ou refuse');
|
||||
}
|
||||
if (dto.action === CardResponseActionType.REFUSE && !dto.comment?.trim()) {
|
||||
throw new BadRequestException('Motivation obligatoire en cas de refus');
|
||||
}
|
||||
|
||||
await this.responsesRepo.save(
|
||||
this.responsesRepo.create({
|
||||
card: { id: card.id },
|
||||
user: { id: userId },
|
||||
action: dto.action,
|
||||
comment: dto.comment?.trim() || undefined,
|
||||
}),
|
||||
);
|
||||
|
||||
// ACK informatif (arrêt / soin) : n’écrit plus sur l’événement (#216)
|
||||
if (dto.action === CardResponseActionType.ACK) {
|
||||
card.statut = CardInstanceStatutType.TRAITEE;
|
||||
} 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;
|
||||
} else if (dto.action === CardResponseActionType.REFUSE) {
|
||||
await this.evenementsService.maj(userId, role, card.id_evenement, {
|
||||
statut: StatutEvenementAgendaType.REFUSE,
|
||||
motif: dto.comment!.trim(),
|
||||
});
|
||||
card.statut = CardInstanceStatutType.REFUSEE;
|
||||
}
|
||||
}
|
||||
|
||||
card.purge_at = this.purgeAt(card.type.retention_days, card.statut);
|
||||
// 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 dtoOut = this.toDto(full, userId);
|
||||
this.emitAudience(full, 'response.added', {
|
||||
action: dto.action,
|
||||
card: dtoOut,
|
||||
});
|
||||
this.emitAudience(full, 'card.updated', dtoOut);
|
||||
return dtoOut;
|
||||
}
|
||||
|
||||
async majEnAttente(
|
||||
userId: string,
|
||||
role: RoleType,
|
||||
cardId: string,
|
||||
dto: MajCarteDto,
|
||||
): Promise<CarteDto> {
|
||||
const card = await this.loadCard(cardId);
|
||||
if (card.cree_par !== userId) {
|
||||
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 (
|
||||
card.statut !== CardInstanceStatutType.OUVERTE &&
|
||||
card.statut !== CardInstanceStatutType.REFUSEE
|
||||
) {
|
||||
throw new BadRequestException('Carte non modifiable dans cet état');
|
||||
}
|
||||
}
|
||||
|
||||
const debut =
|
||||
dto.date_debut ?? String(card.payload?.['date_debut'] ?? '');
|
||||
const fin = dto.date_fin ?? String(card.payload?.['date_fin'] ?? '');
|
||||
if (!debut || !fin || fin < debut) {
|
||||
throw new BadRequestException('Dates invalides');
|
||||
}
|
||||
|
||||
let motif = dto.motif ?? card.payload?.['motif'] ?? null;
|
||||
let finalPayload: Record<string, any> = {
|
||||
...card.payload,
|
||||
date_debut: debut,
|
||||
date_fin: fin,
|
||||
...(dto.payload ?? {}),
|
||||
};
|
||||
|
||||
if (card.type_code === 'soin_enfant') {
|
||||
const p = finalPayload;
|
||||
if (!p || !p?.sous_type || !p?.heure_releve) {
|
||||
throw new BadRequestException('sous_type et heure_releve requis pour soin_enfant');
|
||||
}
|
||||
if (!/^([01]\d|2[0-3]):([0-5]\d)$/.test(p?.heure_releve)) {
|
||||
throw new BadRequestException('Format heure_releve invalide (HH:mm)');
|
||||
}
|
||||
|
||||
if (p?.sous_type === 'fievre') {
|
||||
if (typeof p?.temperature_c !== 'number' || p?.temperature_c < 34.0 || p?.temperature_c > 43.0) {
|
||||
throw new BadRequestException('temperature_c invalide (34.0 - 43.0)');
|
||||
}
|
||||
motif = `${p?.temperature_c.toFixed(1).replace('.', ',')} °C à ${p?.heure_releve}`;
|
||||
if (p?.medicament_donne && typeof p?.medicament_donne === 'string' && p?.medicament_donne.trim()) {
|
||||
motif += ` (Médicament : ${p?.medicament_donne.trim()})`;
|
||||
}
|
||||
} else if (p?.sous_type === 'bobo') {
|
||||
const natures = ['chute', 'coup', 'egratignure', 'piqure', 'brulure', 'autre'];
|
||||
if (!natures.includes(p?.bobo_nature)) {
|
||||
throw new BadRequestException('bobo_nature invalide');
|
||||
}
|
||||
motif = `Bobo (${p?.bobo_nature}) à ${p?.heure_releve}`;
|
||||
if (p?.description && typeof p?.description === 'string' && p?.description.trim()) {
|
||||
const desc = p?.description.trim();
|
||||
if (desc.length > 120) throw new BadRequestException('description trop longue (max 120)');
|
||||
motif += ` : ${desc.length > 30 ? desc.substring(0, 30) + '...' : desc}`;
|
||||
}
|
||||
} else if (p?.sous_type === 'medicament') {
|
||||
if (!p?.medicament_nom || typeof p?.medicament_nom !== 'string' || !p?.medicament_nom.trim()) {
|
||||
throw new BadRequestException('medicament_nom requis');
|
||||
}
|
||||
motif = `Médicament (${p?.medicament_nom.trim()}) à ${p?.heure_releve}`;
|
||||
if (p?.contexte && typeof p?.contexte === 'string' && p?.contexte.trim()) {
|
||||
if (p?.contexte.trim().length > 120) throw new BadRequestException('contexte trop long (max 120)');
|
||||
}
|
||||
} else {
|
||||
throw new BadRequestException('sous_type invalide pour soin_enfant');
|
||||
}
|
||||
finalPayload.motif = motif;
|
||||
|
||||
const hist = Array.isArray(card.payload?.['historique']) ? card.payload['historique'] : [];
|
||||
const oldPayload = { ...card.payload };
|
||||
delete oldPayload.historique;
|
||||
hist.push({
|
||||
...oldPayload,
|
||||
corrige_le: new Date().toISOString(),
|
||||
corrige_par: userId,
|
||||
});
|
||||
finalPayload.historique = hist;
|
||||
finalPayload.corrige_le = new Date().toISOString();
|
||||
} else {
|
||||
finalPayload.motif = motif;
|
||||
}
|
||||
|
||||
if (card.id_evenement) {
|
||||
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.purge_at = this.purgeAt(card.type.retention_days, card.statut);
|
||||
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 dtoOut = this.toDto(full, userId);
|
||||
this.emitAudience(full, 'card.updated', dtoOut);
|
||||
return dtoOut;
|
||||
}
|
||||
|
||||
async supprimer(
|
||||
userId: string,
|
||||
role: RoleType,
|
||||
cardId: string,
|
||||
): Promise<void> {
|
||||
const card = await this.loadCard(cardId);
|
||||
if (card.cree_par !== userId) {
|
||||
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);
|
||||
// Soft-cancel événement lié (matrice temporelle côté evenements) — #216
|
||||
if (card.id_evenement) {
|
||||
await this.evenementsService.supprimer(userId, role, card.id_evenement);
|
||||
}
|
||||
// Soft-cancel carte — aucun DELETE physique applicatif (#216)
|
||||
const now = new Date();
|
||||
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, {
|
||||
id: cardId,
|
||||
});
|
||||
}
|
||||
|
||||
private emitAudience(
|
||||
card: CardInstance,
|
||||
event: 'card.created' | 'card.updated' | 'response.added',
|
||||
data: unknown,
|
||||
): void {
|
||||
const ids = (card.audience ?? []).map((a) => a.id_utilisateur);
|
||||
if (ids.length === 0) return;
|
||||
this.realtime.emitToUsers(ids, event, card.id, data);
|
||||
}
|
||||
|
||||
private async audienceUserIds(card: CardInstance): Promise<string[]> {
|
||||
if (card.audience?.length) {
|
||||
return card.audience.map((a) => a.id_utilisateur);
|
||||
}
|
||||
const rows = await this.audienceRepo.find({ where: { id_card: card.id } });
|
||||
return rows.map((r) => r.id_utilisateur);
|
||||
}
|
||||
|
||||
private mapAbsenceType(typeCode: string): TypeEvenementAgendaType {
|
||||
if (typeCode === 'absence_enfant' || typeCode === 'absence_enfant_modif') {
|
||||
return TypeEvenementAgendaType.ABSENCE_ENFANT;
|
||||
}
|
||||
if (typeCode === 'conge_am') return TypeEvenementAgendaType.CONGE_AM;
|
||||
if (typeCode === '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}`);
|
||||
}
|
||||
|
||||
private async linkAbsenceCard(absenceId: string, cardId: string): Promise<void> {
|
||||
// Update direct pour éviter droits maj vides
|
||||
await this.cardsRepo.manager.query(
|
||||
`UPDATE evenements_agenda SET id_card_instance = $1, modifie_le = now() WHERE id = $2`,
|
||||
[cardId, absenceId],
|
||||
);
|
||||
}
|
||||
|
||||
private async buildAudience(
|
||||
card: CardInstance,
|
||||
type: CardType,
|
||||
placement: AmChildren,
|
||||
creatorId: string,
|
||||
creatorRole: RoleType,
|
||||
): Promise<void> {
|
||||
const members: Partial<CardAudienceMember>[] = [
|
||||
{
|
||||
id_card: card.id,
|
||||
id_utilisateur: creatorId,
|
||||
role_snapshot: creatorRole,
|
||||
is_creator: true,
|
||||
},
|
||||
];
|
||||
|
||||
if (type.audience_resolver === 'couple_am') {
|
||||
// Destinataire métier = AM + miroir foyer : tous les co-parents de l’enfant
|
||||
members.push({
|
||||
id_card: card.id,
|
||||
id_utilisateur: placement.amId,
|
||||
role_snapshot: RoleType.ASSISTANTE_MATERNELLE,
|
||||
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') {
|
||||
const liens = await this.parentsChildrenRepo.find({
|
||||
where: { enfantId: placement.enfantId },
|
||||
});
|
||||
for (const l of liens) {
|
||||
if (l.parentId === creatorId) continue;
|
||||
members.push({
|
||||
id_card: card.id,
|
||||
id_utilisateur: l.parentId,
|
||||
role_snapshot: RoleType.PARENT,
|
||||
is_creator: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// dédup
|
||||
const seen = new Set<string>();
|
||||
const unique = members.filter((m) => {
|
||||
const k = m.id_utilisateur!;
|
||||
if (seen.has(k)) return false;
|
||||
seen.add(k);
|
||||
return true;
|
||||
});
|
||||
await this.audienceRepo.save(this.audienceRepo.create(unique));
|
||||
}
|
||||
|
||||
private purgeAt(
|
||||
retentionDays: number,
|
||||
statut: CardInstanceStatutType,
|
||||
): Date {
|
||||
const days =
|
||||
statut === CardInstanceStatutType.OUVERTE
|
||||
? Math.max(retentionDays, 15)
|
||||
: retentionDays;
|
||||
return new Date(Date.now() + days * 24 * 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
private async loadCard(id: string): Promise<CardInstance> {
|
||||
const card = await this.cardsRepo.findOne({
|
||||
where: { id },
|
||||
relations: ['type', 'responses', 'audience'],
|
||||
});
|
||||
if (!card) throw new NotFoundException('Carte introuvable');
|
||||
return card;
|
||||
}
|
||||
|
||||
private async assertInAudience(card: CardInstance, userId: string): Promise<void> {
|
||||
const ok = (card.audience ?? []).some((a) => a.id_utilisateur === userId);
|
||||
if (!ok) {
|
||||
const row = await this.audienceRepo.findOne({
|
||||
where: { id_card: card.id, id_utilisateur: userId },
|
||||
});
|
||||
if (!row) throw new ForbiddenException('Carte hors de votre audience');
|
||||
}
|
||||
}
|
||||
|
||||
private async assertPlacementAccess(
|
||||
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 introuvable ou inactif');
|
||||
}
|
||||
if (role === RoleType.ASSISTANTE_MATERNELLE) {
|
||||
if (placement.amId !== userId) {
|
||||
throw new ForbiddenException('Placement non autorisé');
|
||||
}
|
||||
return placement;
|
||||
}
|
||||
if (role === RoleType.PARENT) {
|
||||
const lien = await this.parentsChildrenRepo.findOne({
|
||||
where: { parentId: userId, enfantId: placement.enfantId },
|
||||
});
|
||||
if (!lien) throw new ForbiddenException('Placement non autorisé');
|
||||
return placement;
|
||||
}
|
||||
throw new ForbiddenException('Rôle non autorisé');
|
||||
}
|
||||
|
||||
private toDto(card: CardInstance, userId: string): CarteDto {
|
||||
const lastRefuse = [...(card.responses ?? [])]
|
||||
.reverse()
|
||||
.find((r) => r.action === CardResponseActionType.REFUSE);
|
||||
return {
|
||||
id: card.id,
|
||||
type_code: card.type_code,
|
||||
titre: card.type?.titre ?? card.type_code,
|
||||
id_placement: card.id_placement,
|
||||
id_evenement: card.id_evenement ?? null,
|
||||
operation: card.operation,
|
||||
statut: card.statut,
|
||||
payload: card.payload ?? {},
|
||||
purge_at: card.purge_at?.toISOString?.() ?? String(card.purge_at),
|
||||
cree_par: card.cree_par ?? null,
|
||||
is_creator: card.cree_par === userId,
|
||||
response_mode: card.type?.response_mode,
|
||||
last_refuse_comment: lastRefuse?.comment ?? null,
|
||||
cree_le: card.cree_le?.toISOString?.() ?? String(card.cree_le),
|
||||
modifie_le: card.modifie_le?.toISOString?.() ?? String(card.modifie_le),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import {
|
||||
IsDateString,
|
||||
IsEnum,
|
||||
IsOptional,
|
||||
IsObject,
|
||||
IsString,
|
||||
IsUUID,
|
||||
MaxLength,
|
||||
MinLength,
|
||||
ValidateIf,
|
||||
} from 'class-validator';
|
||||
import { CardInstanceStatutType, CardOperationType } from 'src/entities/card_instances.entity';
|
||||
import { CardResponseActionType } from 'src/entities/card_responses.entity';
|
||||
|
||||
export class CreerCarteDto {
|
||||
@ApiProperty({
|
||||
description: 'absence_enfant | absence_enfant_modif | conge_am | arret_maladie_am',
|
||||
})
|
||||
@IsString()
|
||||
type_code: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsUUID()
|
||||
id_placement: string;
|
||||
|
||||
@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;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Requis pour operation=update (même id evenements_agenda)',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
id_evenement?: string;
|
||||
|
||||
@ApiPropertyOptional({ enum: CardOperationType, default: CardOperationType.CREATE })
|
||||
@IsOptional()
|
||||
@IsEnum(CardOperationType)
|
||||
operation?: CardOperationType;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
payload?: Record<string, any>;
|
||||
}
|
||||
|
||||
export class RepondreCarteDto {
|
||||
@ApiProperty({ enum: CardResponseActionType })
|
||||
@IsEnum(CardResponseActionType)
|
||||
action: CardResponseActionType;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Obligatoire si action=refuse' })
|
||||
@ValidateIf((o) => o.action === CardResponseActionType.REFUSE)
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
@MaxLength(2000)
|
||||
comment?: string;
|
||||
}
|
||||
|
||||
export class MajCarteDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
date_debut?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
date_fin?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(2000)
|
||||
motif?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
payload?: Record<string, any>;
|
||||
}
|
||||
|
||||
export class CarteDto {
|
||||
@ApiProperty()
|
||||
id: string;
|
||||
|
||||
@ApiProperty()
|
||||
type_code: string;
|
||||
|
||||
@ApiProperty()
|
||||
titre: string;
|
||||
|
||||
@ApiProperty()
|
||||
id_placement: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
id_evenement?: string | null;
|
||||
|
||||
@ApiProperty({ enum: CardOperationType })
|
||||
operation: CardOperationType;
|
||||
|
||||
@ApiProperty({ enum: CardInstanceStatutType })
|
||||
statut: CardInstanceStatutType;
|
||||
|
||||
@ApiProperty()
|
||||
payload: Record<string, unknown>;
|
||||
|
||||
@ApiProperty()
|
||||
purge_at: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
cree_par?: string | null;
|
||||
|
||||
@ApiProperty()
|
||||
is_creator: boolean;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
response_mode?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
last_refuse_comment?: string | null;
|
||||
|
||||
@ApiProperty()
|
||||
cree_le: string;
|
||||
|
||||
@ApiProperty()
|
||||
modifie_le: string;
|
||||
}
|
||||
|
||||
export class ListeCartesDto {
|
||||
@ApiProperty({ type: [CarteDto] })
|
||||
items: CarteDto[];
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export { CardsModule } from './cards.module';
|
||||
export { CardsService } from './cards.service';
|
||||
export { CardsRealtimeService } from './cards-realtime.service';
|
||||
@@ -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[];
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { EvenementsAgendaController } from './evenements-agenda.controller';
|
||||
import { EvenementsAgendaService } from './evenements-agenda.service';
|
||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||
import { RoleType } from 'src/entities/users.entity';
|
||||
import { TypeEvenementAgendaType } from 'src/entities/evenements_agenda.entity';
|
||||
|
||||
describe('EvenementsAgendaController (#172)', () => {
|
||||
let controller: EvenementsAgendaController;
|
||||
const serviceMock = {
|
||||
lister: jest.fn(),
|
||||
getById: jest.fn(),
|
||||
creer: jest.fn(),
|
||||
maj: jest.fn(),
|
||||
supprimer: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [EvenementsAgendaController],
|
||||
providers: [{ provide: EvenementsAgendaService, useValue: serviceMock }],
|
||||
})
|
||||
.overrideGuard(AuthGuard)
|
||||
.useValue({ canActivate: () => true })
|
||||
.overrideGuard(RolesGuard)
|
||||
.useValue({ canActivate: () => true })
|
||||
.compile();
|
||||
|
||||
controller = module.get(EvenementsAgendaController);
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
it('lister délègue au service', async () => {
|
||||
serviceMock.lister.mockResolvedValue({ items: [] });
|
||||
const res = await controller.lister(
|
||||
'u1',
|
||||
RoleType.PARENT,
|
||||
'pl-1',
|
||||
undefined,
|
||||
undefined,
|
||||
'2026-01-01',
|
||||
'2026-12-31',
|
||||
);
|
||||
expect(serviceMock.lister).toHaveBeenCalledWith('u1', RoleType.PARENT, {
|
||||
placementId: 'pl-1',
|
||||
type: undefined,
|
||||
statut: undefined,
|
||||
from: '2026-01-01',
|
||||
to: '2026-12-31',
|
||||
});
|
||||
expect(res.items).toEqual([]);
|
||||
});
|
||||
|
||||
it('creer délègue au service', async () => {
|
||||
serviceMock.creer.mockResolvedValue({ id: 'a1' });
|
||||
const dto = {
|
||||
id_placement: 'pl-1',
|
||||
type: TypeEvenementAgendaType.ABSENCE_ENFANT,
|
||||
date_debut: '2026-10-01',
|
||||
date_fin: '2026-10-02',
|
||||
};
|
||||
await controller.creer('u1', RoleType.PARENT, dto);
|
||||
expect(serviceMock.creer).toHaveBeenCalledWith(
|
||||
'u1',
|
||||
RoleType.PARENT,
|
||||
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';
|
||||
+29
-1
@@ -10,7 +10,10 @@ describe('AssistantesMaternellesController', () => {
|
||||
const authServiceMock = {
|
||||
createAmDossierStaff: jest.fn(),
|
||||
};
|
||||
const amServiceMock = {};
|
||||
const amServiceMock = {
|
||||
listerCouplesGarde: jest.fn(),
|
||||
definirCoupleGardeCourant: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
@@ -66,4 +69,29 @@ describe('AssistantesMaternellesController', () => {
|
||||
);
|
||||
expect(res.numero_dossier).toBe('2026-000001');
|
||||
});
|
||||
|
||||
it('listerCouplesGarde délègue au service (#171)', async () => {
|
||||
amServiceMock.listerCouplesGarde.mockResolvedValue({
|
||||
couples: [],
|
||||
couple_courant_id: null,
|
||||
});
|
||||
const res = await controller.listerCouplesGarde('am-uuid');
|
||||
expect(amServiceMock.listerCouplesGarde).toHaveBeenCalledWith('am-uuid');
|
||||
expect(res.couple_courant_id).toBeNull();
|
||||
});
|
||||
|
||||
it('definirCoupleGardeCourant délègue au service (#171)', async () => {
|
||||
amServiceMock.definirCoupleGardeCourant.mockResolvedValue({
|
||||
couples: [{ id: 'pl-1', courant: true }],
|
||||
couple_courant_id: 'pl-1',
|
||||
});
|
||||
const res = await controller.definirCoupleGardeCourant('am-uuid', {
|
||||
couple_id: 'pl-1',
|
||||
});
|
||||
expect(amServiceMock.definirCoupleGardeCourant).toHaveBeenCalledWith(
|
||||
'am-uuid',
|
||||
'pl-1',
|
||||
);
|
||||
expect(res.couple_courant_id).toBe('pl-1');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Body,
|
||||
Patch,
|
||||
Param,
|
||||
@@ -20,6 +21,8 @@ import { UpdateAssistanteDto } from '../user/dto/update_assistante.dto';
|
||||
import { UpdateAmFicheAdminDto } from './dto/update-am-fiche-admin.dto';
|
||||
import { StaffCreateAmDossierDto } from './dto/staff-create-am-dossier.dto';
|
||||
import { StaffCreateAmDossierResponseDto } from './dto/staff-create-am-dossier-response.dto';
|
||||
import { CouplesGardeAmResponseDto } from './dto/couples-garde-am.dto';
|
||||
import { DefinirCoupleGardeCourantAmDto } from './dto/definir-couple-garde-courant-am.dto';
|
||||
import { RolesGuard } from 'src/common/guards/roles.guard';
|
||||
import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||
import { User } from 'src/common/decorators/user.decorator';
|
||||
@@ -83,6 +86,36 @@ export class AssistantesMaternellesController {
|
||||
return mapAmsForApi(ams);
|
||||
}
|
||||
|
||||
@Get('me/couples-garde')
|
||||
@Roles(RoleType.ASSISTANTE_MATERNELLE)
|
||||
@ApiOperation({
|
||||
summary: 'Couples de garde de l’AM connectée — ticket #171',
|
||||
description:
|
||||
'Placements actifs (enfant + parents) pour peupler le bandeau couple TdB AM, ' +
|
||||
'avec indication du couple courant.',
|
||||
})
|
||||
@ApiResponse({ status: 200, type: CouplesGardeAmResponseDto })
|
||||
listerCouplesGarde(
|
||||
@User('id') userId: string,
|
||||
): Promise<CouplesGardeAmResponseDto> {
|
||||
return this.assistantesMaternellesService.listerCouplesGarde(userId);
|
||||
}
|
||||
|
||||
@Put('me/couples-garde/courant')
|
||||
@Roles(RoleType.ASSISTANTE_MATERNELLE)
|
||||
@ApiOperation({ summary: 'Définir le couple de garde courant (AM) — ticket #171' })
|
||||
@ApiBody({ type: DefinirCoupleGardeCourantAmDto })
|
||||
@ApiResponse({ status: 200, type: CouplesGardeAmResponseDto })
|
||||
definirCoupleGardeCourant(
|
||||
@User('id') userId: string,
|
||||
@Body() dto: DefinirCoupleGardeCourantAmDto,
|
||||
): Promise<CouplesGardeAmResponseDto> {
|
||||
return this.assistantesMaternellesService.definirCoupleGardeCourant(
|
||||
userId,
|
||||
dto.couple_id,
|
||||
);
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.GESTIONNAIRE, RoleType.ADMINISTRATEUR)
|
||||
@Get(':id')
|
||||
@ApiParam({ name: 'id', description: "UUID de la nounou" })
|
||||
|
||||
@@ -4,13 +4,21 @@ import { AssistantesMaternellesController } from './assistantes_maternelles.cont
|
||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||
import { AmChildren } from 'src/entities/am_children.entity';
|
||||
import { Children } from 'src/entities/children.entity';
|
||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([AssistanteMaternelle, AmChildren, Children, Users]),
|
||||
AuthModule
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([
|
||||
AssistanteMaternelle,
|
||||
AmChildren,
|
||||
Children,
|
||||
Users,
|
||||
ParentsChildren,
|
||||
]),
|
||||
AuthModule,
|
||||
],
|
||||
controllers: [AssistantesMaternellesController],
|
||||
providers: [AssistantesMaternellesService],
|
||||
@@ -19,4 +27,4 @@ import { AuthModule } from '../auth/auth.module';
|
||||
TypeOrmModule,
|
||||
],
|
||||
})
|
||||
export class AssistantesMaternellesModule { }
|
||||
export class AssistantesMaternellesModule {}
|
||||
|
||||
+138
-6
@@ -1,18 +1,150 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||
import { AssistantesMaternellesService } from './assistantes_maternelles.service';
|
||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
import { AmChildren } from 'src/entities/am_children.entity';
|
||||
import { Children } from 'src/entities/children.entity';
|
||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||
|
||||
describe('AssistantesMaternellesService', () => {
|
||||
describe('AssistantesMaternellesService — couples de garde (#171)', () => {
|
||||
let service: AssistantesMaternellesService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [AssistantesMaternellesService],
|
||||
}).compile();
|
||||
const amRepo = { findOne: jest.fn(), update: jest.fn() };
|
||||
const usersRepo = {};
|
||||
const amChildrenRepo = { find: jest.fn(), findOne: jest.fn() };
|
||||
const childrenRepo = {};
|
||||
const parentsChildrenRepo = { find: jest.fn() };
|
||||
|
||||
service = module.get<AssistantesMaternellesService>(AssistantesMaternellesService);
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
AssistantesMaternellesService,
|
||||
{ provide: getRepositoryToken(AssistanteMaternelle), useValue: amRepo },
|
||||
{ provide: getRepositoryToken(Users), useValue: usersRepo },
|
||||
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepo },
|
||||
{ provide: getRepositoryToken(Children), useValue: childrenRepo },
|
||||
{
|
||||
provide: getRepositoryToken(ParentsChildren),
|
||||
useValue: parentsChildrenRepo,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
service = module.get(AssistantesMaternellesService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe('listerCouplesGarde', () => {
|
||||
it('retourne vide si aucun placement', async () => {
|
||||
amRepo.findOne.mockResolvedValue({
|
||||
user_id: 'am-1',
|
||||
id_placement_garde_courant: null,
|
||||
});
|
||||
amChildrenRepo.find.mockResolvedValue([]);
|
||||
const res = await service.listerCouplesGarde('am-1');
|
||||
expect(res).toEqual({ couples: [], couple_courant_id: null });
|
||||
expect(parentsChildrenRepo.find).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('mappe placements + parents et marque le courant', async () => {
|
||||
amRepo.findOne.mockResolvedValue({
|
||||
user_id: 'am-1',
|
||||
id_placement_garde_courant: 'pl-2',
|
||||
});
|
||||
amChildrenRepo.find.mockResolvedValue([
|
||||
{
|
||||
id: 'pl-1',
|
||||
enfantId: 'e1',
|
||||
child: { id: 'e1', first_name: 'Léa', last_name: 'M', photo_url: null },
|
||||
},
|
||||
{
|
||||
id: 'pl-2',
|
||||
enfantId: 'e2',
|
||||
child: { id: 'e2', first_name: 'Emma', last_name: 'M', photo_url: null },
|
||||
},
|
||||
]);
|
||||
parentsChildrenRepo.find.mockResolvedValue([
|
||||
{
|
||||
parentId: 'p1',
|
||||
enfantId: 'e1',
|
||||
parent: { user: { prenom: 'Claire', nom: 'Martin', photo_url: null } },
|
||||
},
|
||||
{
|
||||
parentId: 'p2',
|
||||
enfantId: 'e1',
|
||||
parent: { user: { prenom: 'Thomas', nom: 'Martin', photo_url: null } },
|
||||
},
|
||||
{
|
||||
parentId: 'p1',
|
||||
enfantId: 'e2',
|
||||
parent: { user: { prenom: 'Claire', nom: 'Martin', photo_url: null } },
|
||||
},
|
||||
]);
|
||||
|
||||
const res = await service.listerCouplesGarde('am-1');
|
||||
expect(res.couples).toHaveLength(2);
|
||||
expect(res.couple_courant_id).toBe('pl-2');
|
||||
expect(res.couples[1].courant).toBe(true);
|
||||
expect(res.couples[0].parents).toHaveLength(2);
|
||||
expect(res.couples[0].parents[0].prenom).toBe('Claire');
|
||||
expect(res.couples[0].enfant.prenom).toBe('Léa');
|
||||
});
|
||||
|
||||
it('404 si AM inconnue', async () => {
|
||||
amRepo.findOne.mockResolvedValue(null);
|
||||
await expect(service.listerCouplesGarde('x')).rejects.toBeInstanceOf(
|
||||
NotFoundException,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('definirCoupleGardeCourant', () => {
|
||||
it('persiste si le placement appartient à l’AM', async () => {
|
||||
amRepo.findOne.mockResolvedValue({
|
||||
user_id: 'am-1',
|
||||
id_placement_garde_courant: null,
|
||||
});
|
||||
amChildrenRepo.findOne.mockResolvedValue({
|
||||
id: 'pl-1',
|
||||
amId: 'am-1',
|
||||
enfantId: 'e1',
|
||||
});
|
||||
amRepo.update.mockResolvedValue({ affected: 1 });
|
||||
amChildrenRepo.find.mockResolvedValue([
|
||||
{
|
||||
id: 'pl-1',
|
||||
enfantId: 'e1',
|
||||
child: { id: 'e1', first_name: 'Léa', last_name: null, photo_url: null },
|
||||
},
|
||||
]);
|
||||
parentsChildrenRepo.find.mockResolvedValue([
|
||||
{
|
||||
parentId: 'p1',
|
||||
enfantId: 'e1',
|
||||
parent: { user: { prenom: 'Claire', nom: 'M', photo_url: null } },
|
||||
},
|
||||
]);
|
||||
|
||||
const res = await service.definirCoupleGardeCourant('am-1', 'pl-1');
|
||||
expect(amRepo.update).toHaveBeenCalledWith(
|
||||
{ user_id: 'am-1' },
|
||||
{ id_placement_garde_courant: 'pl-1' },
|
||||
);
|
||||
expect(res.couple_courant_id).toBe('pl-1');
|
||||
expect(res.couples[0].courant).toBe(true);
|
||||
});
|
||||
|
||||
it('404 si placement d’une autre AM', async () => {
|
||||
amRepo.findOne.mockResolvedValue({ user_id: 'am-1' });
|
||||
amChildrenRepo.findOne.mockResolvedValue(null);
|
||||
await expect(
|
||||
service.definirCoupleGardeCourant('am-1', 'pl-x'),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,14 +5,16 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { IsNull, Repository } from 'typeorm';
|
||||
import { In, IsNull, Repository } from 'typeorm';
|
||||
import { RoleType, Users } from 'src/entities/users.entity';
|
||||
import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity';
|
||||
import { AmChildren } from 'src/entities/am_children.entity';
|
||||
import { Children, StatutEnfantType } from 'src/entities/children.entity';
|
||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||
import { CreateAssistanteDto } from '../user/dto/create_assistante.dto';
|
||||
import { UpdateAssistanteDto } from '../user/dto/update_assistante.dto';
|
||||
import { UpdateAmFicheAdminDto } from './dto/update-am-fiche-admin.dto';
|
||||
import { CouplesGardeAmResponseDto } from './dto/couples-garde-am.dto';
|
||||
import { validateNir } from 'src/common/utils/nir.util';
|
||||
|
||||
const AM_CHILDREN_RELATIONS = ['user', 'amChildren', 'amChildren.child'] as const;
|
||||
@@ -28,6 +30,8 @@ export class AssistantesMaternellesService {
|
||||
private readonly amChildrenRepository: Repository<AmChildren>,
|
||||
@InjectRepository(Children)
|
||||
private readonly childrenRepository: Repository<Children>,
|
||||
@InjectRepository(ParentsChildren)
|
||||
private readonly parentsChildrenRepository: Repository<ParentsChildren>,
|
||||
) {}
|
||||
|
||||
async create(dto: CreateAssistanteDto): Promise<AssistanteMaternelle> {
|
||||
@@ -153,7 +157,7 @@ export class AssistantesMaternellesService {
|
||||
}
|
||||
|
||||
if (Object.keys(amPatch).length > 0) {
|
||||
await this.assistantesMaternelleRepository.update(amUserId, amPatch);
|
||||
await this.assistantesMaternelleRepository.update(amUserId, amPatch as any);
|
||||
}
|
||||
|
||||
return this.findOne(amUserId);
|
||||
@@ -264,4 +268,107 @@ export class AssistantesMaternellesService {
|
||||
await this.assistantesMaternelleRepository.delete(id);
|
||||
return { message: 'Assistante maternelle supprimée' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Liste les couples de garde (enfant ↔ parents) de l’AM connectée — ticket #171.
|
||||
* Un couple = un placement actif dans enfants_assistantes_maternelles pour cette AM.
|
||||
*/
|
||||
async listerCouplesGarde(amUserId: string): Promise<CouplesGardeAmResponseDto> {
|
||||
const am = await this.assistantesMaternelleRepository.findOne({
|
||||
where: { user_id: amUserId },
|
||||
});
|
||||
if (!am) {
|
||||
throw new NotFoundException('Assistante maternelle introuvable');
|
||||
}
|
||||
|
||||
const placements = await this.amChildrenRepository.find({
|
||||
where: { amId: amUserId, date_fin: IsNull() },
|
||||
relations: ['child'],
|
||||
order: { date_debut: 'ASC' },
|
||||
});
|
||||
|
||||
if (placements.length === 0) {
|
||||
return { couples: [], couple_courant_id: null };
|
||||
}
|
||||
|
||||
const enfantIds = placements.map((p) => p.enfantId);
|
||||
const liens = await this.parentsChildrenRepository.find({
|
||||
where: { enfantId: In(enfantIds) },
|
||||
relations: ['parent', 'parent.user'],
|
||||
});
|
||||
const parentsByEnfant = new Map<
|
||||
string,
|
||||
{ id: string; prenom: string | null; nom: string | null; photo_url: string | null }[]
|
||||
>();
|
||||
for (const l of liens) {
|
||||
const list = parentsByEnfant.get(l.enfantId) ?? [];
|
||||
const u = l.parent?.user;
|
||||
list.push({
|
||||
id: l.parentId,
|
||||
prenom: u?.prenom ?? null,
|
||||
nom: u?.nom ?? null,
|
||||
photo_url: u?.photo_url ?? null,
|
||||
});
|
||||
parentsByEnfant.set(l.enfantId, list);
|
||||
}
|
||||
|
||||
let idCourant = am.id_placement_garde_courant ?? null;
|
||||
const idsValides = new Set(placements.map((p) => p.id));
|
||||
if (idCourant && !idsValides.has(idCourant)) {
|
||||
idCourant = null;
|
||||
await this.assistantesMaternelleRepository.update(
|
||||
{ user_id: amUserId },
|
||||
{ id_placement_garde_courant: () => 'NULL' },
|
||||
);
|
||||
}
|
||||
if (!idCourant && placements.length === 1) {
|
||||
idCourant = placements[0].id;
|
||||
}
|
||||
|
||||
const couples = placements.map((p) => ({
|
||||
id: p.id,
|
||||
enfant: {
|
||||
id: p.child.id,
|
||||
prenom: p.child.first_name ?? null,
|
||||
nom: p.child.last_name ?? null,
|
||||
photo_url: p.child.photo_url ?? null,
|
||||
},
|
||||
parents: parentsByEnfant.get(p.enfantId) ?? [],
|
||||
courant: idCourant != null && p.id === idCourant,
|
||||
}));
|
||||
|
||||
return {
|
||||
couples,
|
||||
couple_courant_id: idCourant,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Persiste le couple de garde actif pour l’AM — ticket #171.
|
||||
*/
|
||||
async definirCoupleGardeCourant(
|
||||
amUserId: string,
|
||||
coupleId: string,
|
||||
): Promise<CouplesGardeAmResponseDto> {
|
||||
const am = await this.assistantesMaternelleRepository.findOne({
|
||||
where: { user_id: amUserId },
|
||||
});
|
||||
if (!am) {
|
||||
throw new NotFoundException('Assistante maternelle introuvable');
|
||||
}
|
||||
|
||||
const placement = await this.amChildrenRepository.findOne({
|
||||
where: { id: coupleId, amId: amUserId, date_fin: IsNull() },
|
||||
});
|
||||
if (!placement) {
|
||||
throw new NotFoundException('Couple de garde introuvable ou inactif pour cette AM');
|
||||
}
|
||||
|
||||
await this.assistantesMaternelleRepository.update(
|
||||
{ user_id: amUserId },
|
||||
{ id_placement_garde_courant: coupleId },
|
||||
);
|
||||
|
||||
return this.listerCouplesGarde(amUserId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
/** Identité minimale enfant — ticket #171 (miroir #168) */
|
||||
export class CoupleGardeAmEnfantDto {
|
||||
@ApiProperty({ format: 'uuid' })
|
||||
id: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
prenom?: string | null;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
nom?: string | null;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
photo_url?: string | null;
|
||||
}
|
||||
|
||||
/** Identité minimale parent pour bandeau AM — ticket #171 */
|
||||
export class CoupleGardeAmParentDto {
|
||||
@ApiProperty({ format: 'uuid', description: 'UUID utilisateur du parent' })
|
||||
id: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
prenom?: string | null;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
nom?: string | null;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
photo_url?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Un couple côté AM = placement actif enfant ↔ foyer parents.
|
||||
* `id` = enfants_assistantes_maternelles.id (même clé que #168).
|
||||
*/
|
||||
export class CoupleGardeAmDto {
|
||||
@ApiProperty({
|
||||
format: 'uuid',
|
||||
description: 'Id du placement (enfants_assistantes_maternelles.id)',
|
||||
})
|
||||
id: string;
|
||||
|
||||
@ApiProperty({ type: CoupleGardeAmEnfantDto })
|
||||
enfant: CoupleGardeAmEnfantDto;
|
||||
|
||||
@ApiProperty({
|
||||
type: [CoupleGardeAmParentDto],
|
||||
description: 'Parents rattachés à l’enfant (0–2 typiquement)',
|
||||
})
|
||||
parents: CoupleGardeAmParentDto[];
|
||||
|
||||
@ApiProperty({ description: 'True si c’est le couple actuellement sélectionné' })
|
||||
courant: boolean;
|
||||
}
|
||||
|
||||
export class CouplesGardeAmResponseDto {
|
||||
@ApiProperty({ type: [CoupleGardeAmDto] })
|
||||
couples: CoupleGardeAmDto[];
|
||||
|
||||
@ApiPropertyOptional({
|
||||
format: 'uuid',
|
||||
nullable: true,
|
||||
description: 'Id du couple courant (null si aucun)',
|
||||
})
|
||||
couple_courant_id: string | null;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsUUID } from 'class-validator';
|
||||
|
||||
/** Corps PUT couple de garde courant AM — ticket #171 */
|
||||
export class DefinirCoupleGardeCourantAmDto {
|
||||
@ApiProperty({
|
||||
format: 'uuid',
|
||||
description: 'Id du placement (enfants_assistantes_maternelles.id) à sélectionner',
|
||||
})
|
||||
@IsUUID()
|
||||
@IsNotEmpty()
|
||||
couple_id: string;
|
||||
}
|
||||
@@ -564,7 +564,6 @@ export class AuthService {
|
||||
enfant.status = enfantDto.date_naissance ? StatutEnfantType.SANS_GARDE : StatutEnfantType.A_NAITRE;
|
||||
enfant.consent_photo = !!enfantDto.consent_photo;
|
||||
enfant.consent_photo_at = enfant.consent_photo ? new Date() : null!;
|
||||
enfant.is_multiple = enfantDto.grossesse_multiple || false;
|
||||
|
||||
const enfantEnregistre = await manager.save(Children, enfant);
|
||||
enfantsEnregistres.push(enfantEnregistre);
|
||||
@@ -1387,9 +1386,6 @@ export class AuthService {
|
||||
enfant.status = StatutEnfantType.A_NAITRE;
|
||||
}
|
||||
}
|
||||
if (enfantDto.grossesse_multiple !== undefined) {
|
||||
enfant.is_multiple = enfantDto.grossesse_multiple;
|
||||
}
|
||||
if (enfantDto.consent_photo !== undefined) {
|
||||
enfant.consent_photo = !!enfantDto.consent_photo;
|
||||
enfant.consent_photo_at = enfant.consent_photo
|
||||
|
||||
@@ -55,11 +55,6 @@ export class EnfantInscriptionDto {
|
||||
@IsString()
|
||||
photo_filename?: string;
|
||||
|
||||
@ApiProperty({ example: false, required: false, description: 'Grossesse multiple (jumeaux, triplés, etc.)' })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
grossesse_multiple?: boolean;
|
||||
|
||||
@ApiProperty({
|
||||
example: true,
|
||||
required: false,
|
||||
|
||||
@@ -74,11 +74,6 @@ export class CreateEnfantsDto {
|
||||
@IsDateString()
|
||||
consent_photo_at?: string;
|
||||
|
||||
@ApiProperty({ default: false })
|
||||
@Transform(toBoolean)
|
||||
@IsBoolean()
|
||||
is_multiple: boolean;
|
||||
|
||||
/**
|
||||
* Parent pivot du foyer — obligatoire pour staff (gestionnaire/admin).
|
||||
* Ignoré / interdit en externe pour un PARENT (ticket #132).
|
||||
|
||||
@@ -29,9 +29,6 @@ export class EnfantResponseDto {
|
||||
@ApiProperty({ example: false })
|
||||
consent_photo: boolean;
|
||||
|
||||
@ApiProperty({ example: false })
|
||||
is_multiple: boolean;
|
||||
|
||||
@ApiProperty({ example: 'UUID-parent' })
|
||||
parent_id: string;
|
||||
}
|
||||
|
||||
@@ -92,7 +92,6 @@ export class EnfantsService {
|
||||
photo_url: photoUrl,
|
||||
consent_photo: !!dto.consent_photo,
|
||||
consent_photo_at: consentAt,
|
||||
is_multiple: !!dto.is_multiple,
|
||||
});
|
||||
await this.childrenRepository.save(child);
|
||||
|
||||
@@ -218,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
/** Identité minimale enfant pour le bandeau couple — ticket #168 */
|
||||
export class CoupleGardeEnfantDto {
|
||||
@ApiProperty({ format: 'uuid' })
|
||||
id: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
prenom?: string | null;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
nom?: string | null;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
photo_url?: string | null;
|
||||
}
|
||||
|
||||
/** Identité minimale AM pour le bandeau couple — ticket #168 */
|
||||
export class CoupleGardeAmDto {
|
||||
@ApiProperty({ format: 'uuid', description: 'UUID utilisateur de l’AM' })
|
||||
id: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
prenom?: string | null;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
nom?: string | null;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
photo_url?: string | null;
|
||||
}
|
||||
|
||||
/** Un couple de garde = placement actif enfant ↔ AM */
|
||||
export class CoupleGardeDto {
|
||||
@ApiProperty({
|
||||
format: 'uuid',
|
||||
description: 'Id du placement (enfants_assistantes_maternelles.id)',
|
||||
})
|
||||
id: string;
|
||||
|
||||
@ApiProperty({ type: CoupleGardeEnfantDto })
|
||||
enfant: CoupleGardeEnfantDto;
|
||||
|
||||
@ApiProperty({ type: CoupleGardeAmDto })
|
||||
am: CoupleGardeAmDto;
|
||||
|
||||
@ApiProperty({ description: 'True si c’est le couple actuellement sélectionné' })
|
||||
courant: boolean;
|
||||
}
|
||||
|
||||
export class CouplesGardeResponseDto {
|
||||
@ApiProperty({ type: [CoupleGardeDto] })
|
||||
couples: CoupleGardeDto[];
|
||||
|
||||
@ApiPropertyOptional({
|
||||
format: 'uuid',
|
||||
nullable: true,
|
||||
description: 'Id du couple courant (null si aucun / premier couple implicite côté client)',
|
||||
})
|
||||
couple_courant_id: string | null;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsUUID } from 'class-validator';
|
||||
|
||||
/** Corps PUT couple de garde courant — ticket #168 */
|
||||
export class DefinirCoupleGardeCourantDto {
|
||||
@ApiProperty({
|
||||
format: 'uuid',
|
||||
description: 'Id du placement (enfants_assistantes_maternelles.id) à sélectionner',
|
||||
})
|
||||
@IsUUID()
|
||||
@IsNotEmpty()
|
||||
couple_id: string;
|
||||
}
|
||||
@@ -54,9 +54,6 @@ export class DossierFamilleEnfantDto {
|
||||
description: 'Consentement affichage photo (colonne consentement_photo)',
|
||||
})
|
||||
consent_photo?: boolean;
|
||||
|
||||
@ApiProperty({ required: false, description: 'Grossesse multiple (est_multiple)' })
|
||||
est_multiple?: boolean;
|
||||
}
|
||||
|
||||
/** Réponse GET /parents/dossier-famille/:numeroDossier – dossier famille complet. Ticket #119 */
|
||||
|
||||
@@ -13,7 +13,10 @@ describe('ParentsController', () => {
|
||||
createParentDossierStaff: jest.fn(),
|
||||
addCoParentStaff: jest.fn(),
|
||||
};
|
||||
const parentsServiceMock = {};
|
||||
const parentsServiceMock = {
|
||||
listerCouplesGarde: jest.fn(),
|
||||
definirCoupleGardeCourant: jest.fn(),
|
||||
};
|
||||
const userServiceMock = {};
|
||||
|
||||
beforeEach(async () => {
|
||||
@@ -39,6 +42,31 @@ describe('ParentsController', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
it('listerCouplesGarde délègue au service (#168)', async () => {
|
||||
parentsServiceMock.listerCouplesGarde.mockResolvedValue({
|
||||
couples: [],
|
||||
couple_courant_id: null,
|
||||
});
|
||||
const res = await controller.listerCouplesGarde('parent-uuid');
|
||||
expect(parentsServiceMock.listerCouplesGarde).toHaveBeenCalledWith('parent-uuid');
|
||||
expect(res.couples).toEqual([]);
|
||||
});
|
||||
|
||||
it('definirCoupleGardeCourant délègue au service (#168)', async () => {
|
||||
parentsServiceMock.definirCoupleGardeCourant.mockResolvedValue({
|
||||
couples: [{ id: 'pl-1', courant: true }],
|
||||
couple_courant_id: 'pl-1',
|
||||
});
|
||||
const res = await controller.definirCoupleGardeCourant('parent-uuid', {
|
||||
couple_id: 'pl-1',
|
||||
});
|
||||
expect(parentsServiceMock.definirCoupleGardeCourant).toHaveBeenCalledWith(
|
||||
'parent-uuid',
|
||||
'pl-1',
|
||||
);
|
||||
expect(res.couple_courant_id).toBe('pl-1');
|
||||
});
|
||||
|
||||
it('createDossier delegates to authService.createParentDossierStaff with CGU accepted', async () => {
|
||||
authServiceMock.createParentDossierStaff.mockResolvedValue({
|
||||
message: 'Dossier famille créé et validé. Un e-mail de création de mot de passe a été envoyé.',
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Put,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ParentsService } from './parents.service';
|
||||
@@ -39,6 +40,8 @@ import { User } from 'src/common/decorators/user.decorator';
|
||||
import { PendingFamilyDto } from './dto/pending-family.dto';
|
||||
import { DossierFamilleCompletDto } from './dto/dossier-famille-complet.dto';
|
||||
import { mapParentForApi, mapParentsForApi } from './parents.mapper';
|
||||
import { CouplesGardeResponseDto } from './dto/couples-garde.dto';
|
||||
import { DefinirCoupleGardeCourantDto } from './dto/definir-couple-garde-courant.dto';
|
||||
|
||||
@ApiTags('Parents')
|
||||
@ApiBearerAuth('access-token')
|
||||
@@ -51,6 +54,39 @@ export class ParentsController {
|
||||
private readonly authService: AuthService,
|
||||
) {}
|
||||
|
||||
@Get('me/couples-garde')
|
||||
@Roles(RoleType.PARENT)
|
||||
@ApiOperation({
|
||||
summary: 'Lister les couples de garde du parent connecté — ticket #168',
|
||||
description:
|
||||
'Retourne les placements actifs enfant↔AM rattachés au parent, ' +
|
||||
'avec indication du couple courant (bandeau TdB quotidien).',
|
||||
})
|
||||
@ApiResponse({ status: 200, type: CouplesGardeResponseDto })
|
||||
@ApiResponse({ status: 403, description: 'Réservé au rôle parent' })
|
||||
@ApiResponse({ status: 404, description: 'Parent introuvable' })
|
||||
listerCouplesGarde(@User('id') userId: string): Promise<CouplesGardeResponseDto> {
|
||||
return this.parentsService.listerCouplesGarde(userId);
|
||||
}
|
||||
|
||||
@Put('me/couples-garde/courant')
|
||||
@Roles(RoleType.PARENT)
|
||||
@ApiOperation({
|
||||
summary: 'Définir le couple de garde courant — ticket #168',
|
||||
description:
|
||||
'Persiste la préférence de couple actif (enfant|nounou) pour contextualiser le TdB.',
|
||||
})
|
||||
@ApiBody({ type: DefinirCoupleGardeCourantDto })
|
||||
@ApiResponse({ status: 200, type: CouplesGardeResponseDto })
|
||||
@ApiResponse({ status: 400, description: 'Couple hors périmètre du parent' })
|
||||
@ApiResponse({ status: 404, description: 'Parent ou couple introuvable' })
|
||||
definirCoupleGardeCourant(
|
||||
@User('id') userId: string,
|
||||
@Body() dto: DefinirCoupleGardeCourantDto,
|
||||
): Promise<CouplesGardeResponseDto> {
|
||||
return this.parentsService.definirCoupleGardeCourant(userId, dto.couple_id);
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR, RoleType.GESTIONNAIRE)
|
||||
@Post('dossier')
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
|
||||
@@ -5,6 +5,7 @@ import { JwtModule } from '@nestjs/jwt';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { DossierFamille, DossierFamilleEnfant } from 'src/entities/dossier_famille.entity';
|
||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||
import { AmChildren } from 'src/entities/am_children.entity';
|
||||
import { ParentsController } from './parents.controller';
|
||||
import { ParentsService } from './parents.service';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
@@ -13,7 +14,14 @@ import { AuthModule } from '../auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Parents, Users, DossierFamille, DossierFamilleEnfant, ParentsChildren]),
|
||||
TypeOrmModule.forFeature([
|
||||
Parents,
|
||||
Users,
|
||||
DossierFamille,
|
||||
DossierFamilleEnfant,
|
||||
ParentsChildren,
|
||||
AmChildren,
|
||||
]),
|
||||
forwardRef(() => UserModule),
|
||||
forwardRef(() => AuthModule),
|
||||
JwtModule.registerAsync({
|
||||
|
||||
@@ -1,12 +1,43 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||
import { ParentsService } from './parents.service';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { Users } from 'src/entities/users.entity';
|
||||
import { DossierFamille } from 'src/entities/dossier_famille.entity';
|
||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||
import { AmChildren } from 'src/entities/am_children.entity';
|
||||
|
||||
describe('ParentsService', () => {
|
||||
describe('ParentsService — couples de garde (#168)', () => {
|
||||
let service: ParentsService;
|
||||
|
||||
const parentsRepository = {
|
||||
findOne: jest.fn(),
|
||||
update: jest.fn(),
|
||||
};
|
||||
const parentsChildrenRepository = {
|
||||
find: jest.fn(),
|
||||
findOne: jest.fn(),
|
||||
};
|
||||
const amChildrenRepository = {
|
||||
find: jest.fn(),
|
||||
findOne: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [ParentsService],
|
||||
providers: [
|
||||
ParentsService,
|
||||
{ provide: getRepositoryToken(Parents), useValue: parentsRepository },
|
||||
{ provide: getRepositoryToken(Users), useValue: {} },
|
||||
{ provide: getRepositoryToken(DossierFamille), useValue: {} },
|
||||
{
|
||||
provide: getRepositoryToken(ParentsChildren),
|
||||
useValue: parentsChildrenRepository,
|
||||
},
|
||||
{ provide: getRepositoryToken(AmChildren), useValue: amChildrenRepository },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<ParentsService>(ParentsService);
|
||||
@@ -15,4 +46,107 @@ describe('ParentsService', () => {
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe('listerCouplesGarde', () => {
|
||||
it('retourne une liste vide si le parent n’a pas d’enfant', async () => {
|
||||
parentsRepository.findOne.mockResolvedValue({
|
||||
user_id: 'p1',
|
||||
id_placement_garde_courant: null,
|
||||
});
|
||||
parentsChildrenRepository.find.mockResolvedValue([]);
|
||||
|
||||
const res = await service.listerCouplesGarde('p1');
|
||||
expect(res).toEqual({ couples: [], couple_courant_id: null });
|
||||
expect(amChildrenRepository.find).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('mappe les placements actifs en couples et marque le courant', async () => {
|
||||
parentsRepository.findOne.mockResolvedValue({
|
||||
user_id: 'p1',
|
||||
id_placement_garde_courant: 'pl-2',
|
||||
});
|
||||
parentsChildrenRepository.find.mockResolvedValue([
|
||||
{ enfantId: 'e1' },
|
||||
{ enfantId: 'e2' },
|
||||
]);
|
||||
amChildrenRepository.find.mockResolvedValue([
|
||||
{
|
||||
id: 'pl-1',
|
||||
amId: 'am-1',
|
||||
child: { id: 'e1', first_name: 'Léo', last_name: 'M', photo_url: null },
|
||||
am: { user: { prenom: 'Marie', nom: 'N', photo_url: '/a.jpg' } },
|
||||
},
|
||||
{
|
||||
id: 'pl-2',
|
||||
amId: 'am-2',
|
||||
child: { id: 'e2', first_name: 'Léa', last_name: 'M', photo_url: null },
|
||||
am: { user: { prenom: 'Sophie', nom: 'P', photo_url: null } },
|
||||
},
|
||||
]);
|
||||
|
||||
const res = await service.listerCouplesGarde('p1');
|
||||
expect(res.couples).toHaveLength(2);
|
||||
expect(res.couple_courant_id).toBe('pl-2');
|
||||
expect(res.couples[1].courant).toBe(true);
|
||||
expect(res.couples[0].am.prenom).toBe('Marie');
|
||||
expect(res.couples[0].enfant.prenom).toBe('Léo');
|
||||
});
|
||||
|
||||
it('404 si parent inconnu', async () => {
|
||||
parentsRepository.findOne.mockResolvedValue(null);
|
||||
await expect(service.listerCouplesGarde('x')).rejects.toBeInstanceOf(
|
||||
NotFoundException,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('definirCoupleGardeCourant', () => {
|
||||
it('persiste le couple si l’enfant est rattaché au parent', async () => {
|
||||
parentsRepository.findOne.mockResolvedValue({
|
||||
user_id: 'p1',
|
||||
id_placement_garde_courant: null,
|
||||
});
|
||||
amChildrenRepository.findOne.mockResolvedValue({
|
||||
id: 'pl-1',
|
||||
enfantId: 'e1',
|
||||
date_fin: null,
|
||||
});
|
||||
parentsChildrenRepository.findOne.mockResolvedValue({
|
||||
parentId: 'p1',
|
||||
enfantId: 'e1',
|
||||
});
|
||||
parentsRepository.update.mockResolvedValue({ affected: 1 });
|
||||
// second call via listerCouplesGarde
|
||||
parentsChildrenRepository.find.mockResolvedValue([{ enfantId: 'e1' }]);
|
||||
amChildrenRepository.find.mockResolvedValue([
|
||||
{
|
||||
id: 'pl-1',
|
||||
amId: 'am-1',
|
||||
child: { id: 'e1', first_name: 'Léo', last_name: null, photo_url: null },
|
||||
am: { user: { prenom: 'Marie', nom: null, photo_url: null } },
|
||||
},
|
||||
]);
|
||||
|
||||
const res = await service.definirCoupleGardeCourant('p1', 'pl-1');
|
||||
expect(parentsRepository.update).toHaveBeenCalledWith(
|
||||
{ user_id: 'p1' },
|
||||
{ id_placement_garde_courant: 'pl-1' },
|
||||
);
|
||||
expect(res.couple_courant_id).toBe('pl-1');
|
||||
expect(res.couples[0].courant).toBe(true);
|
||||
});
|
||||
|
||||
it('400 si le couple n’appartient pas au parent', async () => {
|
||||
parentsRepository.findOne.mockResolvedValue({ user_id: 'p1' });
|
||||
amChildrenRepository.findOne.mockResolvedValue({
|
||||
id: 'pl-1',
|
||||
enfantId: 'e99',
|
||||
});
|
||||
parentsChildrenRepository.findOne.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
service.definirCoupleGardeCourant('p1', 'pl-1'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { In, Repository } from 'typeorm';
|
||||
import { In, IsNull, Repository } from 'typeorm';
|
||||
import { Parents } from 'src/entities/parents.entity';
|
||||
import { DossierFamille } from 'src/entities/dossier_famille.entity';
|
||||
import { RoleType, Users } from 'src/entities/users.entity';
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
import { ParentsChildren } from 'src/entities/parents_children.entity';
|
||||
import { Children } from 'src/entities/children.entity';
|
||||
import { UpdateParentFicheAdminDto } from './dto/update-parent-fiche-admin.dto';
|
||||
import { AmChildren } from 'src/entities/am_children.entity';
|
||||
import { CouplesGardeResponseDto } from './dto/couples-garde.dto';
|
||||
|
||||
@Injectable()
|
||||
export class ParentsService {
|
||||
@@ -32,6 +34,8 @@ export class ParentsService {
|
||||
private readonly dossierFamilleRepository: Repository<DossierFamille>,
|
||||
@InjectRepository(ParentsChildren)
|
||||
private readonly parentsChildrenRepository: Repository<ParentsChildren>,
|
||||
@InjectRepository(AmChildren)
|
||||
private readonly amChildrenRepository: Repository<AmChildren>,
|
||||
) {}
|
||||
|
||||
// Création d’un parent
|
||||
@@ -370,7 +374,6 @@ export class ParentsService {
|
||||
status: child.status,
|
||||
photo_url: child.photo_url ?? undefined,
|
||||
consent_photo: child.consent_photo,
|
||||
est_multiple: child.is_multiple,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -506,4 +509,108 @@ export class ParentsService {
|
||||
}
|
||||
return raw.map((r: { id: string }) => r.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Liste les couples de garde (enfant ↔ AM) du parent connecté — ticket #168.
|
||||
* Un couple = un placement actif dans enfants_assistantes_maternelles pour un enfant du parent.
|
||||
*/
|
||||
async listerCouplesGarde(parentUserId: string): Promise<CouplesGardeResponseDto> {
|
||||
const parent = await this.parentsRepository.findOne({
|
||||
where: { user_id: parentUserId },
|
||||
});
|
||||
if (!parent) {
|
||||
throw new NotFoundException('Parent introuvable');
|
||||
}
|
||||
|
||||
const liensEnfants = await this.parentsChildrenRepository.find({
|
||||
where: { parentId: parentUserId },
|
||||
select: ['enfantId'],
|
||||
});
|
||||
const enfantIds = liensEnfants.map((l) => l.enfantId);
|
||||
if (enfantIds.length === 0) {
|
||||
return { couples: [], couple_courant_id: null };
|
||||
}
|
||||
|
||||
const placements = await this.amChildrenRepository.find({
|
||||
where: { enfantId: In(enfantIds), date_fin: IsNull() },
|
||||
relations: ['child', 'am', 'am.user'],
|
||||
order: { date_debut: 'ASC' },
|
||||
});
|
||||
|
||||
let idCourant = parent.id_placement_garde_courant ?? null;
|
||||
const idsValides = new Set(placements.map((p) => p.id));
|
||||
if (idCourant && !idsValides.has(idCourant)) {
|
||||
idCourant = null;
|
||||
await this.parentsRepository.update(
|
||||
{ user_id: parentUserId },
|
||||
{ id_placement_garde_courant: () => 'NULL' },
|
||||
);
|
||||
}
|
||||
if (!idCourant && placements.length === 1) {
|
||||
idCourant = placements[0].id;
|
||||
}
|
||||
|
||||
const couples = placements.map((p) => {
|
||||
const amUser = p.am?.user;
|
||||
return {
|
||||
id: p.id,
|
||||
enfant: {
|
||||
id: p.child.id,
|
||||
prenom: p.child.first_name ?? null,
|
||||
nom: p.child.last_name ?? null,
|
||||
photo_url: p.child.photo_url ?? null,
|
||||
},
|
||||
am: {
|
||||
id: p.amId,
|
||||
prenom: amUser?.prenom ?? null,
|
||||
nom: amUser?.nom ?? null,
|
||||
photo_url: amUser?.photo_url ?? null,
|
||||
},
|
||||
courant: idCourant != null && p.id === idCourant,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
couples,
|
||||
couple_courant_id: idCourant,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Persiste le couple de garde actif pour le parent — ticket #168.
|
||||
*/
|
||||
async definirCoupleGardeCourant(
|
||||
parentUserId: string,
|
||||
coupleId: string,
|
||||
): Promise<CouplesGardeResponseDto> {
|
||||
const parent = await this.parentsRepository.findOne({
|
||||
where: { user_id: parentUserId },
|
||||
});
|
||||
if (!parent) {
|
||||
throw new NotFoundException('Parent introuvable');
|
||||
}
|
||||
|
||||
const placement = await this.amChildrenRepository.findOne({
|
||||
where: { id: coupleId, date_fin: IsNull() },
|
||||
});
|
||||
if (!placement) {
|
||||
throw new NotFoundException('Couple de garde introuvable ou inactif');
|
||||
}
|
||||
|
||||
const lien = await this.parentsChildrenRepository.findOne({
|
||||
where: { parentId: parentUserId, enfantId: placement.enfantId },
|
||||
});
|
||||
if (!lien) {
|
||||
throw new BadRequestException(
|
||||
'Ce couple ne concerne pas un enfant rattaché à ce parent',
|
||||
);
|
||||
}
|
||||
|
||||
await this.parentsRepository.update(
|
||||
{ user_id: parentUserId },
|
||||
{ id_placement_garde_courant: coupleId },
|
||||
);
|
||||
|
||||
return this.listerCouplesGarde(parentUserId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import 'reflect-metadata';
|
||||
import { GestionnairesController } from './gestionnaires.controller';
|
||||
import { GestionnairesService } from './gestionnaires.service';
|
||||
import { RoleType } from 'src/entities/users.entity';
|
||||
|
||||
describe('GestionnairesController', () => {
|
||||
let controller: GestionnairesController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [GestionnairesController],
|
||||
providers: [GestionnairesService],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<GestionnairesController>(GestionnairesController);
|
||||
describe('GestionnairesController roles (#161)', () => {
|
||||
it('POST /gestionnaires autorise SUPER_ADMIN et ADMINISTRATEUR', () => {
|
||||
const roles = Reflect.getMetadata('roles', GestionnairesController.prototype.create);
|
||||
expect(roles).toEqual(
|
||||
expect.arrayContaining([RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR]),
|
||||
);
|
||||
expect(roles).not.toContain(RoleType.GESTIONNAIRE);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
it('PATCH /gestionnaires/:id autorise SUPER_ADMIN et ADMINISTRATEUR', () => {
|
||||
const roles = Reflect.getMetadata('roles', GestionnairesController.prototype.update);
|
||||
expect(roles).toEqual(
|
||||
expect.arrayContaining([RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR]),
|
||||
);
|
||||
expect(roles).not.toContain(RoleType.GESTIONNAIRE);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,10 +25,10 @@ import { AuthGuard } from 'src/common/guards/auth.guard';
|
||||
export class GestionnairesController {
|
||||
constructor(private readonly gestionnairesService: GestionnairesService) { }
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||
@ApiResponse({ status: 201, description: 'Le gestionnaire a été créé avec succès.', type: Users })
|
||||
@ApiResponse({ status: 409, description: 'Conflit. L\'email est déjà utilisé.' })
|
||||
@ApiOperation({ summary: 'Création d\'un gestionnaire' })
|
||||
@ApiOperation({ summary: 'Création d\'un gestionnaire (admin / super admin)' })
|
||||
@ApiBody({ type: CreateGestionnaireDto })
|
||||
@Post()
|
||||
create(@Body() dto: CreateGestionnaireDto): Promise<Users> {
|
||||
@@ -43,7 +43,7 @@ export class GestionnairesController {
|
||||
return this.gestionnairesService.findAll();
|
||||
}
|
||||
|
||||
@Roles(RoleType.GESTIONNAIRE, RoleType.SUPER_ADMIN)
|
||||
@Roles(RoleType.GESTIONNAIRE, RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Récupérer un gestionnaire par ID' })
|
||||
@ApiResponse({ status: 400, description: 'ID invalide' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||
@@ -56,8 +56,8 @@ export class GestionnairesController {
|
||||
return this.gestionnairesService.findOne(id);
|
||||
}
|
||||
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@ApiOperation({ summary: 'Mettre à jour un gestionnaire' })
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Mettre à jour un gestionnaire (admin / super admin)' })
|
||||
@ApiResponse({ status: 200, description: 'Le gestionnaire a été mis à jour avec succès.', type: Users })
|
||||
@ApiResponse({ status: 404, description: 'Gestionnaire non trouvé' })
|
||||
@ApiResponse({ status: 403, description: 'Accès refusé' })
|
||||
|
||||
@@ -1,20 +1,13 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import 'reflect-metadata';
|
||||
import { UserController } from './user.controller';
|
||||
import { UserService } from './user.service';
|
||||
import { RoleType } from 'src/entities/users.entity';
|
||||
|
||||
describe('UserController', () => {
|
||||
let controller: UserController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [UserController],
|
||||
providers: [UserService],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<UserController>(UserController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
describe('UserController roles (#161)', () => {
|
||||
it('POST /users/admin autorise SUPER_ADMIN et ADMINISTRATEUR', () => {
|
||||
const roles = Reflect.getMetadata('roles', UserController.prototype.createAdmin);
|
||||
expect(roles).toEqual(
|
||||
expect.arrayContaining([RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR]),
|
||||
);
|
||||
expect(roles).not.toContain(RoleType.GESTIONNAIRE);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,10 +22,10 @@ export class UserController {
|
||||
private readonly suppressionService: SuppressionService,
|
||||
) { }
|
||||
|
||||
// Création d'un administrateur (réservée aux super admins)
|
||||
// Création d'un administrateur (admin + super admin) — #161
|
||||
@Post('admin')
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@ApiOperation({ summary: 'Créer un nouvel administrateur (super admin seulement)' })
|
||||
@Roles(RoleType.SUPER_ADMIN, RoleType.ADMINISTRATEUR)
|
||||
@ApiOperation({ summary: 'Créer un nouvel administrateur (admin / super admin)' })
|
||||
createAdmin(
|
||||
@Body() dto: CreateAdminDto,
|
||||
@User() currentUser: Users
|
||||
|
||||
@@ -1,18 +1,87 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { BadRequestException, ForbiddenException } from '@nestjs/common';
|
||||
import { UserService } from './user.service';
|
||||
import { RoleType, StatutUtilisateurType } from 'src/entities/users.entity';
|
||||
|
||||
describe('UserService.createAdmin (#161)', () => {
|
||||
const usersRepository = {
|
||||
findOneBy: jest.fn(),
|
||||
create: jest.fn(),
|
||||
save: jest.fn(),
|
||||
};
|
||||
|
||||
describe('UserService', () => {
|
||||
let service: UserService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [UserService],
|
||||
}).compile();
|
||||
const dto = {
|
||||
email: 'nouveau.admin@ptits-pas.fr',
|
||||
password: 'Password1!',
|
||||
prenom: 'Nina',
|
||||
nom: 'Admin',
|
||||
telephone: '0601020304',
|
||||
};
|
||||
|
||||
service = module.get<UserService>(UserService);
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
service = new UserService(
|
||||
usersRepository as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
it('autorise un administrateur à créer un admin', async () => {
|
||||
usersRepository.findOneBy.mockResolvedValue(null);
|
||||
usersRepository.create.mockImplementation((data) => data);
|
||||
usersRepository.save.mockImplementation(async (entity) => ({
|
||||
id: 'new-admin',
|
||||
...entity,
|
||||
}));
|
||||
|
||||
const result = await service.createAdmin(dto as never, {
|
||||
id: 'admin-1',
|
||||
role: RoleType.ADMINISTRATEUR,
|
||||
} as never);
|
||||
|
||||
expect(result.role).toBe(RoleType.ADMINISTRATEUR);
|
||||
expect(result.statut).toBe(StatutUtilisateurType.ACTIF);
|
||||
expect(usersRepository.save).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('autorise un super_admin à créer un admin', async () => {
|
||||
usersRepository.findOneBy.mockResolvedValue(null);
|
||||
usersRepository.create.mockImplementation((data) => data);
|
||||
usersRepository.save.mockImplementation(async (entity) => ({
|
||||
id: 'new-admin',
|
||||
...entity,
|
||||
}));
|
||||
|
||||
await expect(
|
||||
service.createAdmin(dto as never, {
|
||||
id: 'sa-1',
|
||||
role: RoleType.SUPER_ADMIN,
|
||||
} as never),
|
||||
).resolves.toMatchObject({ role: RoleType.ADMINISTRATEUR });
|
||||
});
|
||||
|
||||
it('refuse un gestionnaire (403 métier)', async () => {
|
||||
await expect(
|
||||
service.createAdmin(dto as never, {
|
||||
id: 'gest-1',
|
||||
role: RoleType.GESTIONNAIRE,
|
||||
} as never),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(usersRepository.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuse un email déjà utilisé', async () => {
|
||||
usersRepository.findOneBy.mockResolvedValue({ id: 'exists' });
|
||||
await expect(
|
||||
service.createAdmin(dto as never, {
|
||||
id: 'admin-1',
|
||||
role: RoleType.ADMINISTRATEUR,
|
||||
} as never),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -117,8 +117,14 @@ export class UserService {
|
||||
}
|
||||
|
||||
async createAdmin(dto: CreateAdminDto, currentUser: Users): Promise<Users> {
|
||||
if (currentUser.role !== RoleType.SUPER_ADMIN) {
|
||||
throw new ForbiddenException('Seuls les super administrateurs peuvent créer un administrateur');
|
||||
// #161 — admin et super_admin peuvent créer un administrateur
|
||||
if (
|
||||
currentUser.role !== RoleType.SUPER_ADMIN &&
|
||||
currentUser.role !== RoleType.ADMINISTRATEUR
|
||||
) {
|
||||
throw new ForbiddenException(
|
||||
'Seuls les administrateurs et super administrateurs peuvent créer un administrateur',
|
||||
);
|
||||
}
|
||||
|
||||
const exist = await this.usersRepository.findOneBy({ email: dto.email });
|
||||
|
||||
@@ -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
|
||||
+101
-25
@@ -35,13 +35,20 @@ DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_avenant_type') THEN
|
||||
CREATE TYPE statut_avenant_type AS ENUM ('propose', 'accepte', 'refuse');
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_evenement_type') THEN
|
||||
CREATE TYPE type_evenement_type AS ENUM (
|
||||
'absence_enfant', 'conge_am', 'conge_parent', 'arret_maladie_am', 'evenement_rpe'
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_evenement_agenda_type') THEN
|
||||
CREATE TYPE type_evenement_agenda_type AS ENUM (
|
||||
'absence_enfant', 'conge_am', 'arret_maladie_am', 'soin_enfant'
|
||||
);
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_evenement_type') THEN
|
||||
CREATE TYPE statut_evenement_type AS ENUM ('propose', 'valide', 'refuse');
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_evenement_agenda_type') THEN
|
||||
CREATE TYPE statut_evenement_agenda_type AS ENUM (
|
||||
'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;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_validation_type') THEN
|
||||
CREATE TYPE statut_validation_type AS ENUM ('en_attente', 'valide', 'refuse');
|
||||
@@ -107,7 +114,8 @@ CREATE TABLE utilisateurs (
|
||||
ville VARCHAR(150),
|
||||
code_postal VARCHAR(10),
|
||||
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
|
||||
@@ -141,7 +149,10 @@ CREATE TABLE assistantes_maternelles (
|
||||
annee_experience SMALLINT,
|
||||
specialite VARCHAR(100),
|
||||
place_disponible INT,
|
||||
numero_dossier VARCHAR(20)
|
||||
numero_dossier VARCHAR(20),
|
||||
-- Préférence couple de garde actif (TdB quotidien AM) — ticket #171
|
||||
-- FK ajoutée après création de enfants_assistantes_maternelles (voir ALTER plus bas)
|
||||
id_placement_garde_courant UUID
|
||||
);
|
||||
|
||||
CREATE INDEX idx_assistantes_maternelles_numero_dossier
|
||||
@@ -154,7 +165,10 @@ CREATE INDEX idx_assistantes_maternelles_numero_dossier
|
||||
CREATE TABLE parents (
|
||||
id_utilisateur UUID PRIMARY KEY REFERENCES utilisateurs(id) ON DELETE CASCADE,
|
||||
id_co_parent UUID REFERENCES utilisateurs(id),
|
||||
numero_dossier VARCHAR(20)
|
||||
numero_dossier VARCHAR(20),
|
||||
-- Préférence couple de garde actif (TdB quotidien) — ticket #168
|
||||
-- FK ajoutée après création de enfants_assistantes_maternelles (voir ALTER plus bas)
|
||||
id_placement_garde_courant UUID
|
||||
);
|
||||
|
||||
CREATE INDEX idx_parents_numero_dossier
|
||||
@@ -174,8 +188,7 @@ CREATE TABLE enfants (
|
||||
date_prevue_naissance DATE,
|
||||
photo_url TEXT,
|
||||
consentement_photo BOOLEAN DEFAULT false,
|
||||
date_consentement_photo TIMESTAMPTZ,
|
||||
est_multiple BOOLEAN DEFAULT false
|
||||
date_consentement_photo TIMESTAMPTZ
|
||||
);
|
||||
|
||||
-- ==========================================================
|
||||
@@ -207,6 +220,26 @@ CREATE UNIQUE INDEX uq_enfant_garde_active
|
||||
ON enfants_assistantes_maternelles (id_enfant)
|
||||
WHERE date_fin IS NULL;
|
||||
|
||||
-- FK couple courant parent → placement (#168) — après table enfants_assistantes_maternelles
|
||||
ALTER TABLE parents
|
||||
ADD CONSTRAINT fk_parents_placement_garde_courant
|
||||
FOREIGN KEY (id_placement_garde_courant)
|
||||
REFERENCES enfants_assistantes_maternelles(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX idx_parents_placement_garde_courant
|
||||
ON parents(id_placement_garde_courant)
|
||||
WHERE id_placement_garde_courant IS NOT NULL;
|
||||
|
||||
-- FK couple courant AM → placement (#171)
|
||||
ALTER TABLE assistantes_maternelles
|
||||
ADD CONSTRAINT fk_am_placement_garde_courant
|
||||
FOREIGN KEY (id_placement_garde_courant)
|
||||
REFERENCES enfants_assistantes_maternelles(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX idx_am_placement_garde_courant
|
||||
ON assistantes_maternelles(id_placement_garde_courant)
|
||||
WHERE id_placement_garde_courant IS NOT NULL;
|
||||
|
||||
-- ==========================================================
|
||||
-- Table : dossier_famille (inscription parent — ticket #119)
|
||||
-- ==========================================================
|
||||
@@ -295,25 +328,68 @@ CREATE TABLE avenants_contrats (
|
||||
);
|
||||
|
||||
-- ==========================================================
|
||||
-- Table : evenements
|
||||
-- Table : agenda_lots (cycles collectifs versionnés — #214)
|
||||
-- ==========================================================
|
||||
CREATE TABLE evenements (
|
||||
CREATE TABLE agenda_lots (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
type type_evenement_type,
|
||||
id_enfant UUID REFERENCES enfants(id) ON DELETE CASCADE,
|
||||
id_am UUID REFERENCES utilisateurs(id),
|
||||
id_parent UUID REFERENCES parents(id_utilisateur),
|
||||
cree_par UUID REFERENCES utilisateurs(id),
|
||||
date_debut TIMESTAMPTZ,
|
||||
date_fin TIMESTAMPTZ,
|
||||
commentaires TEXT,
|
||||
statut statut_evenement_type DEFAULT 'propose',
|
||||
delai_grace TIMESTAMPTZ,
|
||||
urgent BOOLEAN DEFAULT false,
|
||||
cree_le TIMESTAMPTZ DEFAULT now(),
|
||||
modifie_le TIMESTAMPTZ DEFAULT now()
|
||||
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_placement UUID NOT NULL
|
||||
REFERENCES enfants_assistantes_maternelles(id) ON DELETE CASCADE,
|
||||
type type_evenement_agenda_type NOT NULL,
|
||||
date_debut DATE NOT NULL,
|
||||
date_fin DATE NOT NULL,
|
||||
statut statut_evenement_agenda_type NOT NULL DEFAULT 'en_attente',
|
||||
expire_at TIMESTAMPTZ NOT NULL,
|
||||
cree_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
||||
id_card_instance UUID,
|
||||
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(),
|
||||
modifie_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
CONSTRAINT chk_evenements_agenda_dates CHECK (date_fin >= date_debut)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_evenements_agenda_placement_dates
|
||||
ON evenements_agenda (id_placement, date_debut, date_fin);
|
||||
CREATE INDEX idx_evenements_agenda_placement_type_statut
|
||||
ON evenements_agenda (id_placement, type, statut);
|
||||
CREATE INDEX idx_evenements_agenda_expire_at
|
||||
ON evenements_agenda (expire_at)
|
||||
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
|
||||
-- ==========================================================
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"id","statut","prenom","nom","genre","date_naissance","date_prevue_naissance","photo_url","consentement_photo","date_consentement_photo","est_multiple"
|
||||
"5e8574b7-63e6-4d48-9af3-8d3bf7a6a6cf","sans_garde","Emma","Dupont","F","2020-06-01",,,False,,False
|
||||
"a5c3268e-07eb-41a4-9f6c-2f9f16f37c3d","sans_garde",,,,"2020-01-01","2025-01-01",,False,,False
|
||||
"e1a2b3c4-d5e6-4f7a-8b9c-1d2e3f4a5b6c","sans_garde","Emma","Martin",,"2023-02-15",,,False,,False
|
||||
"e2b3c4d5-e6f7-4a8b-9c1d-2e3f4a5b6c7d","sans_garde","Noah","Martin",,"2023-02-15",,,False,,False
|
||||
"e3c4d5e6-f7a8-4b9c-1d2e-3f4a5b6c7d8e","sans_garde","Léa","Martin",,"2023-02-15",,,False,,False
|
||||
"e4d5e6f7-a8b9-4c1d-2e3f-4a5b6c7d8e9f","sans_garde","Chloé","Rousseau",,"2022-04-20",,,False,,False
|
||||
"e5e6f7a8-b9c1-4d2e-3f4a-5b6c7d8e9f1a","sans_garde","Hugo","Rousseau",,"2024-03-10",,,False,,False
|
||||
"e6f7a8b9-c1d2-4e3f-5a6b-7c8d9e0f1a2b","sans_garde","Maxime","Lecomte",,"2023-04-15",,,False,,False
|
||||
"edd19cd1-bb67-4f14-8a37-c66b75c94537","scolarise","Lucas","Durand","H","2018-09-15",,,False,,False
|
||||
"id","statut","prenom","nom","genre","date_naissance","date_prevue_naissance","photo_url","consentement_photo","date_consentement_photo"
|
||||
"5e8574b7-63e6-4d48-9af3-8d3bf7a6a6cf","sans_garde","Emma","Dupont","F","2020-06-01",,,False,
|
||||
"a5c3268e-07eb-41a4-9f6c-2f9f16f37c3d","sans_garde",,,,"2020-01-01","2025-01-01",,False,
|
||||
"e1a2b3c4-d5e6-4f7a-8b9c-1d2e3f4a5b6c","sans_garde","Emma","Martin",,"2023-02-15",,,False,
|
||||
"e2b3c4d5-e6f7-4a8b-9c1d-2e3f4a5b6c7d","sans_garde","Noah","Martin",,"2023-02-15",,,False,
|
||||
"e3c4d5e6-f7a8-4b9c-1d2e-3f4a5b6c7d8e","sans_garde","Léa","Martin",,"2023-02-15",,,False,
|
||||
"e4d5e6f7-a8b9-4c1d-2e3f-4a5b6c7d8e9f","sans_garde","Chloé","Rousseau",,"2022-04-20",,,False,
|
||||
"e5e6f7a8-b9c1-4d2e-3f4a-5b6c7d8e9f1a","sans_garde","Hugo","Rousseau",,"2024-03-10",,,False,
|
||||
"e6f7a8b9-c1d2-4e3f-5a6b-7c8d9e0f1a2b","sans_garde","Maxime","Lecomte",,"2023-04-15",,,False,
|
||||
"edd19cd1-bb67-4f14-8a37-c66b75c94537","scolarise","Lucas","Durand","H","2018-09-15",,,False,
|
||||
|
||||
|
+25
-10
@@ -104,31 +104,46 @@ Ce document recense **toutes les valeurs énumérées** utilisées dans la base
|
||||
|
||||
---
|
||||
|
||||
## 7) Type d’événement — `type`
|
||||
## 7) Type d’absence de garde — `type`
|
||||
|
||||
**Tables/colonnes** : `evenements.type`
|
||||
**Tables/colonnes** : `evenements_agenda.type`
|
||||
**Valeurs autorisées** :
|
||||
|
||||
| Valeur | Description |
|
||||
|---|---|
|
||||
| `absence_enfant` | Enfant absent |
|
||||
| `absence_enfant` | Absence déclarée par un parent |
|
||||
| `conge_am` | Congé de l’assistante maternelle |
|
||||
| `conge_parent` | Congé du parent |
|
||||
| `arret_maladie_am` | Arrêt maladie AM |
|
||||
| `evenement_rpe` | Événement RPE |
|
||||
|
||||
> Remplace l’ancien enum `type_evenement_type` / table `evenements` (supprimés ticket #205 / ex-#193).
|
||||
|
||||
---
|
||||
|
||||
## 8) Statut d’événement — `statut`
|
||||
## 8) Statut d’événement agenda — `statut`
|
||||
|
||||
**Tables/colonnes** : `evenements.statut`
|
||||
**Tables/colonnes** : `evenements_agenda.statut`
|
||||
**Valeurs autorisées** :
|
||||
|
||||
| Valeur | Description |
|
||||
|---|---|
|
||||
| `propose` | Événement proposé |
|
||||
| `valide` | Événement validé |
|
||||
| `rejete` | Événement refusé |
|
||||
| `en_attente` | En attente de validation / ack |
|
||||
| `accepte` | Accepté / acté (conservé en historique métier) |
|
||||
| `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,10 +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é |
|
||||
| **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 |
|
||||
| **evenements(id_enfant)** → `enfants(id)` | **CASCADE** | Événements n’ont plus de sens |
|
||||
| **evenements(id_am)** → `utilisateurs(id)` | **SET NULL** | Garder la trace même si AM supprimée |
|
||||
| **evenements(id_parent)** → `parents(id_utilisateur)` | **SET NULL** | Garder la trace si parent supprimé |
|
||||
| **evenements(cree_par)** → `utilisateurs(id)` | **SET NULL** | Conserver l’historique de création |
|
||||
| **evenements_agenda(id_placement)** → `enfants_assistantes_maternelles(id)` | **CASCADE** | Plus de couple = plus d’absences |
|
||||
| **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é |
|
||||
| **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 |
|
||||
@@ -79,10 +77,8 @@ Documenter, de façon unique et partagée, les règles de suppression/mise à jo
|
||||
- `avenants_contrats.initie_par` → **SET NULL**
|
||||
|
||||
### Événements
|
||||
- `evenements.id_enfant` → **CASCADE**
|
||||
- `evenements.id_am` → **SET NULL**
|
||||
- `evenements.id_parent` → **SET NULL**
|
||||
- `evenements.cree_par` → **SET NULL**
|
||||
- `evenements_agenda.id_placement` → **CASCADE**
|
||||
- `evenements_agenda.cree_par` → **SET NULL**
|
||||
|
||||
### Divers
|
||||
- `signalements_bugs.id_utilisateur` → **SET NULL**
|
||||
@@ -109,11 +105,11 @@ Documenter, de façon unique et partagée, les règles de suppression/mise à jo
|
||||
|
||||
4. **Suppression d’un enfant**
|
||||
- Supprimer `enfants(id=childA)`
|
||||
- Attendu : `enfants_parents` (CASCADE), `dossiers` du childA (CASCADE), `evenements` du childA (CASCADE).
|
||||
- Attendu : `enfants_parents` (CASCADE), `dossiers` du childA (CASCADE), `evenements_agenda` des placements du childA (CASCADE via EAM).
|
||||
|
||||
5. **Suppression d’un utilisateur AM**
|
||||
- Supprimer `utilisateurs(id=amB)`
|
||||
- Attendu : `evenements.id_am` devient **NULL** (historique conservé).
|
||||
- Attendu : absences liées via placement AM (CASCADE si le lien EAM est retiré).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
-- Ticket #193 — Back métier absences / congés / arrêt (périodes par placement)
|
||||
-- Idempotent : safe à rejouer.
|
||||
-- Remplace la table legacy `evenements` (mal conçue, non utilisée en API).
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Enums
|
||||
-- ---------------------------------------------------------------------------
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_absence_garde_type') THEN
|
||||
CREATE TYPE type_absence_garde_type AS ENUM (
|
||||
'absence_enfant',
|
||||
'conge_am',
|
||||
'arret_maladie_am'
|
||||
);
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_absence_garde_type') THEN
|
||||
CREATE TYPE statut_absence_garde_type AS ENUM (
|
||||
'en_attente',
|
||||
'accepte',
|
||||
'refuse'
|
||||
);
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Table absences_garde (1 ligne = 1 période)
|
||||
-- ---------------------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS absences_garde (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
id_placement UUID NOT NULL
|
||||
REFERENCES enfants_assistantes_maternelles(id) ON DELETE CASCADE,
|
||||
type type_absence_garde_type NOT NULL,
|
||||
date_debut DATE NOT NULL,
|
||||
date_fin DATE NOT NULL,
|
||||
statut statut_absence_garde_type NOT NULL DEFAULT 'en_attente',
|
||||
-- TTL purge : obligatoire ; pour statut=accepte utiliser 'infinity' (pas de purge métier)
|
||||
expire_at TIMESTAMPTZ NOT NULL,
|
||||
cree_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
||||
id_card_instance UUID NULL,
|
||||
motif TEXT,
|
||||
cree_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
modifie_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
CONSTRAINT chk_absences_garde_dates CHECK (date_fin >= date_debut)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_absences_garde_placement_dates
|
||||
ON absences_garde (id_placement, date_debut, date_fin);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_absences_garde_placement_type_statut
|
||||
ON absences_garde (id_placement, type, statut);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_absences_garde_expire_at
|
||||
ON absences_garde (expire_at)
|
||||
WHERE statut IN ('en_attente', 'refuse');
|
||||
|
||||
COMMENT ON TABLE absences_garde IS
|
||||
'Vérité métier des absences/congés/arrêts par couple AM↔enfant (placement). Les cartes collectent ; cette table stocke.';
|
||||
COMMENT ON COLUMN absences_garde.expire_at IS
|
||||
'Purge auto (job ultérieur) pour en_attente/refuse. accepte → infinity.';
|
||||
COMMENT ON COLUMN absences_garde.id_card_instance IS
|
||||
'Réf. carte de collecte (FK cards quand le module Cartes existera).';
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Drop legacy evenements (+ enums si plus référencés)
|
||||
-- ---------------------------------------------------------------------------
|
||||
DROP TABLE IF EXISTS evenements CASCADE;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM pg_type WHERE typname = 'type_evenement_type')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE udt_name = 'type_evenement_type'
|
||||
) THEN
|
||||
DROP TYPE type_evenement_type;
|
||||
END IF;
|
||||
IF EXISTS (SELECT 1 FROM pg_type WHERE typname = 'statut_evenement_type')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE udt_name = 'statut_evenement_type'
|
||||
) THEN
|
||||
DROP TYPE statut_evenement_type;
|
||||
END IF;
|
||||
END $$;
|
||||
@@ -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';
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Ticket #171 — Couple de garde courant (préférence AM)
|
||||
-- Idempotent : safe à rejouer.
|
||||
|
||||
ALTER TABLE assistantes_maternelles
|
||||
ADD COLUMN IF NOT EXISTS id_placement_garde_courant UUID
|
||||
REFERENCES enfants_assistantes_maternelles(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_am_placement_garde_courant
|
||||
ON assistantes_maternelles(id_placement_garde_courant)
|
||||
WHERE id_placement_garde_courant IS NOT NULL;
|
||||
@@ -0,0 +1,128 @@
|
||||
-- Ticket #194 — Module Cartes SYSTEM (collecte absences/congés/arrêt)
|
||||
-- Idempotent.
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'card_response_mode_type') THEN
|
||||
CREATE TYPE card_response_mode_type AS ENUM (
|
||||
'none', 'ack', 'accept_refuse'
|
||||
);
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'card_instance_statut_type') THEN
|
||||
CREATE TYPE card_instance_statut_type AS ENUM (
|
||||
'ouverte', 'refusee', 'traitee'
|
||||
);
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'card_operation_type') THEN
|
||||
CREATE TYPE card_operation_type AS ENUM ('create', 'update');
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'card_response_action_type') THEN
|
||||
CREATE TYPE card_response_action_type AS ENUM (
|
||||
'accept', 'refuse', 'ack'
|
||||
);
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS card_types (
|
||||
code VARCHAR(64) PRIMARY KEY,
|
||||
system BOOLEAN NOT NULL DEFAULT true,
|
||||
titre VARCHAR(120) NOT NULL,
|
||||
emitter_roles TEXT[] NOT NULL,
|
||||
recipient_roles TEXT[] NOT NULL,
|
||||
audience_resolver VARCHAR(64) NOT NULL,
|
||||
response_mode card_response_mode_type NOT NULL,
|
||||
retention_days INT NOT NULL DEFAULT 14,
|
||||
couleur VARCHAR(32),
|
||||
cree_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
modifie_le TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS card_instances (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
type_code VARCHAR(64) NOT NULL REFERENCES card_types(code),
|
||||
id_placement UUID NOT NULL
|
||||
REFERENCES enfants_assistantes_maternelles(id) ON DELETE CASCADE,
|
||||
id_absence UUID REFERENCES absences_garde(id) ON DELETE SET NULL,
|
||||
cree_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL,
|
||||
operation card_operation_type NOT NULL DEFAULT 'create',
|
||||
statut card_instance_statut_type NOT NULL DEFAULT 'ouverte',
|
||||
payload JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
purge_at TIMESTAMPTZ NOT NULL,
|
||||
cree_le TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
modifie_le TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_card_instances_placement
|
||||
ON card_instances (id_placement, statut, cree_le DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_card_instances_purge
|
||||
ON card_instances (purge_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_card_instances_absence
|
||||
ON card_instances (id_absence)
|
||||
WHERE id_absence IS NOT NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS card_audience_members (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
id_card UUID NOT NULL REFERENCES card_instances(id) ON DELETE CASCADE,
|
||||
id_utilisateur UUID NOT NULL REFERENCES utilisateurs(id) ON DELETE CASCADE,
|
||||
role_snapshot VARCHAR(64) NOT NULL,
|
||||
is_creator BOOLEAN NOT NULL DEFAULT false,
|
||||
UNIQUE (id_card, id_utilisateur)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_card_audience_user
|
||||
ON card_audience_members (id_utilisateur, id_card);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS card_responses (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
id_card UUID NOT NULL REFERENCES card_instances(id) ON DELETE CASCADE,
|
||||
id_utilisateur UUID NOT NULL REFERENCES utilisateurs(id) ON DELETE CASCADE,
|
||||
action card_response_action_type NOT NULL,
|
||||
comment TEXT,
|
||||
cree_le TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_card_responses_card
|
||||
ON card_responses (id_card, cree_le DESC);
|
||||
|
||||
-- Seeds SYSTEM
|
||||
INSERT INTO card_types (
|
||||
code, system, titre, emitter_roles, recipient_roles,
|
||||
audience_resolver, response_mode, retention_days, couleur
|
||||
) VALUES
|
||||
(
|
||||
'absence_enfant', true, 'Absence enfant',
|
||||
ARRAY['parent'], ARRAY['assistante_maternelle'],
|
||||
'couple_am', 'none', 7, 'peach'
|
||||
),
|
||||
(
|
||||
'absence_enfant_modif', true, 'Absence enfant modifiée',
|
||||
ARRAY['parent'], ARRAY['assistante_maternelle'],
|
||||
'couple_am', 'ack', 7, 'peach'
|
||||
),
|
||||
(
|
||||
'conge_am', true, 'Congé AM',
|
||||
ARRAY['assistante_maternelle'], ARRAY['parent'],
|
||||
'couple_parents', 'accept_refuse', 14, 'lavender'
|
||||
),
|
||||
(
|
||||
'arret_maladie_am', true, 'Arrêt maladie AM',
|
||||
ARRAY['assistante_maternelle'], ARRAY['parent'],
|
||||
'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
|
||||
titre = EXCLUDED.titre,
|
||||
emitter_roles = EXCLUDED.emitter_roles,
|
||||
recipient_roles = EXCLUDED.recipient_roles,
|
||||
audience_resolver = EXCLUDED.audience_resolver,
|
||||
response_mode = EXCLUDED.response_mode,
|
||||
retention_days = EXCLUDED.retention_days,
|
||||
couleur = EXCLUDED.couleur,
|
||||
modifie_le = now();
|
||||
|
||||
COMMENT ON TABLE card_types IS 'Catalogue types de cartes (SYSTEM seeds #194 ; OPTIONNEL plus tard).';
|
||||
COMMENT ON TABLE card_instances IS 'Bulles / file d’attention — collecte, pas vérité métier absences.';
|
||||
@@ -0,0 +1,2 @@
|
||||
-- #152 — Suppression grossesse multiple / est_multiple
|
||||
ALTER TABLE enfants DROP COLUMN IF EXISTS est_multiple;
|
||||
@@ -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,10 @@
|
||||
-- Ticket #168 — Couple de garde courant (préférence parent)
|
||||
-- Idempotent : safe à rejouer.
|
||||
|
||||
ALTER TABLE parents
|
||||
ADD COLUMN IF NOT EXISTS id_placement_garde_courant UUID
|
||||
REFERENCES enfants_assistantes_maternelles(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_parents_placement_garde_courant
|
||||
ON parents(id_placement_garde_courant)
|
||||
WHERE id_placement_garde_courant IS NOT NULL;
|
||||
@@ -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';
|
||||
@@ -69,12 +69,12 @@ ON CONFLICT (id_utilisateur) DO NOTHING;
|
||||
-- - child B : à naître (statut = 'a_naitre' et date_prevue_naissance requise)
|
||||
-- ------------------------------------------------------------
|
||||
|
||||
INSERT INTO enfants (id, prenom, nom, statut, date_naissance, jumeau_multiple)
|
||||
VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Léo', 'Parent', 'sans_garde', '2022-04-12', false)
|
||||
INSERT INTO enfants (id, prenom, nom, statut, date_naissance)
|
||||
VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Léo', 'Parent', 'sans_garde', '2022-04-12')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
INSERT INTO enfants (id, prenom, nom, statut, date_prevue_naissance, jumeau_multiple)
|
||||
VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Mila', 'Parent', 'a_naitre', '2026-02-15', false)
|
||||
INSERT INTO enfants (id, prenom, nom, statut, date_prevue_naissance)
|
||||
VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Mila', 'Parent', 'a_naitre', '2026-02-15')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
@@ -161,23 +161,9 @@ VALUES (
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- Événement (absence enfant)
|
||||
-- Absences_garde : seeds quand placements EAM présents (API / ticket peuplement)
|
||||
-- Legacy evenements supprimée (#193).
|
||||
-- ------------------------------------------------------------
|
||||
INSERT INTO evenements (id, type, id_enfant, id_am, id_parent, cree_par, date_debut, date_fin, commentaires, statut, urgence)
|
||||
VALUES (
|
||||
'e0000000-0000-0000-0000-000000000001',
|
||||
'absence_enfant',
|
||||
'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
|
||||
'66666666-6666-6666-6666-666666666666',
|
||||
'33333333-3333-3333-3333-333333333333',
|
||||
'33333333-3333-3333-3333-333333333333',
|
||||
'2025-09-12',
|
||||
'2025-09-12',
|
||||
'Enfant malade (rhume).',
|
||||
'propose',
|
||||
false
|
||||
)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- Upload (justificatif lié au dossier)
|
||||
|
||||
@@ -49,14 +49,14 @@ VALUES
|
||||
ON CONFLICT (id_utilisateur) DO NOTHING;
|
||||
|
||||
-- ========== ENFANTS ==========
|
||||
INSERT INTO enfants (id, prenom, nom, genre, date_naissance, statut, est_multiple)
|
||||
INSERT INTO enfants (id, prenom, nom, genre, date_naissance, statut)
|
||||
VALUES
|
||||
('e0000001-0001-0001-0001-000000000001', 'Emma', 'MARTIN', 'F', '2023-02-15', 'sans_garde', true),
|
||||
('e0000002-0002-0002-0002-000000000002', 'Noah', 'MARTIN', 'H', '2023-02-15', 'sans_garde', true),
|
||||
('e0000003-0003-0003-0003-000000000003', 'Léa', 'MARTIN', 'F', '2023-02-15', 'sans_garde', true),
|
||||
('e0000004-0004-0004-0004-000000000004', 'Chloé', 'ROUSSEAU', 'F', '2022-04-20', 'sans_garde', false),
|
||||
('e0000005-0005-0005-0005-000000000005', 'Hugo', 'ROUSSEAU', 'H', '2024-03-10', 'sans_garde', false),
|
||||
('e0000006-0006-0006-0006-000000000006', 'Maxime', 'LECOMTE', 'H', '2023-04-15', 'sans_garde', false)
|
||||
('e0000001-0001-0001-0001-000000000001', 'Emma', 'MARTIN', 'F', '2023-02-15', 'sans_garde'),
|
||||
('e0000002-0002-0002-0002-000000000002', 'Noah', 'MARTIN', 'H', '2023-02-15', 'sans_garde'),
|
||||
('e0000003-0003-0003-0003-000000000003', 'Léa', 'MARTIN', 'F', '2023-02-15', 'sans_garde'),
|
||||
('e0000004-0004-0004-0004-000000000004', 'Chloé', 'ROUSSEAU', 'F', '2022-04-20', 'sans_garde'),
|
||||
('e0000005-0005-0005-0005-000000000005', 'Hugo', 'ROUSSEAU', 'H', '2024-03-10', 'sans_garde'),
|
||||
('e0000006-0006-0006-0006-000000000006', 'Maxime', 'LECOMTE', 'H', '2023-04-15', 'sans_garde')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========== ENFANTS_PARENTS (liaison N:N) ==========
|
||||
|
||||
@@ -79,12 +79,41 @@ LEFT JOIN avenants_contrats a ON a.id_contrat = c.id
|
||||
GROUP BY c.id, c.id_dossier, c.statut
|
||||
ORDER BY c.cree_le DESC;
|
||||
|
||||
\echo '=== 9) Evénements par enfant (30 derniers jours) =============='
|
||||
SELECT ev.id, ev.type, ev.id_enfant, e.prenom AS enfant, ev.date_debut, ev.date_fin, ev.statut
|
||||
FROM evenements ev
|
||||
JOIN enfants e ON e.id = ev.id_enfant
|
||||
WHERE ev.date_debut >= (NOW()::date - INTERVAL '30 days')
|
||||
ORDER BY ev.date_debut DESC;
|
||||
\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.id_lot, ag.heure, ag.verrouille_le, ag.expire_at
|
||||
FROM evenements_agenda ag
|
||||
WHERE ag.date_debut >= (NOW()::date - INTERVAL '30 days')
|
||||
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 ======================='
|
||||
SELECT u.courriel, up.fichier_url, up.type_fichier, up.cree_le
|
||||
@@ -135,11 +164,11 @@ FROM avenants_contrats a
|
||||
LEFT JOIN contrats c ON c.id = a.id_contrat
|
||||
WHERE c.id IS NULL;
|
||||
|
||||
-- Evénements sans enfant
|
||||
SELECT ev.*
|
||||
FROM evenements ev
|
||||
LEFT JOIN enfants e ON e.id = ev.id_enfant
|
||||
WHERE e.id IS NULL;
|
||||
-- Absences sans placement
|
||||
SELECT ag.*
|
||||
FROM evenements_agenda ag
|
||||
LEFT JOIN enfants_assistantes_maternelles eam ON eam.id = ag.id_placement
|
||||
WHERE eam.id IS NULL;
|
||||
|
||||
\echo '=== 13) Performance : EXPLAIN sur requêtes clés ==============='
|
||||
|
||||
@@ -151,12 +180,12 @@ WHERE m.id_dossier = 'dddddddd-dddd-dddd-dddd-dddddddddddd'
|
||||
ORDER BY m.cree_le DESC
|
||||
LIMIT 20;
|
||||
|
||||
-- Evénements par enfant et période (idx_evenements_id_enfant_date_debut)
|
||||
-- Absences par placement et période (idx_evenements_agenda_placement_dates)
|
||||
EXPLAIN ANALYZE
|
||||
SELECT ev.*
|
||||
FROM evenements ev
|
||||
WHERE ev.id_enfant = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
|
||||
AND ev.date_debut >= '2025-01-01';
|
||||
SELECT ag.*
|
||||
FROM evenements_agenda ag
|
||||
WHERE ag.id_placement IS NOT NULL
|
||||
AND ag.date_debut >= '2025-01-01';
|
||||
|
||||
-- Notifications non lues (idx_notifications_user_lu_cree_le)
|
||||
EXPLAIN ANALYZE
|
||||
@@ -199,7 +228,7 @@ SELECT
|
||||
(SELECT COUNT(*) FROM messages) AS nb_messages,
|
||||
(SELECT COUNT(*) FROM contrats) AS nb_contrats,
|
||||
(SELECT COUNT(*) FROM avenants_contrats) AS nb_avenants,
|
||||
(SELECT COUNT(*) FROM evenements) AS nb_evenements,
|
||||
(SELECT COUNT(*) FROM evenements_agenda) AS nb_evenements_agenda,
|
||||
(SELECT COUNT(*) FROM uploads) AS nb_uploads,
|
||||
(SELECT COUNT(*) FROM notifications) AS nb_notifications,
|
||||
(SELECT COUNT(*) FROM validations) AS nb_validations;
|
||||
|
||||
+3
-1
@@ -14,10 +14,12 @@ services:
|
||||
networks:
|
||||
- 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:
|
||||
image: dpage/pgadmin4
|
||||
container_name: ptitspas-pgadmin
|
||||
profiles: ["tools"]
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
|
||||
|
||||
+63
-70
@@ -1,94 +1,87 @@
|
||||
# 📚 Index de la Documentation - PtitsPas App
|
||||
# Index de la documentation — P'titsPas
|
||||
|
||||
Bienvenue dans la documentation complète de l'application PtitsPas.
|
||||
Index de navigation du dépôt. Dernière révision : **septembre 2026** (CDC V1.4 + SRS users #117).
|
||||
|
||||
Ce fichier sert d'index pour naviguer dans toute la documentation du projet.
|
||||
## Produit & versions
|
||||
|
||||
## 📖 Table des matières
|
||||
| Doc | Contenu |
|
||||
|-----|---------|
|
||||
| [01 — Cahier des charges V1.4](./01_CAHIER-DES-CHARGES.md) | CDC **complet** (cible) ; gestion utilisateurs alignée `v0.1.0` |
|
||||
| [12 — SRS gestion utilisateurs](./12_SRS-GESTION-UTILISATEURS.md) | Spécification **technique** du domaine users / dossiers |
|
||||
| [05 — Versions & milestones](./05_VERSIONS-ET-MILESTONES.md) | Semver Gitea + bilans |
|
||||
| [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 |
|
||||
| [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 |
|
||||
| [28 — Évolution famille / responsables](./28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md) | Limites modèle foyer / contournements |
|
||||
|
||||
### 📋 Cahier des Charges
|
||||
- [**01 - Cahier des Charges**](./01_CAHIER-DES-CHARGES.md) - Cahier des charges complet du projet P'titsPas (V1.3 - 24/11/2025)
|
||||
## Architecture & infra
|
||||
|
||||
### Architecture & Infrastructure
|
||||
- [**02 - Architecture**](./02_ARCHITECTURE.md) - Vue d'ensemble de l'architecture mono-repo et multi-conteneurs
|
||||
- [**03 - Déploiement**](./03_DEPLOYMENT.md) - Guide complet de déploiement et configuration CI/CD
|
||||
| Doc | Contenu |
|
||||
|-----|---------|
|
||||
| [02 — Architecture](./02_ARCHITECTURE.md) | Mono-repo, conteneurs |
|
||||
| [03 — Déploiement](./03_DEPLOYMENT.md) | Deploy / CI-CD |
|
||||
| [10 — Database](./10_DATABASE.md) | Schéma BDD |
|
||||
| [11 — API](./11_API.md) | Endpoints REST |
|
||||
| [21 — Configuration système](./21_CONFIGURATION-SYSTEME.md) | Config on-premise |
|
||||
| [99 — Règles de codage](./99_REGLES-CODAGE.md) | Conventions |
|
||||
|
||||
### Planification
|
||||
- [**04 - Roadmap Générale**](./04_ROADMAP-GENERALE.md) - Roadmap complète du projet (Phases 1 à 5+)
|
||||
## Workflows & métier
|
||||
|
||||
### Développement
|
||||
- [**10 - Database Schema**](./10_DATABASE.md) - Schéma de la base de données et modèles
|
||||
- [**11 - API Documentation**](./11_API.md) - Documentation complète des endpoints REST
|
||||
- [**14 - Note backend config setup**](./14_NOTE-BACKEND-CONFIG-SETUP.md) - Setup configuration
|
||||
- [**92 - Note backend gestionnaires**](./92_NOTE-BACKEND-GESTIONNAIRES.md) - Gestionnaires
|
||||
- [**99 - Règles de codage**](./99_REGLES-CODAGE.md) - Conventions de code
|
||||
| Doc | Contenu |
|
||||
|-----|---------|
|
||||
| [20 — Workflow création de compte](./20_WORKFLOW-CREATION-COMPTE.md) | Inscription / validation (détail historique) |
|
||||
| [juridique/](./juridique/README.md) | CGU / CGC / privacy + [22 technique](./juridique/22_DOCUMENTS-LEGAUX.md) |
|
||||
|
||||
### Workflows Fonctionnels
|
||||
- [**20 - Workflow Création de Compte**](./20_WORKFLOW-CREATION-COMPTE.md) - Workflow complet de création et validation des comptes utilisateurs
|
||||
- [**21 - Configuration Système**](./21_CONFIGURATION-SYSTEME.md) - Configuration on-premise dynamique
|
||||
- [**22 - Documents Légaux**](./juridique/22_DOCUMENTS-LEGAUX.md) - Gestion CGU/Privacy avec versioning
|
||||
## Charte & maquettes
|
||||
|
||||
### Juridique (sources & technique)
|
||||
- [**Dossier juridique**](./juridique/README.md) - Index : CGU/CGC en Markdown,
|
||||
export PDF, lien vers la doc technique n°22
|
||||
| Doc | Contenu |
|
||||
|-----|---------|
|
||||
| [CHARTE_GRAPHIQUE.md](./CHARTE_GRAPHIQUE.md) | Charte UI |
|
||||
| [maquettes/](./maquettes/README.md) | Maquettes TdB quotidien + Agenda semaine (réf. v4) |
|
||||
|
||||
### Projet & suivi (Gitea / tickets)
|
||||
- [**23 - Liste des Tickets**](./23_LISTE-TICKETS.md) - 61 tickets Phase 1 détaillés
|
||||
- [**24 - Décisions Projet**](./24_DECISIONS-PROJET.md) - Décisions architecturales et fonctionnelles
|
||||
- [**25 - Backlog Phase 2**](./25_PHASE-2-BACKLOG.md) - Fonctionnalités techniques reportées
|
||||
- [**28 - Évolution famille et responsables**](./28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md) - Modèle dossier/famille, recompositions, v1.0.0 vs post-1.0.0
|
||||
- [**26 - API Gitea**](./26_GITEA-API.md) - Procédure d'utilisation de l'API Gitea (issues, PR, branches, labels)
|
||||
- [**27 - Briefing frontend**](./27_BRIEFING-FRONTEND.md) - Accès Git, priorités, scripts Gitea (token)
|
||||
## Projet & outillage
|
||||
|
||||
### Archive & convention de nommage
|
||||
- [**Dossier archive**](./archive/README.md) - Fichiers **sans** `NN_` déplacés
|
||||
(temporaires, obsolètes) ; règles de rangement et suppression
|
||||
- Pointeur : [PROCEDURE-API-GITEA.md](./PROCEDURE-API-GITEA.md) → voir **26**
|
||||
| Doc | Contenu |
|
||||
|-----|---------|
|
||||
| [23 — Suivi tickets](./23_SUIVI-TICKETS.md) | Pointeur Gitea |
|
||||
| [24 — Décisions projet](./24_DECISIONS-PROJET.md) | ADR / décisions |
|
||||
| [26 — API Gitea](./26_GITEA-API.md) | Issues, PR, milestones |
|
||||
| [27 — Briefing frontend](./27_BRIEFING-FRONTEND.md) | Accès Git, priorités |
|
||||
|
||||
### Exceptions de nommage (racine `docs/`)
|
||||
Fichiers **sans préfixe numérique** encore à la racine par **héritage** ou
|
||||
références outils (`.cursorrules`, etc.) — **à renommer** en `NN_` quand
|
||||
possible :
|
||||
- `CHARTE_GRAPHIQUE.md`
|
||||
- [`EVOLUTIONS_CDC.md`](./EVOLUTIONS_CDC.md) — écarts CDC / app ; voir aussi [**28 - Évolution famille**](./28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md)
|
||||
- `SuperNounou_Cahier_Des_Charges_Complet_V1.1.md`
|
||||
- `SuperNounou_SSS-001.md`
|
||||
## Audit
|
||||
|
||||
### Administration (À créer)
|
||||
- [**30 - Guide d'administration**](./30_ADMIN.md) - Gestion des utilisateurs, accès PgAdmin, logs
|
||||
- [**31 - Troubleshooting**](./31_TROUBLESHOOTING.md) - Résolution des problèmes courants
|
||||
| Doc | Contenu |
|
||||
|-----|---------|
|
||||
| [90 — Audit YNOV](./90_AUDIT.md) | Analyse code étudiant |
|
||||
|
||||
### Frontend (À créer)
|
||||
- [**40 - Frontend Flutter**](./40_FRONTEND.md) - Structure de l'application mobile/web
|
||||
## Archive
|
||||
|
||||
### Audit & Analyse
|
||||
- [**90 - Audit du projet YNOV**](./90_AUDIT.md) - Analyse complète du code étudiant et fonctionnalités
|
||||
| Emplacement | Usage |
|
||||
|-------------|--------|
|
||||
| [archive/](./archive/README.md) | Obsolete / temporaires |
|
||||
| [archive/obsolete/](./archive/obsolete/) | CDC V1.3, EVOLUTIONS_CDC, SuperNounou, listes figées |
|
||||
|
||||
## 🚀 Quick Start
|
||||
## Données de test
|
||||
|
||||
| Doc | Contenu |
|
||||
|-----|---------|
|
||||
| [test-data/](./test-data/README.md) | Jeux utilisateurs test |
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
# Cloner le projet
|
||||
git clone ssh://gitea-jmartin/jmartin/app.git ptitspas-app
|
||||
|
||||
# Lancer l'environnement de développement
|
||||
git clone … ptitspas-app
|
||||
cd ptitspas-app
|
||||
docker compose up -d
|
||||
|
||||
# Accéder aux services
|
||||
Frontend: https://app.ptits-pas.fr
|
||||
API: https://app.ptits-pas.fr/api
|
||||
PgAdmin: https://app.ptits-pas.fr/pgadmin
|
||||
# Front https://app.ptits-pas.fr — API /api — PgAdmin /pgadmin
|
||||
```
|
||||
|
||||
## 🔗 Liens utiles
|
||||
## Liens
|
||||
|
||||
- **Gitea** : https://git.ptits-pas.fr
|
||||
- **Production** : https://app.ptits-pas.fr
|
||||
- **Mail** : https://mail.ptits-pas.fr
|
||||
|
||||
## 📝 Maintenance
|
||||
|
||||
Cette documentation est maintenue par Julien Martin (julien.martin@ptits-pas.fr).
|
||||
|
||||
Dernière mise à jour : Juin 2026
|
||||
- Gitea : https://git.ptits-pas.fr/jmartin/petitspas
|
||||
- Prod : https://app.ptits-pas.fr
|
||||
|
||||
Mainteneur : Julien Martin (julien.martin@ptits-pas.fr).
|
||||
|
||||
+155
-70
@@ -1,14 +1,19 @@
|
||||
---
|
||||
title: "P'titsPas - Cahier des Charges Fonctionnel"
|
||||
author: "Julien MARTIN"
|
||||
date: "Novembre 2025"
|
||||
version: "v1.3"
|
||||
date: "Septembre 2026"
|
||||
version: "v1.4"
|
||||
---
|
||||
|
||||
# P'titsPas – Cahier des Charges Fonctionnel
|
||||
|
||||
> **Objet :** Définir le périmètre fonctionnel, les rôles utilisateurs, les processus métiers et les exigences techniques de la plateforme P'titsPas, destinée à accompagner les collectivités locales dans la gestion de la garde d’enfants.
|
||||
|
||||
> **V1.4 (sept. 2026)** — Mise à jour de la **gestion des utilisateurs / dossiers / validation** pour coller au livré produit **`v0.1.0`**. Le reste du CDC (contrats, messagerie, agenda, paie, recherche AM, etc.) est **conservé** comme cible fonctionnelle.
|
||||
> Détail technique du domaine utilisateurs : [12_SRS-GESTION-UTILISATEURS.md](./12_SRS-GESTION-UTILISATEURS.md).
|
||||
> Bilan tickets `v0.1.0` : [29_BILAN-VERSION-0.1.0.md](./29_BILAN-VERSION-0.1.0.md).
|
||||
> Archive V1.3 : [archive/obsolete/01_CAHIER-DES-CHARGES-v1.3.md](./archive/obsolete/01_CAHIER-DES-CHARGES-v1.3.md).
|
||||
|
||||
---
|
||||
|
||||
## Historique des versions
|
||||
@@ -19,6 +24,7 @@ version: "v1.3"
|
||||
| 1.1 | 24/04/2025 | Julien MARTIN | Ajouts : gestion multi-enfants, fin de contrat, tableau de bord étendu |
|
||||
| 1.2 | 26/05/2025 | Julien MARTIN | Remplacement de "SuperNounou" par "P'titsPas" |
|
||||
| 1.3 | 24/11/2025 | Julien MARTIN | Correction : retrait photo de profil parent (section 3.1.1) |
|
||||
| **1.4** | **15/09/2026** | Julien MARTIN | **Gestion utilisateurs** alignée `v0.1.0` (dossiers, validation/refus/reprise, fiches staff, suppressions, retrait naissance multiple & SMS) ; reste du CDC inchangé en cible |
|
||||
|
||||
---
|
||||
|
||||
@@ -42,6 +48,8 @@ version: "v1.3"
|
||||
### 3.4 Création d’un administrateur
|
||||
### 3.5 Fiche enfant
|
||||
### 3.6 Authentification et sécurité
|
||||
### 3.7 Numéro de dossier, validation, refus et reprise
|
||||
### 3.8 Suppressions (vue métier)
|
||||
|
||||
## 4. Tableaux de bord
|
||||
### 4.1 Vue d’ensemble
|
||||
@@ -60,15 +68,15 @@ version: "v1.3"
|
||||
#### 4.3.5 Heures supplémentaires
|
||||
#### 4.3.6 Messagerie
|
||||
### 4.4 Tableau de bord des gestionnaires
|
||||
#### 4.4.1 Comptes à valider
|
||||
#### 4.4.2 Liste des utilisateurs
|
||||
#### 4.4.1 Dossiers à valider
|
||||
#### 4.4.2 Gestion des utilisateurs (partagée)
|
||||
#### 4.4.3 Contrats
|
||||
#### 4.4.4 Messagerie
|
||||
#### 4.4.5 Événements RPE
|
||||
#### 4.4.6 Alertes
|
||||
### 4.5 Tableau de bord des administrateurs
|
||||
#### 4.5.1 Menu Profil
|
||||
#### 4.5.2 Gestion des utilisateurs
|
||||
#### 4.5.2 Gestion des utilisateurs (partagée admin + gestionnaire)
|
||||
#### 4.5.3 Gestion des enfants
|
||||
#### 4.5.4 Paramètres de la plateforme
|
||||
#### 4.5.5 Statistiques et supervision
|
||||
@@ -193,18 +201,23 @@ Les assistantes maternelles peuvent :
|
||||
|
||||
Les gestionnaires (responsables de relais petite enfance) disposent d’un tableau de bord de supervision. Ils peuvent :
|
||||
|
||||
- Valider ou rejeter les demandes de création de compte
|
||||
- Suivre les mises en relation et les contrats
|
||||
- Organiser des événements ou des rendez-vous
|
||||
- Gérer les conflits ou les fins de contrat
|
||||
- Valider ou refuser les **dossiers** (inscriptions parent / AM) et accompagner les reprises
|
||||
- Gérer les usagers (fiches parent / AM / enfant, rattachements, dossiers) — socle partagé avec l’admin
|
||||
- Suivre les mises en relation et les contrats (cible CDC)
|
||||
- Organiser des événements ou des rendez-vous (cible CDC)
|
||||
- Gérer les conflits ou les fins de contrat (cible CDC)
|
||||
- Lancer des sondages ou modérer un blog RPE (si activé)
|
||||
- Voir les historiques et statistiques liés à leur périmètre
|
||||
|
||||
Ils **ne créent pas** les comptes gestionnaire / administrateur (réservé à l’admin).
|
||||
|
||||
### 2.1.4 Administrateurs
|
||||
|
||||
Les administrateurs sont les représentants techniques et institutionnels de la collectivité (DSI ou agents désignés). Ils peuvent :
|
||||
|
||||
- Créer ou supprimer des comptes (gestionnaires, parents, assistantes maternelles)
|
||||
- Tout ce que peut faire un gestionnaire sur les usagers / dossiers
|
||||
- Créer ou supprimer des comptes **staff** (gestionnaires, administrateurs) selon garde-fous
|
||||
- Créer ou supprimer des comptes usagers (parents, AM, enfants) selon droits
|
||||
- Personnaliser l’interface (logo, couleurs, nom de la ville)
|
||||
- Activer ou désactiver des modules complémentaires
|
||||
- Consulter les statistiques d’usage
|
||||
@@ -245,12 +258,15 @@ Le parcours de création d’un compte parent s’effectue en plusieurs étapes
|
||||
**Note** : Le parent 2 ne définit **pas** de mot de passe lors de l'inscription. Il recevra un email avec un lien pour créer son mot de passe après validation du gestionnaire. Cette approche est particulièrement adaptée aux situations de parents séparés ou divorcés où la communication peut être difficile.
|
||||
|
||||
### 3.1.3 Informations sur l'enfant
|
||||
- Un ou **plusieurs** enfants peuvent être ajoutés
|
||||
- Prénom (facultatif si enfant à naître)
|
||||
- Nom (hérité des parents)
|
||||
- Genre (H / F) - obligatoire
|
||||
- Genre (H / F / Autre) — obligatoire
|
||||
- Date de naissance ou **date prévisionnelle de naissance** (si l'enfant n'est pas encore né, un switch modifie le label)
|
||||
- Photo obligatoire si l'enfant est né
|
||||
- Rattachement automatique aux deux parents
|
||||
- Photo (selon règles d’inscription) et **consentement photo**
|
||||
- Rattachement automatique au parent 1 et au parent 2 s’il est renseigné
|
||||
|
||||
**Note V1.4** : il n’existe **pas** de champ « naissance multiple / jumeaux » (retiré du produit).
|
||||
|
||||
### 3.1.4 Présentation du dossier
|
||||
- Zone de texte libre permettant aux parents de décrire leur situation
|
||||
@@ -265,10 +281,12 @@ Le parcours de création d’un compte parent s’effectue en plusieurs étapes
|
||||
### 3.1.6 Récapitulatif et validation
|
||||
- Résumé des données saisies
|
||||
- Vérification, puis envoi de la demande
|
||||
- Attribution d’un **numéro de dossier** (format type AAAA-NNNNNN)
|
||||
- Les comptes parent sont soumis à validation par un gestionnaire avant activation
|
||||
- Une fois validé, chaque parent (Parent 1 et Parent 2 si renseigné) reçoit un e-mail ou un SMS contenant un lien pour créer son mot de passe
|
||||
- Le lien est valable pendant 7 jours
|
||||
- Une fois validé, chaque parent (Parent 1 et Parent 2 si renseigné) reçoit un **e-mail** contenant un lien pour créer son mot de passe
|
||||
- Le lien est valable pendant une durée limitée (jeton à usage unique)
|
||||
- Une fois le mot de passe créé, le parent peut se connecter à son espace
|
||||
- En cas de **refus**, le dossier n’est pas supprimé : l’usager peut **reprendre** sa demande (lien e-mail ou numéro de dossier) — voir §3.7
|
||||
|
||||
## 3.2 Création de compte assistante maternelle
|
||||
|
||||
@@ -298,7 +316,7 @@ Ce parcours est divisé en deux panneaux.
|
||||
- Champ libre : message à destination du gestionnaire
|
||||
- Permet de justifier une demande ou d’ajouter des précisions
|
||||
|
||||
### 3.1.4 – Acceptation des CGU
|
||||
### 3.2.4 – Acceptation des CGU
|
||||
- Les utilisateurs doivent cocher la case
|
||||
« J’ai lu et j’accepte les Conditions Générales d’Utilisation et la Politique de confidentialité ».
|
||||
- Un lien direct ouvre la version PDF des CGU.
|
||||
@@ -307,23 +325,26 @@ Ce parcours est divisé en deux panneaux.
|
||||
### 3.2.5 Récapitulatif et validation
|
||||
- Résumé des données saisies
|
||||
- Vérification, puis envoi de la demande
|
||||
- Attribution d’un **numéro de dossier**
|
||||
- Validation par un gestionnaire requise avant activation
|
||||
- Une fois validé, l'assistante maternelle reçoit un e-mail ou un SMS contenant un lien pour créer son mot de passe
|
||||
- Le lien est valable pendant 7 jours
|
||||
- Une fois validé, l'assistante maternelle reçoit un **e-mail** contenant un lien pour créer son mot de passe
|
||||
- Le lien est valable pendant une durée limitée (jeton à usage unique)
|
||||
- Une fois le mot de passe créé, l'assistante maternelle peut se connecter à son espace
|
||||
- En cas de **refus** : reprise possible — voir §3.7
|
||||
|
||||
## 3.3 Création d’un gestionnaire
|
||||
|
||||
- Réalisée par un administrateur
|
||||
- Champs obligatoires : nom, prénom, adresse e-mail, mot de passe
|
||||
- Affectation à un ou plusieurs relais petite enfance
|
||||
- Le mot de passe doit être modifié lors de la première connexion
|
||||
- Réalisée par un **administrateur** (ou super administrateur) — un gestionnaire ne crée pas de comptes staff
|
||||
- Champs : nom, prénom, e-mail, téléphone, mot de passe, **relais principal** (optionnel)
|
||||
- Le mot de passe peut être modifié à la première connexion si la politique l’exige
|
||||
- Formulaire unifié de création / édition (même présentation que pour les administrateurs)
|
||||
|
||||
## 3.4 Création d’un administrateur
|
||||
|
||||
- Seuls les administrateurs existants peuvent créer de nouveaux comptes administrateurs
|
||||
- Les droits sont équivalents (possibilité de restreindre par périmètre dans une version multi-mairies)
|
||||
- Obligation de changer le mot de passe à la première connexion
|
||||
- Seuls les **administrateurs** (et super administrateur) peuvent créer de nouveaux comptes administrateurs
|
||||
- Champs : nom, prénom, e-mail, téléphone, mot de passe (pas de relais)
|
||||
- Les droits sont équivalents entre administrateurs (le **super administrateur** est un compte d’installation non supprimable)
|
||||
- Obligation de changer le mot de passe à la première connexion si exigé
|
||||
|
||||
## 3.5 Fiche enfant
|
||||
|
||||
@@ -331,22 +352,68 @@ Chaque enfant est représenté par une fiche :
|
||||
|
||||
- Prénom (facultatif si enfant à naître)
|
||||
- Nom
|
||||
- Genre (H / F) - obligatoire
|
||||
- Genre (H / F / Autre) — obligatoire
|
||||
- Date de naissance ou date prévisionnelle
|
||||
- Photo (obligatoire si l'enfant est né ET si l'option *Photo obligatoire* est activée)
|
||||
- Consentement photo enregistré : valeur booléenne + horodatage liés à l'accord donné par le parent
|
||||
- Statut : à naître / actif / scolarisé
|
||||
- Indication possible : jumeaux, triplés, etc.
|
||||
- Possibilité de rattacher un enfant à plusieurs parents (garde alternée)
|
||||
- Photo et consentement photo selon configuration (consentement tracé)
|
||||
- Statut : à naître / actif / scolarisé (évolutions de libellés possibles ultérieurement)
|
||||
- Responsables (parents) rattachés — liens vers les fiches parent
|
||||
- Assistante maternelle de rattachement (le cas échéant)
|
||||
|
||||
**Note V1.4** : pas d’indication « jumeaux / triplés » comme champ dédié.
|
||||
|
||||
Les fiches enfants sont :
|
||||
- Accessibles depuis la fiche parent, la fiche AM, l’onglet **Enfants** du dashboard staff
|
||||
- Créables par le staff pour un foyer existant
|
||||
- Partagées entre les responsables rattachés
|
||||
|
||||
## 3.6 Authentification et sécurité
|
||||
|
||||
- Tous les comptes utilisent une combinaison adresse e-mail + mot de passe
|
||||
- Les gestionnaires et administrateurs doivent modifier leur mot de passe à la première connexion
|
||||
- Des mécanismes de récupération sont disponibles en cas de perte
|
||||
- Authentification par e-mail + mot de passe
|
||||
- Comptes **en attente** ou **suspendus** : connexion refusée
|
||||
- Les gestionnaires et administrateurs doivent modifier leur mot de passe à la première connexion (si exigé)
|
||||
- **Création de mot de passe** post-validation : lien e-mail (jeton TTL, usage unique)
|
||||
- **Mot de passe oublié** : parcours distinct (demande → e-mail → réinitialisation)
|
||||
- Pas d’envoi de lien de mot de passe par SMS (canal **e-mail** uniquement)
|
||||
|
||||
Un lien direct vers les **Mentions légales** et la **Politique de confidentialité** est accessible en permanence depuis le pied de page, y compris avant la connexion.
|
||||
|
||||
## 3.7 Numéro de dossier, validation, refus et reprise
|
||||
|
||||
### Numéro de dossier
|
||||
- Format type **AAAA-NNNNNN**
|
||||
- Affiché dans les listes staff, les modales et les e-mails concernés
|
||||
- Sert de clé métier pour validation, refus et reprise
|
||||
|
||||
### Validation
|
||||
- Le staff (gestionnaire / administrateur) examine le dossier (wizard de revue)
|
||||
- Action **Valider** : activation du circuit comptes + e-mails de création de mot de passe
|
||||
|
||||
### Refus
|
||||
- Action **Refuser** : le dossier est refusé **sans suppression** des données
|
||||
- L’usager est informé par e-mail et peut reprendre sa demande
|
||||
|
||||
### Reprise
|
||||
- Via le **lien** reçu par e-mail, ou depuis l’écran de connexion avec le **numéro de dossier**
|
||||
- Formulaire prérempli / correction des informations
|
||||
- Nouvelle soumission → retour en file « à valider »
|
||||
|
||||
### Création et édition de dossiers par le staff
|
||||
- En plus de l’inscription publique, le staff peut **créer** un dossier famille ou AM (wizard)
|
||||
- Le staff peut **éditer** un dossier existant (y compris ajout d’un 2ᵉ parent pour une famille mono-parent)
|
||||
|
||||
## 3.8 Suppressions (vue métier)
|
||||
|
||||
Sous réserve des droits (détail technique : [SRS gestion utilisateurs](./12_SRS-GESTION-UTILISATEURS.md)) :
|
||||
|
||||
| Cible | Principe |
|
||||
|-------|----------|
|
||||
| Parent, AM, enfant, dossier | Gestionnaire, administrateur, super admin — avec confirmation |
|
||||
| Gestionnaire | Administrateur / super admin uniquement |
|
||||
| Administrateur | Admin / super admin, hors soi-même, hors cible super admin ; garde-fou sur le dernier administrateur |
|
||||
| Super administrateur | Non supprimable |
|
||||
|
||||
Un gestionnaire ne peut pas supprimer **son propre** compte.
|
||||
|
||||
# 4. Tableaux de bord
|
||||
|
||||
Chaque rôle utilisateur dispose d’un tableau de bord personnalisé, adapté à ses fonctions dans la plateforme. Ces interfaces sont pensées pour être lisibles, fonctionnelles et évolutives.
|
||||
@@ -357,8 +424,8 @@ Chaque rôle utilisateur dispose d’un tableau de bord personnalisé, adapté
|
||||
|------------------------|-------------------------------------------------------------------|
|
||||
| Parents | Recherche d'assistante maternelle, gestion des enfants, contrat, agenda |
|
||||
| Assistantes maternelles| Dossiers reçus, enfants accueillis, heures sup, agenda, messagerie|
|
||||
| Gestionnaires | Validation de comptes, contrats, messagerie, événements RPE |
|
||||
| Administrateurs | Paramètres globaux, gestion des utilisateurs, statistiques |
|
||||
| Gestionnaires | Dossiers à valider, gestion utilisateurs/enfants (partagée), contrats, messagerie, événements RPE |
|
||||
| Administrateurs | Paramètres globaux, même gestion utilisateurs (droits staff élargis), statistiques |
|
||||
|
||||
Les tableaux de bord intègrent :
|
||||
- Une **barre de navigation supérieure** (liens de navigation rapide)
|
||||
@@ -502,17 +569,24 @@ L’assistante maternelle accède à une interface dédiée à la gestion de ses
|
||||
|
||||
Le gestionnaire RPE dispose d’une vision transversale sur les utilisateurs, les dossiers et les activités de la structure. Son rôle est d'accompagner, superviser, et arbitrer si nécessaire.
|
||||
|
||||
### 4.4.1 Comptes à valider
|
||||
### 4.4.1 Dossiers à valider
|
||||
|
||||
- File d’attente des demandes de création de compte
|
||||
- Détails de chaque demande : parent, assistante maternelle
|
||||
- Actions possibles : Valider / Refuser / Demander des précisions
|
||||
- File d’attente des **dossiers** (famille / AM) en attente de validation
|
||||
- Affichage du **numéro de dossier** et des informations essentielles
|
||||
- Ouverture en **revue** (wizard étapes) : Valider / Refuser
|
||||
- Le refus n’efface pas le dossier : l’usager peut reprendre (voir §3.7)
|
||||
- L’onglet **Dossiers** du dashboard regroupe aussi une **liste unifiée** des dossiers (au-delà de la seule file « à valider »)
|
||||
|
||||
### 4.4.2 Liste des utilisateurs
|
||||
### 4.4.2 Gestion des utilisateurs (partagée)
|
||||
|
||||
- Filtres par rôle, statut, date d’inscription
|
||||
- Accès rapide aux informations et historiques
|
||||
- Possibilité de contacter un utilisateur
|
||||
> **V1.4** — La gestion opérationnelle des usagers (parents, AM, enfants, dossiers) est **partagée** entre gestionnaire et administrateur via le même dashboard. Seule la gestion des **comptes staff** (création / suppression gestionnaire ou admin) est réservée à l’administrateur.
|
||||
|
||||
- Onglets : Parents, Assistantes maternelles, Enfants, Gestionnaires (selon droits), Administrateurs (admin)
|
||||
- Accès aux **fiches** (identité, rattachements, capacité AM, etc.)
|
||||
- Création de dossiers / enfants par le staff
|
||||
- Filtres et recherche ; ouverture des fiches depuis les cartes / listes
|
||||
|
||||
Le détail des panneaux admin historiques est décrit en §4.5.2 (même socle fonctionnel).
|
||||
|
||||
### 4.4.3 Contrats
|
||||
|
||||
@@ -566,47 +640,56 @@ Le menu profil de l’administrateur comprend uniquement :
|
||||
|
||||
Toutes les fonctionnalités de gestion sont accessibles via des onglets distincts dans le tableau de bord.
|
||||
|
||||
### 4.5.2 Gestion des utilisateurs
|
||||
### 4.5.2 Gestion des utilisateurs (partagée admin + gestionnaire)
|
||||
|
||||
L’administration des utilisateurs est organisée par panneaux distincts pour chaque type de profil.
|
||||
L’administration des utilisateurs est organisée par panneaux / onglets. **Admin et gestionnaire** partagent les panneaux usagers ; l’admin dispose en plus des droits staff.
|
||||
|
||||
#### a. Gestion des gestionnaires
|
||||
- Liste des gestionnaires existants
|
||||
- Création (nom, prénom, e-mail, mot de passe)
|
||||
- Attribution à un ou plusieurs RPE
|
||||
- Réinitialisation du mot de passe
|
||||
- Suppression du compte
|
||||
- Création / édition (nom, prénom, e-mail, téléphone, mot de passe, relais principal) — **administrateur uniquement** pour la création
|
||||
- Réinitialisation / nouveau mot de passe en édition
|
||||
- Suppression du compte — **administrateur uniquement** (pas d’auto-suppression)
|
||||
|
||||
#### b. Gestion des parents
|
||||
- Liste complète des parents enregistrés
|
||||
- Recherche par nom, statut, enfants associés
|
||||
- Modification des informations
|
||||
- Suppression d’un compte
|
||||
- Consultation du statut des dossiers liés
|
||||
- Liste des parents enregistrés
|
||||
- Ouverture de la **fiche parent** (identité, statut, enfants, lien co-parent)
|
||||
- Rattacher / détacher un enfant
|
||||
- Création de dossier famille (wizard staff)
|
||||
- Suppression d’un compte / dossier selon droits (§3.8)
|
||||
|
||||
#### c. Gestion des assistantes maternelles
|
||||
- Liste des assistantes avec numéro d’agrément
|
||||
- Modification ou suppression d’un compte
|
||||
- Filtrage par zone géographique ou capacité
|
||||
- Liste des AM (agrément, capacité, etc.)
|
||||
- **Fiche AM** (identité, professionnel, enfants accueillis)
|
||||
- Respect de la **capacité max** pour les rattachements
|
||||
- Création de dossier AM (wizard staff)
|
||||
- Suppression selon droits
|
||||
|
||||
#### d. Gestion des administrateurs
|
||||
- Création de nouveaux comptes administrateurs
|
||||
- Création de nouveaux comptes administrateurs — **administrateur / super admin**
|
||||
- Suivi des droits
|
||||
- Obligation de modification du mot de passe à la première connexion
|
||||
- Obligation de modification du mot de passe à la première connexion si exigé
|
||||
- Suppression avec garde-fous (pas soi-même, pas le super admin, dernier admin)
|
||||
|
||||
#### e. Onglet Dossiers
|
||||
- Liste unifiée + dossiers à valider
|
||||
- Revue / édition des dossiers (wizards)
|
||||
|
||||
### 4.5.3 Gestion des enfants
|
||||
|
||||
Deux accès possibles à la gestion des enfants :
|
||||
|
||||
#### a. Par fiche parent
|
||||
- Consultation et édition des enfants associés à chaque parent
|
||||
#### a. Par fiche parent (ou fiche AM)
|
||||
- Consultation et édition des enfants associés
|
||||
- Rattacher / détacher depuis la fiche
|
||||
|
||||
#### b. Vue globale “Enfants”
|
||||
- Liste complète avec :
|
||||
- Nom, prénom, date de naissance ou prévisionnelle
|
||||
- Statut (à naître, actif, scolarisé)
|
||||
- Parents associés
|
||||
- Contrat en cours (si applicable)
|
||||
- Parents associés (alerte si **sans responsable**)
|
||||
- AM associée le cas échéant
|
||||
- Contrat en cours (si applicable — module contrats)
|
||||
- Création d’un enfant rattaché à un **foyer existant**
|
||||
- Possibilité de modifier ou supprimer une fiche enfant
|
||||
|
||||
### 4.5.4 Paramètres de la plateforme
|
||||
@@ -905,10 +988,10 @@ Certains outils de la plateforme sont accessibles à plusieurs profils et favori
|
||||
- Le gestionnaire (à titre d’information)
|
||||
- Contient :
|
||||
- Identité
|
||||
- Photo (obligatoire si né)
|
||||
- Photo (selon configuration / consentement)
|
||||
- Statut (à naître / actif / scolarisé)
|
||||
- Parents associés
|
||||
- Mention s’il s’agit de jumeaux, triplés, etc.
|
||||
- AM associée le cas échéant
|
||||
|
||||
## 6.4 Contrats et avenants
|
||||
|
||||
@@ -1185,11 +1268,11 @@ P'titsPas s’inscrit dans une démarche de service public, avec des fondements
|
||||
| **Gestionnaires** | Suivi global des situations, outils de médiation, organisation d’événements |
|
||||
| **Administrateurs** | Supervision complète, gouvernance multi-rôle, contrôle des données |
|
||||
|
||||
## 10.3 Périmètre fonctionnel de la V1
|
||||
## 10.3 Périmètre fonctionnel
|
||||
|
||||
Fonctionnalités incluses dès la première version :
|
||||
- Création de comptes
|
||||
- Recherche et sélection de nounous
|
||||
**Cible CDC (plateforme complète)** — fonctionnalités décrites dans ce document :
|
||||
- Création de comptes et gestion des utilisateurs / dossiers
|
||||
- Recherche et sélection d’assistantes maternelles
|
||||
- Suivi des dossiers
|
||||
- Génération de contrat et avenants
|
||||
- Messagerie
|
||||
@@ -1198,6 +1281,8 @@ Fonctionnalités incluses dès la première version :
|
||||
- Gestion des heures supplémentaires
|
||||
- Suivi RGPD et administration
|
||||
|
||||
**Livré produit `v0.1.0`** (voir [bilan](./29_BILAN-VERSION-0.1.0.md)) : cœur **gestion des utilisateurs** — inscription, validation/refus/reprise, auth, dashboard staff (dossiers, fiches, rattachements, suppressions). Les autres modules du CDC restent la **feuille de route**.
|
||||
|
||||
## 10.4 Perspectives
|
||||
|
||||
La structure du produit permet une montée en charge progressive :
|
||||
|
||||
+15
-15
@@ -44,22 +44,21 @@ Les **Phases 2, 3, 4+** sont des **ébauches indicatives** qui seront affinées
|
||||
- ✅ Logging & Monitoring
|
||||
- ✅ Tests & Documentation
|
||||
|
||||
### Versions incrémentales
|
||||
### Versions incrémentales (semver / Gitea)
|
||||
|
||||
| Version | Objectif | Tickets | Estimation |
|
||||
|---------|----------|---------|------------|
|
||||
| **0.1.0** | MVP Fonctionnel | ~21 | ~45h |
|
||||
| **0.2.0** | Sécurité & RGPD | ~10 | ~35h |
|
||||
| **0.3.0** | Interfaces Complètes | ~17 | ~52h |
|
||||
| **0.4.0** | Tests & Documentation | ~6 | ~24h |
|
||||
| **0.5.0** | Monitoring & Optimisations | ~7 | ~17h |
|
||||
| **1.0.0** | 🎉 **Release Phase 1** | **61** | **~173h** |
|
||||
La table historique « ~21 tickets / 0.1.0 » est **obsolète**.
|
||||
État réel des milestones, bilans et tag : **[05_VERSIONS-ET-MILESTONES.md](./05_VERSIONS-ET-MILESTONES.md)**.
|
||||
|
||||
### Livrable
|
||||
| Version | Statut (sept. 2026) |
|
||||
|---------|---------------------|
|
||||
| **0.1.0** | **Terminée** — [bilan](./29_BILAN-VERSION-0.1.0.md) (48 tickets fermés) |
|
||||
| **0.2.0+** | Ouvertes — voir Gitea + doc 05 |
|
||||
|
||||
Application installable avec création et validation de comptes utilisateurs.
|
||||
### Livrable Phase 1 (visée)
|
||||
|
||||
**Référence** : [23_LISTE-TICKETS.md](./23_LISTE-TICKETS.md)
|
||||
Application installable avec création et validation de comptes utilisateurs, puis enrichissements dashboard / dossiers (0.1.0 livré).
|
||||
|
||||
**Tickets** : Gitea — pointeur [23_SUIVI-TICKETS.md](./23_SUIVI-TICKETS.md).
|
||||
|
||||
---
|
||||
|
||||
@@ -216,7 +215,7 @@ Suivi quotidien des enfants + Fonctionnalités complémentaires.
|
||||
|
||||
Application mature, optimisée et riche en fonctionnalités.
|
||||
|
||||
**Référence** : [25_PHASE-2-BACKLOG.md](./25_PHASE-2-BACKLOG.md) (anciennes fonctionnalités techniques)
|
||||
**Référence** : [archive/obsolete/25_PHASE-2-BACKLOG.md](./archive/obsolete/25_PHASE-2-BACKLOG.md) (figé) + [05_VERSIONS-ET-MILESTONES.md](./05_VERSIONS-ET-MILESTONES.md)
|
||||
|
||||
---
|
||||
|
||||
@@ -317,9 +316,10 @@ Exemples :
|
||||
- [00_INDEX.md](./00_INDEX.md) - Index général de la documentation
|
||||
- [01_CAHIER-DES-CHARGES.md](./01_CAHIER-DES-CHARGES.md) - Cahier des charges v1.3
|
||||
- [20_WORKFLOW-CREATION-COMPTE.md](./20_WORKFLOW-CREATION-COMPTE.md) - Workflow création de comptes
|
||||
- [23_LISTE-TICKETS.md](./23_LISTE-TICKETS.md) - Liste des 61 tickets Phase 1
|
||||
- [23_SUIVI-TICKETS.md](./23_SUIVI-TICKETS.md) / [29_BILAN-VERSION-0.1.0.md](./29_BILAN-VERSION-0.1.0.md) — suivi Gitea + bilan 0.1.0
|
||||
- [24_DECISIONS-PROJET.md](./24_DECISIONS-PROJET.md) - Décisions architecturales
|
||||
- [25_PHASE-2-BACKLOG.md](./25_PHASE-2-BACKLOG.md) - Anciennes fonctionnalités techniques
|
||||
- [05_VERSIONS-ET-MILESTONES.md](./05_VERSIONS-ET-MILESTONES.md) — milestones Gitea
|
||||
- [archive/obsolete/25_PHASE-2-BACKLOG.md](./archive/obsolete/25_PHASE-2-BACKLOG.md) — backlog Phase 2 figé
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
# Versions & milestones — P'titsPas
|
||||
|
||||
**Source de vérité tickets** : Gitea [`jmartin/petitspas`](https://git.ptits-pas.fr/jmartin/petitspas)
|
||||
**Bilans de version** : documents `29_BILAN-…` (et suivants)
|
||||
|
||||
Ce fichier remplace, pour le **semver / milestones**, les anciennes tables figées de la roadmap Phase 1.
|
||||
|
||||
---
|
||||
|
||||
## État des milestones
|
||||
|
||||
| Milestone | Rôle | Statut |
|
||||
|-----------|------|--------|
|
||||
| **0.1.0** | MVP opérable (auth, inscription, dashboard dossiers/fiches, suppressions, cleanups) | **Terminée** — [bilan](./29_BILAN-VERSION-0.1.0.md) |
|
||||
| **0.2.0** | **Quotidien parent / AM** (TdB 3 colonnes, cartes, blog, messagerie) — [#165](https://git.ptits-pas.fr/jmartin/petitspas/issues/165)… | **Ouverte** — [mini-spec](./31_MINI-SPEC-QUOTIDIEN-PARENT-AM.md) · [découpage](./30_DECOUPAGE-TICKETS-QUOTIDIEN.md) |
|
||||
| **0.3.0** | Contrat + planning | Fermée (vide) — à réouvrir au besoin |
|
||||
| **0.4.0** | Carnet de liaison | Fermée (vide) — à réouvrir au besoin |
|
||||
| **0.9.0** | Hors périmètre cleanup 0.1.0 | Fermée (vide) |
|
||||
| **1.0.0** | Release majeure (critères PO) | Fermée (réserve) |
|
||||
| **Backlog transverse** | Doc / CI / RGPD / monitoring | Fermée (vide) |
|
||||
|
||||
Liens Gitea : [milestones](https://git.ptits-pas.fr/jmartin/petitspas/milestones).
|
||||
|
||||
---
|
||||
|
||||
## Bilans
|
||||
|
||||
| Version | Document |
|
||||
|---------|----------|
|
||||
| 0.1.0 | [29_BILAN-VERSION-0.1.0.md](./29_BILAN-VERSION-0.1.0.md) |
|
||||
|
||||
## Documents produit de référence (post-0.1.0)
|
||||
|
||||
| Doc | Rôle |
|
||||
|-----|------|
|
||||
| [01_CAHIER-DES-CHARGES.md](./01_CAHIER-DES-CHARGES.md) | CDC **complet** V1.4 (users mis à jour ; reste = cible) |
|
||||
| [12_SRS-GESTION-UTILISATEURS.md](./12_SRS-GESTION-UTILISATEURS.md) | SRS technique domaine utilisateurs |
|
||||
| [31_MINI-SPEC-QUOTIDIEN-PARENT-AM.md](./31_MINI-SPEC-QUOTIDIEN-PARENT-AM.md) | Besoin quotidien parent/AM (0.2.0) |
|
||||
| [30_DECOUPAGE-TICKETS-QUOTIDIEN.md](./30_DECOUPAGE-TICKETS-QUOTIDIEN.md) | Mapping tickets #165–#189 |
|
||||
| Archive CDC V1.3 | [archive/obsolete/01_CAHIER-DES-CHARGES-v1.3.md](./archive/obsolete/01_CAHIER-DES-CHARGES-v1.3.md) |
|
||||
|
||||
---
|
||||
|
||||
## Relation avec la roadmap phases
|
||||
|
||||
La vision long terme (Phases 2–5 : mise en relation, contrats, carnet…) reste dans [04_ROADMAP-GENERALE.md](./04_ROADMAP-GENERALE.md).
|
||||
Les **jalons livrables** se gèrent ici + dans Gitea.
|
||||
|
||||
Ancien backlog « Phase 2 » technique ([archive](./archive/obsolete/25_PHASE-2-BACKLOG.md)) : à croiser avec les milestones ci-dessus ; ne plus maintenir en double.
|
||||
|
||||
---
|
||||
|
||||
## Suivi des tickets
|
||||
|
||||
- **Création / état** : Gitea uniquement.
|
||||
- **Mémoire d’une version livrée** : bilan `29_…` (pas de re-copie exhaustive dans un fichier tickets).
|
||||
- Ancienne liste figée Phase 1 : [archive/obsolete/23_LISTE-TICKETS.md](./archive/obsolete/23_LISTE-TICKETS.md).
|
||||
- Pointeur court : [23_SUIVI-TICKETS.md](./23_SUIVI-TICKETS.md).
|
||||
|
||||
---
|
||||
|
||||
## Tag Git
|
||||
|
||||
| Tag | Condition |
|
||||
|-----|-----------|
|
||||
| `v0.1.0` | Milestone 0.1.0 fermée + bilan mergé sur `master` |
|
||||
@@ -117,7 +117,6 @@ Table des enfants pris en charge.
|
||||
| `photo_url` | TEXT | | URL de la photo |
|
||||
| `consentement_photo` | BOOLEAN | DEFAULT false | Consentement photo |
|
||||
| `date_consentement_photo` | TIMESTAMPTZ | | Date du consentement |
|
||||
| `est_multiple` | BOOLEAN | DEFAULT false | Indique si grossesse multiple |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
# SRS — Gestion des utilisateurs (domaine livré v0.1.0)
|
||||
|
||||
**Version** : 1.0
|
||||
**Date** : 15/09/2026
|
||||
**Ticket** : [#117](https://git.ptits-pas.fr/jmartin/petitspas/issues/117)
|
||||
**Niveau** : **technique** (dev / QA)
|
||||
**CDC associé** : [01_CAHIER-DES-CHARGES.md](./01_CAHIER-DES-CHARGES.md) (V1.4 — **CDC complet** ; cette SRS ne couvre que le domaine utilisateurs)
|
||||
|
||||
> Périmètre SRS : comptes, auth liée, dossiers famille/AM, enfants, affiliations, dashboard staff, suppressions.
|
||||
> Le CDC V1.4 conserve **l’ensemble** des chapitres cibles (contrats, messagerie, etc.) ; ils ne sont **pas** redécrits ici.
|
||||
> Hors SRS technique : OpenAPI exhaustif, PRA/CI → voir [11_API](./11_API.md), [10_DATABASE](./10_DATABASE.md).
|
||||
|
||||
---
|
||||
|
||||
## 1. Glossaire
|
||||
|
||||
| Terme | Définition |
|
||||
|-------|------------|
|
||||
| **User / utilisateur** | Compte authentifiable (`utilisateurs`) avec `role` et `statut` |
|
||||
| **Parent pivot** | Responsable principal du foyer à l’inscription / création staff |
|
||||
| **Co-parent** | Second responsable optionnel (au plus un), lié au pivot |
|
||||
| **Foyer** | Pivot + co-parent éventuel + enfants affiliés |
|
||||
| **Dossier** | Unité métier identifiée par `numero_dossier` (format `AAAA-NNNNNN`) — famille ou AM |
|
||||
| **Pending / en_attente** | Compte ou dossier en attente de validation staff |
|
||||
| **Refus** | Rejet sans suppression ; ouvre la **reprise** |
|
||||
| **Relais** | Structure RPE ; rattachement optionnel d’un gestionnaire |
|
||||
| **Staff** | `gestionnaire`, `administrateur`, `super_admin` |
|
||||
|
||||
---
|
||||
|
||||
## 2. Acteurs et rôles applicatifs
|
||||
|
||||
| `role` | Inscription publique | Dashboard staff | Créer staff | Suppressions métier usagers | Supprimer gestionnaire | Supprimer admin |
|
||||
|--------|---------------------|-----------------|-------------|----------------------------|------------------------|-----------------|
|
||||
| `parent` | oui | non | non | non | non | non |
|
||||
| `assistante_maternelle` | oui | non | non | non | non | non |
|
||||
| `gestionnaire` | non (créé staff) | oui | non | oui* | non | non |
|
||||
| `administrateur` | non | oui | oui | oui* | oui | oui** |
|
||||
| `super_admin` | non (install) | oui | oui | oui* | oui | oui** |
|
||||
|
||||
\* Sous réserve des garde-fous (pas soi-même pour sa fiche staff, etc.).
|
||||
\*\* Pas soi-même ; pas de cible `super_admin` ; dernier admin : règles `canDeleteAdministrateur` (front `staff_deletion_rights.dart`).
|
||||
|
||||
Réf. front : `frontend/lib/utils/staff_deletion_rights.dart`
|
||||
- `canCreateStaffAccounts` → admin / super_admin
|
||||
- `canDeleteMetier` → gestionnaire / admin / super_admin
|
||||
- `canDeleteGestionnaire` → admin / super_admin
|
||||
|
||||
---
|
||||
|
||||
## 3. Statuts
|
||||
|
||||
### 3.1 Utilisateur (`statut_utilisateur_type`)
|
||||
|
||||
| Statut | Signification |
|
||||
|--------|----------------|
|
||||
| `en_attente` | Inscrit, non validé ; **login refusé** |
|
||||
| `actif` | Validé / utilisable |
|
||||
| `suspendu` | Bloqué ; **login refusé** |
|
||||
|
||||
### 3.2 Enfant (`statut_enfant_type`)
|
||||
|
||||
Valeurs actuelles : `a_naitre`, `actif`, `scolarise` (évolution métier « gardé / sans garde » **hors** cette SRS — ticket dédié).
|
||||
|
||||
### 3.3 Validation dossier
|
||||
|
||||
Circuit staff : revue → **valider** ou **refuser**. Refus ≠ delete. Reprise → nouveau passage en attente.
|
||||
|
||||
---
|
||||
|
||||
## 4. Modèle de données (vue synthétique)
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
user[utilisateurs]
|
||||
parent[parents]
|
||||
am[assistantes_maternelles]
|
||||
enfant[enfants]
|
||||
ep[enfants_parents]
|
||||
df[dossier_famille]
|
||||
user --> parent
|
||||
user --> am
|
||||
parent --> ep
|
||||
enfant --> ep
|
||||
parent --> df
|
||||
```
|
||||
|
||||
| Concept | Tables / liens clés |
|
||||
|---------|---------------------|
|
||||
| Compte | `utilisateurs` (role, statut, email, numero_dossier, relais…) |
|
||||
| Parent | `parents` (+ `id_co_parent` optionnel) |
|
||||
| AM | `assistantes_maternelles` (agrément, capacité, NIR…) |
|
||||
| Enfant | `enfants` |
|
||||
| Affiliation parent | `enfants_parents` (N–N) |
|
||||
| Dossier famille | `dossier_famille` (+ enfants dossier) |
|
||||
| Tokens MDP | tables / flux tokens création & reset (TTL, usage unique) |
|
||||
|
||||
Détail colonnes : [10_DATABASE.md](./10_DATABASE.md).
|
||||
|
||||
### Invariants
|
||||
|
||||
1. **Pas** de champ `est_multiple` / naissance multiple (#152).
|
||||
2. Au plus **un** co-parent par fiche parent.
|
||||
3. Affiliation création enfant : rattache **pivot + co-parent** s’il existe (#158).
|
||||
4. Détachement du **dernier** parent → enfant **sans responsable** possible (#157).
|
||||
5. Rattachement AM plafonné par **capacité** (#148 / #149).
|
||||
6. `super_admin` **non supprimable**.
|
||||
|
||||
---
|
||||
|
||||
## 5. Flux
|
||||
|
||||
### 5.1 Inscription → validation → mot de passe
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as Usager
|
||||
participant API as API
|
||||
participant S as Staff
|
||||
participant M as Mail
|
||||
U->>API: register parent/AM
|
||||
API-->>U: numero_dossier, statut en_attente
|
||||
S->>API: review / valider
|
||||
API->>M: mail lien create-password
|
||||
U->>API: verify token + set password
|
||||
API-->>U: compte actif, login OK
|
||||
```
|
||||
|
||||
Variante **refus** : staff refuse → mail refus → usager **reprise** (token lien ou n° dossier) → resoumission → à valider.
|
||||
|
||||
### 5.2 Mot de passe oublié
|
||||
|
||||
Flux distinct de la création post-validation : demande → e-mail → reset (#127). Tokens durcis (#123).
|
||||
|
||||
### 5.3 Création dossier staff
|
||||
|
||||
- Famille : wizard + `POST` staff parent/dossier (#129).
|
||||
- AM : wizard + API staff AM (#156).
|
||||
- Édition : mode `edit` wizards + PATCH fiches ; ajout co-parent `POST …/co-parent` (#135).
|
||||
|
||||
### 5.4 Rattachements
|
||||
|
||||
| Lien | Opérations |
|
||||
|------|------------|
|
||||
| Parent ↔ enfant | attach / detach (fiche parent, fiche enfant) |
|
||||
| AM ↔ enfant | attach / detach (fiche AM, fiche enfant) ; UI capacité |
|
||||
|
||||
API : tickets #115 / #116 ; liste enfants enrichie #136.
|
||||
|
||||
---
|
||||
|
||||
## 6. Matrice droits × actions (synthèse)
|
||||
|
||||
| Action | gestionnaire | administrateur | super_admin |
|
||||
|--------|:------------:|:--------------:|:-----------:|
|
||||
| Voir dashboard usagers / dossiers | ✓ | ✓ | ✓ |
|
||||
| Valider / refuser dossier | ✓ | ✓ | ✓ |
|
||||
| Créer dossier parent / AM | ✓ | ✓ | ✓ |
|
||||
| Éditer fiches parent / AM / enfant | ✓ | ✓ | ✓ |
|
||||
| Rattacher / détacher enfant | ✓ | ✓ | ✓ |
|
||||
| GET liste relais (combo) | ✓ | ✓ | ✓ |
|
||||
| Créer gestionnaire / admin | ✗ | ✓ | ✓ |
|
||||
| Supprimer parent / AM / enfant / dossier | ✓ | ✓ | ✓ |
|
||||
| Supprimer gestionnaire | ✗ | ✓ | ✓ |
|
||||
| Supprimer admin (garde-fous) | ✗ | ✓* | ✓* |
|
||||
| Supprimer super_admin | ✗ | ✗ | ✗ |
|
||||
| Supprimer son propre compte staff | ✗ | ✗ | ✗ |
|
||||
|
||||
\* Voir `canDeleteAdministrateur` / messages `adminDeleteBlockedReason`.
|
||||
|
||||
---
|
||||
|
||||
## 7. UI staff (points d’entrée code)
|
||||
|
||||
| Zone | Emplacement typique |
|
||||
|------|---------------------|
|
||||
| Panneau gestion users | `widgets/dashboard/user_management_panel.dart` |
|
||||
| Onglets parents / AM / enfants / dossiers | `widgets/dashboard/*_management_widget.dart` |
|
||||
| Fiche parent | `parent_edit_modal.dart` |
|
||||
| Fiche AM | `am_edit_modal.dart` |
|
||||
| Fiche enfant | `child_detail_modal.dart` |
|
||||
| Wizards dossier | `parent_dossier_wizard.dart`, `am_dossier_wizard.dart` |
|
||||
| Modale staff | `staff_user_form_modal.dart` (`StaffUserFormModal`) |
|
||||
| Confirm suppressions | `widgets/dashboard/common/suppression_confirm_dialog.dart` |
|
||||
| Champs contrôlés | `validation_detail_section.dart` (`ValidationEmailField`, `ValidationPhoneField`…) |
|
||||
| Thème primaire modales | `validation_modal_theme.dart` |
|
||||
|
||||
Shell fiches / wizards : largeur **930**, labels au-dessus, primaire violet `ValidationModalTheme`.
|
||||
|
||||
---
|
||||
|
||||
## 8. API — groupes (renvoi)
|
||||
|
||||
Ne pas dupliquer OpenAPI ici. Groupes utiles au domaine :
|
||||
|
||||
| Groupe | Exemples d’usage |
|
||||
|--------|------------------|
|
||||
| Auth / register | Inscription parent & AM, login, tokens MDP, oubli MDP |
|
||||
| Dossiers | `GET /dossiers/:numero`, listes à valider / unifiées, validate/refuse |
|
||||
| Parents | Fiche PATCH, co-parent POST, dossier staff POST |
|
||||
| AM | Fiche PATCH, dossier staff POST |
|
||||
| Enfants | CRUD staff, attach/detach parent & AM |
|
||||
| Users / staff | CRUD gestionnaires / admins, DELETE métier |
|
||||
| Relais | `GET /relais` (autorisé gestionnaire — #151) |
|
||||
| Config | setup / configuration instance |
|
||||
|
||||
Référence : [11_API.md](./11_API.md) (à maintenir en parallèle si écart).
|
||||
|
||||
---
|
||||
|
||||
## 9. Exigences non fonctionnelles (domaine users)
|
||||
|
||||
| ID | Exigence |
|
||||
|----|----------|
|
||||
| NFR-U1 | Tokens création / reset MDP : TTL strict, usage unique |
|
||||
| NFR-U2 | Mots de passe : politique min. longueur (création staff / usager selon flux) |
|
||||
| NFR-U3 | E-mails métier (validation, refus, MDP) via config SMTP instance |
|
||||
| NFR-U4 | Pas de login si `en_attente` ou `suspendu` |
|
||||
| NFR-U5 | Confirmations explicites avant toute suppression |
|
||||
| NFR-U6 | Champs e-mail / téléphone : validation & normalisation côté UI staff (SRS UX #164) |
|
||||
|
||||
Hors scope immédiat : normalisation erreurs auth globale (#121), observabilité (#122), audit trail complet (#128).
|
||||
|
||||
---
|
||||
|
||||
## 10. Limites modèle famille (assumées)
|
||||
|
||||
Documentées pour les développeurs — détail produit : [28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md](./28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md).
|
||||
|
||||
- Un `numero_dossier` / user ; un seul co-parent.
|
||||
- Familles recomposées multi-contextes : contournement (2ᵉ compte / composition staff) jusqu’à epic #139.
|
||||
- La SRS **n’exige pas** N responsables en v0.1.0.
|
||||
|
||||
---
|
||||
|
||||
## 11. Traçabilité livré 0.1.0
|
||||
|
||||
Source : [29_BILAN-VERSION-0.1.0.md](./29_BILAN-VERSION-0.1.0.md) — 48 tickets milestone 0.1.0 (auth, inscription, fiches, dossiers, suppressions, cleanups #152/#155/#162/#164).
|
||||
|
||||
---
|
||||
|
||||
## 12. Hors périmètre de cette SRS
|
||||
|
||||
- Contrats, avenants, fin de contrat (restent dans le **CDC** cible)
|
||||
- Messagerie, agenda, événements RPE (idem CDC)
|
||||
- Paie / Pajemploi
|
||||
- Recherche AM côté parent
|
||||
- PRA, CI/CD, monitoring infra
|
||||
- Spécification OpenAPI ligne à ligne
|
||||
- Texte fonctionnel complet → [01_CAHIER-DES-CHARGES.md](./01_CAHIER-DES-CHARGES.md)
|
||||
@@ -1,8 +0,0 @@
|
||||
# Fichier déplacé
|
||||
|
||||
La documentation **Documents légaux** a été déplacée vers :
|
||||
|
||||
**[juridique/22_DOCUMENTS-LEGAUX.md](./juridique/22_DOCUMENTS-LEGAUX.md)**
|
||||
|
||||
Voir aussi le dossier **[juridique/](./juridique/)** pour les sources **CGU**
|
||||
et **CGC** en Markdown.
|
||||
@@ -0,0 +1,14 @@
|
||||
# Suivi des tickets — P'titsPas
|
||||
|
||||
**Source de vérité** : [Gitea — issues](https://git.ptits-pas.fr/jmartin/petitspas/issues)
|
||||
**Milestones / versions** : [05_VERSIONS-ET-MILESTONES.md](./05_VERSIONS-ET-MILESTONES.md)
|
||||
**API Gitea** : [26_GITEA-API.md](./26_GITEA-API.md)
|
||||
|
||||
Ne plus maintenir de catalogue exhaustif des tickets dans le dépôt : l’état (ouvert / fermé / milestone) change dans Gitea.
|
||||
|
||||
Pour une **version livrée**, lire le bilan correspondant (ex. [29_BILAN-VERSION-0.1.0.md](./29_BILAN-VERSION-0.1.0.md)).
|
||||
|
||||
**Backlog en cours `0.2.0` (quotidien)** : epic [#165](https://git.ptits-pas.fr/jmartin/petitspas/issues/165) · [découpage #166–#189](./30_DECOUPAGE-TICKETS-QUOTIDIEN.md) · [mini-spec](./31_MINI-SPEC-QUOTIDIEN-PARENT-AM.md).
|
||||
|
||||
Archive historique (liste Phase 1 figée, avril 2026) :
|
||||
[archive/obsolete/23_LISTE-TICKETS.md](./archive/obsolete/23_LISTE-TICKETS.md).
|
||||
+68
-33
@@ -1,7 +1,7 @@
|
||||
# 📋 Décisions Projet - P'titsPas
|
||||
|
||||
**Version** : 1.2
|
||||
**Date** : 16 Juin 2026
|
||||
**Version** : 1.4
|
||||
**Date** : 24 Septembre 2026
|
||||
**Auteur** : Équipe PtitsPas
|
||||
|
||||
---
|
||||
@@ -423,31 +423,23 @@ ptitspas-app/
|
||||
- Maintenance (tout au même endroit)
|
||||
- Versioning (Git)
|
||||
|
||||
**Structure** :
|
||||
**Structure** (sept. 2026) :
|
||||
```
|
||||
docs/
|
||||
├── 00_INDEX.md
|
||||
├── 01_CAHIER-DES-CHARGES.md
|
||||
├── 02_ARCHITECTURE.md
|
||||
├── 03_DEPLOYMENT.md
|
||||
├── 10_DATABASE.md
|
||||
├── 11_API.md
|
||||
├── 20_WORKFLOW-CREATION-COMPTE.md
|
||||
├── 21_CONFIGURATION-SYSTEME.md
|
||||
├── 22_DOCUMENTS-LEGAUX.md # pointeur → juridique/
|
||||
├── 27_BRIEFING-FRONTEND.md
|
||||
├── PROCEDURE-API-GITEA.md # pointeur → 26_GITEA-API.md
|
||||
├── juridique/
|
||||
│ ├── README.md
|
||||
│ ├── cgu.md
|
||||
│ ├── cgc.md
|
||||
│ └── 22_DOCUMENTS-LEGAUX.md
|
||||
├── archive/
|
||||
│ ├── README.md
|
||||
│ ├── temporaires/
|
||||
│ └── obsolete/
|
||||
├── 23_LISTE-TICKETS.md
|
||||
├── 01_CAHIER-DES-CHARGES.md # V1.4 fonctionnel
|
||||
├── 05_VERSIONS-ET-MILESTONES.md
|
||||
├── 12_SRS-GESTION-UTILISATEURS.md
|
||||
├── 23_SUIVI-TICKETS.md
|
||||
├── 24_DECISIONS-PROJET.md (ce document)
|
||||
├── 26_GITEA-API.md
|
||||
├── 27_BRIEFING-FRONTEND.md
|
||||
├── 28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md
|
||||
├── 29_BILAN-VERSION-0.1.0.md
|
||||
├── 99_REGLES-CODAGE.md
|
||||
├── CHARTE_GRAPHIQUE.md
|
||||
├── juridique/ # CGU + 22_DOCUMENTS-LEGAUX.md
|
||||
├── archive/ # obsolete / temporaires
|
||||
├── 90_AUDIT.md
|
||||
└── test-data/
|
||||
```
|
||||
@@ -473,19 +465,34 @@ docs/
|
||||
|
||||
---
|
||||
|
||||
### 26. Branches Git
|
||||
### 26. Branches Git + merge squash (norme)
|
||||
|
||||
**Décision** : ✅ **Stratégie simple : master + feature branches**
|
||||
**Décision** : ✅ **`develop` + `master` + `feature/*`, merges en squash**
|
||||
|
||||
**Justification** :
|
||||
- Simplicité (petite équipe)
|
||||
- Flexibilité
|
||||
- Historique lisible sur `develop` / `master` (1 commit = 1 ticket)
|
||||
- Déploiement prod uniquement depuis `master`
|
||||
|
||||
**Branches** :
|
||||
- `master` : Production
|
||||
- `archive/*` : Archives (ex: maquette initiale)
|
||||
- `migration/*` : Migrations (ex: intégration YNOV)
|
||||
- `feature/*` : Nouvelles fonctionnalités
|
||||
- `master` : Production (déploiement auto)
|
||||
- `develop` : Intégration / recette
|
||||
- `feature/*` : Ticket en cours (depuis `develop`)
|
||||
- `archive/*`, `migration/*` : Archives / migrations ponctuelles
|
||||
|
||||
**Flux (norme à partir de #169+)** :
|
||||
1. Branche `feature/N-…` depuis `develop`
|
||||
2. PR **feature → `develop`** : merge **squash** (`Do: squash` côté Gitea)
|
||||
3. Quand un lot est prêt : PR **`develop` → `master`** : merge **squash** également
|
||||
4. Message squash : `feat(#N): …` / `fix(#N): …` + `Closes #N` si applicable
|
||||
|
||||
**Exception** : les merges `--no-ff` déjà poussés (ex. #167, #168) restent tels quels — pas de réécriture d’historique.
|
||||
|
||||
**API Gitea** (rappel) :
|
||||
```http
|
||||
POST /repos/jmartin/petitspas/pulls/{index}/merge
|
||||
{"Do":"squash","MergeTitleField":"feat(#N): …","MergeMessageField":"Closes #N"}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -563,6 +570,33 @@ docs/
|
||||
|
||||
---
|
||||
|
||||
### 32. Module Absences + Cartes (séparation back / collecte)
|
||||
|
||||
**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** :
|
||||
- Premier vrai module d’interaction multi-acteurs
|
||||
- Évite de stocker l’historique dans des bulles éphémères
|
||||
- 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
|
||||
|
||||
**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`
|
||||
|
||||
---
|
||||
|
||||
## 📋 Résumé des décisions critiques
|
||||
|
||||
| # | Décision | Statut | Impact |
|
||||
@@ -583,6 +617,7 @@ docs/
|
||||
| 14 | Migration données | ❌ Rejeté | N/A |
|
||||
| 15 | Doc utilisateur | ⏸️ Phase 2 | Formation |
|
||||
| 31 | Logs Winston | ✅ Phase 1 | Monitoring |
|
||||
| 32 | Absences back + Cartes collecte | ✅ 0.2.0 | Métier / archi |
|
||||
| 5bis | Familles recomposées — 2ᵉ compte v1.0.0 | ✅ v1.0.0 | Métier / dossier |
|
||||
|
||||
---
|
||||
@@ -594,11 +629,11 @@ docs/
|
||||
| 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 |
|
||||
| 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.3 | Précision 5bis — cible post-1.0.0 : parcours gestionnaire § 7.5 (#139), visibilité par enfant |
|
||||
| 24/09/2026 | 1.4 | Décision 32 — Absences (`evenements_agenda`) ≠ Cartes ; Epic C recentré ; drop `evenements` |
|
||||
|
||||
---
|
||||
|
||||
**Dernière mise à jour** : 16 Juin 2026
|
||||
**Version** : 1.2
|
||||
**Dernière mise à jour** : 24 Septembre 2026
|
||||
**Version** : 1.4
|
||||
**Statut** : ✅ Document validé
|
||||
|
||||
|
||||
@@ -116,10 +116,17 @@ curl -s -H "Authorization: token $GITEA_TOKEN" \
|
||||
"https://git.ptits-pas.fr/api/v1/repos/jmartin/petitspas/pulls?state=open" | jq .
|
||||
|
||||
# Créer une PR (head = branche source, base = branche cible)
|
||||
# Norme : feature/* → develop, puis develop → master
|
||||
curl -s -X POST -H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"head":"develop","base":"master","title":"Titre de la PR"}' \
|
||||
-d '{"head":"feature/XX-nom","base":"develop","title":"feat(#XX): Titre","body":"Closes #XX"}' \
|
||||
"https://git.ptits-pas.fr/api/v1/repos/jmartin/petitspas/pulls"
|
||||
|
||||
# Merger en squash (norme — voir 24_DECISIONS-PROJET.md §26)
|
||||
curl -s -X POST -H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"Do":"squash","MergeTitleField":"feat(#XX): Titre","MergeMessageField":"Closes #XX"}' \
|
||||
"https://git.ptits-pas.fr/api/v1/repos/jmartin/petitspas/pulls/{index}/merge"
|
||||
```
|
||||
|
||||
### 3.4 Branches
|
||||
|
||||
@@ -194,6 +194,9 @@ frontend/lib/
|
||||
|
||||
## Workflow Git
|
||||
|
||||
Norme projet : **squash merge** (voir [24_DECISIONS-PROJET.md](./24_DECISIONS-PROJET.md) §26).
|
||||
Cible habituelle : `feature/*` → `develop` ; puis `develop` → `master` quand le lot est prêt.
|
||||
|
||||
```bash
|
||||
# 1. Créer une branche feature
|
||||
git checkout develop
|
||||
@@ -204,15 +207,22 @@ git checkout -b feature/XX-nom-ticket
|
||||
git add .
|
||||
git commit -m "feat(#XX): Description courte"
|
||||
|
||||
# 3. Pousser et créer PR
|
||||
# 3. Pousser et créer PR vers develop
|
||||
git push -u origin feature/XX-nom-ticket
|
||||
|
||||
# 4. Créer PR vers master via Gitea ou API
|
||||
# 4. Créer PR (base = develop)
|
||||
curl -X POST \
|
||||
-H "Authorization: token giteabu_1796c6aace0e2ef7e4fdb49cdc3bc1bf8ee31fbc" \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"title":"feat(#XX): Titre","body":"Description\n\nCloses #XX","head":"feature/XX-nom-ticket","base":"master"}' \
|
||||
-d '{"title":"feat(#XX): Titre","body":"Description\n\nCloses #XX","head":"feature/XX-nom-ticket","base":"develop"}' \
|
||||
"https://git.ptits-pas.fr/api/v1/repos/jmartin/petitspas/pulls"
|
||||
|
||||
# 5. Merger en squash (pas merge commit)
|
||||
curl -X POST \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"Do":"squash","MergeTitleField":"feat(#XX): Titre","MergeMessageField":"Closes #XX"}' \
|
||||
"https://git.ptits-pas.fr/api/v1/repos/jmartin/petitspas/pulls/{index}/merge"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
**Version** : 1.1
|
||||
**Date** : 16 juin 2026
|
||||
**Statut** : Réflexions produit / architecture — complément au [CDC](./01_CAHIER-DES-CHARGES.md)
|
||||
**Documents liés** : [EVOLUTIONS_CDC.md](./EVOLUTIONS_CDC.md), [24_DECISIONS-PROJET.md](./24_DECISIONS-PROJET.md), [23_LISTE-TICKETS.md](./23_LISTE-TICKETS.md)
|
||||
**Documents liés** : [01_CAHIER-DES-CHARGES.md](./01_CAHIER-DES-CHARGES.md) (V1.4), [12_SRS-GESTION-UTILISATEURS.md](./12_SRS-GESTION-UTILISATEURS.md), [24_DECISIONS-PROJET.md](./24_DECISIONS-PROJET.md), [23_SUIVI-TICKETS.md](./23_SUIVI-TICKETS.md), [29_BILAN-VERSION-0.1.0.md](./29_BILAN-VERSION-0.1.0.md)
|
||||
**Archive** : ancien patch CDC → [archive/obsolete/EVOLUTIONS_CDC.md](./archive/obsolete/EVOLUTIONS_CDC.md)
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
# Bilan — Version 0.1.0
|
||||
|
||||
**Statut** : terminée
|
||||
**Milestone Gitea** : [0.1.0](https://git.ptits-pas.fr/jmartin/petitspas/milestone/10)
|
||||
**Dépôt** : `jmartin/petitspas`
|
||||
**Tag prévu** : `v0.1.0` (sur `master` après merge de cette doc)
|
||||
|
||||
Ce document est la **mémoire produit** de la version 0.1.0 : ce qui a été livré, ticket par ticket, et ce qui a été reporté.
|
||||
|
||||
---
|
||||
|
||||
## 1. Périmètre produit livré
|
||||
|
||||
La 0.1.0 couvre le **MVP opérable** pour une collectivité :
|
||||
|
||||
- Authentification, création / oubli de mot de passe, e-mails associés
|
||||
- Inscription parent & AM, validation / refus gestionnaire, reprise après refus
|
||||
- Dashboard staff (admin + gestionnaire) : listes, fiches, rattachements
|
||||
- Onglet **Dossiers** + wizards création / édition (famille & AM)
|
||||
- Suppressions métier (droits, confirms, cascades API)
|
||||
- Cleanups structurels (préfixe `Admin*`, panels dashboard, modale staff, retrait `est_multiple`)
|
||||
|
||||
**Hors 0.1.0** (reporté) : doublons avancés, famille N responsables, statut enfant gardé/sans garde, combobox RPE AM, chantier CDC (#117), tickets tech/observabilité — voir §4 et [05_VERSIONS-ET-MILESTONES.md](./05_VERSIONS-ET-MILESTONES.md).
|
||||
|
||||
---
|
||||
|
||||
## 2. Thèmes livrés
|
||||
|
||||
### 2.1 Auth, mot de passe, e-mails
|
||||
|
||||
| # | Titre | Livré |
|
||||
|---|-------|--------|
|
||||
| 24 | API Création mot de passe | Endpoints token → création MDP post-validation |
|
||||
| 28 | Templates Email — Validation | Mails validation avec lien MDP |
|
||||
| 30 | Connexion — Vérification statut | Blocage comptes pending / suspendus à la connexion |
|
||||
| 43 | Écran Création Mot de Passe | UI lien e-mail création MDP |
|
||||
| 47 | Écran Changement MDP Obligatoire | Première connexion staff |
|
||||
| 50 | Affichage dynamique CGU | CGU/Privacy versionnées à l’inscription |
|
||||
| 118 | Page création mot de passe (Front + API) | Alignement front/API du flux lien e-mail |
|
||||
| 123 | Durcissement token création MDP | TTL, usage unique, contrôles API |
|
||||
| 127 | Mot de passe oublié | Demande → e-mail → réinitialisation (flux distinct de #24/#43) |
|
||||
|
||||
### 2.2 Inscription, numéros de dossier, reprise
|
||||
|
||||
| # | Titre | Livré |
|
||||
|---|-------|--------|
|
||||
| 104 | Numéro de dossier — frontend | Affichage listes / mails / modales ; format AAAA-… |
|
||||
| 112 | Reprise après refus — frontend | Lien e-mail `/reprise` + reprise par n° dossier |
|
||||
| 120 | Inscription AM — photo & UX | Chaîne photo / API / UX alignée parents |
|
||||
| 144 | Consentement photo enfant | Persistance du consentement à l’inscription |
|
||||
|
||||
### 2.3 Dashboard — fiches, listes, rattachements
|
||||
|
||||
| # | Titre | Livré |
|
||||
|---|-------|--------|
|
||||
| 115 | Rattachement enfants — backend | Attach/detach parent↔enfant et AM↔enfant |
|
||||
| 116 | Rattachement enfants — frontend | UI fiches parent / AM |
|
||||
| 130 | UserService — APIs métier | Branchement parents / AM / enfants côté front |
|
||||
| 131 | Édition fiche parent + AM | Modales édition dashboard |
|
||||
| 132 | Création enfant (onglet Enfants) | Création + rattachement foyer |
|
||||
| 136 | API enfants — droits & liste | Droits gestionnaire + enrichissement liste |
|
||||
| 137 | Onglet Enfants — liste globale | Panneau liste dashboard |
|
||||
| 138 | Fiche enfant + liste dans parent | Fiche enfant ; enfants dans fiche parent |
|
||||
| 140 | Epic fiche parent / affiliation | Livraison regroupée dashboard admin/gestionnaire |
|
||||
| 142 | Clic carte → modale | Ouverture fiche depuis les listes |
|
||||
| 145 | Lien co-parent cliquable | Navigation fiche parent → co-parent |
|
||||
| 146 | Modale sélection enfant | UX rattacher enfant (AM + parent) |
|
||||
| 147 | Modale sélection AM | UX rattacher AM depuis fiche enfant |
|
||||
| 148 | Capacité max AM | Désactivation rattachement si capacité atteinte |
|
||||
| 149 | Case libre AM → rattacher | Clic emplacement vide pour rattacher |
|
||||
| 151 | GET /relais pour gestionnaire | Combo relais dans modale staff |
|
||||
| 157 | Enfant sans responsable | Détachement dernier parent + alerte liste |
|
||||
| 158 | Affiliation foyer (pivot + co-parent) | Attach/detach cohérents sur le foyer |
|
||||
|
||||
### 2.4 Dossiers staff (création, édition, liste)
|
||||
|
||||
| # | Titre | Livré |
|
||||
|---|-------|--------|
|
||||
| 129 | Création dossier parent | Wizard + API staff famille |
|
||||
| 135 | Édition dossier + 2ᵉ parent | Mode edit wizards + `POST …/co-parent` |
|
||||
| 153 | Onglet Dossiers | Liste unifiée + à valider (sans création dans l’onglet) |
|
||||
| 156 | Création dossier AM | Wizard + API staff AM |
|
||||
|
||||
### 2.5 Suppressions & droits staff
|
||||
|
||||
| # | Titre | Livré |
|
||||
|---|-------|--------|
|
||||
| 133 | Suppression parent + AM (UI) | Première vague UI (complétée par #160) |
|
||||
| 134 | Droits « Ajouter gestionnaire » | Visibilité / API selon rôle |
|
||||
| 143 | Bug supprimer sa propre fiche | Masquage / interdiction auto-suppression |
|
||||
| 154 | Epic suppressions | Cadrage règles métier suppressions |
|
||||
| 159 | Suppressions métier — backend | Cascades, garde-fous, droits API |
|
||||
| 160 | Suppressions dashboard — frontend | Poubelles + dialogues de confirmation |
|
||||
| 161 | Admin création staff 403 | Admin peut créer gestionnaire et administrateur |
|
||||
|
||||
### 2.6 Cleanups structure & UX
|
||||
|
||||
| # | Titre | Livré |
|
||||
|---|-------|--------|
|
||||
| 25 | API Liste comptes en attente | Historique ; couvert par flux dossiers / validation |
|
||||
| 26 | API Validation / Refus | Historique ; couvert par flux dossiers / validation |
|
||||
| 152 | Retrait `est_multiple` | Suppression full stack (BDD, API, front, docs) |
|
||||
| 155 | Rename préfixe `Admin*` | Widgets partagés sans préfixe Admin (option C) |
|
||||
| 162 | Panels → `widgets/dashboard/` | Suite #155 — panels staff sous dashboard |
|
||||
| 164 | Modale staff uniformisée | `StaffUserFormModal` (shell 930, champs contrôlés) |
|
||||
|
||||
---
|
||||
|
||||
## 3. Inventaire exhaustif (48 tickets fermés, milestone 0.1.0)
|
||||
|
||||
| # | Titre |
|
||||
|---|-------|
|
||||
| 24 | [Backend] API Création mot de passe |
|
||||
| 25 | [Backend] API Liste comptes en attente |
|
||||
| 26 | [Backend] API Validation/Refus comptes |
|
||||
| 28 | [Backend] Templates Email - Validation |
|
||||
| 30 | [Backend] Connexion - Vérification statut |
|
||||
| 43 | [Frontend] Écran Création Mot de Passe |
|
||||
| 47 | [Frontend] Écran Changement MDP Obligatoire |
|
||||
| 50 | [Frontend] Affichage dynamique CGU lors inscription |
|
||||
| 104 | Numéro de dossier – frontend |
|
||||
| 112 | Reprise après refus – frontend |
|
||||
| 115 | [Backend] Rattachement enfants — parent et AM |
|
||||
| 116 | [Frontend] Rattachement enfants — parent et AM |
|
||||
| 118 | Page création mot de passe (lien email) – Front + API |
|
||||
| 120 | [Full-stack] Inscription AM — photo, API et UX alignés sur les parents |
|
||||
| 123 | [Tech] Durcissement token création MDP |
|
||||
| 127 | [Full-stack] Mot de passe oublié — flux complet |
|
||||
| 129 | Création dossier parent (wizard + API staff) |
|
||||
| 130 | [Frontend] UserService — brancher APIs parents, AM et enfants |
|
||||
| 131 | [Frontend] Édition fiche parent + AM |
|
||||
| 132 | Création enfant depuis l’onglet Enfants |
|
||||
| 133 | [Frontend] Suppression compte parent + AM |
|
||||
| 134 | Droits bouton « Ajouter gestionnaire » |
|
||||
| 135 | Mode édition dossier (+ ajout 2ᵉ parent) |
|
||||
| 136 | [Backend] API enfants — droits gestionnaire + enrichissement liste |
|
||||
| 137 | [Frontend] Onglet Enfants — liste globale |
|
||||
| 138 | [Frontend] Fiche enfant + liste enfants dans fiche parent |
|
||||
| 140 | Dashboard admin — fiche parent, enfants et affiliation |
|
||||
| 142 | Clic sur carte → ouvrir la modale |
|
||||
| 143 | Bug — Gestionnaire Supprimer sur sa propre fiche |
|
||||
| 144 | Bug — Consentement photo enfant non sauvegardé |
|
||||
| 145 | Lien co-parent cliquable |
|
||||
| 146 | UX — modale sélection d'enfant |
|
||||
| 147 | UX — modale sélection d'AM |
|
||||
| 148 | Bug — capacité max AM |
|
||||
| 149 | Fiche AM — clic case libre pour rattacher |
|
||||
| 151 | Bug — GET /relais gestionnaire |
|
||||
| 152 | Cleanup — supprimer `est_multiple` |
|
||||
| 153 | Onglet permanent « Dossiers » |
|
||||
| 154 | Epic — suppressions utilisateurs / dossiers / enfants / AM |
|
||||
| 155 | Cleanup — renommer préfixe Admin* |
|
||||
| 156 | Création dossier AM (wizard + API staff) |
|
||||
| 157 | Enfant sans responsable |
|
||||
| 158 | Affiliation enfant au foyer (pivot + co-parent) |
|
||||
| 159 | Backend suppressions métier (#154) |
|
||||
| 160 | Frontend suppressions dashboard (#154) |
|
||||
| 161 | Bug — Admin création gestionnaire / administrateur |
|
||||
| 162 | Cleanup — panels vers `widgets/dashboard/` |
|
||||
| 164 | Uniformisation modale staff + champs contrôlés |
|
||||
|
||||
Issues : https://git.ptits-pas.fr/jmartin/petitspas/issues?q=&type=all&state=closed&labels=&milestone=10&assignee=0
|
||||
|
||||
---
|
||||
|
||||
## 4. Reporté hors 0.1.0
|
||||
|
||||
| # | Titre | Destination typique |
|
||||
|---|-------|---------------------|
|
||||
| 113 / 114 | Doublons inscription / alerte gestionnaire | 0.9.0 |
|
||||
| 117 | Évolution du cahier des charges | Doc (amendement CDC post-0.1.0) |
|
||||
| 121–122, 124–125 | Tech auth / photos / DB | 0.9.0 |
|
||||
| 126 | Upload documents légaux 500 | 0.9.0 |
|
||||
| 128 | Audit / traçabilité modifications | 0.9.0 |
|
||||
| 139 | Famille complexe N responsables | Post-0.1.0 / epic |
|
||||
| 141 | Statut enfant gardé / sans garde | Post-0.1.0 |
|
||||
| 150 | Combobox rattachement RPE (AM) | 0.2.0 |
|
||||
|
||||
Voir aussi [05_VERSIONS-ET-MILESTONES.md](./05_VERSIONS-ET-MILESTONES.md).
|
||||
|
||||
---
|
||||
|
||||
## 5. Suite documentaire
|
||||
|
||||
1. **Amendement CDC (#117)** — CDC V1.4 : mise à jour **gestion utilisateurs** ; le reste du CDC reste la cible. SRS technique : [12_SRS-GESTION-UTILISATEURS.md](./12_SRS-GESTION-UTILISATEURS.md). Intrants historiques archivés : [archive/obsolete/EVOLUTIONS_CDC.md](./archive/obsolete/EVOLUTIONS_CDC.md), [28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md](./28_EVOLUTION-FAMILLE-ET-RESPONSABLES.md).
|
||||
2. **Tag** `v0.1.0` sur `master` lorsque milestone fermée + ce bilan mergé.
|
||||
3. Enchaîner les milestones **0.2.0+** selon [05_VERSIONS-ET-MILESTONES.md](./05_VERSIONS-ET-MILESTONES.md).
|
||||
|
||||
---
|
||||
|
||||
## 6. Références code (points d’entrée)
|
||||
|
||||
- Modale staff : `frontend/lib/widgets/dashboard/staff_user_form_modal.dart`
|
||||
- Fiches : `parent_edit_modal.dart`, `am_edit_modal.dart`, `child_detail_modal.dart`
|
||||
- Wizards dossiers : `parent_dossier_wizard.dart`, `am_dossier_wizard.dart`
|
||||
- Règles suppressions : tickets #154 / #159 / #160
|
||||
- Cleanup `est_multiple` : #152
|
||||
@@ -0,0 +1,212 @@
|
||||
# Découpage tickets — Quotidien parent / AM
|
||||
|
||||
> **Statut :** backlog Gitea **0.2.0** / épic [#165](https://git.ptits-pas.fr/jmartin/petitspas/issues/165) — architecture absences + cartes recentrée (sept. 2026).
|
||||
> **Réf. visuelle :** [maquettes/courantes/maquette-dashboard-parent-quotidien-v4.png](./maquettes/courantes/maquette-dashboard-parent-quotidien-v4.png)
|
||||
> **Mini-spec :** [31_MINI-SPEC-QUOTIDIEN-PARENT-AM.md](./31_MINI-SPEC-QUOTIDIEN-PARENT-AM.md)
|
||||
> **Décision :** [24_DECISIONS-PROJET.md](./24_DECISIONS-PROJET.md) §32 (Cartes ≠ back Absences).
|
||||
|
||||
## Intention produit (rappel)
|
||||
|
||||
- TdB PC en **3 colonnes** : **cartes** | **blog** (défaut) | **messagerie**
|
||||
- Contexte actif = **couple** enfant–nounou (parent) / enfant–parent(s) (AM)
|
||||
- Blog **indispensable** (AM + RPE) ; messagerie type WhatsApp (BABA, 2 parents = même fil AM)
|
||||
- Look **papier / pastel / lignée inscription** (pas le dashboard staff)
|
||||
- **Widgets partagés** parent ↔ AM (blog, messagerie, cartes, coquille, couple paramétré) — pas de double implémentation
|
||||
- « Effet démo » = logiciel peuplé + sync live multi-écrans — **pas** un sous-MVP jetable
|
||||
- **Hors ce découpage** (jalons suivants) : page Contrat riche (Pajemploi, CP), notifs CDC fourre-tout, masquage messages, posts blog parent, Agenda « riche » (entrée bandeau possible en stub)
|
||||
|
||||
## Contrainte technique front (dictée 23/09)
|
||||
|
||||
Les panneaux parent et AM étant **quasiment identiques**, le découpage impose des **briques réutilisables** :
|
||||
|
||||
| Widget / module | Tickets concernés |
|
||||
|-----------------|-------------------|
|
||||
| Coquille TdB 3 colonnes + bandeau | A1, B1 — B1 **réutilise** la coquille d’A1 |
|
||||
| Sélecteur couple (mode parent vs AM) | A2, B2 — **un** composant, 2 modes |
|
||||
| Flux de cartes | C2, C3 — **un** widget + config rôles |
|
||||
| Blog (fil + composeur) | D2, D3, D4 — même brique |
|
||||
| Messagerie (chat + onglets) | E4, E5, E6 — même brique |
|
||||
|
||||
Les tickets **[Front] AM** (B1, B2, C3, D3, E5) = **intégration / mode rôle**, pas une 2ᵉ copie du code.
|
||||
|
||||
|
||||
## Proposition de milestone
|
||||
|
||||
| Champ | Valeur |
|
||||
|-------|--------|
|
||||
| Titre | **`0.2.0`** (rouvert) |
|
||||
| Description | Quotidien parent / AM — TdB 3 colonnes, cartes, blog, messagerie |
|
||||
| Label | `v0.2.0` |
|
||||
|
||||
## Mapping Gitea
|
||||
|
||||
| Id | Issue | Titre |
|
||||
|----|-------|-------|
|
||||
| Epic | [#165](https://git.ptits-pas.fr/jmartin/petitspas/issues/165) | Epic quotidien |
|
||||
| A1 | [#166](https://git.ptits-pas.fr/jmartin/petitspas/issues/166) | [Front] Coquille TdB parent |
|
||||
| A2 | [#167](https://git.ptits-pas.fr/jmartin/petitspas/issues/167) | [Front] Couple enfant–nounou |
|
||||
| A3 | [#168](https://git.ptits-pas.fr/jmartin/petitspas/issues/168) | [Backend] API couples parent |
|
||||
| B1 | [#169](https://git.ptits-pas.fr/jmartin/petitspas/issues/169) | [Front] Coquille TdB AM |
|
||||
| B2 | [#170](https://git.ptits-pas.fr/jmartin/petitspas/issues/170) | [Front] Couple enfant–parent(s) |
|
||||
| B3 | [#171](https://git.ptits-pas.fr/jmartin/petitspas/issues/171) | [Backend] API enfants AM |
|
||||
| C1 | [#172](https://git.ptits-pas.fr/jmartin/petitspas/issues/172) | [Backend] API cartes |
|
||||
| C2 | [#173](https://git.ptits-pas.fr/jmartin/petitspas/issues/173) | [Front] Cartes parent |
|
||||
| C3 | [#174](https://git.ptits-pas.fr/jmartin/petitspas/issues/174) | [Front] Cartes AM |
|
||||
| C4 | [#175](https://git.ptits-pas.fr/jmartin/petitspas/issues/175) | [Front] Déclarer absence |
|
||||
| C5 | [#176](https://git.ptits-pas.fr/jmartin/petitspas/issues/176) | [Front] Formulaires AM cartes |
|
||||
| D1 | [#177](https://git.ptits-pas.fr/jmartin/petitspas/issues/177) | [Backend] API blog |
|
||||
| D2 | [#178](https://git.ptits-pas.fr/jmartin/petitspas/issues/178) | [Front] Blog parent |
|
||||
| D3 | [#179](https://git.ptits-pas.fr/jmartin/petitspas/issues/179) | [Front] Blog AM |
|
||||
| D4 | [#180](https://git.ptits-pas.fr/jmartin/petitspas/issues/180) | [Front] Blog gestionnaire |
|
||||
| E1 | [#181](https://git.ptits-pas.fr/jmartin/petitspas/issues/181) | [Backend] Socle messagerie |
|
||||
| E2 | [#182](https://git.ptits-pas.fr/jmartin/petitspas/issues/182) | [Backend] Mess. AM |
|
||||
| E3 | [#183](https://git.ptits-pas.fr/jmartin/petitspas/issues/183) | [Backend] Mess. RPE |
|
||||
| E4 | [#184](https://git.ptits-pas.fr/jmartin/petitspas/issues/184) | [Front] Messagerie parent |
|
||||
| E5 | [#185](https://git.ptits-pas.fr/jmartin/petitspas/issues/185) | [Front] Messagerie AM |
|
||||
| E6 | [#186](https://git.ptits-pas.fr/jmartin/petitspas/issues/186) | [Front] Mess. RPE gestionnaire |
|
||||
| F1 | [#187](https://git.ptits-pas.fr/jmartin/petitspas/issues/187) | [Front] Stubs Agenda / Contrat |
|
||||
| F2 | [#188](https://git.ptits-pas.fr/jmartin/petitspas/issues/188) | [Front] Swipe mobile |
|
||||
| G1 | [#189](https://git.ptits-pas.fr/jmartin/petitspas/issues/189) | [Backend] Seeds quotidien |
|
||||
|
||||
---
|
||||
|
||||
## Epic A — Coquille TdB parent
|
||||
|
||||
### A1 — [Front] Coquille TdB parent 3 colonnes + bandeau → [#166](https://git.ptits-pas.fr/jmartin/petitspas/issues/166)
|
||||
Bandeau TdB / Agenda / Contrat + menu user ; corps en 3 colonnes (cartes | blog | messagerie) ; fond papier / pastel. **Livrer la coquille comme widget/layout réutilisable** (l’AM B1 s’en branche). Remplace / refactor `ParentDashboardScreen` + `dashbord_parent/`.
|
||||
|
||||
### A2 — [Front] Sélecteur couple enfant–nounou → [#167](https://git.ptits-pas.fr/jmartin/petitspas/issues/167)
|
||||
Composant **paramétrable** (mode parent : enfant|nounou). Dropdown si plusieurs gardes ; informatif si une seule. B2 = même widget en mode AM.
|
||||
|
||||
### A3 — [Back] API contexte de garde actif (couples parent)
|
||||
Endpoint(s) listant les couples enfant–AM du parent connecté + couple « courant » (persistance session / préférence). Données mini : ids, noms, photos.
|
||||
|
||||
---
|
||||
|
||||
## Epic B — Coquille TdB AM (miroir)
|
||||
|
||||
### B1 — [Front] Coquille TdB AM 3 colonnes + bandeau → [#169](https://git.ptits-pas.fr/jmartin/petitspas/issues/169)
|
||||
**Réutilise** la coquille d’A1/#166 ; point de départ `am_dashboard_screen.dart`.
|
||||
|
||||
### B2 — [Front] Sélecteur couple enfant–parent(s) → [#170](https://git.ptits-pas.fr/jmartin/petitspas/issues/170)
|
||||
**Même widget** qu’A2 en mode AM : gauche photo enfant ; droite parent1+parent2 empilés ou un parent centré.
|
||||
|
||||
### B3 — [Back] API contexte enfants accueillis (AM)
|
||||
Liste des enfants / foyers pour l’AM + contexte courant (symétrique A3).
|
||||
|
||||
---
|
||||
|
||||
## Epic C — Absences + Cartes (file d’attention)
|
||||
|
||||
**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)
|
||||
|
||||
| Étape | Contenu |
|
||||
|-------|---------|
|
||||
| BDD | Table `evenements_agenda` + drop `evenements` |
|
||||
| API | CRUD + **GET liste** (`placementId` \| tous les placements du user) |
|
||||
| Cartes SYSTEM | Module `cards/` types S1–S3 (sans sondages V1) |
|
||||
| Realtime | WS/SSE bulles → **SSE** `GET /cards/stream` (#195) |
|
||||
| Purge TTL | Job `expire_at` / `purge_at` |
|
||||
|
||||
### Front (après API — hors chantier back immédiat)
|
||||
|
||||
| Ticket | Contenu |
|
||||
|--------|---------|
|
||||
| Feed parent / AM | File d’attention bulles (widget partagé) |
|
||||
| Modale « Ajouter une bulle » | Générique + absence parent / congé·arrêt AM |
|
||||
| Agenda | Consommer GET liste (lignes) |
|
||||
|
||||
### Hors V1 cartes
|
||||
|
||||
Sondages / catalogue admin OPTIONNEL / sortie riche / desktop 2 panneaux (évolution séparée).
|
||||
|
||||
---
|
||||
|
||||
## Epic D — Blog
|
||||
|
||||
### D1 — [Back] Modèle + API blog (posts + médias)
|
||||
Posts par auteur AM ou gestionnaire (RPE) ; texte + photos ; ciblage enfants (AM) / audience (RPE) ; fil visible parents (et AM selon règles). Sync temps réel ou polling acceptable V1.
|
||||
|
||||
### D2 — [Front] Colonne Blog parent (défaut)
|
||||
Fil de posts ; auteur **distinct** AM vs RPE ; miniatures ; pas de bouton « Écrire un post » parent en V1 (reporté).
|
||||
|
||||
### D3 — [Front] Colonne Blog AM — lecture + écrire un post
|
||||
Composer texte + photos + sélection enfants concernés ; publication.
|
||||
|
||||
### D4 — [Front] Publication blog gestionnaire (point d’entrée staff)
|
||||
UI minimale côté dashboard gestionnaire (ou réutilisation) pour publier une annonce RPE visible sur les TdB parent/AM.
|
||||
|
||||
---
|
||||
|
||||
## Epic E — Messagerie
|
||||
|
||||
### E1 — [Back] Socle messagerie (choix lib / protocole) + API
|
||||
Évaluer brique existante (style chat WhatsApp : texte, emoji, images). Conversations, participants, pièces jointes images. Temps réel (WS ou équivalent) souhaité pour l’effet multi-écrans.
|
||||
|
||||
### E2 — [Back] Mess. AM — conversation foyer ↔ AM
|
||||
Une conversation par couple/foyer ; **les deux parents** voient le **même** fil. Pas de masquage V1.
|
||||
|
||||
### E3 — [Back] Mess. RPE — privée + ajout de participants
|
||||
Fil 1↔1 par défaut (parent↔RPE ou AM↔RPE) ; possibilité d’**ajouter** 2ᵉ parent / AM / parent pour médiation.
|
||||
|
||||
### E4 — [Front] Colonne messagerie parent (onglets Mess. AM | Mess. RPE)
|
||||
UI chat + saisie + PJ ; défaut = Mess. AM.
|
||||
|
||||
### E5 — [Front] Colonne messagerie AM (onglets équivalents)
|
||||
Miroir parent ; Mess. AM = foyer courant ; Mess. RPE = canal relais.
|
||||
|
||||
### E6 — [Front] Mess. RPE côté gestionnaire (entrée minimale)
|
||||
Liste / réponse aux fils RPE + ajout de participants pour médiation.
|
||||
|
||||
---
|
||||
|
||||
## Epic F — Navigation & mobile (socle)
|
||||
|
||||
### F1 — [Front] Navigation Agenda / Contrat (stubs ou routes)
|
||||
Entrées bandeau : pages **placeholder** ou squelette (Agenda / Contrat pleine page) pour ne pas bloquer le TdB — contenu métier = jalons suivants.
|
||||
|
||||
### F2 — [Front] Adaptation mobile — swipe 3 panneaux
|
||||
Sur téléphone : swipe Blog ↔ Cartes ↔ Messagerie ; navigation TdB/Agenda/Contrat hors swipe. Contrat peut rester limité (« mieux sur PC ») en V1 si besoin.
|
||||
|
||||
---
|
||||
|
||||
## Epic G — Données de démo / peuplement
|
||||
|
||||
### G1 — [Back/Outillage] Jeu de données peuplé quotidien
|
||||
Scripts / seeds : foyer 2 parents, AM, enfant(s), quelques cartes, posts blog, fils messagerie — pour enchaîner une démo multi-écrans sans saisie manuelle lourde.
|
||||
|
||||
---
|
||||
|
||||
## Hors découpage (volontairement)
|
||||
|
||||
| Sujet | Motif |
|
||||
|-------|--------|
|
||||
| Page Contrat (Pajemploi, CP, avenants) | Module valué — jalon dédié |
|
||||
| Agenda calendrier riche | Entrée bandeau OK en stub ; métier plus tard |
|
||||
| Notifs CDC (contrat/paiement/dossier) | Plus tard |
|
||||
| Masquage messages / privé parent↔AM | Plus tard |
|
||||
| Parent auteur de posts blog | Hypothétique / plus tard |
|
||||
| Photo parent à l’inscription | Non ; éventuel menu profil plus tard |
|
||||
|
||||
---
|
||||
|
||||
## Ordre de réalisation suggéré
|
||||
|
||||
1. **A1 → A2 → A3** (coquille + contexte parent) — *fait*
|
||||
2. **BDD absences → API absences** puis **Cartes SYSTEM** (congés/absences/arrêt)
|
||||
3. **Feed / modale bulles** (front) + agenda lignes
|
||||
4. **D1 → D2 / D3** (blog)
|
||||
5. **E1 → E2 → E4** (messagerie AM)
|
||||
6. **B1 → B2 → B3** + miroirs AM
|
||||
7. Realtime / purge TTL / RPE / F/G
|
||||
|
||||
Desktop 2 panneaux (cartes prioritaires sur blog) = **évolution hors 0.2.0**.
|
||||
|
||||
---
|
||||
|
||||
## Validation
|
||||
|
||||
Backlog créé sur Gitea (**#165–#189**, milestone `0.2.0`).
|
||||
**Implémentation code** : seulement après relecture PO / ajustements éventuels sur le découpage.
|
||||
@@ -0,0 +1,112 @@
|
||||
# Mini-spec — Quotidien parent / AM
|
||||
|
||||
> **Statut :** figée pour backlog (sept. 2026)
|
||||
> **Réf. visuelle :** [maquettes/courantes/maquette-dashboard-parent-quotidien-v4.png](./maquettes/courantes/maquette-dashboard-parent-quotidien-v4.png)
|
||||
> **Découpage tickets :** [30_DECOUPAGE-TICKETS-QUOTIDIEN.md](./30_DECOUPAGE-TICKETS-QUOTIDIEN.md)
|
||||
> **CDC :** vision d’origine conservée ; priorités UX évoluées (blog central, couple enfant–nounou)
|
||||
|
||||
## 1. Objectif
|
||||
|
||||
Construire les **espaces parent et AM du quotidien** : tableau de bord 3 colonnes, file de cartes (absences / congés / sorties), **blog** (cœur du jour), **messagerie** AM et RPE. Logiciel réel peuplé de données ; une démo = sync live multi-écrans (parent / AM / gestionnaire).
|
||||
|
||||
## 2. UI — contrainte non négociable
|
||||
|
||||
- Look **papier / pastel**, lignée **login / inscription** (`paper2.png`), pas le dashboard staff violet Material
|
||||
- PC paysage : **3 colonnes** égales
|
||||
- Mobile : **swipe** entre les 3 panneaux ; TdB / Agenda / Contrat via nav dédiée
|
||||
|
||||
### Architecture front — maximiser les widgets partagés
|
||||
|
||||
Parent et AM sont **quasi identiques** : **ne pas dupliquer** les colonnes métier.
|
||||
|
||||
| Brique | Usage |
|
||||
|--------|--------|
|
||||
| Widget **Blog** | Colonne milieu parent **et** AM (+ entrée publication gestionnaire qui réutilise le composeur) |
|
||||
| Widget **Messagerie** | Colonne droite parent **et** AM (+ vue gestionnaire RPE) |
|
||||
| Widget **flux de cartes** | Colonne gauche parent **et** AM (actions / droits selon rôle) |
|
||||
| Widget **bandeau couple** | Variante *enfant\|nounou* (parent) vs *enfant\|parent(s)* (AM) — même composant paramétré |
|
||||
| Coquille TdB 3 colonnes | Layout / bandeau navig commun ; le rôle injecte le couple + droits |
|
||||
|
||||
Principe : **briques correctement encapsulées** (API claire props / callbacks), branchées sur le même back ; seules les **différences de rôle** (qui crée quoi, libellés d’action) restent hors du widget partagé.
|
||||
|
||||
|
||||
## 3. Layout TdB
|
||||
|
||||
| Colonne | Contenu |
|
||||
|---------|---------|
|
||||
| **Gauche** | Couple actif · flux de **cartes** · actions (ex. Déclarer une absence) |
|
||||
| **Milieu** | **Blog** — affichage **par défaut** à l’arrivée |
|
||||
| **Droite** | **Messagerie** seule — onglets Mess. AM (défaut) \| Mess. RPE |
|
||||
|
||||
Bandeau : **TdB** · **Agenda** · **Contrat** · menu user (recherche AM, paramètres…).
|
||||
|
||||
### Parent — couple
|
||||
|
||||
- Un bandeau **enfant | nounou** (photos + noms)
|
||||
- Plusieurs gardes → dropdown unique (bascule de couple)
|
||||
- Une seule garde → affichage informatif (pas de chevron)
|
||||
|
||||
### AM — couple (miroir)
|
||||
|
||||
- Bandeau **enfant | parent(s)**
|
||||
- 2 parents : noms empilés à droite ; 1 parent : nom centré
|
||||
- Pas de photo parent obligatoire (option profil plus tard)
|
||||
|
||||
## 4. Canaux (ne pas mélanger)
|
||||
|
||||
| Canal | Rôle |
|
||||
|-------|------|
|
||||
| **Cartes** | Décisions / futur proche : absences, congés, maladie AM, sorties à valider |
|
||||
| **Blog** | Mémoire / actus du quotidien (texte + photos) — **indispensable**, plus un module optionnel CDC §9 |
|
||||
| **Mess. AM** | Chat foyer ↔ AM (style WhatsApp : texte, emoji, images) |
|
||||
| **Mess. RPE** | Privée par défaut ; ajout de participants pour médiation / conflit |
|
||||
|
||||
## 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 |
|
||||
|------|------------|-------------------|
|
||||
| Absence enfant | Parent | Pas de veto AM ; période **acceptée** tout de suite ; bulle info AM |
|
||||
| Congé AM | AM | **1 parent** accepte **ou** refuse (+ motivation) → bounce AM (modif/renvoi ou DELETE) |
|
||||
| Modification congé AM déjà accepté | AM | Même `id` absence ; re-validation parents ; dates actives = anciennes tant qu’en attente |
|
||||
| Modification absence enfant | Parent | Update immédiat + bulle **ack** AM (OK) |
|
||||
| Maladie AM | AM | Parent **ack** (« bien reçu ») ; **aucun** doc médical |
|
||||
| Sortie / sondage | — | **Plus tard** (types optionnels) |
|
||||
|
||||
**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).
|
||||
|
||||
- Mess. AM : les **2 parents** voient le **même** fil — **pas** de masquage V1
|
||||
- Blog auteurs V1 : **AM** + **gestionnaire (RPE)** — parent auteur = plus tard
|
||||
- Couple actif filtre cartes + messagerie + blog (hypothèse produit : **oui**)
|
||||
|
||||
## 6. Hors périmètre de ce jalon
|
||||
|
||||
- Page **Contrat** riche (Pajemploi, CP…) — 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…)
|
||||
- Masquage messages ; posts blog parent
|
||||
- Carnet repas/sieste (roadmap Phase 4)
|
||||
|
||||
## 7. Critères « effet démo » (acceptation)
|
||||
|
||||
Avec données peuplées, sur au moins 2 supports :
|
||||
|
||||
1. Parent et AM voient le **même contexte de garde** (couple / enfant)
|
||||
2. Parent déclare une **absence** → carte visible côté AM
|
||||
3. AM publie un **post blog** (texte + photo) → visible colonne blog parent
|
||||
4. Gestionnaire publie une **annonce RPE** → visible sur les TdB concernés
|
||||
5. Message **Mess. AM** d’un côté → apparaît de l’autre (près temps réel)
|
||||
6. Look conforme charte papier / pastel
|
||||
|
||||
## 8. Point de départ code
|
||||
|
||||
- Parent : `frontend/lib/screens/home/parent_screen/ParentDashboardScreen.dart` + `dashbord_parent/`
|
||||
- AM : `frontend/lib/screens/am/am_dashboard_screen.dart` (placeholder)
|
||||
- Cartes couleurs : `frontend/assets/cards/` (8 teintes max)
|
||||
|
||||
## 9. Ordre de build suggéré
|
||||
|
||||
Voir [30_DECOUPAGE-TICKETS-QUOTIDIEN.md](./30_DECOUPAGE-TICKETS-QUOTIDIEN.md) § ordre — A (coquille parent) → C (cartes) → D (blog) → E (messagerie) → B (miroir AM) → RPE → F/G (mobile + seeds).
|
||||
@@ -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.
|
||||
@@ -276,9 +276,6 @@ export class Enfants {
|
||||
@Column({ name: 'consentement_photo', type: 'boolean', default: false })
|
||||
consentementPhoto: boolean;
|
||||
|
||||
@Column({ name: 'est_multiple', type: 'boolean', default: false })
|
||||
estMultiple: boolean;
|
||||
|
||||
@Column({
|
||||
type: 'enum',
|
||||
enum: StatutEnfantType,
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
# Fichier déplacé / fusionné
|
||||
|
||||
La procédure **API Gitea** est désormais documentée sous :
|
||||
|
||||
**[26_GITEA-API.md](./26_GITEA-API.md)**
|
||||
|
||||
L’ancienne copie `PROCEDURE-API-GITEA.md` est archivée dans
|
||||
`docs/archive/obsolete/` (doublon).
|
||||
+8
-19
@@ -1,30 +1,19 @@
|
||||
# Archive documentation · P'titsPas
|
||||
|
||||
Ce dossier regroupe les fichiers **sans préfixe numérique** à la racine de
|
||||
`docs/` qui ne sont plus des **références actives**, ou qui sont des
|
||||
**brouillons / temporaires**.
|
||||
Fichiers **hors références actives** : brouillons livrés, CDC historiques, listes figées.
|
||||
|
||||
## Règle de nommage (racine `docs/`)
|
||||
|
||||
- Les documents **normatifs** à la racine portent un préfixe **`NN_`**
|
||||
(deux chiffres), ex. `23_LISTE-TICKETS.md`.
|
||||
- **Exceptions** (héritage ou outillage) listées dans
|
||||
[**00_INDEX.md**](../00_INDEX.md#exceptions-de-nommage) : charte, CDC
|
||||
historique, évolutions — **cible** : les renommer progressivement en `NN_`
|
||||
et mettre à jour `.cursorrules` / liens.
|
||||
- Documents **normatifs** : préfixe **`NN_`**.
|
||||
- Exceptions héritage listées dans [00_INDEX.md](../00_INDEX.md) (`CHARTE_GRAPHIQUE.md`).
|
||||
|
||||
## Sous-dossiers ici
|
||||
## Sous-dossiers
|
||||
|
||||
| Dossier | Usage |
|
||||
|---------|--------|
|
||||
| [**temporaires/**](./temporaires/) | Notes jetables, exports de travail.
|
||||
**Supprimables** quand la tâche associée est close. |
|
||||
| [**obsolete/**](./obsolete/) | Ancienne doc **remplacée** ou **doublon**
|
||||
(conservée un temps pour historique). **Supprimer** après bascule confirmée
|
||||
si plus aucune référence. |
|
||||
| [**temporaires/**](./temporaires/) | Brouillons jetables. **Vider** dès livraison. |
|
||||
| [**obsolete/**](./obsolete/) | Doc remplacée (CDC SuperNounou, ancienne liste tickets, notes ponctuelles, backlog Phase 2 figé). |
|
||||
|
||||
## Hors `docs/` racine
|
||||
## Politique `tmp/`
|
||||
|
||||
Les dossiers thématiques (**`juridique/`**, **`test-data/`**, etc.) peuvent
|
||||
contenir des fichiers sans `NN_` : la règle `NN_` s’applique surtout aux
|
||||
fichiers **directement** sous `docs/`.
|
||||
Le dossier `docs/tmp/` **n’est plus utilisé**. Les mini-specs de tickets livrés sont purgés ; la mémoire produit = bilans de version (`29_…`) + tickets Gitea.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user